Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/examples/dashboard-profile-review.html
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,15 @@ <h2 class="panel-heading" aria-labelledby="chart-title"></h2>
function trace(box,raw,scope='capture'){
const c=captureById(raw.context_id)||raw, o=c.trace||{},request=o.request||c.request||{},selection=o.selection||{};
const root=el('div');root.className='kt-view';box.append(root);
const delivery=c.context_delivery;
if(delivery){
const returned=delivery.items_returned;
p(root,tr(`${returned} items returned · 0 contexts delivered · 0 UTF-8 bytes`,
`返回 ${returned} 条 · 交付 0 组上下文 · 0 UTF-8 字节`),'kt-note');
const retry=delivery.retry;
if(retry)p(root,tr(`Retry one item with a ${retry.required_bytes}-byte budget`,
`使用 ${retry.required_bytes} 字节预算重试一条`)+` · ${retry.ref} @ ${retry.revision}`,'kt-note');
}
fold(root,tr('Retrieval path and ranking','检索路径与排序')+' · '+c.context_id,scope+':'+c.context_id,b=>{
p(b,captureTerms(c)||tr('No search terms recorded.','未记录检索词。'),'kt-query');
if(c.purpose)p(b,c.purpose);
Expand Down
8 changes: 8 additions & 0 deletions docs/guides/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ For either exact-ID assembly, `--relevance WORDS` guides optional file selection
inside the specified bundles.
See the [assembly rules](../knowledge-operations.md#ranked-discovery-and-budgeted-context).

When bounded Collect assembles zero bytes, the CLI and verified archive view
show the number of returned items and the empty delivery. The JSON response
starts with `context_delivery`. If an evaluated item exceeded the budget, the
retry hint gives the qualified ref and revision of the item with the smallest
required byte budget. Retry that item alone with its source flags and set
`--context-bytes` to the reported `required_bytes`. Empty archives carry an
`empty_context` reference.

#### Collect a pinned body and its L1 decision card

Keep the qualified ref, revision and source options from Find or a known read.
Expand Down
16 changes: 15 additions & 1 deletion src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from pathlib import Path

from ...contracts.runspec import revision_matches as _revision_matches
from ...harness.records.knowledge_capture import empty_collect_summary
from ...knowledge.catalog import BACKENDS, get_knowledge, list_knowledge
from ...knowledge.knowledge_operations import KnowledgeReader
from ..host.prepared_environment import inspect_environment
Expand Down Expand Up @@ -248,6 +249,12 @@ def _decision_cards(requests: list[str]) -> dict[str, str | None]:
return cards


def _collect_summary(result: dict) -> dict | None:
if result.get("context_bytes") == 0:
return empty_collect_summary(result["items"], result["context_omissions"])
return None


def _tsv(value: str) -> str:
# One line per record: free-text fields may contain tabs or line breaks.
return (
Expand Down Expand Up @@ -792,8 +799,15 @@ def main(argv: list[str] | None = None, *, entry_protocol: str | None = None) ->
return 0
result = reader.collect(**options)
if args.json:
_print(result)
summary = _collect_summary(result)
_print({"context_delivery": summary, **result} if summary else result)
else:
if summary := _collect_summary(result):
print(f"Context assembly: {summary['items_returned']} items returned, "
"0 contexts delivered, 0 UTF-8 bytes.")
if retry := summary.get("retry"):
print(f"Retry {_tsv(retry['ref'])} @ {_tsv(retry['revision'])} "
f"with --context-bytes {retry['required_bytes']}.")
for identity in result["collisions"]:
print(
f"{identity}\tcollision\towned by multiple authorities; qualify the ref"
Expand Down
2 changes: 1 addition & 1 deletion src/inferrsi/apps/views/capture_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def capture_return_texts(trace, lines, references, context_ids, *, exec_returns=
def is_archived_collect(doc):
observation = doc.get("retrieval") or {}
return (observation.get("entrypoint") == "collect"
and observation.get("receipt_kind") == "delivered_context")
and observation.get("receipt_kind") in ("delivered_context", "empty_context"))


def _collect_source_is_pinned(source):
Expand Down
9 changes: 9 additions & 0 deletions src/inferrsi/apps/views/knowledge_view.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@
function trace(box,raw,scope='capture'){
const c=captureById(raw.context_id)||raw, o=c.trace||{},request=o.request||c.request||{},selection=o.selection||{};
const root=el('div');root.className='kt-view';box.append(root);
const delivery=c.context_delivery;
if(delivery){
const returned=delivery.items_returned;
p(root,tr(`${returned} items returned · 0 contexts delivered · 0 UTF-8 bytes`,
`返回 ${returned} 条 · 交付 0 组上下文 · 0 UTF-8 字节`),'kt-note');
const retry=delivery.retry;
if(retry)p(root,tr(`Retry one item with a ${retry.required_bytes}-byte budget`,
`使用 ${retry.required_bytes} 字节预算重试一条`)+` · ${retry.ref} @ ${retry.revision}`,'kt-note');
}
fold(root,tr('Retrieval path and ranking','检索路径与排序')+' · '+c.context_id,scope+':'+c.context_id,b=>{
p(b,captureTerms(c)||tr('No search terms recorded.','未记录检索词。'),'kt-query');
if(c.purpose)p(b,c.purpose);
Expand Down
11 changes: 10 additions & 1 deletion src/inferrsi/apps/views/optimization_story.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
import re
from pathlib import Path

from inferrsi.harness.records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES
from inferrsi.harness.records.knowledge_capture import (
MAX_CONTEXT_CAPTURE_BYTES,
empty_collect_summary,
)
from inferrsi.harness.records.optimization_log import read_latest_log

from ..workflows.campaign import verify_capture
Expand Down Expand Up @@ -46,6 +49,12 @@ def _capture(root: Path, entry: dict, campaign_id: str) -> dict:
return {**view, "state": state}
if document.get("campaign_id") != campaign_id or document.get("context_id") != context_id:
return {**view, "state": "identity_mismatch"}
observation = document.get("retrieval")
if (isinstance(observation, dict) and observation.get("entrypoint") == "collect"
and document.get("context_bytes_used") == 0):
view["context_delivery"] = empty_collect_summary(
document["items"], document["context_omissions"],
)
contexts = [{"ref": context["ref"], "revision": context["revision"],
"resources": [{"path": resource["path"], "role": resource.get("role"),
"sha256": resource["sha256"],
Expand Down
4 changes: 3 additions & 1 deletion src/inferrsi/apps/workflows/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,9 @@ def collect_archive(
result = reader.collect(
context_bytes=65536 if context_bytes is None else context_bytes, **options,
)
result["retrieval"]["receipt_kind"] = "delivered_context"
result["retrieval"]["receipt_kind"] = (
"empty_context" if result["context_bytes"] == 0 else "delivered_context"
)
document = prepare_retrieval(manifest, context_id, result, None, None, None)
path, digest = knowledge_capture.store_capture(root, document)
return knowledge_capture.collect_envelope(document, path.relative_to(root).as_posix(), digest)
34 changes: 32 additions & 2 deletions src/inferrsi/harness/records/knowledge_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,42 @@
_IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")


def empty_collect_summary(items: list[dict], omissions: list[dict]) -> dict:
"""Describe a bounded Collect that assembled no content."""
summary = {
"state": "empty_context" if items else "no_match",
"items_returned": len(items),
"contexts_delivered": 0,
"context_bytes": 0,
}
revisions = {item["ref"]: item["revision"] for item in items
if isinstance(item.get("ref"), str)
and isinstance(item.get("revision"), str) and item["revision"]}
candidates = []
for omission in omissions:
ref = omission.get("ref")
required = omission.get("required_bytes")
if (omission.get("reason") == "context_limit" and type(required) is int
and required > 0 and isinstance(ref, str) and ref in revisions):
candidates.append((required, ref))
if candidates:
required, ref = min(candidates)
summary["retry"] = {"ref": ref, "revision": revisions[ref], "required_bytes": required}
return summary


def collect_envelope(document: dict, path: str, digest: str) -> dict:
"""Expose the retained reference and the exact context in a single Collect response."""
return {
"reference": {"path": path, "sha256": digest, "kind": "delivered_context"},
empty = (document.get("retrieval") or {}).get("receipt_kind") == "empty_context"
envelope = {
"reference": {"path": path, "sha256": digest,
"kind": "empty_context" if empty else "delivered_context"},
"context": document,
}
if empty:
summary = empty_collect_summary(document["items"], document["context_omissions"])
return {"context_delivery": summary, **envelope}
return envelope


def read_retained(root, reference):
Expand Down
39 changes: 35 additions & 4 deletions tests/apps/test_codex_knowledge_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,11 @@ def test_unarchived_compatibility_query_prevents_false_complete_coverage(tmp_pat
assert record["unresolved_command_lines"] == [3]


def _archive_collect(tmp_path, *, inventory=False, empty=False):
def _archive_collect(tmp_path, *, inventory=False, empty=False, budget=65536):
_cli(tmp_path, "evidence", "init", "--directory", "campaign", "--id", "example")
options = ("--skill-root", str(LIBRARY))
kwargs = {"context_bytes": 65536}
options += ("--context-bytes", "65536")
kwargs = {"context_bytes": budget}
options += ("--context-bytes", str(budget))
if inventory:
options += ("--kind", "case", "--limit", "1")
kwargs.update(kind="case", limit=1)
Expand Down Expand Up @@ -441,16 +441,47 @@ def test_collect_receipt_retains_identifiable_source(tmp_path, source):
@pytest.mark.parametrize("empty", [False, True])
def test_collect_inventory_receipt_is_not_a_search(tmp_path, empty):
argv, stdout = _archive_collect(tmp_path, inventory=True, empty=empty)
response = json.loads(stdout)
capture = response["context"]
assert response["reference"]["kind"] == "empty_context"
assert "retry" not in response["context_delivery"]
if empty:
capture = json.loads(stdout)["context"]
assert capture["items"] == capture["contexts"] == []
assert response["context_delivery"]["state"] == "no_match"
else:
omission, = capture["context_omissions"]
assert omission["reason"] == "unsupported_context"
assert response["context_delivery"]["state"] == "empty_context"
rows = _operation(tmp_path, argv, stdout, "collect")
for record in _import(tmp_path, rows, context_ids=["r1"]):
assert record["coverage"] == "complete"
assert record["events"][0]["action"] == "inventory"
assert record["counts"] == {"searches": 0, "hits": 0, "unique_hits": 0, "used": 0}


@pytest.mark.parametrize("legacy", [False, True])
def test_empty_collect_tool_returns_preserve_coverage_without_a_read(tmp_path, legacy):
argv, stdout = _archive_collect(tmp_path, budget=1)
response = json.loads(stdout)
reference, capture = response["reference"], response["context"]
assert capture["contexts"] == [] and len(capture["items"]) == 1
assert reference["kind"] == "empty_context"
if legacy:
# Older Collect wrote the same zero-byte context under the delivery label.
capture["retrieval"]["receipt_kind"] = "delivered_context"
raw = (json.dumps(capture, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
(tmp_path / "campaign" / reference["path"]).write_bytes(raw)
reference.update(kind="delivered_context", sha256=hashlib.sha256(raw).hexdigest())
stdout = json.dumps({"reference": reference, "context": capture}, ensure_ascii=False,
indent=2) + "\n"
rows = _desktop_collect(tmp_path, argv, stdout)
for record in _import(tmp_path, rows, context_ids=["r1"]):
assert record["coverage"] == "complete"
event, = record["events"]
assert event["delivery"]["visible_resources"] == []
assert record["adoption"]["direct_reads"]["read_only"] == 0


@pytest.mark.parametrize("case", [
"omitted", "matched", "wrong_id", "clipped", "inventory", "exact",
])
Expand Down
59 changes: 58 additions & 1 deletion tests/apps/test_knowledge_navigation_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,68 @@

import pytest

from inferrsi.apps.cli import main
from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard
from inferrsi.apps.views.dashboard_live import DashboardServer
from inferrsi.apps.workflows.campaign import capture_context
from tests.apps.test_optimization_story import FakeReader, context, log_document, write_log
from tests.apps.test_optimization_story import (
COLLECT_REFS,
FakeReader,
context,
log_document,
write_log,
)
from tests.apps.test_optimization_story import campaign as make_campaign
from tests.apps.test_retrieval_projection import FIXTURE

playwright = pytest.importorskip("playwright.sync_api")


@pytest.mark.parametrize("profile_first", [False, True])
def test_empty_collect_summary_is_visible_in_knowledge_navigation(
browser, tmp_path, capsys, profile_first,
):
make_campaign(tmp_path)
ids = [option for ref in COLLECT_REFS for option in ("--id", ref)]
assert main(["collect", *ids, "--context-bytes", "1",
"--archive", str(tmp_path), "--capture-id", "bounded"]) == 0
capture = json.loads(capsys.readouterr().out)
document = log_document(capture["reference"]["sha256"])
document["knowledge"][0]["context_id"] = "bounded"
document["iterations"][0]["context_ids"] = ["bounded"]
write_log(tmp_path, document)
snapshot = dashboard_snapshot(tmp_path)
if profile_first:
snapshot["data"]["review_layout"] = "profile_first"
path = tmp_path / "dashboard.html"
path.write_text(render_dashboard(snapshot), encoding="utf-8")
page = browser.new_page()
try:
page.goto(path.as_uri() + "#knowledge-navigation")
if profile_first:
page.locator("#language").click()
root = page.locator("#knowledge-navigation")
root.get_by_role("button", name="bounded", exact=True).click()
capture_view = root.locator('[data-kt-key="navigation:bounded"]').locator("..")
playwright.expect(capture_view.get_by_text(
"2 items returned · 0 contexts delivered · 0 UTF-8 bytes", exact=True,
)).to_be_visible()
retry = capture["context_delivery"]["retry"]
playwright.expect(capture_view.get_by_text(
f"Retry one item with a {retry['required_bytes']}-byte budget"
f" · {retry['ref']} @ {retry['revision']}", exact=True,
)).to_be_visible()
if profile_first:
page.locator("#language").click()
else:
page.get_by_role("button", name="中文", exact=True).click()
playwright.expect(capture_view.get_by_text(
"返回 2 条 · 交付 0 组上下文 · 0 UTF-8 字节", exact=True,
)).to_be_visible()
finally:
page.close()


def test_round_filter_shows_attempt_tokens_and_unknown_values(browser, tmp_path):
make_campaign(tmp_path)
snapshot = dashboard_snapshot(tmp_path)
Expand All @@ -31,7 +83,12 @@ def test_round_filter_shows_attempt_tokens_and_unknown_values(browser, tmp_path)
page.goto(html.as_uri())
page.get_by_role("link", name="Knowledge trace", exact=True).click()
usage = page.locator('[data-kt-key="round-usage"]')
# Let the native toggle record the open panel before the filter replaces it.
usage.evaluate("""details => details.addEventListener('toggle', () => {
details.dataset.toggleObserved = 'true';
}, {once: true})""")
usage.locator("summary").click()
playwright.expect(usage).to_have_attribute("data-toggle-observed", "true")
rows = usage.get_by_role("row")
playwright.expect(rows).to_have_count(3)
playwright.expect(rows.nth(1).get_by_role("cell", name="0", exact=True)).to_have_count(5)
Expand Down
36 changes: 36 additions & 0 deletions tests/apps/test_optimization_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -1198,6 +1198,42 @@ def test_round_cites_the_cuda_skill_read_and_rejects_the_search(session, capsys)
assert completed["knowledge_refs"] == [citation]


def test_round_rejects_new_empty_context_in_both_reference_forms(session, capsys):
archive = session.parent / "archive"
campaign_id = json.loads((session / "campaign.json").read_bytes())["campaign_id"]
assert main(["evidence", "init", "--directory", str(archive), "--id", campaign_id]) == 0
capsys.readouterr()
ref = "package:inferrsi.common.skills.inference_benchmark_design"
assert main(["collect", "--archive", str(archive), "--capture-id", "empty",
"--id", ref, "--context-bytes", "1"]) == 0
empty = json.loads(capsys.readouterr().out)["reference"]
assert empty["kind"] == "empty_context"
receipt = session / empty["path"]
receipt.parent.mkdir(exist_ok=True)
capture = json.loads((archive / empty["path"]).read_bytes())
assert capture["context_bytes_used"] == 0 and capture["items"][0]["ref"] == ref

plan, state = optimization._load(session)
binding = optimization._knowledge_request(plan, state, action="read").binding
# Give the fixture the managed round's binding so admission reaches the citation gate.
capture["diagnosis_binding"] = binding
capture["request"]["ranking_policy"] = plan["ranking_policy"]
raw = (json.dumps(capture, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
receipt.write_bytes(raw)
state_file = session / "state.json"
state["contexts"].append({**empty, "sha256": hashlib.sha256(raw).hexdigest(),
"diagnosis_id": binding["diagnosis_id"]})
before = json.dumps(state).encode("utf-8")
state_file.write_bytes(before)
args = round_arguments(session, 2)
for citation in (empty["path"], f"{empty['path']}#{ref}"):
with pytest.raises(SystemExit) as error:
main([*args, "--knowledge-ref", citation])
assert error.value.code == 2
assert "Cite a delivered context" in capsys.readouterr().err
assert state_file.read_bytes() == before and receipt.read_bytes() == raw


def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(session, capsys):
from inferrsi.apps.views.dashboard import dashboard_snapshot
from tests.fixtures.knowledge_retrieval import install_legacy_capture
Expand Down
Loading
Loading