From cbeb57eb5232b2a61ab21395c1b2f31745503f56 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 15:59:35 +0800 Subject: [PATCH 1/7] Unify knowledge lookup and retain exact read evidence Use find for discovery and read for the selected body or resource. Keep explicit bundle assembly, historical imports, and the benchmark delivery contract. Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Zhou ziheng --- docs/apps-module-migrations.json | 10 +- docs/benchmarks/benchmark-comparison.md | 19 +- docs/benchmarks/moe-forward-benchmark.md | 3 +- docs/benchmarks/optimization-benchmarks.md | 22 +- docs/dashboard.md | 79 ++-- docs/examples/dashboard-profile-review.html | 8 +- docs/guides/knowledge/external-channels.md | 26 +- docs/guides/knowledge/knowledge-layout.md | 18 +- .../knowledge/knowledge-retrieval-trace.md | 60 ++- docs/guides/operations.md | 233 ++++++---- .../optimization-workflow-unification.md | 28 +- docs/guides/plugins/codex-plugin.md | 30 +- docs/guides/plugins/dsh-plugin.md | 5 +- docs/guides/service-reuse-campaigns.md | 13 +- docs/knowledge-base.md | 4 +- docs/knowledge-operations.md | 126 +++--- docs/knowledge-store.md | 8 +- docs/quickstart.md | 20 +- docs/searchspace-index.json | 2 +- plugins/inferrsi-dsh/form.cjs | 2 +- plugins/inferrsi/skills/inferrsi/SKILL.md | 73 ++- .../inferrsi/skills/inferrsi/SKILL.md | 49 +- src/inferrsi/apps/cli/__init__.py | 243 ++++++---- src/inferrsi/apps/cli/arguments.py | 177 ++++---- src/inferrsi/apps/handoff/context_provider.py | 96 +++- .../apps/integrations/mindie/context.py | 4 + .../apps/integrations/mindie/navigation.py | 9 +- .../apps/integrations/mindie/project.py | 12 +- src/inferrsi/apps/views/capture_delivery.py | 148 ++++-- src/inferrsi/apps/views/codex_knowledge.py | 254 +++++++++-- src/inferrsi/apps/views/codex_search.py | 180 ++++++-- src/inferrsi/apps/views/codex_tool_returns.py | 190 ++++++-- src/inferrsi/apps/views/comparison_report.py | 14 +- src/inferrsi/apps/views/dashboard_data.py | 2 +- .../apps/views/retrieval_projection.py | 42 +- src/inferrsi/apps/views/round_citations.py | 171 +++++-- .../apps/views/round_decision_view.html | 8 +- src/inferrsi/apps/views/search_archive.py | 6 +- src/inferrsi/apps/views/search_attribution.py | 14 +- src/inferrsi/apps/views/template.html | 4 +- .../apps/workflows/benchmark_compare.py | 236 +++++++--- src/inferrsi/apps/workflows/campaign.py | 16 +- src/inferrsi/apps/workflows/knowledge.py | 129 +++++- .../apps/workflows/session_knowledge.py | 382 ++++++++++++++++ .../tasks/qwen21-denoise-npu/TASK.md | 3 +- src/inferrsi/harness/optimization.py | 88 +--- src/inferrsi/harness/optimization_session.py | 28 +- .../harness/records/campaign_records.py | 3 +- src/inferrsi/harness/records/evidence.py | 25 +- .../harness/records/knowledge_capture.py | 74 +++ src/inferrsi/harness/session_runtime.py | 4 +- src/inferrsi/knowledge/_skill_selection.py | 80 +++- src/inferrsi/knowledge/catalog.py | 81 ++-- src/inferrsi/knowledge/channels.py | 10 + src/inferrsi/knowledge/context_projection.py | 5 +- .../knowledge/data/skill_library/README.md | 4 +- .../data/skill_library/records/README.md | 2 +- .../h3-c/audit-h3-runtime-residency/SKILL.md | 4 +- .../references/minimax-h3-apple.md | 8 +- .../references/minimax-h3-profile.json} | 0 .../references/validation.md | 2 +- .../inference-engine-research/SKILL.md | 14 +- .../references/model-aware-preparation.md | 64 +-- src/inferrsi/knowledge/knowledge_find.py | 309 ++++++++++--- .../knowledge/knowledge_operations.py | 425 ++++++------------ src/inferrsi/knowledge/research.py | 130 +----- tests/apps/check_workswarm_installed.py | 8 +- tests/apps/test_apps_context_provider.py | 155 ++++++- tests/apps/test_campaign_record_injection.py | 32 +- tests/apps/test_campaign_task_selection.py | 166 +++---- tests/apps/test_cannbot_boundaries.py | 30 +- tests/apps/test_cannbot_channel_acceptance.py | 4 +- tests/apps/test_cli_catalog.py | 6 +- tests/apps/test_codex_knowledge_search.py | 96 +++- tests/apps/test_codex_plugin.py | 22 +- tests/apps/test_codex_search_delivery.py | 167 ++++++- tests/apps/test_codex_search_shell_forms.py | 72 +++ tests/apps/test_dsh_plugin.py | 5 +- .../test_engineering_benchmark_plugins.py | 15 +- tests/apps/test_indexer_deliveries.py | 36 +- tests/apps/test_knowledge_read_ranges.py | 185 ++++++++ tests/apps/test_mindie_project.py | 21 +- tests/apps/test_mindie_runtime.py | 148 ++++++ tests/apps/test_mlx_discovery.py | 2 +- tests/apps/test_optimization_session.py | 133 ++++-- tests/apps/test_optimization_story.py | 21 +- tests/apps/test_optimization_trace.py | 2 +- tests/apps/test_project_explanation.py | 9 +- tests/apps/test_project_optimization.py | 96 ++-- tests/apps/test_project_service_reuse.py | 82 +++- tests/apps/test_retrieval_projection.py | 48 +- tests/apps/test_round_citations.py | 350 ++++++++++++++- tests/apps/test_round_decisions_browser.py | 11 + tests/apps/test_search_archive.py | 6 +- tests/apps/test_search_attribution.py | 6 +- tests/apps/test_search_capture_delivery.py | 220 ++++++++- tests/apps/test_service_knowledge_snapshot.py | 170 +++++++ tests/apps/test_session_ranking_policy.py | 9 +- tests/benchmark/test_benchmark_compare.py | 345 +++++++++++--- tests/fixtures/knowledge_retrieval.py | 57 +-- .../legacy/model_research_returns.json.gz | Bin 0 -> 4399 bytes tests/fixtures/pre_find_read_captures.json.gz | Bin 0 -> 9488 bytes tests/fixtures/service_reuse.py | 5 +- tests/knowledge/_catalog_find.py | 14 + tests/knowledge/test_collect_selection.py | 48 +- tests/knowledge/test_decision_cards.py | 17 +- tests/knowledge/test_flare_knowledge.py | 5 +- tests/knowledge/test_h3_knowledge.py | 5 +- tests/knowledge/test_h3_metal_knowledge.py | 5 +- tests/knowledge/test_hopper_knowledge.py | 3 +- .../test_indexer_evaluation_summary.py | 57 +++ tests/knowledge/test_knowledge_channels.py | 8 +- tests/knowledge/test_knowledge_cli.py | 191 +++++--- .../test_knowledge_compatibility_shells.py | 2 + tests/knowledge/test_knowledge_find.py | 42 +- tests/knowledge/test_knowledge_install.py | 57 ++- tests/knowledge/test_knowledge_operations.py | 42 +- tests/knowledge/test_knowledge_store.py | 69 ++- tests/knowledge/test_knowledge_tiers.py | 2 +- tests/knowledge/test_mlx_knowledge.py | 5 +- tests/knowledge/test_qwen3_tts_knowledge.py | 5 +- tests/knowledge/test_ranking_policy.py | 35 +- tests/knowledge/test_raw_string_selection.py | 4 +- tests/knowledge/test_research.py | 315 ++++--------- tests/knowledge/test_skill_index.py | 4 +- tests/knowledge/test_skill_library.py | 11 +- tests/knowledge/test_vllm_ascend_skills.py | 6 +- tests/repository/check_installed.py | 104 ++--- tools/evaluate_indexer.py | 194 ++++---- 129 files changed, 6069 insertions(+), 2459 deletions(-) create mode 100644 src/inferrsi/apps/workflows/session_knowledge.py rename src/inferrsi/knowledge/data/skill_library/{config/research_profiles/minimax-h3.json => systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json} (100%) create mode 100644 tests/apps/test_knowledge_read_ranges.py create mode 100644 tests/apps/test_service_knowledge_snapshot.py create mode 100644 tests/fixtures/legacy/model_research_returns.json.gz create mode 100644 tests/fixtures/pre_find_read_captures.json.gz create mode 100644 tests/knowledge/_catalog_find.py diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 9256effd3..f12a73bc9 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -228,7 +228,12 @@ "src/inferrsi/apps/cli/__init__.py", "src/inferrsi/apps/views/capture_delivery.py", "src/inferrsi/apps/views/optimization_story.py", + "src/inferrsi/apps/workflows/session_knowledge.py", "src/inferrsi/harness/optimization_session.py", + "tests/apps/test_codex_knowledge_search.py", + "tests/apps/test_codex_search_delivery.py", + "tests/benchmark/test_benchmark_compare.py", + "tests/knowledge/test_knowledge_cli.py", "tests/repository/check_installed.py", "tests/fixtures/dashboard_profile_review.py", "tests/fixtures/knowledge_retrieval.py", @@ -473,6 +478,7 @@ "src/inferrsi/apps/integrations/mindie/mcp.py", "src/inferrsi/apps/integrations/mindie/navigation.py", "src/inferrsi/apps/integrations/mindie/project.py", + "src/inferrsi/apps/views/codex_knowledge.py", "tests/repository/check_installed.py", "tests/apps/test_apps_module_migrations.py", "tests/apps/test_mindie_context.py", @@ -547,9 +553,11 @@ "consumers": [ "docs/guides/operations.md", "src/inferrsi/apps/cli/__init__.py", + "src/inferrsi/apps/workflows/session_knowledge.py", "tests/apps/test_apps_context_provider.py", "tests/apps/test_apps_knowledge.py", - "tests/harness/test_harness_generation_seal.py" + "tests/harness/test_harness_generation_seal.py", + "tools/evaluate_indexer.py" ], "status": "retired", "first_removal_version": "0.3.4" diff --git a/docs/benchmarks/benchmark-comparison.md b/docs/benchmarks/benchmark-comparison.md index 32504281b..826affd06 100644 --- a/docs/benchmarks/benchmark-comparison.md +++ b/docs/benchmarks/benchmark-comparison.md @@ -176,13 +176,18 @@ Report generation verifies the campaign again to detect changes after collection Tasks can require delivery of a package knowledge card in the on arm. The task manifest's `knowledge_delivery` declares a `query`, `scenario`, and -package `ref`. Preparing the comparison freezes those fields along with the -card revision, body hash, and context byte budget. The on dispatch prompt -provides the corresponding `session knowledge` command. Collection checks for -the actual assembled text and card body at that budget in the verified inputs -to the first search round. Collection retains the evidence for a missing body, -late capture, or budget mismatch and excludes the affected pair. The delivery -requirement applies to plans that declare it. +package `ref`. Its optional `context_bytes` sets the experiment allowance +(default 65,536 bytes). Preparation freezes those fields, the card revision, +and its body hash. The on dispatch prompt supplies the query and scenario to +`find` in the trial session. Follow the required +card's returned `read` command before submitting the first candidate. The report +verifies the revision and body against that round's retained inputs. It sums the +UTF-8 resource bytes delivered through each matching search, including repeated +reads and attachments. An over-budget read stays visible as delivered. The pair +is excluded if the card was missing, arrived late, or the actual delivery +exceeded the plan’s allowance. A later retry cannot qualify it. Historical +plans and receipts retain their original requested-budget checks. +Plans without a required card keep their original comparison rules. Each round can supply `--strategy ` and repeated `--knowledge-ref ` in addition to `--hypothesis`. diff --git a/docs/benchmarks/moe-forward-benchmark.md b/docs/benchmarks/moe-forward-benchmark.md index 6e2e8a574..9f871ee1d 100644 --- a/docs/benchmarks/moe-forward-benchmark.md +++ b/docs/benchmarks/moe-forward-benchmark.md @@ -118,8 +118,7 @@ inferrsi benchmarks session round --session ./outputs/moe-session \ inferrsi benchmarks session final --session ./outputs/moe-session ``` -知识库开启时使用 `benchmarks session knowledge` 检索并留存实际交付内容;关闭时拒绝 -受管检索。外部来源和直接文件读取的隔离由对照实验的执行环境与 Agent 访问约定负责。 +知识库开启时,用 `find "<问题>" --session <目录>` 留存命中,执行选中命中返回的 `read` 后留存正文。关闭知识时,受管检索和读取均受冻结条件约束。外部来源和直接文件读取的隔离由对照实验的执行环境与 Agent 访问约定负责。 Profiling 由 Agent 按瓶颈选择,不是每轮必经步骤。 Harness 留存每轮源码、假设、实际评测、历史最佳选择和独立 final。迭代 assessor 核对 diff --git a/docs/benchmarks/optimization-benchmarks.md b/docs/benchmarks/optimization-benchmarks.md index 76e45afe2..7238efa0c 100644 --- a/docs/benchmarks/optimization-benchmarks.md +++ b/docs/benchmarks/optimization-benchmarks.md @@ -66,21 +66,21 @@ default; `--final-reserve-seconds` changes that explicit reservation. Use Use profile data or existing measurements for the same workload and environment. Record the bottleneck and a UTF-8 summary of its measured evidence before the first candidate round. When the condition allows knowledge retrieval, use -it after diagnosis for a specific implementation question. The session retains -the exact delivered context with its hash. +search after diagnosis for a specific implementation question. Run a selected +hit's scoped read command to receive the body and its delivery reference. ```bash inferrsi benchmarks session diagnose --session ./outputs/qwen-rsi \ --bottleneck '' --evidence ./measurement-summary.txt -inferrsi benchmarks session knowledge --session ./outputs/qwen-rsi \ - --query 'Ascend denoising conditioning reuse normalization fusion' \ - --context-bytes 16384 +inferrsi find 'Ascend denoising conditioning reuse normalization fusion' --session ./outputs/qwen-rsi +# Execute the returned read command for the chosen hit. ``` -Read the returned content. Make one justified candidate change. Knowledge -selection method and the external Agent configuration are caller-controlled -variables. A retained delivery establishes what was supplied. Model consumption -and access to material outside this session require their own observation. +The search records the hits. Each scoped read records the body it returns. +Use the read receipt when material informs a candidate change. A benchmark +comparison can require a named card in round one. Follow its supplied Find +request and read that hit before submitting the first candidate. The plan +sets the experiment allowance. The report checks the bytes the round received. ### Include CANNBot in the round @@ -99,8 +99,8 @@ CANNBot and still delivers local knowledge. Start a new benchmark session from the approved Git project if your session has no binding. Use the original frozen InferRSI release to resume sessions created with an earlier runtime. -`knowledge` queries both sources for the next round. It returns the local -context and a separate `external` result, with its own ranking, channel state +`find QUERY --session DIR` queries both sources for the next round. It returns +local hits and a separate `external` result, with its own ranking, channel state and `reference.path`. A CANNBot timeout still returns the local result. The external request and worker cleanup use the remaining search budget before the final reserve. Use task keywords and keep private details out. diff --git a/docs/dashboard.md b/docs/dashboard.md index 6cb4c9062..b9797808f 100644 --- a/docs/dashboard.md +++ b/docs/dashboard.md @@ -230,28 +230,34 @@ inferrsi campaign import-search --directory "$campaign" --round 1 \ For round 2 take a new first/last pair, even in the same session. Windows are one-based and inclusive. If the host buffers events, import after they have -flushed. After an interruption the host can do the same handoff. Use -`--context-id ` once per `campaign capture-context` performed in this round. -These inputs can be combined with the rollout or used alone for an Indexer-only -round. Each capture is verified and its returned refs, revisions, request and -resource paths are recorded. Opening a resource and receiving a prepared context -are distinct observations. For a new Collect retrieval that must be retained, use -`campaign capture-context` with the same query or exact IDs. +flushed. After an interruption the host can do the same handoff. For scoped +Find and read receipts with a `sha256`, add +`--context-id --context-id ` to the import. +Take each ID from the respective `reference.path` (`knowledge/.json`). +A manual campaign creates each search receipt with `find QUERY --session DIR`. Follow the hit's scoped +`read` to retain the selected body. For an inventory or assembly of already +known IDs, use `campaign capture-context`. Captures can be imported with a +rollout or on their own. Each verified capture supplies the recorded request, +returned refs, revisions and resource paths. A tool return with the body +establishes visibility. A later decision citation identifies declared use. The importer reads Desktop `CommandExecution` events. Run `find` and `read` in -separate simple tool calls and retain both call/return pairs in the selected +separate simple tool calls, apart from line counting, pipes and redirections. +Retain both call/return pairs in the selected window. It accepts Find's default text and `--json` output. Find records result references in returned order, including separately qualified external hits. When an installed Skill links to its package projection, `read_ref` gives the identity in the open command. Read records the resolved reference and -returned revision. Only `read --material` or `read --resource` can verify a -returned body. A metadata-only read records a visible reference. +returned revision. For a standalone read, `--material` or `--resource` +returns a body. In a session, the emitted `read_args` include `--search-ref` +and bind the read to the hit in the saved search. A metadata-only read records +a visible reference. The importer verifies direct CLI delivery against the agent-facing tool response. Missing, clipped or uncorrelated outputs leave coverage partial -even with `--complete`. Compatibility queries through `collect`, `knowledge -search`, `knowledge research` and `context` require separate capture evidence -for their results. The importer marks these standalone calls unresolved. +even with `--complete`. Historical traces may contain `collect`, `knowledge search`, `knowledge research` +or `context` text queries. Their results require the original capture evidence. +A standalone legacy call without that evidence remains unresolved. Remote tools and external card reads also require their own evidence. For file searches the importer supports text and filename matches with `rg` @@ -375,9 +381,12 @@ retrievals require separate evidence. Review query text and paths before sharing If a delivered passage changes a candidate or validation choice, explain that choice in the round's existing reason and append `[use REF | EXACT SOURCE EXCERPT]`. -Use the qualified reference from `read` or the reference in the delivered -context. Pick a short verbatim excerpt on one source line that identifies the -passage. A round whose choice did not depend on a passage needs no citation. +Use the material `ref` from `read` or the reference in the delivered context. +The read's `reference.path` is the receipt for `round --knowledge-ref`. +Pick a short verbatim excerpt on one source line that identifies the +passage. If a compact record includes a URL or private path on that same line, +the archive can retain just the cited excerpt when it survives redaction. +A round whose choice did not depend on a passage needs no citation. For managed project and benchmark rounds, use the existing `--hypothesis`. A local mask-memory experiment submitted this hypothesis. @@ -388,11 +397,23 @@ At round close, after the completed round response is in the rollout, run the existing `campaign import-search` over that round. Use the start boundary captured before retrieval and the end of the flushed rollout. A review file with `task`, `corpus` and `"decisions": []` is enough for automatic alignment. -Include `--context-id` for AB/BA or benchmark captures used in the round. +Include a `--context-id` for each standard Find and read capture returned in the round. The importer locates matching managed JSON returns within the window for those captures. It locates the submitted hypothesis from the round call and verifies the round receipt. The return containing the source passage must precede the -round call. Service-reuse sessions retain knowledge in their own records. +round call. If the round ran asynchronously and its final output was clipped, +read its short receipt after completion and include that call and its return +in the same window: + +```sh +inferrsi campaign status --session "$campaign" --round-receipt 1 +``` + +For a benchmark use `benchmarks session status` with the same options. The +receipt identifies the original submitted observation by its path and digest. +The original round call still determines when the decision was made. A receipt read +after a historical window supplies no evidence inside that window. +Service-reuse sessions retain knowledge in their own records. See [service reuse](guides/service-reuse-campaigns.md#records-compatibility-and-validation). For a manual campaign, put the citation in the existing log's round @@ -672,23 +693,19 @@ to understand the whole optimization: what knowledge was retrieved and why, the declared search space and how it was narrowed, each round's hypothesis and reason, the decision, and the success and failure summaries. It has two parts. -**1. Capture the knowledge context while working.** Run the same retrieval the -agent uses through `campaign capture-context`. It calls `collect` to rank the -question with Find and assemble resources within a context budget. The capture -keeps the request, the selected items, -everything left out and why, and every resource body with its SHA-256. The -dashboard re-derives the assembled text from those resources and withholds a -capture whose bytes or hashes no longer match. +**1. Capture the knowledge context while working.** Run Find in the manual +campaign. Give the search a fresh ID, then run the scoped read returned for +the hit whose body you need. ```sh -inferrsi campaign capture-context --directory --id r1-diagnosis \ - --relevance '' --backend --context-bytes 65536 +inferrsi find '' --session ``` -Each call writes a new `knowledge/.json` and prints its SHA-256; an -existing id is never overwritten. The capture records what InferRSI prepared, -not what a model read. Hash checks detect changes relative to the cited bytes -and internal inconsistencies; they do not authenticate who produced a capture. +The search record identifies the hits. The read records which revision and +resource were returned. Use `--knowledge-ref` when a managed round actually +uses a delivery. In a manual campaign, enter the read and its use in the +optimization log below. The dashboard verifies retained resources and assembled +text against their recorded hashes. A hash establishes byte consistency. The campaign root and its `knowledge` directory must remain trusted and stable while reading or writing. Captured text comes from the selected knowledge sources; review it before sharing if a store or checkout source was added. diff --git a/docs/examples/dashboard-profile-review.html b/docs/examples/dashboard-profile-review.html index 0e73f6339..da80ac2ce 100644 --- a/docs/examples/dashboard-profile-review.html +++ b/docs/examples/dashboard-profile-review.html @@ -925,7 +925,13 @@

for(const entry of record.items){ const card=item(local,entry.title||entry.ref); field(card,tr('Reference','引用'),entry.ref); - field(card,tr('Delivery','交付'),entry.delivered?tr('Context prepared','已装配上下文'):tr('Context omitted','未装配上下文')); + if(Array.isArray(entry.reads)){ + if(!entry.reads.length)field(card,tr('Read receipts','读取凭据'),tr('No read recorded','暂无读取记录')); + for(const read of entry.reads){ + field(card,read.omission?tr('Read omitted','读取未交付'):tr('Read resource','已读资源'),[read.resource,read.omission].filter(Boolean).join(' · ')); + p(card,read.path,'rd-note'); + } + }else field(card,tr('Delivery','交付'),entry.delivered?tr('Context prepared','已装配上下文'):tr('Context omitted','未装配上下文')); } const result=record.external; if(!result)return; diff --git a/docs/guides/knowledge/external-channels.md b/docs/guides/knowledge/external-channels.md index 8bccdede3..66d951643 100644 --- a/docs/guides/knowledge/external-channels.md +++ b/docs/guides/knowledge/external-channels.md @@ -10,17 +10,17 @@ This is the **default and intended state**, not a missing installation step. ```bash $ inferrsi find "CeilDivision 向上取整" -no_match 135 entries searched; rephrase, or search the corpus directly with rg +local_no_match 135 entries searched; try another query or scope external (not locally verified; scores are not comparable across channels) cannbot-knowledge [not_enabled] cannbot knowledge is not enabled for this project fix: inferrsi cannbot enable --checkout --python ``` -`no_match` there is honest: the packaged corpus really holds nothing for that -query. The `not_enabled` line says an external source exists, was not approved -for this checkout, and how to approve it. Without that line a caller would -conclude the knowledge does not exist anywhere, which would be wrong. +`local_no_match` describes the packaged corpus. Each external source reports +its own status. In JSON, an external hit makes `no_match` false even when +`items` is empty. If an attempted source did not answer and no other source +found a hit, `no_match` is null. `matched` counts local matches. On `main` `6c7e2379`, the packaged corpus holds **6 Ascend content cards and 0 per-API cards**. The external cannbot-knowledge corpus holds **10,550 cards, @@ -36,8 +36,9 @@ terms for your intended use before enabling it. Keeping the content outside the package does not establish permission to use, transmit or redistribute it; that organisational decision remains open in #476 Q1. -Nothing from an external checkout is ever copied into `src/inferrsi/knowledge/data/`, -a wheel, or `evidence/`. +An external lookup does not add upstream content to the packaged corpus. +Managed CANNBot receipts retain metadata. For MindIE, a caller can explicitly +archive native query and explain returns with `campaign import-mindie`. ## Setting one up @@ -113,7 +114,7 @@ Or declare it per call: ```bash inferrsi find "AscendC tiling 参数怎么算" --backend ascend --platform a2 -inferrsi cannbot search "CeilDivision 向上取整" --platform a2 --limit 100 +inferrsi find "CeilDivision 向上取整" --backend ascend --platform a2 --external-limit 100 inferrsi cannbot read ops/ascendc/apis/utils_api/cpp_stdlib/math_functions/ceil_division ``` @@ -229,10 +230,11 @@ conclusion. | Capability | State | | --- | --- | -| `cannbot enable / disable / describe / search / read` | implemented | -| `find` integration with gating, budgets, per-channel states | implemented | -| Managed CANNBot benchmark and AB/BA round query, read and Dashboard attribution | implemented | -| MindIE native navigation | Explicit opt-in for [standalone Find](../plugins/codex-plugin.md#find-navigation) under an approved Ascend project. Returns navigation references. | +| CANNBot project grant | `cannbot enable`, `cannbot describe`, `cannbot disable` | +| CANNBot navigation and pinned card reads | `find QUERY --backend ascend` queries the approved source. Use the hit's `cannbot read` command for a pinned page. | +| Managed CANNBot benchmark and AB/BA retrieval | `find QUERY --session DIR` follows the frozen source rule. The external hit's `knowledge-read` command returns the page and a receipt for round attribution. | +| MindIE project grant and navigation | `mindie enable`, `mindie describe`, `mindie disable`. Use `find QUERY --backend ascend --external-source mindie-agent` for navigation or `find --input FILE` for a native request. [Find navigation](../plugins/codex-plugin.md#find-navigation) | +| MindIE card reads and evidence | `mindie explain` reads selected units. `campaign import-mindie` retains the supplied query and explain returns. [MindIE workflow](../plugins/codex-plugin.md#mindie-knowledge) | | `cannbot serve` (stdio MCP proxying `discover` / `search` / `read_card`) | not yet | | `campaign import-cannbot` (receipts into evidence) | not yet | | Automatic clone, index build or deployment | deliberately absent | diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index 8caf9ec7f..8211eb532 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -35,7 +35,7 @@ flowchart LR L --> S["80 supporting owners in systems/, playbooks/, workflows/, casebooks/"] P & H & S --> O["One SKILL.md owns procedure and typed fields · 88 registered IDs"] L --> F["records/<stable-id>.json · 48 authored findings"] - L --> CFG["config/ · aliases and research profiles"] + L --> CFG["config/ · query aliases"] L --> REG["skill-index.json · stable ID → owner and backend"] L --> BUILD["_compiled/ · inputs.json and _provenance.json"] O & REG -.->|fingerprint resources and compile host headers at the source commit| BUILD @@ -51,22 +51,20 @@ flowchart TB P --> R["Capture actual run, acceptance gates and search budget"] R --> D["Observation triggers a supporting question"] D -->|Known owner| I["Explicit read / resource / capture by ID and revision"] - D -->|Unknown owner| F["Find lexical ranker · ranked Collect / campaign capture share selector"] - D -->|Need catalog scope| C["knowledge search · filter by repo, backend, scenario or tier"] - C -->|Query| F - C -->|No query| B["Catalog by ID · 48 findings + 88 skill views at #516
default limit 10 · 136 entries in that snapshot"] + D -->|Question| F["find QUERY · add --session DIR to record the hits for a round"] + D -->|Need inventory| B["knowledge list · filter catalog by repo, backend, scenario or tier"] F --> A["Rank the existing searchable fields and procedure text
Exclude 7 primary skills and legacy router before IDF and limits
default 135 evidence owners · 80 skills + 48 findings + 7 cases"] I -->|Authored finding| E["Validate selected record and its dependencies
retain linked-library bundle and pin checks when skill documents are declared"] I -->|Other exact owner| V["Check revision, device, model, flags and measurement against this run"] A --> H["Find card · limited caveats and withheld count
next_read_content_bytes measures content at Find time"] E & H & B --> V - V --> Z["Read the procedure and structured metadata, or Collect within budget
Pinned resource read returns original SKILL.md bytes"] + V --> Z["Run the selected read · open supporting files by resource path as needed
A scoped read retains the material delivered for the round"] Z --> X["Meets gates → cite reproducible evidence and scope"] V --> G["Gap → name missing evidence; test the next distinction or record exhausted budget"] G -.->|budget remains| D ``` -![Search paths and evidence delivery (Chinese)](../../assets/knowledge-layout/03-search-and-delivery.png) +[Search and delivery diagram from the #516 snapshot (Chinese)](../../assets/knowledge-layout/03-search-and-delivery.png) ## 4. Before and after @@ -104,6 +102,8 @@ Claude reads `disable-model-invocation` from the native YAML header. Across this Edit the owner's `SKILL.md` for a procedure, including its `metadata.inferrsi` fields. Keep supporting examples and scripts with that owner. Add a new owner's ID, path and backend to `skill-index.json` and regenerate the two `_compiled/` files from committed sources. Author a separate `records/.json` for an independent finding. +The MiniMax-H3 component profile now lives beside the weight inventory and worked example under the [h3.c audit's references](../../../src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json). The before-and-after diagram above describes the earlier #516 migration. + This migration folds the fields from 107 paired files into their procedures, including 19 nested procedures. The 19 remain resources of their registered parents. The 48 JSON findings each represent independently addressable evidence. Query aliases, route cards, case records and test inputs retain their own file formats. ## Seven deliverables @@ -129,7 +129,7 @@ LLM, Omni, TTS, Diffusion and RLT describe workload conditions. CUDA, ROCm, Asce ```bash inferrsi skills enter task-accuracy inferrsi find "TTS quality regression after engine upgrade" -inferrsi knowledge search --tier peer --repo-type qwen3_tts_engine --backend ascend --json +inferrsi knowledge list --tier peer --repo-type qwen3_tts_engine --backend ascend --json inferrsi knowledge show flashinfer.cuda.llm.paged_decode_dispatch ``` @@ -137,7 +137,7 @@ For an inference task, run `inferrsi skills enter ` and read its return For an exact read of an authored finding, the reader validates the selected record and the inputs of its bundle. A stale metadata edit in an unrelated skill cannot block a standalone finding such as FlashInfer paged decode. A record that declares linked skill documents retains its library dependencies and bundle revision checks. Changes to those dependencies can invalidate a pinned read. -Find skips incidental system files such as `.DS_Store` beside the records and still validates record JSON. It ranks each eligible evidence owner once. A scoped catalog query reuses Find; a catalog listing without a query includes the eight task entries. Ranked Collect and managed campaign capture use the same evidence selector, and explicit IDs can still capture a task owner. Check revision, applicability and verification before using a result. Propose a reusable finding for human review with its source, scoped conclusion and retry condition. +Find skips incidental system files such as `.DS_Store` beside the records and still validates record JSON. It ranks each eligible evidence owner once. `knowledge list` includes task entries in the inventory. A scoped Find records the ranked hits for the round. Execute the selected read to receive and retain its body. Exact IDs can still capture a task owner. Check revision, applicability and verification before using a result. Propose a reusable finding for human review with its source, scoped conclusion and retry condition. ## Design choices and benefits diff --git a/docs/guides/knowledge/knowledge-retrieval-trace.md b/docs/guides/knowledge/knowledge-retrieval-trace.md index 6e3bf1f3f..faf8fd9a7 100644 --- a/docs/guides/knowledge/knowledge-retrieval-trace.md +++ b/docs/guides/knowledge/knowledge-retrieval-trace.md @@ -60,16 +60,13 @@ and synthetic measurements; they are not real optimization results: ## Execution observations -`campaign capture-context` uses Find ranking for a single free-text question, -then assembles selected material through Collect. The capture records both -operations. Pass one question as a positional query or `--relevance`. Explicit -IDs select material in caller order. See the [migration guide](../operations.md#migrate-old-text-queries) -for callers that previously passed a separate query filter and ranking cue. +Use `find QUERY` for standalone discovery, or add the session directory to +record the search inside an optimization run. Each search returns its receipt +path in `reference.path`. Run a selected hit's scoped read command +to retrieve and record that body. A Find hit can remain unopened. ```sh -inferrsi find 'decode launch' --explain --json -inferrsi campaign capture-context --directory --id r1-context \ - --relevance 'decode launch' --context-bytes 65536 +inferrsi find 'decode launch' --session ``` To capture an installed Case at its observed revision, select the bundled @@ -86,9 +83,8 @@ The capture records the requested pin. A stale revision is recorded as of a queryless inventory is an inventory operation. Both retain their items and revisions in the round record. The search and hit totals count text discovery. -`knowledge search --explain` returns a JSON envelope with `items` and `retrieval`. -Python callers use `search_knowledge(..., explain=True)` for the same -catalog envelope. `collect` includes a `retrieval` member outside its +Previously saved catalog search observations have `items` and `retrieval`. +Python's `list_knowledge(..., explain=True)` also produces a catalog envelope. `collect` includes a `retrieval` member outside its budgeted item and resource payloads. | `retrieval` field | Meaning | @@ -103,7 +99,7 @@ budgeted item and resource payloads. | `assembly` | `performed` or `not_requested`; old missing evidence is `unknown` | | `candidate_details` | `not_recorded`: no reconstruction of a full rejected candidate set | -A catalog text query records `knowledge search → find` and returns catalog +Earlier catalog searches recorded `knowledge search → find` and returned catalog records. Its `catalog-sha256:` revision hashes the returned record using sorted, UTF-8 JSON. It identifies those catalog bytes. A Collect revision identifies the normalized bundle used to deliver resources. @@ -128,10 +124,10 @@ same immutable capture envelope used by `capture-context`: ```python from pathlib import Path -from inferrsi.knowledge.catalog import search_knowledge +from inferrsi.knowledge.catalog import list_knowledge from inferrsi.apps.workflows.campaign import save_retrieval -result = search_knowledge("decode launch", explain=True) +result = list_knowledge(backend="cuda", explain=True) path, sha256 = save_retrieval( Path(""), context_id="r1-catalog", result=result, ) @@ -150,8 +146,9 @@ assembly byte budget are retained independently. ## Connect a new round -1. Save the retrieval while working, using `capture-context` or - `save_retrieval`. Retain the returned capture hash. +1. Run `find QUERY --session DIR` and follow the emitted read + for the selected hit. Retain the capture IDs and hashes from the search and + read. For an already executed exact assembly use `save_retrieval`. 2. Register the candidate and its exact run using `campaign record`. Retain code locations/revisions in `--details-json` and the existing run artifacts. 3. Add the capture ID/hash to `knowledge[]`, and its ID to the matching @@ -161,7 +158,7 @@ assembly byte budget are retained independently. 4. Import the round's captures and, when available, its explicitly bounded local trace with `campaign import-search`. Use `--archive-review` for the existing portable v2 passage-to-decision contract. A decision citing a rendered - resource from a verified `find` or `collect` capture supplies `passage_path` + resource from a visible scoped `read` or a verified assembly tool return supplies `passage_path` with the resource's bundle-relative key. Its `passage_line` counts from the first line of that resource. See [the import contract](../../dashboard.md#import-one-rounds-searches) for the input fields. Mark complete coverage only when established. @@ -172,21 +169,20 @@ assembly byte budget are retained independently. The legacy manual campaign operations above are for externally recorded campaigns. Managed optimization sessions retain their controller-owned state; this read-only dashboard extension does not create another controller. -For a managed AB/BA or benchmark capture selected with `--context-id`, the -importer looks for the complete `campaign knowledge` or -`benchmarks session knowledge` JSON tool return in the trace window. The returned -capture reference and contents must match the saved capture. Delivery is recorded -for matching resource blocks even when the round has no use citation. Reviewers -can also supply the return line in `capture_returns`. A managed query without a -verified matching capture keeps coverage partial and complete counts unavailable. -[Service-reuse campaigns](../service-reuse-campaigns.md#records-compatibility-and-validation) -retain knowledge in their own fingerprint-free format, outside this importer. - -A manual `campaign capture-context` text query likewise needs its selected -`--context-id` and a matching tool receipt to establish complete coverage. -The receipt records preparation. A matching resource body in a tool return -establishes delivery separately. Queryless inventory and explicit ID assembly -can be retained with zero searches. +For a scoped Find and read, run each in its own tool call with its full return. +Select their captures with `--context-id --context-id ` +from the actual rollout window. Each ID is the filename stem in its returned +`reference.path`, `knowledge/.json`. A Find result identifies the hit and read route. +To establish delivery, the importer matches the returned material with the +retained read. Missing or clipped output leaves visibility unverified. An +uncited delivered passage retains unknown use. + +Retained older `campaign knowledge`, `benchmarks session knowledge` and +`campaign capture-context` invocations keep their historical interpretation. +A path-only receipt records preparation. A matching resource block in a +verified tool return establishes visibility. Queryless inventory and explicit +ID assemblies contribute zero searches. [Service-reuse campaigns](../service-reuse-campaigns.md#records-compatibility-and-validation) +retain their source revisions and prepared resources in their own receipt format. Reasons in a submitted managed hypothesis or a manual optimization log can carry an explicit use citation. The importer aligns it with the verified diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 24a168e62..29812cdf3 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -12,23 +12,48 @@ Effect classes used below: ## Intent map +Use `find ""` to look up inference knowledge. Run the `read_args` +from a relevant hit to read its body. A normal read brings back the selected +body. Open any supporting file you need by its resource path and revision. + +In a managed project or benchmark, run `find "" --session ` +when the frozen plan permits knowledge. A manual campaign uses the same command. +The result includes the campaign-relative path of its search receipt. Follow the emitted scoped `read` command to +receive the selected body and retain its delivery. Append `--resource PATH` +to those same read arguments to open one supporting file. Each requested file +has its own delivery receipt. A large file returns `next_read_args`; run those +arguments until no continuation remains. Each page records only its returned +bytes, with UTF-8 boundaries preserved. The continuation keeps the same +resource, revision and search reference. +Cite a used read's `reference.path` with `round --knowledge-ref` in an AB/BA +project or benchmark. A service-reuse attempt retains prepared contexts +automatically. Record any passage that influenced the candidate in its +hypothesis. If the host clipped an asynchronous round's response, read +`campaign status --session DIR --round-receipt N` or +`benchmarks session status --session DIR --round-receipt N` before closing +the archive. It reads the verified observation for completed round N. +For a benchmark with a required card, run the supplied query with its scenario +and read the required hit before submitting round one. The comparison report +uses the budget frozen in the experiment plan. It counts bytes actually delivered +and excludes over-budget pairs. +See [round decisions](knowledge/knowledge-retrieval-trace.md#round-decisions). + | Intent | Entry | Effect class | Boundary | | --- | --- | --- | --- | | Verify whether RSI knowledge improves optimization efficiency | CLI `benchmarks compare`; [comparison workflow](../benchmarks/benchmark-comparison.md) | Local experiment records / explicit native handoff / report-generating | Apps freezes two-task on/off plans, returns host actions, verifies retained finals and reports Benchmark comparisons; no hidden Agent launch | -| Complete a task optimization in the current Agent | CLI `benchmarks session start/knowledge/round/status/final/recover` | Experiment-executing / local records | Frozen budget, actual candidates and independent task outcomes. The current Agent drives edits. Real usage is imported explicitly. Recovery collects an existing execution using its [pinned runtime](optimization-workflow-unification.md#release-boundary-recovery) | -| Optimize an ordinary project in the current Agent | CLI `campaign start/knowledge/round/status/final/recover` | Experiment-executing / local records | Harness freezes explicit caller-provided checks, manages multi-file candidates, executes and assesses retained results. This path does not depend on Benchmark or infer acceptance from the goal. See [shared workflow](optimization-workflow-unification.md) | +| Complete a task optimization in the current Agent | CLI `benchmarks session start/round/status/final/recover`, `find --session` / `read` | Experiment-executing / local records | Frozen budget, actual candidates and independent task outcomes. The current Agent drives edits. Real usage is imported explicitly. Recovery collects an existing execution using its [pinned runtime](optimization-workflow-unification.md#release-boundary-recovery) | +| Optimize an ordinary project in the current Agent | CLI `campaign start/round/status/final/recover`, `find --session` / `read` | Experiment-executing / local records | Harness freezes explicit caller-provided checks, manages multi-file candidates, executes and assesses retained results. This path does not depend on Benchmark or infer acceptance from the goal. See [shared workflow](optimization-workflow-unification.md) | | Reuse one project service across multi-scenario checks | CLI `campaign start --evaluation-mode service_reuse`, then `baseline/round/profile/status/recover/final` | Experiment-executing / local records | Caller supplies protocol and service scripts. An optional profiler can run inline or on a settled round. `resume`, `refresh-references` and explicit retry retain recovery decisions. See [service reuse](service-reuse-campaigns.md) | | Prepare and record a fresh native Agent | CLI `agents prepare/dispatch/bind/record/status` | Local records / explicit host handoff | The initiating Agent calls native host tools. Records prevent repeated dispatch; exported host observations do not establish task acceptance. See [native sessions](native-agent-sessions.md) | | Discover packaged tasks | CLI `benchmarks list [--iterative]` / `benchmarks show`; Python `benchmark.registry.builtin_tasks` / `describe_task` | Read-only | Reads the installed registry and [task manifests](../benchmarks/engineering-benchmarks.md). The optional filter selects task packages with an `optimization.py` file at their root | | Execute one packaged task | CLI `benchmarks run`; Python `apps.workflows.benchmark_operations.run_task` | Experiment-executing | Application launches the task entry, supplies the execution callback and preserves arguments and exit status. The task owns its device, measurement and assessment protocol | -| Find relevant cases, skills and records | CLI `find` | Read-only | Default discovery across the registered library and package records. Follow the emitted command to read a hit and its revision | -| Inspect the package catalog | CLI `knowledge search` / `knowledge show`; catalog API | Read-only | Filtered inventory and existing catalog scripts. Uses the installed package's tier/repo/backend/scenario filters and IDs | -| Prepare model-aware engine research | CLI `knowledge research`; Python `research_knowledge` | Read-only | Independent model/framework/task/modality/mechanism queries over the same package catalog; source-grounded known profiles, deduplicated matches and explicit target annotations; no engine/hardware qualification | +| Find relevant cases, skills and records | CLI `find` | Read-only standalone / local records with `--session` | Find returns hits with read commands. A scoped read records a delivery for the round | +| Inspect the package catalog | CLI `knowledge list` / `knowledge show`; catalog API | Read-only | Filtered inventory and existing catalog scripts. Uses the installed package's tier/repo/backend/scenario filters and IDs | | Enter an inference task or discover/read skills | CLI `skills enter` / `list` / `show` / `resource` / `reference` | Read-only | `enter` loads one primary owner's complete procedure before evidence search. `list`/ `show` inspect skill metadata and instructions. `resource`/`reference` resolve paths for your file reader. | -| Retrieve and cite external round knowledge | CLI `benchmarks session knowledge / knowledge-read`, AB/BA `campaign knowledge / knowledge-read` | Local evidence-writing | Requires an explicit `--cannbot-platform` at start and an approved project grant. Retains search and read metadata. Cite a delivered receipt with `round --knowledge-ref`. See [round retrieval](../benchmarks/optimization-benchmarks.md#include-cannbot-in-the-round) | -| Collect selected knowledge | CLI `collect`; Python `KnowledgeReader.collect` | Read-only | Batch selection and budgeted assembly by query or exact IDs, with revisions and omissions. The only accepted explicit `--relevance-method` value is `find-lexical-v1` | +| Retrieve and cite external round knowledge | CLI `find --session`, then `campaign knowledge-read` or `benchmarks session knowledge-read` | Local evidence-writing | Requires an explicit `--cannbot-platform` at start and an approved project grant. Retains search and read metadata. Cite a delivered receipt with `round --knowledge-ref`. See [round retrieval](../benchmarks/optimization-benchmarks.md#include-cannbot-in-the-round) | +| Collect selected knowledge | CLI `collect`; Python `KnowledgeReader.collect` | Read-only | Inventory or batch assembly of known IDs, with revision pins, resources and omissions | | Read exact material/resources | CLI `read` / `resource`; Python `KnowledgeReader.read` / `KnowledgeReader.resource` | Read-only | Returns the requested revision or an explicit unavailable/stale error; never substitutes newer bytes | -| Export legacy cited material | CLI `context` | Read-only | Cited package export for manual use with a coding agent; not a conversation store and not a full Collect equivalent | +| Export legacy cited material | CLI `context` | Read-only | Markdown export of package records selected by filters or explicit IDs | | Create/update a store candidate | Python `KnowledgeStore.create` / `KnowledgeStore.update` | Candidate-writing | One explicitly authorized local store; expected-revision updates with reason and evidence; retained history; no promotion and no edits to package/checkout content | | Inspect a store candidate's history | Python `open_knowledge_store(...).history` | Read-only | Opens an existing store and reads the revision lineage for one store ID | | Amend repository-owned knowledge | Scoped repository PR | — | Repository review and integration authority apply; this is not a runtime store Update | @@ -55,7 +80,7 @@ Effect classes used below: | Seal a generation with frozen feedback authorization | Python `harness.generation.prepare_generation`; [opt-in feedback profile](../contracts/generation-feedback-policy.md) | Local context / policy / generation-plan retention | Optional fixed policy and source record Refs authorize original scope/check proofs before provider calls. Absent-policy calls remain a trusted-host path; no automatic execution or policy-approval authentication | | Seal host-approved generation context without a policy Ref | Python `harness.generation.prepare_generation`; [feedback boundary](../contracts/generation-feedback.md) | Local context / generation-plan retention | The trusted host authorizes feedback and excludes final-only results before handoff. Without the opt-in policy Ref, H seals supplied material and does not prove feedback-policy enforcement or execute a worker | | Visualize a recorded run or campaign | CLI `dashboard`; [dashboard](../dashboard.md) | Report-generating / local read-only serving | Writes an offline HTML snapshot or serves an optional live view on loopback; does not run an agent or validate a claim | -| Capture a knowledge context | CLI `campaign capture-context`; [offline dashboard](../dashboard.md#record-the-optimization-story-campaign-trace) | Local evidence-writing | Saves assembled context and resource hashes in a new `knowledge/.json`. Supports ordinary questions and explicit IDs. The only accepted explicit `--relevance-method` value is `find-lexical-v1` | +| Capture a knowledge context | CLI `campaign capture-context`; [offline dashboard](../dashboard.md#record-the-optimization-story-campaign-trace) | Local evidence-writing | Archives an exact-ID assembly or inventory in a manual campaign. For an observed search, use `find QUERY --session DIR` | | Retain an executed retrieval | Python `apps.workflows.campaign.save_retrieval`; [capture contract](knowledge/knowledge-retrieval-trace.md#retain-a-standalone-result) | Local evidence-writing | Saves an existing catalog/collect result under a fresh campaign capture ID; no new search or automatic publication | | Import one round of knowledge searches | CLI `campaign import-search`; [round import](../dashboard.md#import-one-rounds-searches) | Local evidence-writing | Reads a Codex rollout window or context captures. With `--archive-review`, retains excerpts of attributable tool returns and reviewed decisions for readers of the evidence bundle. | | Record the optimization log | CLI `campaign log`; [offline dashboard](../dashboard.md#record-the-optimization-story-campaign-trace) | Local evidence-writing | Validates and stores a new numbered campaign log version; the dashboard cross-checks it against captures and runs | @@ -78,9 +103,9 @@ Effect classes used below: | Recover goal progress and the next proposal | [Offline goal checkpoints](goal-checkpoints.md), `python -m tools.goal_checkpoint` | Read-only | Explicit scope/criteria, pinned owner decisions and existing comparison receipts; a disposable view, never execution or acceptance authority | | Summarize campaign gains | `tools/campaign_summary_chart.py`; `report`/`run` figure | Figure-generating | Renders recorded values into one gain figure plus a matching table; validates the specification and computes nothing new | -The `collect`, `read` and `resource` commands share the reader's rules; they -are distinct from `knowledge search`, whose package catalog filters -(tier/repo/backend/scenario) intentionally exclude checkout and store items. +`knowledge list` enumerates the installed package catalog by tier, repository, +backend and scenario. `collect`, `read` and `resource` can also open known IDs +in a selected checkout or store. ## Discovery and reading @@ -119,46 +144,44 @@ are distinct from `knowledge search`, whose package catalog filters backend, engine or kernel path is compatible. compatibility stays unverified. - **Example:** inferrsi doctor --repo . --repo-type vllm_omni --backend ascend --device-ids 0 --device-model 910B3 -### Search packaged records — `knowledge search` / `knowledge show` - -Use `find` for ordinary discovery. With no query, `knowledge search` lists -matching package records in ID order. With a query, it uses Find ranking over -the filtered package catalog and still returns complete catalog records. The -`context` export shares this selector. Text query results can change in both -membership and order. Use `--explain` for the recorded ranking and counts. - -- **Inputs:** optional query words and `--tier`, `--repo-type`, `--backend`, `--scenario`, `--limit`, `--json`, `--explain`; `show` takes one record ID. -- **Scope:** the installed package catalog (authored records and registered skill views in `skill_library/`) only. -- **Output:** tab-separated record lines (id, status, backend, title), or a JSON list with `--json`; `--explain` returns a JSON envelope with `items` and `retrieval` (entry, ranking, scores and counts). Python uses `search_knowledge(..., explain=True)` for that envelope. `show` prints one full record as JSON. -- **Side effects:** none. -- **Failure behavior:** no match prints nothing and exits 0 — an empty result is not an error (an empty JSON list with `--json`, or empty `items` in the `--explain` envelope); an unknown `show` ID and unsupported filter values exit 2. -- **Example:** `inferrsi knowledge search --repo-type vllm_omni --backend ascend --json` - -The tier/repo/backend/scenario filters are package-only: an empty filtered -result does not mean that no checkout or store knowledge exists. See the -[three-tier guide](../../src/inferrsi/knowledge/data/skill_library/records/README.md) for all sources. - -### Prepare model-aware research — `knowledge research` - -- **Inputs:** model identity; repeatable `--framework`, `--task`, `--modality`, `--mechanism`; existing `--tier`, `--repo-type`, `--backend`, `--scenario` hard filters and `--limit` output cap; optional `--target-backend`, `--target-device`, positive finite `--target-memory-gib` annotations. -- **Scope:** installed package records only. A packaged MiniMax-H3 profile supplies its source-grounded diffusion/video/audio identity and component roles. Unknown models use only caller-supplied dimensions and need source inspection; no architecture is guessed. -- **Output:** JSON query groups and match counts, a bounded deduplicated union with `matched_queries`, unchanged full records/provenance, active filters, component roles, preparation/example resource paths and an unverified target state. Queries take turns contributing results; this ordering does not rank engine quality. -- **Side effects:** none; no network requests, hardware probes, model download or engine execution. Target annotations do not add runtime backends. -- **Failure behavior:** no match returns an explicit empty envelope and exits 0; invalid limits/memory or unsupported catalog filters exit 2. A zero-match dimension stays visible. -- **Example:** `inferrsi knowledge research MiniMax-H3 --framework mlx --target-backend metal --target-device "M5 Mac Studio" --target-memory-gib 64 --limit 12` -- **Python:** `from inferrsi.knowledge.research import research_knowledge`; `research_knowledge("MiniMax-H3", frameworks=["mlx"], modalities=["video"], limit=12)`. - -Each research query uses Find over the same filtered package catalog. Querying -separate dimensions broadens discovery while preserving the active package filters. -Keep those filters explicit when transferring mechanisms from other backends; -target intent does not qualify their applicability. Read the canonical -[preparation procedure](../../src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md) -and the repository-owned [h3.c residency audit](../../src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md) -for native-engine reference selection, full encoder/DiT/VAE accounting, -quantized-package compatibility and target hardware decisions. Returned resource -paths are relative to `importlib.resources.files("inferrsi")` and ship in the wheel. -The small model profile links that skill's full inventory and worked example; -those resources retain their repository owner and source attribution. +### List and inspect package records + +`knowledge list` lists installed records in ID order. `--tier`, `--repo-type`, +`--backend` and `--scenario` restrict that inventory. Use `--limit` for the +number of rows, `--json` for the complete records, and `knowledge show ID` for +one record. `--explain` reports the applied filters, counts and inventory +selection state (`not_requested` for ranking). An empty list is a successful inventory result. An unknown ID or +invalid filter exits with status 2. + +```sh +inferrsi knowledge list --repo-type vllm_omni --backend ascend --json +``` + +For a ranked question over knowledge use `find`. The [catalog guide](../../src/inferrsi/knowledge/data/skill_library/records/README.md) +explains the three package tiers. + +### Research a model one question at a time + +For a MiniMax-H3 Apple Silicon feasibility study, put the intended device, +available memory, workload and quality gate in the experiment plan. Ask separate +questions about the component inventory and the engine behavior you need to verify. + +```bash +inferrsi find "MiniMax-H3 component inventory on Apple Silicon" +inferrsi find "MLX lazy evaluation and buffer lifetime" +``` + +Open each selected hit using its returned read command. The h3.c audit links +`references/minimax-h3-profile.json`. Read that resource at the same revision to +get the model aliases, sourced component roles, full weight inventory link and +worked example. For an unfamiliar model, establish those facts from its model +card and selected checkpoint before estimating feasibility. +[Model preparation procedure](../../src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md) · [h3.c residency audit](../../src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md) + +During a campaign, add `--session DIR` to each Find and follow its scoped read +commands. This keeps the questions, their hits and the selected reads separately +addressable. When the same revision answers two questions, cite that revision +once and identify both questions in the research notes. ### Discover/read packaged or custom skills — `skills list` / `enter` / `show` / `resource` / `reference` @@ -174,7 +197,7 @@ packaged bodies; the two matrices remain authoritative. ### Export legacy cited material — `context` -- **Inputs:** optional query; **required** `--repo-type` and `--backend`; optional `--tier`, `--scenario`, `--limit`, `--output`. +Select package records with `--repo-type` and `--backend` filters, or supply `--id` for each known package record. Use `--output` to write the cited Markdown to a file. - **Scope:** cited catalog material from the installed package. - **Output:** a Markdown reference bundle at the chosen path (the resolved path and record count are reported), or to stdout without `--output` (text only). - **Side effects:** writes only the caller-chosen output file. @@ -188,9 +211,9 @@ upstream instructions. ### Find — `find` / `inferrsi.knowledge.knowledge_find.find` -One ranked list for one question, across packaged skills, imported records and -checkout cases. Run a result's `open` command to read its complete entry and -receive a revision. Use that revision with the same ID and source selection +One ranked list for one question, across packaged skills, imported records, +checkout cases and an explicitly selected store. Run a result's `open` command +to read its primary body and receive a revision. Use that revision with the same ID and source selection for a pinned `read` or `resource` call. Cases are ranked alongside skills, so prior rejected directions can surface @@ -215,7 +238,11 @@ are omitted. Conditions such as `not`, `without`, `before` and `after` still contribute. Backend preference uses platform names in the original query, including `昇腾` for Ascend. When the query names exactly one supported backend, results declared for a different backend receive half their lexical score. -`--explain` reports the adjusted contribution of each matched term. +`--explain` reports the adjusted contribution of each matched term. Passing +`--backend` explicitly restricts local results to that backend and shared +material. Use `--repo-type`, `--tier` or `--scenario` to scope the package +catalog before ranking. A workload scenario also admits packaged procedures +tagged `skills.discovery`. Chinese query terms expand through `data/skill_library/config/query_aliases.json` before ranking. The packaged library is English by policy while its readers work in Chinese, and @@ -244,8 +271,8 @@ question calls for prior evidence. - **Inputs:** the query, `--limit`, `--kinds` (subset of `case,skill,record`), `--skill-root` to select the library for cases and skills, `--explain` for per-term contributions, `--json`. - **Scope:** installed package records and the packaged (or selected) skill library, including its cases. Packaged-skill projections are excluded from the record side so one owner is not ranked under two identities. -- **Output.** Items identify their `id`, `authority` (`package` or `checkout`), - `source_location` (`installed` or `checkout`), `kind`, recorded `state`, +- **Output.** Items identify their `id`, `authority` (`package`, `checkout` or `store`), + `source_location` (`installed`, `checkout` or `store`), `kind`, recorded `state`, `score`, `title` and corpus-relative `path`. `source_location` identifies where the material was indexed. For installed skill and case bodies, the `checkout:` read reference uses `--installed-library` to resolve the source @@ -274,16 +301,18 @@ question calls for prior evidence. `next_read_content_bytes` counts the UTF-8 bytes in that command's `content` on the snapshot inspected by Find. For a future unpinned read this field is a size estimate. A later edit can change the content and its size. - Use Collect's context budget for bounded delivery. The count excludes the - envelope and additional resources. Remove - `--omit-resources` to list the bundle's resources. Hits that fail the reader's - material check carry `unreadable` with the reason. + The count excludes the envelope and additional resources. Follow + `next_read_args` to finish a paged read. To list resource paths and digests, + run a standalone `inferrsi read --revision ` with the same + source flags. Leave out `--material`, `--resource` and `--omit-resources`. + Hits that fail the reader's material check carry `unreadable` with the reason. - **Without PyYAML.** PyYAML is a core dependency. When an install lacks it (for example, one made without dependencies), an installed Skill with a matching valid package record opens its original text through that record, using `read --resource` and its exact revision. The result names the selected resource in `content_resource`. A Skill in a custom root may require PyYAML. -- **Side effects:** none. Retain the revision returned by `read` for evidence and resource followups. +- Standalone Find and Read are read-only. With `--session DIR`, Find records the + ordered hits and following a hit's scoped Read records the bytes served. - **Example:** `inferrsi find "NPU OOM after caching per-step masks" --limit 3` returns the casebook entry recording that attempt first. A vaguer phrasing ranks the procedural skills above it, which is the first limit below rather than a defect. #### Show SearchSpace coordinates on Find hits @@ -314,7 +343,9 @@ for the explicit per-checkout grant and source access requirements. - **Inputs:** `--backend ` declares the task backend; **without it and without an approved grant, no channel is searched** and each one reports - `backend_unknown`. `--no-external` skips all channels for CI and offline runs. + `backend_unknown`. Use `--backend ascend` for eligible CANNBot results. + For MindIE navigation, use `--backend ascend --external-source mindie-agent`. + `--no-external` keeps queries inside the local corpus. `--external-limit ` overrides the per-channel cap (`cannbot-knowledge` 100, `mindie-agent` 5). `--external-timeout ` bounds discovery and search together (8s default); `--platform` overrides the upstream platform in the grant. @@ -330,14 +361,14 @@ for the explicit per-checkout grant and source access requirements. ### Collect — `collect` / `KnowledgeReader.collect` -Use Collect to take known material in caller-specified order. With -`--context-bytes `, it assembles complete files up to a UTF-8 body budget and -reports unavailable or oversized context. With no IDs and one question, Collect -uses the same local Find ranking as `campaign knowledge`, `benchmarks session -knowledge`, and `campaign capture-context`. See [selection and context](../knowledge-operations.md#ranked-discovery-and-budgeted-context) -for provenance and accounting. To capture an installed Case exactly, follow the -`find` result to `read`, then pass its ref and revision to +Use `collect --id REF --revision REF=REV` to assemble known material in +caller-specified order. `--context-bytes N` requests a complete context bundle +within a UTF-8 resource budget and reports omissions. A standalone `read` of +the primary body needs no such bundle. For an exact-ID manual capture, use `campaign capture-context --installed-library --id-ref REF --revision REF=REV`. +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). #### Collect a pinned body and its L1 decision card @@ -365,34 +396,48 @@ To reopen a projected card's source or body, use `read REF --revision REV --resource PATH` with the same source options and the returned `source_resource` or `body_resource`. -#### Migrate old text queries - -- `knowledge search QUERY` and `context QUERY` keep their package scope and - output format. Text queries now use Find and can match entries that contain - only part of the query. Omit `QUERY` for filtered inventory or use - `knowledge show ID` for one known record. -- Pass one question as `collect QUERY` or `collect --relevance QUERY`. If an - old script combines a positional query and a separate cue, write one question - and express hard constraints with structured flags such as `--kind` and - `--backend`. Use `--kind knowledge` to search only the package catalog. -- Remove old `--relevance-method` values from scripts and managed calls. Find - is the default and `find-lexical-v1` is the only accepted explicit value. - Check the new rank order before using it to select material in automation. -- For exact collection and replay, use the retained IDs and revisions without - a positional query. With explicit IDs, `--relevance` can order optional - context resources while membership and caller order remain fixed. Read - historical captures for their original selected and delivered bytes. - -- **Inputs:** optional query, `--kind`, repeatable explicit `--id`, repeatable `--revision ID=REV`, `--limit`, `--max-bytes`, `--material`; `--skill-root` selects an explicit skills root, `--store` opens an existing store read-only (the store records its reserved skills root and rejects a mismatched or missing `--skill-root`). -- **Scope:** installed package records, the selected library, and any explicitly opened store. A text query without a custom library or store can discover bundled Cases and Skills. Exact inventory selects the bundled library with `--installed-library`. +- **Inputs:** `--kind`, repeatable `--id` and `--revision ID=REV`, `--limit`, `--max-bytes`, `--material`. With explicit IDs, `--relevance` can guide selection of optional files inside their bundles. Select a library with `--skill-root` or `--installed-library`. An existing store opened read-only with `--store` requires its recorded skills root. +- **Scope:** installed package records, the selected library and any explicitly opened store. - **Output:** with `--json`, the complete **normalized** envelope — items carrying the bundle's normalized metadata, resources and dependencies, plus `no_match`, `omissions`, `collisions`, `material_bytes` and the recorded limitations; fields that exist only in a package record's original entrypoint document are not projected into the normalized metadata and are read via `--material` or `resource`. Without `--json`, the envelope's selection is projected line-wise: one tab-separated line per item (`ref`, `revision`, `kind`, `state`, recorded `applicability`; free-text fields are control-character-escaped so one item stays one line), `collision` lines for multi-authority IDs, `omitted` lines with reason codes, an explicit `no_match` line when nothing was selected (query, filters or limits; when items were skipped the `omitted` lines above it carry the per-item causes), and — with `--material` — the entrypoint content in delimited blocks. The text mode does not print `material_bytes` or the envelope limitations; use `--json` for the complete envelope. The recorded `state` and applicability are printed as recorded and no validation status is invented. Exit 0 covers a result envelope, including no-match and omissions. - **Side effects:** none; both adapters and the read-only store connection are read-only. -- **Failure behavior:** discovery-wide invalid identities fail the call. Per-item omissions are reported individually. Repository, tier and scenario filters use the package catalog. A backend filter scopes ranked discovery to the requested backend and shared material. +- **Failure behavior:** discovery-wide invalid identities fail the call. Per-item omissions are reported individually. Repository, tier and scenario filters use the package catalog. A backend filter admits package records for the requested backend and shared material. - **Example:** `inferrsi collect --id package:inferrsi.ascend.skills.ascend_graph_mode --id package:inferrsi.ascend.skills.ascend_device_health --context-bytes 65536 --json` +### Migrate old knowledge queries + +`find` is the only CLI command that takes a knowledge question. This is a +breaking change for scripts that run the previous query commands. They now +exit with status 2 and a migration hint. Update scripts when upgrading the +CLI. Update installed plugin bundles to get the matching instructions and runtime. + +| Previous command | Replacement | +| --- | --- | +| `knowledge search QUERY` | `find QUERY` with the same catalog filters. To list records without a question, use `knowledge list`. | +| `knowledge research MODEL`, `find --model MODEL` | Ask each research question with `find QUERY` and follow its read command. Model profiles and inventories are resources of their owning procedure. | +| `context QUERY` | `find QUERY`, then `context --id ID` for each selected package record to export cited Markdown. A filtered export still accepts `context --repo-type REPO --backend BACKEND`. | +| `collect QUERY` or `collect --relevance QUERY` | `find QUERY`, then the selected hit's read command. To assemble a group, use `collect --id REF` with a flag for each selected identity and its revision. | +| `campaign knowledge` or `benchmarks session knowledge` | `find QUERY --session DIR`, then the returned scoped read. AB/BA projects and benchmarks accept its delivery receipt with `round --knowledge-ref`. | +| `campaign capture-context` with a question | `find QUERY --session DIR`, then the scoped read. Use `campaign capture-context --id-ref REF` to retain a known bundle. | +| `cannbot search QUERY` | `find QUERY --backend ascend` with the project grant. Set the upstream cap with `--external-limit N` and use the returned locator for a card read. | +| `mindie query --input FILE` | `find --input FILE` with the same native request and project grant. | + +Python callers use `find(question, load_corpus(...))` from +`inferrsi.knowledge.knowledge_find`. For a filtered inventory use +`catalog.list_knowledge(...)`. The existing query-free `search_knowledge` +spelling and explicit-ID `KnowledgeReader.collect` remain available. Catalog +filters select packaged records. A custom Skill root or store combined with a +package-only filter produces an explicit error. + +To import a historical round, give `campaign import-search` its original +tool returns and retained captures. This preserves what that round actually +received, even when the current search returns different results. + ### Read exact material/resources — `read` / `resource` / `KnowledgeReader.read` / `.resource` -- **Inputs:** `read` takes a qualified or unambiguous public ID and an optional `--revision` (the current revision when omitted). Use `--material` for the entrypoint or `--resource ` for a specific UTF-8 bundle resource. The `resource` command takes the ID, resource key, exact `--revision` and `--output` path. +- Use `read` with a qualified or unambiguous public ID and an optional `--revision`. + Use `--material` for the entrypoint or `--resource` with an exact key or a Markdown link + relative to the primary body. + The `resource` command takes the ID, full key, exact revision and output path. - **Scope:** one selected bundle from the package, checkout or store adapter. - **Output:** `read` returns the bundle view at the requested revision. With `--resource`, it identifies the returned text with `content_resource`. The `resource` command writes raw bytes to the requested output path. Use the same source flag when following up with either command. - **Side effects:** `resource` writes only the caller-chosen output file. diff --git a/docs/guides/optimization-workflow-unification.md b/docs/guides/optimization-workflow-unification.md index 09d2465f9..81dc8689f 100644 --- a/docs/guides/optimization-workflow-unification.md +++ b/docs/guides/optimization-workflow-unification.md @@ -62,16 +62,15 @@ sequenceDiagram A->>A: 分析反馈,按需 profiling,明确本轮问题 A->>C: campaign diagnose:记录瓶颈及其测量依据 opt 需要资料且知识开关允许 - A->>C: campaign knowledge:提交查询、检索方式和上下文预算 - C->>H: session_command:传入查询、KnowledgeReader 和记录回调 - H->>H: 检查运行状态、预算和知识开关 - H->>O: 调用注入的 capture_context,传入 reader 和查询 - O->>K: reader.collect 检索 - K-->>O: 返回资料正文、版本、来源和遗漏信息 - O-->>H: 经 harness/records 保存 knowledge/context-….json,返回路径与哈希 - H->>H: 更新 state.contexts 引用 - H-->>C: 返回留存引用与正文 - C-->>A: 返回可阅读的资料,供本轮分析使用 + A->>C: find QUERY --session DIR + C->>H: 检查本轮状态、诊断和知识开关 + H->>O: 在允许的资料范围内查询 + O->>K: Find 排序 + K-->>O: 返回命中与读取参数 + O-->>A: 留存命中,返回本轮 read 命令 + A->>C: 按命中返回的参数执行 read + C->>H: 核对查询、版本和本轮读取权限 + H-->>A: 返回所选正文,留存读取凭据 end A->>A: 提出假设,修改声明范围内代码,形成候选 A->>C: campaign round:提交候选路径、假设和可用用量 @@ -144,8 +143,8 @@ Harness 没有常驻 Agent 驱动。Agent 逐次调用这些操作,代码在 | 场景 | 入口 | 候选与停止规则 | | --- | --- | --- | -| 普通项目优化 | `campaign start/diagnose/knowledge/round/status/final/recover` | 声明多个文件或目录;默认 `up_to` 轮次上限,final 必须说明结束原因;也支持 `exact` | -| 题库优化 | `benchmarks session start/diagnose/knowledge/round/status/final/recover` | 题包定义候选和评测;当前 Qwen 是单个 Python 文件、固定轮数 | +| 普通项目优化 | `campaign start/diagnose/round/status/final/recover`,`find QUERY --session DIR` | 声明多个文件或目录;默认 `up_to` 轮次上限,final 必须说明结束原因;也支持 `exact` | +| 题库优化 | `benchmarks session start/diagnose/round/status/final/recover`,`find QUERY --session DIR` | 题包定义候选和评测;当前 Qwen 是单个 Python 文件、固定轮数 | | 题库默认新会话 | `agents prepare/dispatch/bind/record` + 宿主工具 | 先派发任务;新会话创建 campaign 并执行到 final,父会话回收结果 | | 一次测量 | 原有 `run` 或 `benchmarks run` | 保留独立使用方式;不会自动生成多轮候选 | | 旧式手动 campaign | 原有 `campaign init/record/decide` | 兼容已有记录;不允许写进新控制器管理的 campaign 形成第二套状态 | @@ -202,14 +201,15 @@ assessment 另附 `paired_statistics`:同一次重复内的第 k 个基线与 ```bash inferrsi campaign diagnose --directory --bottleneck '' --evidence -inferrsi campaign knowledge --directory --query '' --context-bytes +inferrsi find '' --session +# 运行所选命中返回的 read 命令,取得正文和读取凭据。 inferrsi campaign round --directory --candidate --hypothesis '' inferrsi campaign status --directory inferrsi campaign final --directory --reason '' inferrsi dashboard --input --output ``` -两个受管 `knowledge` 入口都用 Find 为当前问题排序,再按预算装配选中的正文和需要的资料,留存引用、版本和省略原因。显式传入旧 `--relevance-method` 可以复用对应的排序。知识检索和 profiling 按当前问题需要进行。冻结条件为 `--knowledge off` 时,受管 `knowledge` 操作拒绝执行。 +普通项目和题库都用 `find` 查询。本轮先记录返回的命中,执行命中的 `read` 后记录实际返回的正文、版本和凭据;引用凭据的候选另行说明采用了什么。需要附件时再按资源路径读取。冻结为 `--knowledge off` 的对照组禁止轮内检索和读取。 Harness 将证据优先的顺序默认写入新会话计划,适用于知识开启和关闭。Agent 先用同条件的 profile 或测量确定瓶颈,提交包含 workload 和观测值的 UTF-8 摘要,再按需检索和 diff --git a/docs/guides/plugins/codex-plugin.md b/docs/guides/plugins/codex-plugin.md index 8ecc2e943..33f48b8ef 100644 --- a/docs/guides/plugins/codex-plugin.md +++ b/docs/guides/plugins/codex-plugin.md @@ -185,7 +185,10 @@ reports `match_status="matched"`. It uses up to 8,000 native tokens and returns to five references by default. `--external-limit` can raise the cap to 20, and `--external-timeout` covers both the availability check and the query. The MindIE section contains navigation metadata only. The plain Find command -selects CANNBot when eligible. Use `--no-external` for local results alone. +selects CANNBot when eligible. An explicit source selects its Ascend backend. +Use `--no-external` for local results alone. +Round search import recognizes the local hits and the versioned MindIE +references shown in either text or JSON output. ### MCP configuration and queries @@ -202,12 +205,13 @@ enabled_tools = ["knowledge_query", "knowledge_explain"] For the plugin ZIP, set `command` to the Python executable and prepend the absolute bundled launcher path to `args`. -Call `knowledge_query` with a `query` and observed `conditions`. Pass relevant -versioned `ref` values as `refs` to `knowledge_explain` and read the returned -`units` and `requires`. The same reads are available through the CLI. +For the native MindIE request, use Find with a JSON file that supplies the +`query` and observed `conditions`. Pass relevant versioned `ref` values +as `refs` to explain and read the returned `units` and `requires`. +MCP clients can send the same arguments using the two configured tools. ```sh -inferrsi mindie query --input query.json +inferrsi find --input query.json inferrsi mindie explain --input explain.json ``` @@ -218,6 +222,18 @@ The reader automatically stores receipts under receipts outside the source checkout; the caller does not select their location. Recorded read failures report their receipt path in the error message. +When importing a Codex rollout with `campaign import-search`, select the lines +containing the native Find and its tool return. The importer reads that return +offline. It counts each versioned unit displayed on the returned page once across +`cards`, `foundation_cards`, `unverified_cards` and `results`. A graded +navigation response can populate these cards while leaving `results` empty. +The event retains each unit's navigation lists, reported condition status and +readiness. It uses `mindie-agent:/units/@` as the archive +material key for the native `mindie:///units/@` reference. +An empty returned page has zero visible hits. A failed call or incomplete tool +return leaves coverage partial. New native Find returns include the sanitized +query. Earlier returns can identify units even when the query text is unknown. + ### Associate reads with a candidate Use the `receipt_directory` from each call. Import the `input.json` and @@ -313,9 +329,9 @@ registers no MCP server, hooks, daemon or scheduled task. | --- | --- | | Python cannot be found or is too old | Select/install Python 3.10+ and use its executable consistently | | Incomplete bundle or version mismatch | Rebuild/reinstall the distribution; do not substitute an unrelated installed runtime | -| PyYAML is missing | Load a primary procedure with `skills enter ` or use packaged Collect/Read. Install PyYAML in the chosen interpreter for checkout/frontmatter operations. | +| PyYAML is missing | Use `skills enter ` for a primary procedure. For lookup, run `find` and follow the returned read command for the packaged Skill. Install PyYAML to open a custom checkout Skill. | | No knowledge match | Inspect the query/source selection; no match does not establish lack of an optimization | -| Target backend unavailable | Fix the target environment; knowledge research remains usable | +| Target backend unavailable | Local knowledge lookup with `find` is available while you repair the target environment. | | Interrupted experiment | Inspect its existing status/evidence before deciding on a new run | Execution remains local to the prepared target machine. The plugin does not diff --git a/docs/guides/plugins/dsh-plugin.md b/docs/guides/plugins/dsh-plugin.md index d2f81741d..36c2610e3 100644 --- a/docs/guides/plugins/dsh-plugin.md +++ b/docs/guides/plugins/dsh-plugin.md @@ -289,8 +289,9 @@ every three seconds and keeps the current selections where possible. The header shows the last successful check and refresh failures. Recorded verdicts, missing evidence, and partial results remain visible in the dashboard. -Populate the campaign as the work happens. Use `campaign capture-context` for -the knowledge retrievals being prepared, `campaign record` to associate runs +Populate the campaign as the work happens. In a manual campaign, use +`find "" --session ` and open the returned +read command for a relevant hit. Use `campaign record` to associate runs with candidates and rounds, and `campaign log` for the reviewed goal, search space, round hypotheses, decisions, and success/failure summaries. Follow the [campaign integration guide](https://github.com/InferMatrixLab/InferRSI/blob/main/docs/dashboard.md#campaign-integration) for the exact diff --git a/docs/guides/service-reuse-campaigns.md b/docs/guides/service-reuse-campaigns.md index 0848b32ff..0fc849378 100644 --- a/docs/guides/service-reuse-campaigns.md +++ b/docs/guides/service-reuse-campaigns.md @@ -120,7 +120,8 @@ quality-command and sampling flags. Mixing both parameter sets is an error. inferrsi campaign start --evaluation-mode service_reuse --evaluation-config ... inferrsi campaign baseline --session inferrsi campaign diagnose --session --bottleneck --evidence -inferrsi campaign knowledge --session --query --context-bytes +inferrsi find "" --session +# Run the scoped read command returned for the selected hit. inferrsi campaign round --session --candidate --hypothesis inferrsi campaign profile --session --round inferrsi campaign status --session @@ -283,8 +284,14 @@ tamper detection. Old AB/BA and other APIs retain their default checks. selection, repair history, reference epoch, reminders and final prerequisites. There is no summed multi-objective speedup. Service-mode knowledge capture retains source text and existing commit attribution without the old content-identity -reader. It uses Find ranking over the package catalog and records core documents -and unloaded references. Checkout and store sources require content identity +reader. Find ranks the package catalog and retains the selected source files +before publishing its receipt. Read and its page continuations use that source +snapshot, so later package changes cannot replace the searched material. +Only requested pages are delivered; retained attachments are not automatically +sent to the Agent. Existing source commits remain attribution, without new +fingerprint fields. A historical search without retained source files must be +repeated to supply new reads; its saved deliveries remain readable. +Checkout and store sources require content identity and are unavailable in this mode. Captured material proves preparation, not model consumption. diff --git a/docs/knowledge-base.md b/docs/knowledge-base.md index 08b0f081f..3e9968837 100644 --- a/docs/knowledge-base.md +++ b/docs/knowledge-base.md @@ -87,7 +87,7 @@ src/inferrsi/knowledge/data/skill_library/ src/inferrsi/knowledge/catalog.py Installed knowledge reader src/inferrsi/knowledge/skill_catalog.py Packaged or custom-root skill reader src/inferrsi/knowledge/data/skill_library/records/.json Authored engineering findings -src/inferrsi/knowledge/data/skill_library/config/ Aliases and research profiles +src/inferrsi/knowledge/data/skill_library/config/ Query aliases src/inferrsi/knowledge/data/skill_library/_compiled/ Generated YAML headers and Git provenance src/inferrsi/harness/data/repo_packs//pack.json Target descriptor, read by repository_pack evidence// Frozen plans, results, patches and validators @@ -327,7 +327,7 @@ retained Apple feasibility/header-inventory research. Its source-derived candidate state and imported header observations remain separate from native execution, media quality, target memory and performance qualification. -Use `inferrsi knowledge search --repo-type inferrsi --limit 100` to list installed +Use `inferrsi knowledge list --repo-type inferrsi --limit 100` to list installed package records in stable ID order. A text query uses Find to rank eligible package records and returns the original catalog JSON. `knowledge show` reads that JSON by exact ID. Catalog JSON and full package bundle reads need no YAML diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index 0816b78eb..f3e53595e 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -166,65 +166,74 @@ or duplicate Case ID. ## Ranked discovery and budgeted context -Collect with one text input uses the local Find ranker. -Pass a positional query or use `relevance` (`--relevance` on the CLI). -Existing callers can explicitly pass `relevance_method="find-lexical-v1"`. -For a retired method, omit the method argument and supply one question. If you -used a positional filter and a relevance cue together, combine them into one -question and pass scope constraints through the structured filters. [Operation guide](operations.md) +Use `find QUERY` to rank Cases, Skills and Records. Its result contains hits and +commands to open them. Following a hit's `read_args` returns the primary body. +A linked procedure, example or data file can be read separately by its exact +resource path and revision. An ordinary search or body read does not request +the owner's attachment bundle. -```python -reader = KnowledgeReader() -matches = reader.collect("cgroupv2 cpu.stat.local", material=True, limit=3) -selected = reader.collect( - ids=["package:inferrsi.ascend.skills.ascend_graph_mode", - "package:inferrsi.ascend.skills.ascend_device_health"], - context_bytes=65536, -) +For an optimization question, use the same search within the campaign: + +```sh +inferrsi find "fixed seed diffusion baseline" --session ``` -```bash +Run the emitted scoped `read` for the relevant hit. The session records the +ordered hits, then the read it actually served. Each operation returns its +campaign-relative receipt in `reference.path`. To follow a link in the primary body, +append the path as printed, for example `--resource references/benchmark-commands.md`, +to the hit's read arguments. Keep the original `--session` and `--search-ref`. +Read resolves the link inside the pinned bundle and the receipt names the full +resource key in `content_resource`. A file link with a section fragment opens the entire file. + +Each read records the actual UTF-8 bytes it returned at the hit's revision. +Large resources return a page with `content_range` and executable +`next_read_args`. Run those arguments to continue the same resource, revision +and search reference. Pages limit their JSON content string to 6 KiB so the +normal Agent tool response can carry the content and its receipt together. +This is a per-response size limit; it does not limit how much of the file you +can read. `next_byte_range` also exposes the continuation coordinates for +callers using `--byte-range START LENGTH`. Each receipt identifies only the +byte range it delivered; one page does not prove receipt of the whole file. +Content responses omit the full resource inventory. To inspect that inventory, +run `read ID --revision REVISION` without `--material` or `--resource`. + +A benchmark plan can require a particular card under a fixed query, scenario +and byte allowance. Run its supplied Find request and open the card before +submitting round one. Reads return their content even when the allowance is +zero. The report counts the real bytes returned for that request, including +repeated reads and attachments. An over-budget delivery, a late read or a +retry with a larger allowance excludes the pair from card-effect conclusions. +A service-reuse Find retains the hit's actual body and available supporting +files before returning the search receipt. Reads and continuations use this +retained source, including after the installed package changes. The source +commit remains provenance. Each read retains its own content, resource path +and search reference under that campaign’s fingerprint-free protocol. Historical +receipts remain readable; a search made before source retention must be repeated +before it can supply new reads. + +Use `collect` to assemble a batch when the identities are already known. Without +IDs it enumerates available items in qualified identity order. Explicit IDs +retain caller order, subject to filters, revision availability and `--limit`. +`--relevance` with explicit IDs can prioritize optional files within those +bundles. A store attached to this reader supplies its retained revisions. See +the [store read and revision rules](knowledge-store.md). + +```sh inferrsi collect --id package:inferrsi.ascend.skills.ascend_graph_mode \ --id package:inferrsi.ascend.skills.ascend_device_health \ --context-bytes 65536 --json ``` -An empty query and no `relevance` give inventory in qualified identity order. -Explicit `ids` retain caller order and are subject to filters, revision -availability and output limits. `limit` caps the number of returned items. -For explicit IDs, omit the positional query -and optionally pass `relevance` to guide selection of optional context files. -`selection.ranking_applied` records whether the items themselves were ranked. - -Text discovery scores local Cases, Skills and Records within the requested kind -and filters. Installed Skills selected with `--kind skill` can be delivered -through package records with bundle kind `knowledge`. Their original `SKILL.md` -is available through assembled context or `read --resource`. This works on a -base install. In a mixed search using a custom `--skill-root`, that library -provides its registered Skills. Installed projections supply missing names. -Each version remains available by its qualified reference. - -Case applicability text stays searchable. For backend-scoped discovery, a Case's -top-level `backend` names a supported backend or `common`. Discovery without a -backend also includes Cases without that declaration. Scoped selection counts -those Cases under `ranking_scope`. With a scenario, ranked discovery includes -package Records matching that workload and packaged Skills tagged -`skills.discovery`. Captured hits keep the scenario declared by their owner. -Inventory and explicit IDs filter on that declared scenario. - -Set `campaign init --backend ` to retain the runtime backend for -ranked campaign capture. A backend supplied on a capture takes precedence. -Existing campaigns can also supply `--backend` directly on each capture. - -`KnowledgeStore.collect` delegates to the same selector. With a store attached, -discovery includes its candidate bundles under qualified `store:` -references. See the [store read and revision rules](knowledge-store.md). - -`context_bytes` requests a separate context view with a positive byte budget. -Ranked discovery can capture a complete engine `record.json` or Case entrypoint -and its required resources. The assembled context for indexed Skills follows -the resource rules below. `material=True` on a package Skill record returns its -`record.json` entrypoint. +A Harness candidate generator can request a reproducible input file for a +question. It selects pins with Find, packs the primary bodies in rank order up +to the input limit, then uses any remaining bytes for supporting resources. +Its manifest identifies the bytes delivered and the omissions. Manual +`campaign capture-context --id-ref REF` saves an exact bundle snapshot. + +This explicit bundle operation has its own byte cap. The published context +for an indexed Skill includes its declared references, notices and licenses. +Its `record.json` package entrypoint remains available with `--material`. | Additional result | Meaning | | --- | --- | @@ -269,8 +278,7 @@ provenance/accounting. CLI text mode prints complete context bodies in delimited blocks plus resource/owner omission codes. Collect validates a generated Skill projection against the packaged registry, -owner mapping and resource hashes before returning a ranked hit or building an -exact context view. Missing or stale bindings produce `index_unavailable` in +owner mapping and resource hashes when building an exact context view. Missing or stale bindings produce `index_unavailable` in the corresponding item or context omissions. Refresh projections with the existing `tools/build_skill_index.py` after committing their inputs. @@ -296,9 +304,15 @@ the delivered SHA-256, source SHA-256 and half-open byte ranges in the source. The explicit resource read at the same revision returns the original bytes, including the annotation. Older sidecar-backed procedures retain their original entrypoint content. Use `read --resource ` to display a specific -UTF-8 resource in `content` and its key in `content_resource`. Remove -`--omit-resources` to list resource paths and digests. These views use the same -full-bundle revision. +UTF-8 resource in `content` and its key in `content_resource`. Read accepts an +exact key or a path relative to the primary body. Exact keys take precedence. +Use `./` to select a body-relative path if the two names overlap. +A Markdown link with an anchor, such as `note.md#setup`, opens the file +relative to the body when that file is in the bundle. Follow +`next_read_args` to finish a paged read. To list resource paths and digests, +run a standalone `inferrsi read --revision ` with the same +source flags. Leave out `--material`, `--resource` and `--omit-resources`. +These views use the same full-bundle revision. - Local skills include their complete owner folder (except incidental `__pycache__`, `*.pyc` and `.DS_Store`) and declared cross-skill references, diff --git a/docs/knowledge-store.md b/docs/knowledge-store.md index 3133c84a9..fa08300b9 100644 --- a/docs/knowledge-store.md +++ b/docs/knowledge-store.md @@ -36,11 +36,11 @@ or `None` to declare package-only use. `store.reader()` / `store.collect` combin package, checkout and store items with qualified `store:` refs. An ID owned by the store and a read-only adapter is reported as ambiguous, never shadowed. -Pass a query or `relevance` to `store.collect` for local Find discovery. -Discovery follows the store's reserved sources. With `skill_root=None` it -searches package Records, projected Skills and store-owned candidates. +Run `find QUERY --store DIR` to include an existing store. Supply the same +`--skill-root` that was reserved when the store was created. With a package-only +store, Find searches package Records, projected Skills and store-owned candidates. Store-owned candidates participate using their metadata and entrypoint text. -An unpinned query ranks the current revision. A query with a revision pin ranks +An unpinned query ranks the current revision. With `--revision store:ID=REV`, Find ranks the retained entrypoint at that revision and returns that same revision if it matches. Use explicit IDs and revisions for exact collection of historical bundles and `resource` for their contents. diff --git a/docs/quickstart.md b/docs/quickstart.md index 0586a2b5d..9fdfb66b8 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -27,11 +27,11 @@ benchmark/quality command contract; set the acceptance threshold from your plan. ## MLX discovery and source knowledge On the target checkout, use its existing repo type to probe Apple Silicon and -search the package catalog for MLX references. +list the installed MLX dependency records. ```bash inferrsi doctor --repo . --repo-type vllm_omni --backend mlx -inferrsi knowledge search --tier dependency --repo-type mlx --backend mlx --json +inferrsi knowledge list --tier dependency --repo-type mlx --backend mlx --json ``` The probe reads chip and package metadata. See the @@ -64,7 +64,7 @@ records with exact filters and `context` to export a cited package selection. See the [operation guide](guides/operations.md) for command boundaries. ```bash -inferrsi knowledge search --repo-type vllm_omni --backend ascend --json +inferrsi knowledge list --repo-type vllm_omni --backend ascend --json inferrsi context --repo-type vllm_omni --backend cuda --output context.md inferrsi skills list --json ``` @@ -98,10 +98,16 @@ library or `--skill-root` for a custom library. Reuse the source flag when following a result. An existing store opened read-only with `--store` requires its recorded skills root if one was configured. -During a managed optimization, `campaign knowledge` and -`benchmarks session knowledge` use Find when the frozen plan permits knowledge. -They assemble the selected Case, Skill or Record material within the requested -budget and retain its revisions with the campaign. +During a managed project or benchmark, use `find "" --session ` +after diagnosis when the frozen plan permits knowledge. The command records +the hits. Run a selected hit's scoped `read` command to receive the body and +record that delivery. It returns the selected material without automatically +adding linked files. To open an attachment, add `--resource PATH` to the +same read arguments. A byte cap supplied on an ordinary session search applies +to these attachments. +At candidate submission, cite the receipt for material that informed the decision. +A benchmark that specifies a required card supplies the frozen Find request; +read that card at the supplied byte limit before the first round. ## Establish acceptance criteria diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index d5eefeacc..3435da8d9 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -6,7 +6,7 @@ "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "f4399276c8389f33ad81a2a25ccd0ff4392a37635ae9c53943ece4995c84d246" + "metadata_sha256": "a53785505447da4280bbd8b59d75ea606d1b1c98cc70362e1e0e40ba450eac64" }, "skills": { "ascend-aclgraph-capture-replay": {"path": "systems/platforms/ascend/ascend-aclgraph-capture-replay/SKILL.md", "state": "covered", "coordinates": [["Accelerator", "Configure"], ["Accelerator", "Diagnose"], ["Accelerator", "Optimize"], ["Accelerator", "Verify"]]}, diff --git a/plugins/inferrsi-dsh/form.cjs b/plugins/inferrsi-dsh/form.cjs index a8e3c85a9..fc5e579cb 100644 --- a/plugins/inferrsi-dsh/form.cjs +++ b/plugins/inferrsi-dsh/form.cjs @@ -160,7 +160,7 @@ function buildPrompt(form, connection) { '2. 优先使用用户提供的验收标准,包括 constraints 和 acceptance 引用中的已有条件,不得用估计值替换或降低门槛。未提供验收标准时,使用仓库的 performance-ceiling-analysis 技能及其 acceptance-criteria.md 流程制定标准;部分提供时保留已有要求,只推导缺失项并标明来源。记录基线、校准依据、不确定性和已有冻结授权;理论上限不能直接当作可达目标或质量容差。条件冲突时先澄清,证据不足时列出缺口和补测计划。冻结 baseline、工作负载、验证器和数值门槛后再开始候选实验。', '3. 在用户选择的 plane 范围内逐轮提出假设、修改、比较和决策。使用 maxRounds 限制优化迭代轮数,使用 maxMinutes 限制总时间。每轮中的 A/B 重复测量次数由冻结计划确定。到达预算后停止新实验并汇报当前证据。', '4. 使用现有 InferRSI CLI 和目标仓库的基准、质量脚本。远程 run_script 必须传入 maxMinutes,远程长时间 cli 操作也传入该参数,按任务剩余总时间预算设置,不能为每次调用重新分配完整预算。保留现有用户改动,遵守已有资源和执行授权。复用已准备好的目标环境。', - '5. 使用明确的 campaign 记录目标、知识检索上下文、搜索空间、每轮假设、决策和 run_id 关联,保留失败、跳过和回滚记录。使用 campaign capture-context、campaign record 和 campaign log。', + '5. 使用明确的 campaign 记录目标、知识检索上下文、搜索空间、每轮假设、决策和 run_id 关联,保留失败、跳过和回滚记录。用 find "<问题>" --session <目录> 检索,按命中返回的 read 命令读取正文。手动 campaign 查询返回回执路径,随后用 campaign record 和 campaign log 记录候选及采用依据。', '6. execution=remote 时通过 inferrsi_remote 的 dashboard 操作打开该 campaign 的实时页面,保留连接标识;本机模式通过随包启动器运行 dashboard --live --port 0 并保留服务进程标识。返回实际 URL,实时监控和历史轮次由现有 dashboard 展示。', '7. 结论依据冻结验证器与运行证据,保留 PASS、FAIL、INCONCLUSIVE。服务性能结论需要相应 L4 或 campaign 定义的端到端证据。', '8. 汇报完成的轮数、候选决策、证据目录、dashboard 链接、剩余缺口和下一步。', diff --git a/plugins/inferrsi/skills/inferrsi/SKILL.md b/plugins/inferrsi/skills/inferrsi/SKILL.md index d039ebeff..382bf81cb 100644 --- a/plugins/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/inferrsi/skills/inferrsi/SKILL.md @@ -91,14 +91,25 @@ This command uses the same Harness controller as the packaged task path below. Edit the returned working candidate. Submit each hypothesis and candidate with `campaign round`, read the feedback, and keep failed attempts. Retrieve needed -knowledge through `campaign knowledge` when the frozen condition allows it. +knowledge with `find "" --session ` when the frozen condition +allows it. Follow a hit's scoped `read` command to receive its body and a +round receipt. Use a pinned `read --resource` for a particular attachment. +If a read returns `next_read_args`, run those arguments to continue the same +resource, revision and search. Read all needed pages before treating a file as +fully received; each receipt records only its returned bytes. When a passage you read changes the candidate or check you choose, explain that choice in the existing `--hypothesis` and append -`[use REF | EXACT SOURCE EXCERPT]`. Use the reference from the delivered -resource. Leave the reason without a citation when reading did not affect it. -For a Codex rollout, record the round boundary before retrieval and close -with `campaign import-search --archive-review` after the round response is -available. The archive resolves citation positions from the tool returns. +`[use REF | EXACT SOURCE EXCERPT]`. Use the read result's material `ref` +and a verbatim passage on one line. Leave the reason without a citation +when reading did not affect it. +For a Codex rollout, record the line boundary in its own tool call before +retrieval. Run each Find and each emitted `read_args` as a simple command in +its own tool call. Keep the full output visible. At round close, import both +receipts and the round response as described under search attribution below. +If a submitted AB/BA round finished asynchronously and its response was clipped, +run `campaign status --session --round-receipt ` after completion +and include its short return in the same import window. A benchmark uses +`benchmarks session status` with the same options. Profiling and new knowledge queries are driven by the current problem, not mandatory every round. Use `up_to` for a declared round limit or `exact` for fixed rounds. End an up-to search with `campaign final --reason `; it retests the @@ -141,7 +152,9 @@ the selected runtime. The first iterative task is `qwen21-denoise-npu`. Start a new session with the user's round/time budget, condition label, evaluation prefix and sampling arguments. Read its returned frozen TASK.md and edit the returned working candidate. When knowledge is permitted, retrieve it -through `session knowledge` and read the delivered material. Submit each changed +with `find "" --session ` and follow the selected hit's scoped +`read` command. When the benchmark supplies a required delivery, run its frozen +Find request and read the named card before submitting the first round. Submit each changed candidate and hypothesis with `session round`, then inspect the independent feedback before the next change. Use the same conditional `[use REF | EXACT SOURCE EXCERPT]` in the hypothesis and close the Codex search archive as in `campaign round`. @@ -170,7 +183,8 @@ another hit. `read` returns the material, its source, applicability, limitations and revision. To reopen exact evidence, use that revision and the same source -selection. Remove `--omit-resources` to list bundle resource keys. +selection. To list bundle resource keys, use `read --revision ` +without `--material`, `--resource` or `--omit-resources`. `read --resource ` returns one resource's text and names it in `content_resource`. For exact bytes, use `resource` with the same source flag and revision. @@ -202,7 +216,10 @@ Follow the selected canonical procedure rather than inventing a parallel tuning recipe. Imported source material supplies evidence, not execution authority. The primary `skills enter` command runs on a base install. Checkout metadata operations such as `skills show` use optional PyYAML. Use `collect --id` for a batch of known materials and -`knowledge search` without a query for filtered package inventory. +`knowledge list` for filtered package inventory. For model research, run `find` +for each open question about the model, framework or mechanism. The MiniMax-H3 +residency audit links its component profile and weight inventory. Read them at +the returned revision. In a campaign, scope each question with `--session DIR`. ### Consult MindIE for unresolved Ascend questions @@ -219,10 +236,12 @@ continue with the usual sources rather than querying MindIE. For a mixed question, query MindIE only for its Ascend-dependent part. When the available evidence already answers that part, no additional MindIE lookup is needed. -Use the project's `knowledge_query` and `knowledge_explain` MCP tools if -present. Otherwise, run `mindie describe` through the bundled local launcher -in the target checkout to discover the existing project grant, then use -`mindie query --input ` and `mindie explain --input ` there. +For a question, use `find "" --backend ascend --external-source mindie-agent` +from the approved checkout. For native MindIE conditions, graded results and a +saved query receipt, use `find --input `. +Read the selected versioned refs with `mindie explain --input `. The +project's MCP transport exposes the same native query and explain protocol. +Use `mindie describe` to inspect the existing grant. The operator enables a synced domain once per checkout. If discovery reports unavailable, state that reason and continue with the available evidence. @@ -271,22 +290,28 @@ available. If the context or reasoning was not captured, state that it is missing instead of inferring it from a verdict. The optional campaign trace format and association workflow are documented in `docs/dashboard.md`. -For a managed optimization use `campaign knowledge` or `benchmarks session -knowledge`. These use Find by default and retain the assembled context, -revisions and budget under the frozen knowledge condition. Managed rounds -record reasons in their submitted hypotheses. In legacy manual campaigns, -use `campaign capture-context` (one capture per retrieval). After each manual -round, update the optimization log and record it with -`campaign log`: the hypothesis, why this optimization was chosen, which +For managed rounds, Find records the returned hits. Following a hit's scoped +`read` command records the material delivered. In an AB/BA project or a +benchmark, pass a used read's `reference.path` to `round --knowledge-ref`. +A service-reuse attempt retains prepared contexts automatically. Record what +influenced the change in the hypothesis. For a manual campaign, use +`find "" --session ` and the returned read +command. After each manual round, use `campaign log` to record the +hypothesis, why this optimization was chosen, which knowledge it relied on, the search options tried, pruned or left untried and why, the decision and its reason. At the end, write success and failure summaries that cite `candidate:` evidence and name the failing stage. Resolve every **Narrative vs evidence** warning the dashboard shows, or explain it. -When recording search attribution, mark the first line of the current round -in the caller-selected Codex rollout before searching. At round close, use -`campaign import-search` once with that round's inclusive line range, corpus -root and any capture IDs. If the rollout is available only after interruption, +When recording search attribution, keep line counting, Find and each read in +separate tool calls. Pipes, redirections and compound shell commands can leave +the archive partial. After the round response, run `campaign import-search` +with the inclusive line range and corpus root. For standard capture receipts +with a `sha256`, pass +`--context-id --context-id `, repeating the flag for each +additional receipt. A returned `reference.path` of `knowledge/.json` +supplies the ID between the slash and the suffix. +If the rollout is available only after interruption, the host can import the same range later. Keep private raw traces outside the campaign. The round-import section of `docs/dashboard.md` describes how to distinguish observed reads, explicit use and missing capture. diff --git a/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md b/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md index 6ad0d78ab..495171fee 100644 --- a/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md +++ b/plugins/workswarm/inferrsi/skills/inferrsi/SKILL.md @@ -77,15 +77,19 @@ text through its package record. A Skill from a custom library may require PyYAML. If a hit reports it cannot open, check the reason before choosing another hit. -Use the same source flag and returned revision to reopen material. Remove -`--omit-resources` to list bundle keys. `read --resource ` returns one +Use the same source flag and returned revision to reopen material. To list +bundle keys, use `read --revision ` without `--material`, +`--resource` or `--omit-resources`. `read --resource ` returns one resource's text and identifies it in `content_resource`. Use `resource` with the same source flag and revision to extract the exact bytes. -Use `collect --id` to assemble a batch of known materials. Use -`knowledge search` without a query for filtered package inventory. For a -model with several research dimensions, `knowledge research` uses Find within -the filtered package catalog for each dimension. +Use `collect --id` to assemble a batch of known materials. If a read returns +`next_read_args`, run those arguments to continue the same resource, revision +and search. Each receipt records only its returned bytes. Use +`knowledge list` for filtered package inventory. For model research, ask each +model or framework question with `find` and follow its read link. The MiniMax-H3 +residency audit links a component profile and weight inventory. In a campaign, +scope each question with `--session DIR`. Retain qualified identities, exact revisions, source attribution, applicability, candidate/verification state and omissions. Package search does not inspect live @@ -113,17 +117,27 @@ fixed scripts/inputs. Confirm checks use retained `{candidate}`, `{baseline}`, installed package or service. This shares the packaged task's Harness controller. Edit the working candidate, submit each hypothesis with `campaign round`, read -feedback and keep failed rounds. Use `campaign knowledge` when the frozen plan -allows knowledge. It uses Find by default and retains the selected material and -revisions within the requested context budget. Search and profile when the -current question needs it. +feedback and keep failed rounds. When the frozen plan permits knowledge, use +`find "" --session `. Find records the hits. Follow a selected +hit's scoped `read` command for its body and receipt. Read an attachment by +its resource link when needed. In an AB/BA project or benchmark, pass a used +read's `reference.path` to `round --knowledge-ref`. Service-reuse attempts +retain prepared contexts automatically. If a passage you read changes a concrete choice, explain the choice in the -existing `--hypothesis` and append `[use REF | EXACT SOURCE EXCERPT]`. Cite the -delivered reference and a short verbatim excerpt. Leave out citations when +existing `--hypothesis` and append `[use REF | EXACT SOURCE EXCERPT]`. Use the +read result's material `ref` and a verbatim excerpt on one line. Leave out citations when reading did not affect the choice. When the host supplies a Codex rollout, -record the boundary before searching and close the round with -`campaign import-search --archive-review` after the round returns. The importer -resolves the passage and decision positions. +record the starting line in a separate tool call before searching. Run each +Find and emitted `read_args` alone in its own call, keeping the full output +visible. At round close run `campaign import-search` with the inclusive line +range, corpus root and `--archive-review`. For standard capture receipts with +a `sha256`, pass both `--context-id ` and `--context-id `. +Take each ID from its returned +`reference.path` (`knowledge/.json`). Compound commands or missing +returns can leave the archive partial. +For a completed AB/BA round whose asynchronous response was clipped, run +`campaign status --session --round-receipt ` in its own call +before import. For a benchmark use `benchmarks session status` with the same options. Use `up_to` for a round limit or `exact` for fixed rounds. End an up-to search with `campaign final --reason `; final retests the retained best candidate, @@ -164,8 +178,9 @@ the selected runtime. The first iterative task is `qwen21-denoise-npu`. Start a new session with the user's round/time budget, condition label, evaluation prefix and sampling arguments. Read its returned frozen TASK.md and edit the returned working candidate. When knowledge is permitted, use -`session knowledge` for the same Find selection and budgeted context, and -read the delivered material. Submit each changed +`find "" --session ` and follow a selected hit's scoped `read` +command. When a benchmark supplies a frozen Find request, execute it and read +the required card before submitting the first round. Submit each changed candidate and hypothesis with `session round`, then inspect the independent feedback before the next change. Use the same conditional citations in the hypothesis and close any Codex search archive as in `campaign round`. diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index c76418009..b90010f21 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -11,13 +11,13 @@ from pathlib import Path from ...contracts.runspec import revision_matches as _revision_matches -from ...knowledge.catalog import get_knowledge, search_knowledge +from ...knowledge.catalog import BACKENDS, get_knowledge, list_knowledge from ...knowledge.knowledge_operations import KnowledgeReader -from ...knowledge.research import research_knowledge +from ...knowledge.ranking_policy import DEFAULT_RANKING_POLICY from ..host.prepared_environment import inspect_environment from ..legacy.reporting import write_report from ..workflows.campaign import capture_context, create_campaign -from ..workflows.knowledge import knowledge_reader +from ..workflows.knowledge import knowledge_reader, read_continuation from ..workflows.knowledge import read as read_knowledge from .arguments import SUPPLIED, command_parser, device_ids, make_spec, parser @@ -26,6 +26,64 @@ def _print(value: object) -> None: print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)) +def run_find(args, *, ranking_policy=DEFAULT_RANKING_POLICY, backend=None, local_only=False): + """Run Find over the selected sources, using the session policy when supplied.""" + from ...knowledge.knowledge_find import find, load_corpus + + if (args.query is None) == (args.input is None): + raise ValueError("Supply a question or --input FILE for a native MindIE request") + if args.input is not None: + from ..integrations.mindie.project import query_input + + if (local_only or args.no_external or args.external_source is not None + or args.backend or args.platform): + raise ValueError("Use find --input FILE for a native MindIE request. " + "The file and project grant specify its source and conditions.") + if (args.store or args.skill_root or args.revisions or args.repo_type or args.tier + or args.scenario or args.kinds != "case,skill,record" or args.decision_cards + or args.explain or args.searchspace_coordinate or args.show_searchspace_coordinates + or args.external_limit is not None or args.external_timeout != 8.0): + raise ValueError("Supply MindIE conditions and limits in the --input JSON") + return query_input(args.input) + kinds = tuple(k.strip() for k in args.kinds.split(",") if k.strip()) + if not kinds or set(kinds) - {"case", "skill", "record"}: + raise ValueError("--kinds takes a subset of case,skill,record") + backend = args.backend or backend + if args.external_source == "mindie-agent" and not args.no_external: + if backend != "ascend": + raise ValueError("--external-source mindie-agent requires --backend ascend") + if args.platform: + raise ValueError("--platform applies to CANNBot. MindIE uses the approved domain.") + coordinate = None + index = None + if args.searchspace_coordinate is not None: + from ...knowledge.searchspace_index import load_searchspace_coordinate + + coordinate = load_searchspace_coordinate(args.skill_root, *args.searchspace_coordinate) + index = coordinate.index + elif args.show_searchspace_coordinates: + from ...knowledge.searchspace_index import load_searchspace_index_for_skill_root + + index = load_searchspace_index_for_skill_root( + args.skill_root, option="--show-searchspace-coordinates", + ) + reader = knowledge_reader(skill_root=args.skill_root, store_root=args.store) + corpus = load_corpus( + args.skill_root, kinds=kinds, searchspace_index=index, repo=args.repo_type, tier=args.tier, + scenario=args.scenario, backend=backend, store=reader.store, + revisions=_revisions(args.revisions or []), + ) + return find( + args.query, corpus, limit=args.limit, explain=args.explain, + decision_cards=args.decision_cards, pin_material=args.session is not None, + ranking_policy=ranking_policy, + registry=None if local_only or args.no_external else _channels(source=args.external_source), + backend=backend, platform=args.platform, external_limit=args.external_limit, + external_timeout=args.external_timeout, searchspace_coordinate=coordinate, + show_searchspace_coordinates=args.show_searchspace_coordinates, + ) + + def _round_provider(plan): from ..integrations.external_channels import round_provider @@ -33,6 +91,12 @@ def _round_provider(plan): def _optimization_session(args, *, task_source=None, report_metadata=None): + if args.session_action == "status" and args.round_receipt is not None: + from ..views.round_citations import read_round_receipt + + return read_round_receipt(args.session.resolve(), args.round_receipt, + project=args.command == "campaign") + from ...harness.optimization_session import session_command from ...knowledge.ranking_policy import managed_ranking_policy @@ -46,9 +110,8 @@ def _optimization_session(args, *, task_source=None, report_metadata=None): "platform": args.cannbot_platform} external_project = freeze_project(args.repo if args.project_task else None) return session_command( - args, task_source=task_source, retain_context=capture_context, + args, task_source=task_source, ranking_policy_for=managed_ranking_policy, - knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None, external_knowledge=settings, external_project=external_project, external_provider_for=_round_provider, report_metadata=report_metadata, @@ -232,9 +295,9 @@ def _print_find(result: dict) -> None: f"{source['matrix_path']} (sha256 {source['matrix_sha256']})") elif source := result.get("searchspace_source"): print(f"SearchSpace\t{source['matrix_path']} (sha256 {source['matrix_sha256']})") - if result["no_match"]: - print(f"no_match\t{result['corpus_size']} entries searched; " - f"rephrase, or search the corpus directly with rg") + if not result["items"]: + scope = "local_no_match" if result.get("external") else "no_match" + print(f"{scope}\t{result['corpus_size']} entries searched; try another query or scope") _print_external(result) return for item in result["items"]: @@ -244,6 +307,10 @@ def _print_find(result: dict) -> None: if item.get("locally_verified") is False: labels.append("not locally verified") print(f"\n{item['id']}\t[{' · '.join(labels)}]\tscore {item['score']}") + if item.get("authority") and item["authority"] != ( + "package" if item["kind"] == "record" else "checkout" + ): + print(f" material: {item['authority']}:{item['id']}") if coverage := item.get("searchspace_coordinates"): pairs = ", ".join( f"{resource} × {stage}" for resource, stage in coverage["coordinates"] @@ -434,7 +501,26 @@ def _check_baseline_revision(task: dict, environment: dict) -> None: def main(argv: list[str] | None = None) -> int: argument_parser = parser() - args = argument_parser.parse_args(argv) + argv = sys.argv[1:] if argv is None else argv + replacements = { + ("knowledge", "search"): "find QUERY, or knowledge list for filtered inventory", + ("knowledge", "research"): "find QUERY for each research question", + ("campaign", "knowledge"): "find QUERY --session DIR", + ("benchmarks", "session", "knowledge"): "find QUERY --session DIR", + ("cannbot", "search"): "find QUERY --backend ascend (use --external-limit N for CANNBot)", + ("mindie", "query"): "find --input FILE", + } + for words, replacement in replacements.items(): + if tuple(argv[:len(words)]) == words: + argument_parser.error(f"{' '.join(words)} has retired. Use {replacement}") + args, extra = argument_parser.parse_known_args(argv) + if extra: + message = "unrecognized arguments: " + " ".join(extra) + if args.command in ("collect", "context") or ( + args.command == "campaign" and args.campaign_action == "capture-context" + ): + message += ". Use find QUERY to search for material" + argument_parser.error(message) task = None if args.command in ("plan", "run"): supplied = vars(args).pop(SUPPLIED, ()) @@ -473,10 +559,6 @@ def main(argv: list[str] | None = None) -> int: result = cannbot.project.disable() elif action == "describe": result = cannbot.project.describe() - elif action == "search": - result = cannbot.project.search( - args.query, platform=args.platform, limit=args.limit, - ) else: channel = _channels().named(cannbot.CHANNEL_NAME) if channel is None: @@ -589,25 +671,8 @@ def main(argv: list[str] | None = None) -> int: if args.command == "knowledge": if args.knowledge_action == "show": _print(get_knowledge(args.id)) - elif args.knowledge_action == "research": - _print(research_knowledge( - args.model, - frameworks=args.framework, - tasks=args.task, - modalities=args.modality, - mechanisms=args.mechanism, - repo=args.repo_type, - tier=args.tier, - backend=args.backend, - scenario=args.scenario, - limit=args.limit, - target_backend=args.target_backend, - target_device=args.target_device, - target_memory_gib=args.target_memory_gib, - )) else: - records = search_knowledge( - args.query, + records = list_knowledge( repo=args.repo_type, tier=args.tier, backend=args.backend, @@ -615,9 +680,6 @@ def main(argv: list[str] | None = None) -> int: limit=args.limit, explain=args.explain, ) - if args.query.strip(): - print("knowledge search text queries use Find ranking in the package catalog. " - "Omit QUERY for filtered inventory.", file=sys.stderr) if args.json or args.explain: _print(records) else: @@ -627,54 +689,29 @@ def main(argv: list[str] | None = None) -> int: ) return 0 if args.command == "find": - from ...knowledge.knowledge_find import find, load_corpus - - kinds = tuple(k.strip() for k in args.kinds.split(",") if k.strip()) - unknown = [k for k in kinds if k not in ("case", "skill", "record")] - if unknown or not kinds: - raise ValueError("--kinds takes a subset of case,skill,record") - if args.external_source and not args.no_external: - if args.backend != "ascend": - raise ValueError("--external-source mindie-agent requires --backend ascend") - if args.platform: - raise ValueError( - "--platform applies to CANNBot. MindIE uses the approved domain." - ) - coordinate = None - searchspace_index = None - if args.searchspace_coordinate is not None: - from ...knowledge.searchspace_index import load_searchspace_coordinate - - coordinate = load_searchspace_coordinate( - args.skill_root, *args.searchspace_coordinate, - ) - searchspace_index = coordinate.index - elif args.show_searchspace_coordinates: - from ...knowledge.searchspace_index import load_searchspace_index_for_skill_root - - searchspace_index = load_searchspace_index_for_skill_root( - args.skill_root, option="--show-searchspace-coordinates", - ) - result = find( - args.query, load_corpus( - args.skill_root, kinds=kinds, searchspace_index=searchspace_index, - ), - limit=args.limit, explain=args.explain, decision_cards=args.decision_cards, - registry=None if args.no_external else _channels(source=args.external_source), - backend=args.backend, platform=args.platform, - external_limit=args.external_limit, - external_timeout=args.external_timeout, - searchspace_coordinate=coordinate, - show_searchspace_coordinates=args.show_searchspace_coordinates, - ) - if args.json: + if args.backend is not None and args.backend not in BACKENDS: + raise ValueError(f"Unknown package backend {args.backend!r}. " + f"Choose one of {', '.join(BACKENDS)}") + if args.input is not None and args.limit is not None: + raise ValueError("Supply the native MindIE limit in the --input JSON") + if args.limit is None: + args.limit = 5 + if args.session is not None: + from ..workflows.session_knowledge import find_in_session + + result = find_in_session(args, run_find) + else: + result = run_find(args) + if args.json or args.session or args.input: _print(result) else: _print_find(result) return 0 if args.command == "collect": + if args.relevance is not None and not args.ids: + raise ValueError("--relevance selects attachments within --id; " + "use find QUERY to search for material") result = _knowledge_reader(args).collect( - args.query, ids=args.ids, revisions=_revisions(args.revisions or []), kind=args.kind, @@ -690,9 +727,6 @@ def main(argv: list[str] | None = None) -> int: context_bytes=args.context_bytes, decision_cards=_decision_cards(args.decision_card or []), ) - if args.relevance_method is None and result.get("selection", {}).get("ranking_applied"): - print("collect text queries use Find ranking. " - "Use --id and --revision for exact material.", file=sys.stderr) if args.json: _print(result) else: @@ -745,8 +779,17 @@ def main(argv: list[str] | None = None) -> int: ) return 0 if args.command == "read": + if args.session is not None: + from ..workflows.knowledge import read_selected_hit + from ..workflows.session_knowledge import read_in_session + + _print(read_in_session(args, read_selected_hit)) + return 0 + if args.search_ref is not None: + raise ValueError("--search-ref requires --session") if args.layer == "L1": - if args.material or args.resource is not None or args.omit_resources: + if (args.material or args.resource is not None or args.omit_resources + or args.byte_range is not None): raise ValueError("L1 accepts --finding, --compact and --max-bytes") reader = _knowledge_reader(args) result = reader.read_decision_card( @@ -780,12 +823,13 @@ def main(argv: list[str] | None = None) -> int: raise ValueError("--finding, --max-bytes and --compact require --layer L1") ref, _, view = read_knowledge( _knowledge_reader(args), args.id, revision=args.revision, material=args.material, - resource=args.resource, + resource=args.resource, byte_range=args.byte_range, ) - if args.omit_resources: + if args.omit_resources or "content" in view: view.pop("resources") view.pop("required_resources", None) - _print({**view, "ref": ref}) + next_read = read_continuation(args, view) + _print({**({"next_read_args": next_read} if next_read else {}), **view, "ref": ref}) return 0 if args.command == "resource": data = _knowledge_reader(args).resource(args.id, args.path, revision=args.revision) @@ -795,17 +839,21 @@ def main(argv: list[str] | None = None) -> int: _print({"resource": str(destination.resolve())}) return 0 if args.command == "context": - records = search_knowledge( - args.query, - repo=args.repo_type, - tier=args.tier, - backend=args.backend, - scenario=args.scenario, - limit=args.limit, - ) - if args.query.strip(): - print("context text queries use Find ranking in the package catalog. " - "Omit QUERY for filtered inventory.", file=sys.stderr) + if args.ids: + if any(value is not None for value in ( + args.repo_type, args.tier, args.backend, args.scenario, args.limit, + )): + raise ValueError("Supply exact --id values or catalog filters") + records = [ + get_knowledge(identity.removeprefix("package:")) for identity in args.ids + ] + else: + if not args.repo_type or not args.backend: + raise ValueError("Filtered export requires --repo-type and --backend") + records = list_knowledge( + repo=args.repo_type, tier=args.tier, backend=args.backend, + scenario=args.scenario, limit=5 if args.limit is None else args.limit, + ) text = _context(records) if args.output: destination = Path(args.output) @@ -881,6 +929,9 @@ def main(argv: list[str] | None = None) -> int: review=args.review)) return 0 if args.campaign_action == "capture-context": + if args.relevance is not None and not args.ids: + raise ValueError("--relevance selects attachments within --id-ref; " + "use find QUERY --session DIR to search for material") require_manual_campaign(Path(args.directory).resolve()) sources = ("package",) if args.skill_root is not None or args.installed_library: @@ -889,8 +940,8 @@ def main(argv: list[str] | None = None) -> int: sources += ("store",) path, digest = capture_context( args.directory, context_id=args.id, reader=_knowledge_reader(args), - query=args.query, relevance=args.relevance, - relevance_method=args.relevance_method, ids=args.ids, kind=args.kind, + ids=args.ids, kind=args.kind, relevance=args.relevance, + relevance_method=args.relevance_method, revisions=_revisions(args.revision or []), repo=args.knowledge_repo, tier=args.tier, backend=args.backend, scenario=args.scenario, limit=args.limit, diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index c6c241b2f..308234ea8 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -175,7 +175,7 @@ def _search_arguments(commands) -> None: read.add_argument("--output", type=Path, required=True) -def _optimization_actions(stages, *, project=False): +def _optimization_actions(stages, *, project=False, historical=False): start = stages.add_parser("start", help="Freeze explicit task conditions and search budget") start.set_defaults(session_action="start", project_task=project) if project: @@ -226,13 +226,18 @@ def _optimization_actions(stages, *, project=False): help="Opt into CANNBot retrieval on the declared Ascend platform") start.add_argument("--evaluation-prefix", default="", help="Quoted allocator argv prefix") start.add_argument("--python", default=sys.executable) - actions = ("status", "diagnose", "round", "final", "recover", "knowledge", "knowledge-read") + actions = ("status", "diagnose", "round", "final", "recover", "knowledge-read") + if historical: + actions += ("knowledge",) if project: actions += ("baseline", "refresh-references", "resume", "profile") for name in actions: stage = stages.add_parser(name) stage.set_defaults(session_action=name) stage.add_argument("--session", "--directory", dest="session", type=Path, required=True) + if name == "status": + stage.add_argument("--round-receipt", type=int, metavar="N", + help="Read the verified submission receipt for completed round N") if name == "profile": stage.add_argument("--round", type=int, required=True, help="Capture profiling for the last settled attempt of this round") @@ -318,7 +323,24 @@ def _task_overrides(parser: argparse.ArgumentParser) -> None: parser.add_argument(field.flag, **options) -def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: +def _historical_model_dimensions(command): + for dimension in ("framework", "task", "modality", "mechanism"): + command.add_argument(f"--{dimension}", action="append", default=[], + help=f"Additional model research {dimension} (repeatable)") + command.add_argument("--target-backend", help="Caller-declared research target backend") + command.add_argument("--target-device", help="Caller-declared research target device") + command.add_argument("--target-memory-gib", type=float, help="Caller-declared memory in GiB") + + +def _catalog_filters(command): + command.add_argument("--repo-type", choices=KNOWLEDGE_REPOS) + command.add_argument("--tier", choices=KNOWLEDGE_SCOPES) + command.add_argument("--backend", choices=BACKENDS) + command.add_argument("--scenario") + + +def parser(*, parser_class=argparse.ArgumentParser, historical=False) -> argparse.ArgumentParser: + """Build the live CLI, or also recognize retired spellings when decoding recorded argv.""" root = parser_class( description="CLI-first reproducible experiments and tuning knowledge" ) @@ -339,7 +361,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: mindie_actions.add_parser("disable", help="Revoke the project grant") mindie_actions.add_parser("describe", help="Discover read tools for the current project") mindie_actions.add_parser("serve", help="Expose the approved read tools over stdio MCP") - for action in ("query", "explain"): + for action in (("query", "explain") if historical else ("explain",)): read = mindie_actions.add_parser(action, help=f"Run a MindIE {action} and keep a receipt") read.add_argument("--input", type=Path, required=True, help="JSON tool arguments") cannbot = commands.add_parser( @@ -361,12 +383,11 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: ) cannbot_actions.add_parser("disable", help="Revoke the project grant") cannbot_actions.add_parser("describe", help="Probe the approved checkout and its index") - cannbot_search = cannbot_actions.add_parser( - "search", help="Search the approved checkout; returns card locators, not text" - ) - cannbot_search.add_argument("query") - cannbot_search.add_argument("--platform") - cannbot_search.add_argument("--limit", type=int, default=100) + if historical: + cannbot_search = cannbot_actions.add_parser("search") + cannbot_search.add_argument("query") + cannbot_search.add_argument("--platform") + cannbot_search.add_argument("--limit", type=int, default=100) cannbot_read = cannbot_actions.add_parser("read", help="Read one card by locator") cannbot_read.add_argument("locator") cannbot_read.add_argument( @@ -454,7 +475,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: "session", help="Drive iterative optimization in the current Agent" ) stages = session.add_subparsers(dest="session_action", required=True) - _optimization_actions(stages) + _optimization_actions(stages, historical=historical) doctor = commands.add_parser( "doctor", help="Inspect a prepared local target without installing dependencies" ) @@ -584,7 +605,7 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: campaign = commands.add_parser("campaign", help="Create local campaign correlation records") campaign_actions = campaign.add_subparsers(dest="campaign_action", required=True) - _optimization_actions(campaign_actions, project=True) + _optimization_actions(campaign_actions, project=True, historical=historical) create = campaign_actions.add_parser("init", help="Create a new campaign manifest") create.add_argument("--directory", type=Path, required=True) create.add_argument("--id", required=True) @@ -631,14 +652,15 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: help="Caller-reviewed campaign-relative optimization trace JSON") capture = campaign_actions.add_parser( "capture-context", - help="Save the exact knowledge context selected for a question or explicit IDs", + help="Archive explicit IDs or a filtered inventory in a manual campaign", ) capture.add_argument("--directory", type=Path, required=True) capture.add_argument("--id", required=True, help="New context id, e.g. r1-diagnosis") - capture.add_argument("query", nargs="?", default="") - capture.add_argument("--relevance", help="Alternate spelling for one Find query") + capture.add_argument("--relevance", help="Select optional attachments within explicit --id-ref") capture.add_argument("--relevance-method", metavar="find-lexical-v1", - help="Find is the default and only ranking method") + help="Attachment ranking method (default: find-lexical-v1)") + if historical: + capture.add_argument("query", nargs="?", default="") capture.add_argument("--id-ref", action="append", dest="ids", metavar="ID", help="Exact knowledge identity to include (repeatable)") capture.add_argument("--revision", action="append", metavar="ID=REV", @@ -706,56 +728,53 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: reference.add_argument("name") reference.add_argument("path") - knowledge = commands.add_parser( - "knowledge", help="Search or inspect source-grounded imported experience" - ) + knowledge = commands.add_parser("knowledge", help="List or inspect installed catalog records") actions = knowledge.add_subparsers(dest="knowledge_action", required=True) - search = actions.add_parser( - "search", - help="List filtered package records, or search that catalog with Find ranking", - ) - search.add_argument("query", nargs="?", default="") - search.add_argument("--repo-type", choices=KNOWLEDGE_REPOS) - search.add_argument("--tier", choices=KNOWLEDGE_SCOPES) - search.add_argument("--backend", choices=BACKENDS) - search.add_argument("--scenario") - search.add_argument("--limit", type=int, default=10) - search.add_argument("--explain", action="store_true", - help="Return JSON with recorded matching and ranking observations") - search.add_argument("--json", action="store_true") + listing = actions.add_parser("list", help="List installed catalog records by filter") + _catalog_filters(listing) + listing.add_argument("--limit", type=int, default=10) + listing.add_argument("--explain", action="store_true", + help="Include inventory scope, returned IDs and exclusion counts as JSON") + listing.add_argument("--json", action="store_true") show = actions.add_parser("show") show.add_argument("id") - research = actions.add_parser( - "research", help="Combine model research dimensions with package-scoped Find queries" - ) - research.add_argument("model") - for dimension in ("framework", "task", "modality", "mechanism"): - research.add_argument( - f"--{dimension}", action="append", default=[], - help=f"Additional independent {dimension} query (repeatable)", - ) - research.add_argument("--repo-type", choices=KNOWLEDGE_REPOS) - research.add_argument("--tier", choices=KNOWLEDGE_SCOPES) - research.add_argument("--backend", choices=BACKENDS, help="Hard package-record filter") - research.add_argument("--scenario") - research.add_argument("--limit", type=int, default=10) - research.add_argument( - "--target-backend", help="Research target only; no runtime support implied" - ) - research.add_argument("--target-device", help="Caller-declared research target") - research.add_argument( - "--target-memory-gib", type=float, help="Caller-declared unified/device GiB" - ) + if historical: + search = actions.add_parser("search") + search.add_argument("query", nargs="?", default="") + _catalog_filters(search) + search.add_argument("--limit", type=int, default=10) + search.add_argument("--explain", action="store_true") + search.add_argument("--json", action="store_true") + research = actions.add_parser("research") + research.add_argument("model") + _historical_model_dimensions(research) + _catalog_filters(research) + research.add_argument("--limit", type=int, default=10) find = commands.add_parser( "find", help="Rank packaged skills, imported records and checkout cases for one " "question; returns corpus paths with optional pinned decision card reads", ) - find.add_argument("query", help="Describe the problem in your own words") + find.add_argument("query", nargs="?", help="Describe the problem in your own words") + if historical: + find.add_argument("--model") + _historical_model_dimensions(find) + find.add_argument("--session", type=Path, help="Find under this session's knowledge policy") + if historical: + find.add_argument("--capture-id") + find.add_argument("--context-bytes", type=int) + find.add_argument("--repo-type", choices=KNOWLEDGE_REPOS, help="Scope to this package catalog") + find.add_argument("--tier", choices=KNOWLEDGE_SCOPES, help="Scope to this package tier") + find.add_argument("--scenario", help="Find records for this workload and applicable guides") + find.add_argument("--store", type=Path, help="Include an existing local knowledge store") + find.add_argument("--revision", action="append", dest="revisions", metavar="store:ID=REV", + help="Search a retained store revision") + find.add_argument("--input", type=Path, + help="Run a native MindIE JSON request under the project grant") find.add_argument("--decision-cards", action="store_true", help="Add pinned L1 read commands and their UTF-8 card sizes") - find.add_argument("--limit", type=int, default=5) + find.add_argument("--limit", type=int, default=5 if historical else None) find.add_argument( "--kinds", default="case,skill,record", help="Comma-separated subset of case,skill,record; default is all three", @@ -777,12 +796,12 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: ) find.add_argument( "--backend", - help="Declare the task backend once, e.g. ascend; external channels run only " - "for a declared backend and are never inferred from the query", + help="Select matching backend and common material, and route eligible external sources", ) find.add_argument("--platform", help="Override the grant’s upstream platform, e.g. a2") find.add_argument( - "--external-source", choices=("mindie-agent",), + "--external-source", choices=(("none", "mindie-agent", "cannbot-knowledge") if historical + else ("mindie-agent",)), help="Explicitly select MindIE navigation for this Find; requires --backend ascend", ) find.add_argument( @@ -801,14 +820,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: collect = commands.add_parser( "collect", - help="Collect exact IDs, list material, or use Find to assemble context for a question", + help="Assemble explicit knowledge IDs or list a filtered inventory", ) - collect.add_argument("query", nargs="?", default="") collect.add_argument("--kind", choices=("skill", "knowledge", "case")) - collect.add_argument("--repo-type", choices=KNOWLEDGE_REPOS) - collect.add_argument("--tier", choices=KNOWLEDGE_SCOPES) - collect.add_argument("--backend", choices=BACKENDS, help="Include this backend and common") - collect.add_argument("--scenario", help="Workload scenario (also admits packaged skills)") + _catalog_filters(collect) collect.add_argument( "--id", action="append", dest="ids", metavar="ID", help="Exact requested identity" ) @@ -822,11 +837,11 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: collect.add_argument("--limit", type=int, default=10) collect.add_argument("--max-bytes", type=int) collect.add_argument("--material", action="store_true") - collect.add_argument( - "--relevance", help="Alternate spelling for a Find query, or a resource cue with --id", - ) + collect.add_argument("--relevance", help="Select optional attachments within explicit --id") collect.add_argument("--relevance-method", metavar="find-lexical-v1", - help="Find is the default and only ranking method") + help="Attachment ranking method (default: find-lexical-v1)") + if historical: + collect.add_argument("query", nargs="?", default="") collect.add_argument( "--context-bytes", type=int, help="UTF-8 budget for context bodies and any explicitly requested L1 cards", @@ -843,17 +858,24 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: help="Read one bundle from the package, a skill library, or a store", ) read.add_argument("id") + read.add_argument("--session", type=Path, help="Read and retain a hit for this session") + read.add_argument("--search-ref", help="Search receipt returned by find --session") read.add_argument("--layer", choices=("L1",), help="Read a decision card at --revision") read.add_argument("--compact", action="store_true", help="Read the compact L1 decision card") read.add_argument("--finding", help="L1 Case selector returned by find --decision-cards") read.add_argument("--max-bytes", type=int, help="Maximum canonical UTF-8 L1 card bytes") read.add_argument("--revision", help="Exact revision returned by collect or read") read.add_argument("--material", action="store_true") + read.add_argument("--byte-range", nargs=2, type=int, metavar=("START", "LENGTH"), + help="Read up to LENGTH UTF-8 bytes at START in the pinned material; " + "large reads return executable next_read_args for continuation") read.add_argument( "--omit-resources", action="store_true", - help="Omit the resource inventory from output; the revision still covers the full bundle", + help="Omit the resource inventory; content reads already omit it. " + "The revision still covers the full bundle", ) - read.add_argument("--resource", help="Include the UTF-8 text at this bundle resource key") + read.add_argument("--resource", + help="Read a UTF-8 bundle key or a link relative to the primary body") _read_sources(read) resource = commands.add_parser( @@ -869,14 +891,13 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: resource.add_argument("--output", type=Path, required=True, help="File receiving the raw bytes") context = commands.add_parser( - "context", help="Export cited knowledge for manual Codex/Agent handoff" - ) - context.add_argument("query", nargs="?", default="") - context.add_argument("--repo-type", choices=KNOWLEDGE_REPOS, required=True) - context.add_argument("--tier", choices=KNOWLEDGE_SCOPES) - context.add_argument("--backend", choices=BACKENDS, required=True) - context.add_argument("--scenario") - context.add_argument("--limit", type=int, default=5) + "context", help="Export selected package IDs or a filtered catalog to cited Markdown" + ) + if historical: + context.add_argument("query", nargs="?", default="") + context.add_argument("--id", action="append", dest="ids", help="Package record to export") + _catalog_filters(context) + context.add_argument("--limit", type=int, help="Maximum filtered inventory size (default 5)") context.add_argument("--output", help="Write a Markdown context file instead of stdout") return root diff --git a/src/inferrsi/apps/handoff/context_provider.py b/src/inferrsi/apps/handoff/context_provider.py index 559a3ed35..3101002d5 100644 --- a/src/inferrsi/apps/handoff/context_provider.py +++ b/src/inferrsi/apps/handoff/context_provider.py @@ -5,7 +5,15 @@ from hashlib import sha256 from inferrsi.contracts.json_v1 import MAX_SAFE_INTEGER -from inferrsi.knowledge.knowledge_find import installed_skill_root +from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method +from inferrsi.knowledge.catalog import KNOWLEDGE_SCOPES +from inferrsi.knowledge.knowledge_find import ( + Corpus, + find, + installed_skill_projection, + installed_skill_root, + load_corpus, +) from inferrsi.knowledge.knowledge_operations import KnowledgeReader _REQUEST_FIELDS = {"query", "ids", "pins", "selection_limits", "max_bytes", "round_id"} @@ -58,21 +66,30 @@ def collect(self, request: dict) -> DeliveredContextDraft: ): raise ValueError("invalid Knowledge selection option value") - reader = self.reader - if reader.skill_root is None and reader.store is None and any( - identity.startswith("checkout:") for identity in ids - ): - reader = KnowledgeReader(skill_root=installed_skill_root()) - result = reader.collect( - query or "", ids=ids or None, revisions=_revisions(pins), - context_bytes=max_bytes or None, **limits, - ) - selection = {**result.get("selection", {}), **result["retrieval"]["selection"]} + revisions = _revisions(pins) + if ids and query and query.strip(): + raise ValueError("Use explicit IDs or a Find query to select Knowledge") + cue = (query or "").strip() or limits.get("relevance") + if not ids and cue is not None: + if query and query.strip() and limits.get("relevance") is not None: + raise ValueError("Find takes one query or relevance cue") + if "relevance" in limits and not re.search(r"\w", cue): + raise ValueError("Find requires at least one word") + result, selection = self._find(cue, revisions, limits, max_bytes) + else: + reader = self.reader + if reader.skill_root is None and reader.store is None and any( + identity.startswith("checkout:") for identity in ids + ): + reader = KnowledgeReader(skill_root=installed_skill_root()) + result = reader.collect(ids=ids or None, revisions=revisions, + context_bytes=max_bytes or None, **limits) + selection = {**result.get("selection", {}), **result["retrieval"]["selection"]} selection.update(no_match=result["no_match"], collisions=result["collisions"]) omissions = [_omission(item, stage="knowledge_selection") for item in result["omissions"]] limitations = list(result["limitations"]) items, payloads = [], [] - if max_bytes == 0: + if max_bytes == 0 and "contexts" not in result: omissions.extend( _omission({**item, "reason": "context_limit"}, stage="context_delivery") for item in result["items"] @@ -113,6 +130,61 @@ def collect(self, request: dict) -> DeliveredContextDraft: omissions=omissions, limitations=list(dict.fromkeys(limitations)), ) + def _find(self, cue, revisions, limits, max_bytes): + """Find within the request's scope, then assemble those exact pins for sealing.""" + validate_relevance_method(limits.get("relevance_method")) + kind = limits.get("kind") + kinds = {None: ("case", "skill", "record"), "skill": ("skill",), + "case": ("case",), "knowledge": ("skill", "record")} + if kind not in kinds: + raise ValueError("Unknown content kind") + if "tier" in limits and limits["tier"] not in KNOWLEDGE_SCOPES: + raise ValueError(f"Unknown knowledge tier: {limits['tier']}") + reader = self.reader + if reader.skill_root is None and reader.store is None: + reader = KnowledgeReader(skill_root=installed_skill_root()) + fixed = {} + for name, revision in revisions.items(): + ref = reader.resolve(name) + if fixed.setdefault(ref, revision) != revision: + raise ValueError(f"Conflicting revisions for {ref}") + scope = {key: limits[key] for key in ("repo", "tier", "backend", "scenario") + if key in limits} + catalog_scope = any(key in scope for key in ("repo", "tier", "scenario")) + store_pins = {ref: rev for ref, rev in fixed.items() if ref.startswith("store:")} + unavailable = [] + corpus = load_corpus( + self.reader.skill_root, + kinds=kinds[kind], store=self.reader.store, + revisions={} if catalog_scope else store_pins, unavailable_store_revisions=unavailable, + **scope, + ) + if kind == "knowledge": + # This older DTO calls imported records and catalog-projected skills "knowledge". + corpus = Corpus([doc for doc in corpus.documents if doc.kind == "record" + or installed_skill_projection(doc, reader.record) is not None]) + limit = limits.get("limit", 10) + # A material-size limit or caller pin may exclude a higher-ranked item. + # Let exact assembly continue down the same ranked list in that case. + preview_limit = max(1, len(corpus.documents)) if fixed or "max_bytes" in limits else limit + unreadable = [] + hits = find(cue, corpus, limit=preview_limit, pin_material=True, unreadable_hits=unreadable) + result = reader.pack_find_hits(hits["items"], cue=cue, revisions=fixed, limit=limit, + max_bytes=limits.get("max_bytes"), context_bytes=max_bytes) + result["limitations"][:1] = hits["limitations"] + result["omissions"].extend({"id": ref, "reason": "unavailable_revision"} + for ref in unavailable) + result["omissions"].extend( + {"id": f"{hit['authority']}:{hit['id']}", "reason": "invalid"} for hit in unreadable + ) + selection = {"method": FIND_RELEVANCE, "cue": cue, "ranking_applied": True, + "state": "applied", "tie_break": "state_then_id_then_ref", + "scope": "package-records-library-and-store" if self.reader.store is not None + else "package-records-and-library", + "ranking_policy": hits["ranking_policy"], "matched_count": hits["matched"], + "returned_count": len(result["items"])} + return result, selection + def _identifier(value: object) -> bool: return isinstance(value, str) and _ID.fullmatch(value) is not None diff --git a/src/inferrsi/apps/integrations/mindie/context.py b/src/inferrsi/apps/integrations/mindie/context.py index 7f5377f5c..7b8cc9932 100644 --- a/src/inferrsi/apps/integrations/mindie/context.py +++ b/src/inferrsi/apps/integrations/mindie/context.py @@ -15,6 +15,10 @@ MAX_BYTES = 2 * 1024 * 1024 _ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") _REF = re.compile(r"mindie://([A-Za-z0-9_.-]+)/units/([A-Za-z0-9_.-]+)@([1-9][0-9]*)") +UNIT_REFERENCE = re.compile( + r"mindie://(?P[a-z][a-z0-9-]{0,63})/units/" + r"(?P[A-Za-z0-9][A-Za-z0-9_.-]{0,127})@(?P[1-9][0-9]*)" +) def _object(pairs): diff --git a/src/inferrsi/apps/integrations/mindie/navigation.py b/src/inferrsi/apps/integrations/mindie/navigation.py index 5b79e03c1..1f9654668 100644 --- a/src/inferrsi/apps/integrations/mindie/navigation.py +++ b/src/inferrsi/apps/integrations/mindie/navigation.py @@ -4,7 +4,6 @@ import os import queue -import re import signal import subprocess import threading @@ -14,14 +13,10 @@ from ....knowledge.channels import ChannelHit, ChannelRequest, ChannelResult, ChannelStatus from ..project_binding import checkout_identity, matches_checkout from . import project -from .context import MAX_BYTES, _parse +from .context import MAX_BYTES, UNIT_REFERENCE, _parse _TOKEN_BUDGET = 8000 _NATIVE_LIMIT = 20 -_REF = re.compile( - r"mindie://(?P[a-z][a-z0-9-]{0,63})/units/" - r"(?P[A-Za-z0-9][A-Za-z0-9_.-]{0,127})@(?P[1-9][0-9]*)" -) _NOT_ENABLED = ChannelStatus( "not_enabled", detail="No active MindIE grant matches the captured project checkout.", fix="Enable MindIE knowledge for the current project.", @@ -114,7 +109,7 @@ def _navigation_hits(payload: dict, *, domain: str, limit: int) -> tuple[Channel valid = False for row in rows: ref = row.get("ref") if isinstance(row, dict) else None - match = _REF.fullmatch(ref) if isinstance(ref, str) and len(ref) <= 256 else None + match = UNIT_REFERENCE.fullmatch(ref) if isinstance(ref, str) and len(ref) <= 256 else None if match is None or match["domain"] != domain: continue revision = row.get("revision") diff --git a/src/inferrsi/apps/integrations/mindie/project.py b/src/inferrsi/apps/integrations/mindie/project.py index 2ec6daa6f..9c45280e3 100644 --- a/src/inferrsi/apps/integrations/mindie/project.py +++ b/src/inferrsi/apps/integrations/mindie/project.py @@ -240,6 +240,15 @@ def call(action: str, arguments: dict, *, session: str | None = None) -> dict: return {"receipt_directory": str(receipt), "result": _parse(response)} +def query_input(path: Path) -> dict: + """Run a Find with the native conditions, controls and receipt of the approved domain.""" + from inferrsi.harness.records.evidence import sanitized_text + + request = _read_object(path) + response = call("query", request, session=os.environ.get("CODEX_THREAD_ID")) + return {"query": sanitized_text(request["query"], ""), **response} + + def dispatch(args) -> dict | None: if args.mindie_action == "enable": return enable(args.adapter_config, args.domain) @@ -252,5 +261,4 @@ def dispatch(args) -> dict | None: serve() return None - return call(args.mindie_action, _read_object(args.input), - session=os.environ.get("CODEX_THREAD_ID")) + return call("explain", _read_object(args.input), session=os.environ.get("CODEX_THREAD_ID")) diff --git a/src/inferrsi/apps/views/capture_delivery.py b/src/inferrsi/apps/views/capture_delivery.py index b0670e5c1..486981393 100644 --- a/src/inferrsi/apps/views/capture_delivery.py +++ b/src/inferrsi/apps/views/capture_delivery.py @@ -2,6 +2,7 @@ import hashlib import json +import re from inferrsi.apps.workflows.campaign import verify_capture from inferrsi.harness.records.campaign_records import _identifier @@ -14,16 +15,21 @@ from inferrsi.harness.records.evidence import ( sanitized_text as _text, ) -from inferrsi.harness.records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES +from inferrsi.harness.records.knowledge_capture import ( + MAX_CONTEXT_CAPTURE_BYTES, + ranking_identity, + scoped_response, +) from inferrsi.harness.records.optimization_log import _unique from inferrsi.knowledge.context_projection import assemble_context_text -from .codex_tool_returns import _output_lines, _response_text +from .codex_knowledge import external_hit_refs +from .codex_tool_returns import _output_lines, _response_chunks, _response_text _EXTERNAL_SUFFIX = ',\n "external": ' -def capture_return_texts(trace, lines, references, context_ids): +def capture_return_texts(trace, lines, references, context_ids, *, exec_returns=None): """Read only tool-return text at the caller's line references in this round.""" if not isinstance(references, dict): raise ValueError("capture_returns must map capture IDs to tool-return lines") @@ -48,16 +54,8 @@ def capture_return_texts(trace, lines, references, context_ids): "function_call_output", "custom_tool_call_output" ): raise ValueError("capture return must reference a model-facing tool response") - output = payload.get("output") - if isinstance(output, str): - texts[number] = [output] - elif isinstance(output, list): - texts[number] = [ - part["text"] for part in output if isinstance(part, dict) - and part.get("type") == "input_text" and isinstance(part.get("text"), str) - ] - else: - texts[number] = [] + verified = exec_returns.get(number) if exec_returns else None + texts[number] = _response_chunks(row, verified) or [] if wanted == texts.keys(): break if wanted != texts.keys(): @@ -66,9 +64,25 @@ def capture_return_texts(trace, lines, references, context_ids): def _managed_envelope(doc, reference): + action = (doc.get("retrieval") or {}).get("entrypoint") + if action in ("find", "read") and "display" in doc["retrieval"]: + ref = {"path": reference["path"], "kind": ("knowledge_search" if action == "find" + else "delivered_context"), + "sha256": reference["sha256"]} + return json.dumps(scoped_response(doc, ref, "."), ensure_ascii=False, indent=2) return json.dumps({"reference": reference, "context": doc}, ensure_ascii=False, indent=2) +def portable_find_return(text): + """Compare scoped read commands after relocating their local CLI argument paths.""" + if ('"kind": "knowledge_search"' not in text + and not ('"kind": "delivered_context"' in text and '"next_read_args"' in text)): + return text + markers = {"session": ".", "skill-root": "SKILL_ROOT", "store": "STORE"} + return re.sub(r'(^\s*"--(session|skill-root|store)",\n\s*)"(?:(?:\\.)|[^"\\])*"', + lambda m: m[1] + json.dumps(markers[m[2]]), text, flags=re.MULTILINE) + + def capture_receipts(captures): """Render the manual CLI's capture receipts without material bodies.""" return {key: json.dumps({"context": source, "sha256": digest}, ensure_ascii=False, indent=2) @@ -81,38 +95,40 @@ def managed_envelopes(captures): }) for key, (doc, source, digest) in captures.items()} -def _joint_output_end(chunk, start): +def _joint_output(chunk, start): try: external, end = json.JSONDecoder(object_pairs_hook=_unique).raw_decode(chunk, start) except (ValueError, RecursionError): - return None + return None, None if (isinstance(external, dict) and external.get("channel") == "cannbot-knowledge" and chunk.startswith("\n}", end)): - return end + 2 - return None + return end + 2, external + return None, None def managed_local_output(output): """Return the exact local envelope from a complete joint CLI response.""" prefix, separator, _ = output.rpartition(_EXTERNAL_SUFFIX) - if separator and _joint_output_end(output, len(prefix) + len(separator)) == len(output): + if separator and _joint_output(output, len(prefix) + len(separator))[0] == len(output): return prefix + "\n}" return output -def _contains_envelope(chunk, body): +def _matched_envelope(chunk, body): chunk = "\n" + chunk.replace("\r\n", "\n") + "\n" + if '"kind": "knowledge_search"' in body or '"next_read_args"' in body: + chunk = portable_find_return(chunk) if f"\n{body}\n" in chunk: - return True + return True, None prefix = f"\n{body[:-2]}{_EXTERNAL_SUFFIX}" start = chunk.find(prefix) if start < 0: - return False - end = _joint_output_end(chunk, start + len(prefix)) - return end is not None and chunk[end:end + 1] == "\n" + return False, None + end, external = _joint_output(chunk, start + len(prefix)) + return (True, external) if end is not None and chunk[end:end + 1] == "\n" else (False, None) -def managed_return_lines(trace, lines, envelopes, *, reserved): +def managed_return_lines(trace, lines, envelopes, *, reserved, exec_returns=None): """Locate exact tool returns for selected managed captures in the round.""" if not envelopes: return {} @@ -131,10 +147,10 @@ def managed_return_lines(trace, lines, envelopes, *, reserved): "function_call_output", "custom_tool_call_output", )): continue - text = _response_text(row) + text = _response_text(row, exec_returns.get(number) if exec_returns else None) if text is None: continue - keys = [key for key, body in envelopes.items() if _contains_envelope(text, body)] + keys = [key for key, body in envelopes.items() if _matched_envelope(text, body)[0]] if len(keys) == 1: found.setdefault(keys[0], number) return found @@ -152,7 +168,10 @@ def visible_capture_resources(doc, texts): **context, "resources": [resource], "omissions": [], }]) if any("\n" + block in chunk for chunk in chunks): - visible.append({"ref": context["ref"], "path": resource["path"]}) + item = {"ref": context["ref"], "path": resource["path"]} + if "content_range" in resource: + item["content_range"] = resource["content_range"] + visible.append(item) return visible @@ -164,6 +183,15 @@ def _archive_capture_metadata(doc): value = request.get(key) if isinstance(value, str): safe_request[key] = _text(value, "", limit=len(value)) + if "display" in (doc.get("retrieval") or {}): + if policy := ranking_identity(request.get("ranking_policy")): + safe_request["ranking_policy"] = policy + if isinstance(kinds := request.get("kinds"), str): + safe_request["kinds"] = _text(kinds, "", limit=len(kinds)) + for key in ("resource", "search_ref"): + value = request.get(key) + if isinstance(value, str) and _relative_location(value) == value: + safe_request[key] = value ids = request.get("ids") if isinstance(ids, list): safe_request["ids"] = [value for value in ids if isinstance(value, str) @@ -201,6 +229,16 @@ def load_campaign_capture(root, campaign_id, context_id): return doc, path.relative_to(root).as_posix(), hashlib.sha256(raw).hexdigest() +def citation_excerpts(text, quotes): + """Keep exact quoted bytes that are still present after sanitizing the source line.""" + requested = [quote for quote in quotes if quote and quote in text] + if not requested: + return [] + public = _text(text, "", limit=None) + return sorted((q for q in requested if q in public and _text(q, "", limit=None) == q), + key=lambda q: (text.index(q), q)) + + def _capture_passages(doc, selections, visible, excerpts): locators = dict.fromkeys((item["ref"], item["passage_path"], item["passage_line"]) for item in selections) @@ -215,9 +253,10 @@ def _capture_passages(doc, selections, visible, excerpts): if len(resources) != 1: raise ValueError("Indexer review must name one exact captured resource") lines = _output_lines(resources[0]["content"]) - if line > len(lines) or not lines[line - 1]: + offset = line - resources[0].get("content_range", {}).get("first_line", 1) + if not 0 <= offset < len(lines) or not lines[offset]: raise ValueError("Indexer review source line is missing or empty") - text = lines[line - 1] + text = lines[offset] if _text(text, "", limit=len(text)) != text: raise ValueError("Indexer review source passage is not safe to publish verbatim") passages.append({"ref": ref, "path": path, "line": line, "text": text}) @@ -229,11 +268,17 @@ def _capture_passages(doc, selections, visible, excerpts): path = resource["path"] if (ref, path) not in visible: continue - for line, text in enumerate(_output_lines(resource["content"]), 1): - if ((ref, path, line) not in locators - and any(quote in text for quote in excerpts[ref]) - and _text(text, "", limit=len(text)) == text): - passages.append({"ref": ref, "path": path, "line": line, "text": text}) + first_line = resource.get("content_range", {}).get("first_line", 1) + for line, text in enumerate(_output_lines(resource["content"]), first_line): + if (ref, path, line) in locators: + continue + quoted = citation_excerpts(text, excerpts[ref]) + if not quoted: + continue + source = {"ref": ref, "path": path, "line": line} + passages.extend({**source, "text": quote, "quoted": True, + **({"truncated": True} if quote != text else {})} + for quote in quoted) return passages @@ -241,19 +286,24 @@ def capture_event(context_id, captured, *, archive=False, return_chunks=None, return_line=None, selected_passages=(), excerpts=None): doc, source, digest = captured resources = {c["ref"]: [r["path"] for r in c["resources"]] for c in doc["contexts"]} + ranges = {c["ref"]: r["content_range"] for c in doc["contexts"] + for r in c["resources"] if "content_range" in r} materials = [] + scoped_find = (doc.get("retrieval") or {}).get("entrypoint") == "find" for item in doc["items"]: ref, revision = item.get("ref"), item.get("revision") - if not isinstance(ref, str) or not isinstance(revision, str): + if not isinstance(ref, str) or (not isinstance(revision, str) and not scoped_find): raise ValueError("capture item is missing its ref or revision") - materials.append({"ref": ref, "revision": revision, "resources": resources.get(ref, [])}) + materials.append({"ref": ref, **({"revision": revision} if revision else {}), + "resources": resources.get(ref, []), + **({"content_range": ranges[ref]} if ref in ranges else {})}) observation = doc.get("retrieval") or {} calls = observation.get("calls", []) if "knowledge search" in calls: tool = "knowledge search" else: recorded_tool = calls[-1] if calls else None - tool = recorded_tool if recorded_tool in ("collect", "find") else "collect" + tool = recorded_tool if recorded_tool in ("collect", "find", "read") else "collect" action = "search" recorded_selection = observation.get("selection") request = observation.get("request") @@ -272,17 +322,22 @@ def capture_event(context_id, captured, *, archive=False, return_chunks=None, event = {"action": action, "tool": tool, "context_id": context_id, "source": source, "sha256": digest, "request": doc["request"], "selection": doc.get("selection"), "materials": materials} - exact_return = bool(return_chunks) and _contains_envelope( - "".join(return_chunks), + exact_return, external = _matched_envelope( + "".join(return_chunks or []), _managed_envelope(doc, {"path": source, "sha256": digest, "kind": "delivered_context"}), ) + if scoped_find and external and external.get("context_ref") == source: + materials.extend({"ref": ref, "resources": []} for ref in external_hit_refs(external)) visible = [r for r in visible_capture_resources( doc, [doc["assembled_text"]] if exact_return else return_chunks, ) if _relative_location(r["ref"]) == r["ref"] and _relative_location(r["path"]) == r["path"]] + visible_refs = [item["ref"] for item in materials] if exact_return and scoped_find else [] if not archive: - if visible: + if visible or visible_refs: event["delivery"] = {"state": "visible", "return_line": return_line, "visible_resources": visible} + if visible_refs: + event["delivery"]["visible_refs"] = visible_refs return event omissions = {o["ref"]: o.get("reason") for o in @@ -290,8 +345,9 @@ def capture_event(context_id, captured, *, archive=False, return_chunks=None, if isinstance(o, dict) and isinstance(o.get("ref"), str)} visible_keys = {(r["ref"], r["path"]) for r in visible} for material in materials: - ref, revision = material["ref"], material["revision"] - if _relative_location(ref) != ref or _text(revision, "", len(revision)) != revision: + ref, revision = material["ref"], material.get("revision") + if (_relative_location(ref) != ref + or (revision and _text(revision, "", len(revision)) != revision)): raise ValueError("capture contains a nonportable material ref or revision") paths = material["resources"] material["preparation_state"] = "prepared" if paths else "not_recorded" @@ -301,17 +357,19 @@ def capture_event(context_id, captured, *, archive=False, return_chunks=None, material["omission_reason"] = _text(omissions[ref]) material["resources"] = [p for p in paths if _relative_location(p) == p] material["delivery_state"] = ("visible" if any((ref, p) in visible_keys for p in paths) - else "unknown") + else "ref_visible" if ref in visible_refs else "unknown") event["id"] = f"capture:{context_id}" event["request"], event["selection"] = _archive_capture_metadata(doc) event["capture"] = {"state": "verified", "source": source, "sha256": digest} - event["delivery"] = {"state": "visible" if visible else "unknown", + event["delivery"] = {"state": "visible" if visible or visible_refs else "unknown", "output_state": "verified" if exact_return or visible else "unknown", "visible_resources": visible, "passages": _capture_passages( doc, selected_passages, visible_keys, excerpts or {})} + if visible_refs: + event["delivery"]["visible_refs"] = visible_refs if return_line is not None: event["trace_line"] = return_line - if visible: + if visible or visible_refs: event["delivery"]["return_line"] = return_line return event diff --git a/src/inferrsi/apps/views/codex_knowledge.py b/src/inferrsi/apps/views/codex_knowledge.py index 2a2e2ea64..2f88c41eb 100644 --- a/src/inferrsi/apps/views/codex_knowledge.py +++ b/src/inferrsi/apps/views/codex_knowledge.py @@ -10,6 +10,7 @@ from pathlib import Path from inferrsi.harness.records.evidence import relative_location, sanitized_text +from inferrsi.harness.records.knowledge_capture import ranking_identity, valid_content_range from .codex_tool_returns import _output_lines @@ -41,7 +42,7 @@ def exit(self, status=0, message=None): def _parser(): from ..cli.arguments import parser - return parser(parser_class=_QuietParser) + return parser(parser_class=_QuietParser, historical=True) def cli_arguments(argv): @@ -84,6 +85,8 @@ def _ref(value): def _external_ref(channel, locator): + if channel == "mindie-agent": + return _mindie_locator(locator)[0] if (isinstance(channel, str) and re.fullmatch(r"[a-z0-9][a-z0-9-]*", channel) and isinstance(locator, str) and relative_location(locator) == locator): ref = f"{channel}:{locator}" @@ -100,26 +103,157 @@ def _item(ref, read_args=()): opened = _ref(read_args[1]) if opened and opened != ref: row["read_ref"] = opened + elif opened and "--revision" in read_args: + revision = read_args[read_args.index("--revision") + 1:] + if not revision or not _REVISION.fullmatch(revision[0]): + raise ValueError("invalid revision in Find read arguments") + row["revision"] = revision[0] return row +def external_hit_refs(channels): + for channel in [channels] if isinstance(channels, dict) else channels: + if channel["state"] == "ok": + hits = channel.get("items", []) + if channel["count"] != len(hits): + raise ValueError("incomplete external Find result") + for hit in hits: + yield _external_ref(channel["channel"], hit["locator"]) + + +def mindie_unit_from_key(ref): + """Parse the archive's versioned unit key without admitting it as a filesystem location.""" + from ..integrations.mindie.context import UNIT_REFERENCE + + prefix = "mindie-agent:" + if (isinstance(ref, str) and len(ref) <= 240 and ref.startswith(prefix) + and sanitized_text(ref, "") == ref): + return UNIT_REFERENCE.fullmatch("mindie://" + ref[len(prefix):]) + return None + + +def _mindie_locator(locator): + if isinstance(locator, str) and locator.startswith("mindie://"): + key = "mindie-agent:" + locator.removeprefix("mindie://") + if unit := mindie_unit_from_key(key): + return key, unit + raise ValueError("invalid native navigation reference") + + +def _external_material(ref): + if ref.startswith("mindie-agent:"): + return {"ref": ref, "revision": ref.rsplit("@", 1)[1]} + return {"ref": ref} + + +def _native_mindie_find(text): + from ..integrations.mindie.context import _payload + + envelope = json.loads(text) + if not isinstance(envelope.get("receipt_directory"), str) or not envelope["receipt_directory"]: + raise ValueError("missing native query receipt") + page, _ = _payload(envelope["result"], {"results"}) + if "retrieval" in page and ( + page["retrieval"] != "graded-bm25" or not {"cards", "foundation_cards"} <= page.keys() + ): + raise ValueError("incomplete graded navigation page") + domain = page.get("domain") + if domain is not None and (not isinstance(domain, str) + or not re.fullmatch(r"[a-z][a-z0-9-]{0,63}", domain)): + raise ValueError("invalid native query domain") + materials = {} + for name in ("cards", "foundation_cards", "unverified_cards", "results"): + rows = page.get(name, []) + if not isinstance(rows, list): + raise ValueError("invalid native navigation list") + for row in rows: + key, unit = _mindie_locator(row["ref"]) + if domain is not None and unit["domain"] != domain: + raise ValueError("invalid native navigation domain") + domain = unit["domain"] + if (row.get("id", unit["id"]) != unit["id"] + or "revision" in row and (type(row["revision"]) is not int + or str(row["revision"]) != unit["revision"])): + raise ValueError("invalid native navigation identity") + material = materials.setdefault(key, {"ref": key, "revision": unit["revision"], + "navigation": []}) + observed = {"list": name} + if "match_status" in row: + if row["match_status"] not in ("matched", "mismatched", "condition_unknown"): + raise ValueError("invalid native navigation status") + observed["match_status"] = row["match_status"] + if "ready_to_apply" in row: + if type(row["ready_to_apply"]) is not bool: + raise ValueError("invalid native navigation applicability") + observed["ready_to_apply"] = row["ready_to_apply"] + if observed not in material["navigation"]: + material["navigation"].append(observed) + request = {"external_source": "mindie-agent"} + if domain is not None: + request["domain"] = domain + event = {"materials": list(materials.values()), "request": request} + if query := sanitized_text(envelope.get("query"), ""): + event["query"] = query + if type(page.get("usage", {}).get("has_more")) is bool: + event["has_more"] = page["usage"]["has_more"] + return event + + def _find_json(args, text): + from ...knowledge.channels import no_match_across_sources + result = json.loads(text) items, matched, no_match = result["items"], result["matched"], result["no_match"] - if (result["query"] != args.query or not isinstance(items, list) - or type(matched) is not int or matched < 0 or type(no_match) is not bool - or len(items) != min(args.limit, matched) or no_match != (matched == 0)): + query = args.query or getattr(args, "model", None) + external = result.get("external", []) + if external and (args.no_external or args.external_source == "none"): + raise ValueError("An offline Find has no external return") + if (args.session is not None and isinstance(external, dict) + and external.get("channel") == "cannbot-knowledge"): + # Session Find sends the same redacted query to its local and frozen external sources. + query = sanitized_text(query, "", limit=None) + if (result["query"] != query or not isinstance(items, list) + or type(matched) is not int or matched < 0 + or len(items) != min(args.limit, matched)): raise ValueError("invalid Find result") - materials = [_item(f"{row['authority']}:{row['id']}", row.get("read_args", [])) - for row in items] - for channel in result.get("external", []): - if channel["state"] != "ok": - continue - hits = channel.get("items", []) - if channel["count"] != len(hits): - raise ValueError("incomplete external Find result") - materials.extend({"ref": _external_ref(channel["channel"], hit["locator"])} - for hit in hits) + channels = [external] if isinstance(external, dict) else external + # Earlier transcripts used no_match for the local corpus alone. + if (no_match is not (matched == 0) + and no_match is not no_match_across_sources(matched, channels)): + raise ValueError("Find match status disagrees with its results") + materials = [] + for row in items: + if getattr(args, "session", None) and row.get("material_ref"): + material = _item(row["material_ref"]) + if isinstance(row.get("revision"), str): + material["revision"] = row["revision"] + else: + material = _item(f"{row['authority']}:{row['id']}", row.get("read_args", [])) + if ("revision" in material + and row.get("revision", material["revision"]) != material["revision"]): + raise ValueError("Find result and read revision disagree") + materials.append(material) + materials.extend(_external_material(ref) for ref in external_hit_refs(external)) + return materials + + +def _legacy_model_materials(args, text): + """The original model command returned package records without bundle revision pins.""" + result = json.loads(text) + items, queries = result["items"], result["queries"] + scope = {"repo": args.repo_type, "tier": args.tier, + "backend": args.backend, "scenario": args.scenario} + if (result["model"] != args.model.strip() or result["filters"] != scope + or not isinstance(items, list) or not isinstance(queries, list) or not queries + or result["no_match"] is not (not items) or args.limit < 1): + raise ValueError("invalid historical model result") + counts = [q["matches"] for q in queries] + if (any(type(n) is not int or n < 0 for n in counts) + or not min(args.limit, max(counts)) <= len(items) <= min(args.limit, sum(counts))): + raise ValueError("incomplete historical model result") + materials = [_item("package:" + row["record"]["id"]) for row in items] + if len({row["ref"] for row in materials}) != len(materials): + raise ValueError("duplicate historical model result") return materials @@ -133,22 +267,33 @@ def _find_text(text): if line == _EXTERNAL_HEADING: channel = "" elif channel is not None: - heading = re.fullmatch(r" ([a-z0-9-]+) @ [^\t]+\t\[[^\t]+\]\t(\d+) hit\(s\)\t\d+ ms", - line) + heading = re.fullmatch( + r" ([a-z0-9-]+)(?: @ [^\t]+\t\[[^\t]+\])?\t(\d+) hit\(s\)\t\d+ ms", line, + ) if heading: if remaining: raise ValueError("incomplete external hits") channel, remaining = heading[1], int(heading[2]) - elif remaining and (hit := re.fullmatch(r" [\d.-]+\t[^\t]*\t([^\t]+)", line)): - external.append({"ref": _external_ref(channel, hit[1])}) - remaining -= 1 + elif remaining: + row = r" [^\t]*\t([^\t]+)" if channel == "mindie-agent" else ( + r" [\d.-]+\t[^\t]*\t([^\t]+)") + if hit := re.fullmatch(row, line): + external.append(_external_material(_external_ref(channel, hit[1]))) + remaining -= 1 + else: + raise ValueError("incomplete external hit") elif not line.startswith(" "): raise ValueError("unrecognized external Find result") - elif line.startswith("no_match\t") and " entries searched;" in line: + elif line.startswith(("no_match\t", "local_no_match\t")) and " entries searched;" in line: no_match = True elif match := _FIND_ROW.fullmatch(line): authority = "package" if match[2] == "record" else "checkout" local.append(_item(f"{authority}:{match[1]}")) + elif local and line.startswith(" material: "): + ref = line.removeprefix(" material: ") + if ref.partition(":")[2] != local[-1]["ref"].partition(":")[2]: + raise ValueError("Find material does not identify the displayed item") + local[-1] = _item(ref) elif local and (opening := re.fullmatch(r" open(?: \(PowerShell\))?: (.+)", line)): candidate = invocation(shlex.split(opening[1].removeprefix("& "))) if candidate and candidate[0] == "read": @@ -165,19 +310,40 @@ def _read_result(args, output): revision = view["revision"] identity = view["id"] ref = view.get("ref") or args.id # Older qualified commands already record the authority. + scoped = getattr(args, "session", None) is not None + revision_known = _REVISION.fullmatch(revision) or ( + scoped and re.fullmatch("[0-9a-f]{40}", revision)) if (not _ref(ref) or identity != ref.partition(":")[2] - or args.id not in (ref, identity) or not _REVISION.fullmatch(revision) + or args.id not in (ref, identity) or not revision_known or (args.revision is not None and args.revision != revision)): raise ValueError("read result does not identify the requested material") material = {"ref": ref, "revision": revision} - if args.resource is None and not args.material: + if scoped and any(item["ref"] == ref for item in view.get("context_omissions", [])): + return material, None + if not scoped and args.resource is None and not args.material: return material, None - path = view["content_resource"] if args.resource is not None else view["entrypoint"] + path = view["content_resource"] if args.resource is not None or scoped else view["entrypoint"] body = view["content"] if (relative_location(path) != path or not isinstance(path, str) - or (args.resource is not None and args.resource != path) or not isinstance(body, str)): raise ValueError("read result does not contain the requested resource") + if args.resource is not None and args.resource != path: + from inferrsi.knowledge.knowledge_operations import resolve_resource_key + + base = view["body_resource"] + if not isinstance(base, str) or relative_location(base) != base: + raise ValueError("read result does not identify the source of its resource link") + resolve_resource_key(args.resource, base, (path,)) + bounds = view.get("content_range") + if bounds is not None or args.byte_range is not None: + if not valid_content_range(bounds, body): + raise ValueError("read returned inconsistent byte range") + start, end = bounds["start"], bounds["end"] + if (args.byte_range is None and start != 0 + or args.byte_range is not None and (start != args.byte_range[0] + or end - start > args.byte_range[1])): + raise ValueError("read returned inconsistent byte range") + material["content_range"] = bounds return material, (path, body) @@ -187,6 +353,9 @@ def decode(call, code, output): return None, True, None try: args = _parser().parse_args(argv) + if tool == "find" and not any( + arg == "--limit" or arg.startswith("--limit=") for arg in argv): + args.limit = 10 if getattr(args, "model", None) else 5 except _ArgumentError: args = None @@ -224,8 +393,16 @@ def decode(call, code, output): or not output.strip() or len(output) > _MAX_RESULT): return event, False, spec try: - if tool == "find": - event["materials"] = _find_json(args, output) if args.json else _find_text(output) + if tool == "find" and args.input is not None: + if (args.external_source not in (None, "mindie-agent") or args.session is not None + or args.query is not None or args.model is not None): + raise ValueError("unsupported native Find arguments") + event.update(_native_mindie_find(output)) + elif tool == "find": + structured = args.json or args.session or args.model or args.input + event["materials"] = _find_json(args, output) if structured else _find_text(output) + elif tool == "knowledge research": + event["materials"] = _legacy_model_materials(args, output) elif tool == "read": material, spec["resource"] = _read_result(args, output) event["materials"] = [material] @@ -233,6 +410,31 @@ def decode(call, code, output): # Compatibility tools have separate output shapes. A recognized # invocation must not pass a complete-coverage check as zero. return event, False, spec + if getattr(args, "session", None) is not None and tool in ("find", "read"): + returned = json.loads(output) + reference = returned["reference"] + kind = "knowledge_search" if tool == "find" else "delivered_context" + if (reference["kind"] != kind or not isinstance(reference["path"], str) + or relative_location(reference["path"]) != reference["path"]): + raise ValueError("invalid scoped receipt") + if "sha256" in reference: + if not re.fullmatch("[0-9a-f]{64}", reference["sha256"]): + raise ValueError("invalid scoped receipt digest") + spec["capture"] = (reference["path"], reference["sha256"]) + spec["directory"] = args.session + spec["context_id"] = getattr(args, "capture_id", None) + request = {} + if policy := ranking_identity(returned.get("ranking_policy")): + request["ranking_policy"] = policy + if tool == "find": + request["kinds"] = sanitized_text(args.kinds, "") + else: + if relative_location(args.search_ref) == args.search_ref and args.search_ref: + request["search_ref"] = args.search_ref + path = returned.get("content_resource") + if isinstance(path, str) and relative_location(path) == path: + request["resource"] = path + event["request"] = request except (ValueError, KeyError, TypeError, AttributeError, RecursionError): return event, False, spec spec["decoded"] = True diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index a57a52797..a5c6a4946 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -2,6 +2,7 @@ from __future__ import annotations +import ast import json import os import re @@ -16,7 +17,7 @@ sanitized_text as _text, ) -from .capture_delivery import managed_local_output +from .capture_delivery import citation_excerpts, managed_local_output, portable_find_return from .codex_knowledge import decode as decode_knowledge from .codex_knowledge import invocation as knowledge_invocation from .codex_tool_returns import _output_lines, _path, correlate_window @@ -166,6 +167,9 @@ def _rg_args(args: list[str]) -> tuple[str, list[str], str, list[str], bool] | N options.extend([arg, _text(value)]) if arg in ("-A", "-B", "-C", "--context"): context = True + elif re.fullmatch(r"-[ABC][0-9]+", arg): + options.append(_text(arg)) + context = True elif arg in ("--files-with-matches", "-l"): mode = "files" options.append(arg) @@ -267,11 +271,14 @@ def _program(word): return re.split(r"[\\/]", word)[-1].lower().removesuffix(".exe") -def _without_env(argv): - """Drop a leading `env` and its NAME=value words; None for env options it cannot read.""" +def _without_env(argv, *, allow_unset=False): + """Unwrap recorded env assignments and, for submissions, explicit variable removals.""" if _program(argv[0]) != "env": return argv rest = argv[1:] + while (allow_unset and len(rest) >= 2 and rest[0] == "-u" + and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", rest[1])): + rest = rest[2:] while rest and "=" in rest[0] and not rest[0].startswith("-"): rest = rest[1:] return rest if rest and not rest[0].startswith("-") else None @@ -306,12 +313,67 @@ def _runs_unread_code(words): for word in words[1:]) -def _recorded_argv(item): +def _python_heredoc(script): + """Read one quoted Python stdin script as the equivalent visible -c argument.""" + head, newline, body = script.partition("\n") + match = re.fullmatch(r'''(.*?)\s*<<(['"])([A-Za-z_]\w*)\2\s*''', head) + if not newline or not match: + return None + try: + argv = shlex.split(match[1]) + except ValueError: + return None + if (len(argv) != 2 or argv[1] != "-" + or not re.fullmatch(r"python(?:[23](?:\.\d+)?)?", _program(argv[0]))): + return None + lines = body.rstrip("\r\n").split("\n") + if lines[-1].removesuffix("\r") != match[3] or any( + line.removesuffix("\r") == match[3] for line in lines[:-1]): + return None + return [argv[0], "-c", "\n".join(lines[:-1])] + + +def _inline_python_retrieval(argv, cwd, corpus): + """Flag visible references to the knowledge API, tools or corpus.""" + if (len(argv) != 3 or argv[1] != "-c" + or not re.fullmatch(r"python(?:[23](?:\.\d+)?)?", _program(argv[0]))): + return False + try: + tree = ast.parse(argv[2]) + except SyntaxError: + return True + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + else: + module = node.module or "" + names = [module, *(f"{module}.{alias.name}" for alias in node.names)] + if any(name in ("inferrsi.knowledge", "inferrsi.apps.cli") + or name.startswith(("inferrsi.knowledge.", "inferrsi.apps.cli.")) + for name in names): + return True + if not isinstance(node, ast.Constant) or not isinstance(node.value, str): + continue + value = node.value + try: + words = shlex.split(value) + except ValueError: + words = [] + if words and (_program(words[0]) in (*_TOOLS, "inferrsi", "inferrsi.py") + or knowledge_invocation(words)): + return True + if cwd is not None and Path(os.path.normpath(cwd / value)).is_relative_to(corpus): + return True + return False + + +def _recorded_argv(item, *, submission=False): original_argv = item.get("command") if (not isinstance(original_argv, list) or not original_argv or not all(isinstance(arg, str) for arg in original_argv)): return None, False - argv = _without_env(original_argv) + argv = _without_env(original_argv, allow_unset=submission) if not argv: return None, False multiline = False @@ -323,10 +385,16 @@ def _recorded_argv(item): if script is None: # Code this reader cannot see may still have searched. return None, False - try: - argv, multiline = _shell_argv(script, for_commands=True) - except ValueError: - return None, False + argv = _python_heredoc(script) + if argv is None: + try: + argv, multiline = _shell_argv(script, for_commands=True) + except ValueError: + return None, False + if submission and argv: + argv = _without_env(argv, allow_unset=True) + if not argv: + return None, False # After one unwrap, each simple command is checked as the same command run # directly would be. Its program follows any reserved words and NAME=value words. command = [] @@ -349,10 +417,30 @@ def _command(item, corpus): if not argv: return None, True, None tool = _program(argv[0]) + if _inline_python_retrieval(argv, _path(item.get("cwd")), corpus): + return None, False, None if compound: in_scope = any(_program(word) in _TOOLS or knowledge_invocation(argv[index:]) for index, word in enumerate(argv)) - return None, not in_scope, None + if not in_scope: + return None, True, None + # Exclude only static file operations whose individual scopes are all + # outside the corpus. A cwd change, pipe or redirection needs review. + if any(word in ("|", ">", ">>", "<") for word in argv): + return None, False, None + command = [] + for word in [*argv, ";"]: + if word in (";", "&&", "||"): + if command: + if _program(command[0]) in ("cd", "pushd", "popd"): + return None, False, None + event, complete, _ = _command({**item, "command": command}, corpus) + if event is not None or not complete: + return None, False, None + command = [] + else: + command.append(word) + return None, True, None code, output = item.get("exit_code"), item.get("aggregated_output") if call := knowledge_invocation(argv): return decode_knowledge(call, code, output) @@ -450,19 +538,8 @@ def _archive_text(value, corpus, limit=_MAX_PASSAGE_CHARS): return fields -def _passage(ref, line, text, corpus, quotes=()): - excerpt_only = False - if len(text) > _MAX_PASSAGE_CHARS and quotes: - spans = [(pos, pos + len(quote)) for quote in quotes if (pos := text.find(quote)) >= 0] - if spans: - first = min(start for start, _ in spans) - last = max(end for _, end in spans) - if last > _MAX_PASSAGE_CHARS and last - first <= _MAX_PASSAGE_CHARS: - text, excerpt_only = text[first:last], True - safe = _archive_text(text, corpus) - if excerpt_only: - safe["truncated"] = True - return {"ref": ref, "line": line, **safe} +def _passage(ref, line, text, corpus): + return {"ref": ref, "line": line, **_archive_text(text, corpus)} def _unique_candidates(candidates): @@ -512,9 +589,13 @@ def _delivery(event, spec, join, corpus, event_line, selections, excerpts): if resource := spec.get("resource"): path, body = resource ref, = refs - base["visible_resources"] = [{"ref": ref, "path": path}] + bounds = event["materials"][0].get("content_range") + extent = {"content_range": bounds} if bounds else {} + base["visible_resources"] = [{"ref": ref, "path": path, **extent}] candidates = [{"ref": ref, "path": path, "line": index, "text": line} - for index, line in enumerate(_output_lines(body), 1) if line.strip()] + for index, line in enumerate(_output_lines(body), + bounds["first_line"] if bounds else 1) + if line.strip()] elif spec["kind"] == "search": observations, _ = _rg_observations( "".join(aggregate_lines), spec["cwd"], corpus, spec["scopes"], spec["mode"], @@ -556,9 +637,20 @@ def _delivery(event, spec, join, corpus, event_line, selections, excerpts): candidates.append({"ref": ref, "line": line_number, "text": text}) excerpts = excerpts if event["action"] == "read" else {} passages, omitted, unmatched = _select_passages(candidates, event_line, selections, excerpts) - safe_passages = [_passage(item["ref"], item["line"], item["text"], corpus, - excerpts.get(item["ref"], ())) - | ({"path": item["path"]} if "path" in item else {}) for item in passages] + safe_passages = [] + for item in passages: + ref, line, text = item["ref"], item["line"], item["text"] + passage = _passage(ref, line, text, corpus) + if "path" in item: + passage["path"] = item["path"] + quoted = citation_excerpts(text, excerpts.get(ref, ())) + if quoted: + location = {key: item[key] for key in ("ref", "path", "line") if key in item} + safe_passages.extend({**location, "text": quote, "quoted": True, + **({"truncated": True} if quote != text else {})} + for quote in quoted) + else: + safe_passages.append(passage) visible_refs = refs[:_MAX_VISIBLE_REFS] omitted_refs = max(0, len(refs) - len(visible_refs)) truncated_passages = sum(item.get("truncated", False) for item in safe_passages) @@ -745,22 +837,29 @@ def _matched_capture(spec, item, join, capture_outputs): if not capture_outputs or join.get("state") != "visible" or join["runtime_truncated"]: return False output = "".join(join["aggregate_lines"]).replace("\r\n", "\n").rstrip("\n") - root = capture_outputs.get((spec["context_id"], output)) - if root is None and spec["context_id"] is None: - root = capture_outputs.get((None, managed_local_output(output))) + if spec["tool"] == "campaign capture-context": + root = capture_outputs.get((spec["context_id"], output)) + else: + envelope = portable_find_return(managed_local_output(output)) + root = capture_outputs.get((None, envelope)) + if (root and spec["context_id"] + and spec["capture"][0] != f"knowledge/{spec['context_id']}.json"): + return False cwd = _path(item.get("cwd")) return (root is not None and cwd is not None and spec["directory"] is not None and (cwd / spec["directory"]).resolve() == root) def read_window(trace: Path, lines: tuple[int, int], corpus: Path, *, archive=False, - selections=None, excerpts=None, capture_outputs=None): + selections=None, excerpts=None, capture_outputs=None, exec_returns=None): """Return window, events, full transient decisions, uncertainty and detail. In archive mode, selections maps a command event's trace line to [(corpus_relative_ref, source_line_or_None), ...]. Requested lines are retained alongside the default first 12 passages per event. Each selected line must be present in the model-facing tool return. + When matching selected captures, exec_returns receives verified complete + serialized command results by their model-facing return line. """ first, last = lines if first < 1 or last < first or not corpus.is_absolute(): @@ -810,6 +909,13 @@ def read_window(trace: Path, lines: tuple[int, int], corpus: Path, *, archive=Fa continue seen.add(event_id) event, complete, spec = _command(item, corpus) + # A selected capture represents its own Find or Read exactly once. With + # no selected capture the CLI return is still evidence in its own right. + if spec and spec.get("capture") and capture_outputs and ( + "reference", *spec["capture"]) in capture_outputs: + spec = {**spec, "kind": "captured_search", + "tool": event["tool"], "action": event["action"]} + event, complete = None, False commands.append((number, item, event_id, event, complete, spec)) if event is not None: events.append(dict(event, trace_line=number, event_id=event_id)) @@ -823,9 +929,11 @@ def read_window(trace: Path, lines: tuple[int, int], corpus: Path, *, archive=Fa reviewed_commands = (commands if archive else [ row for row in commands if row[-1] and row[-1]["kind"] in ("knowledge", "captured_search") ]) - if reviewed_commands: - joinable = [(line, item, event_id) for line, item, event_id, _, _, _ in reviewed_commands] - joins = correlate_window(trace, joinable, meta_cwd, (first, last)) + to_join = commands if exec_returns is not None else reviewed_commands + if to_join: + joinable = [(line, item, event_id) for line, item, event_id, _, _, _ in to_join] + joins = correlate_window(trace, joinable, meta_cwd, (first, last), + exec_returns=exec_returns) event_by_line = {event["trace_line"]: event for event in events} for line, item, event_id, event, complete, spec in reviewed_commands: if spec and spec["kind"] == "captured_search": @@ -833,7 +941,7 @@ def read_window(trace: Path, lines: tuple[int, int], corpus: Path, *, archive=Fa uncertain.remove(line) elif archive: unresolved_details.append(_detail( - f"file-{line}", line, "search", "capture_unverified", + f"file-{line}", line, spec.get("action", "search"), "capture_unverified", {"tool": spec["tool"]}, )) continue diff --git a/src/inferrsi/apps/views/codex_tool_returns.py b/src/inferrsi/apps/views/codex_tool_returns.py index 56542804d..655a156d4 100644 --- a/src/inferrsi/apps/views/codex_tool_returns.py +++ b/src/inferrsi/apps/views/codex_tool_returns.py @@ -14,6 +14,8 @@ _SHELLS = ("sh", "bash", "zsh", "dash") _MAX_JOIN_CHARS = 1_000_000 _MAX_JOIN_LINES = 8_000 +_JS_STRING = r'''"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`''' +_TOOL_HEADER = re.compile(r"^(?:Script completed\nWall time[^\n]*\n)?Output:\n") def _output_lines(text, *, keepends=False): @@ -58,35 +60,70 @@ def _signature(item): def _js_string_property(source, name): - pattern = (r"(?:\{\s*|,\s*)" + re.escape(name) - + r"\s*:\s*(\"(?:\\.|[^\"\\])*\")") + key = rf'''(?:{re.escape(name)}|"{re.escape(name)}"|'{re.escape(name)}')''' + pattern = (r"(?:\{\s*|,\s*)" + key + + rf"\s*:\s*({_JS_STRING})(?=\s*[,}}])") matches = re.findall(pattern, source) if len(matches) != 1: return None, False + literal = matches[0] + delimiter = literal[0] + + # Normalize delimiters and multiline templates to JSON string syntax. + # Interpolation and expressions cannot identify an authored command. + def json_escape(match): + token = match[0] + if token == "${" and delimiter == "`": + raise ValueError("dynamic template") + if token in (r"\'", r"\`", r"\$"): + return token[1:] + return json.dumps(token)[1:-1] if token in ('"', "\n", "\r") else token + try: - value = json.loads(matches[0]) - except json.JSONDecodeError: + if delimiter != '"': + literal = '"' + re.sub(r'\\.|[\r\n"]|\$\{', json_escape, literal[1:-1]) + '"' + value = json.loads(literal) + except ValueError: return None, False return (value, True) if isinstance(value, str) else (None, False) +def _emits_exec_result(source): + """Recognize code-mode calls that print one complete exec_command result.""" + # A quoted shell command can contain braces, JS-looking text and semicolons. + source = re.sub(_JS_STRING, '""', source).strip() + invocation = r"await\s+tools\.exec_command\s*\(\s*\{[^{}();]*\}\s*\)" + binding = re.match(r"(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*" + invocation, source) + if binding: + value = re.escape(binding[1]) + source = source[binding.end():].lstrip().removeprefix(";").lstrip() + else: + value = invocation + value = rf"(?:{value}|\(\s*{value}\s*\))" + return re.fullmatch(rf"text\(\s*(?:{value}|JSON\.stringify\(\s*{value}\s*\))\s*\)\s*;?", + source) is not None + + def _outer_call_spec(row, meta_cwd): payload = row.get("payload", {}) if not isinstance(payload, dict): return None payload_type, name = payload.get("type"), payload.get("name") command = workdir = None + emits_exec_result = False if payload_type == "custom_tool_call" and name in ("exec", "exec_command"): source = payload.get("input") if not isinstance(source, str): return None + emits_exec_result = name == "exec" and _emits_exec_result(source) command, valid = _js_string_property(source, "cmd") if not valid: command, valid = _js_string_property(source, "command") if not valid: return None workdir, workdir_set = _js_string_property(source, "workdir") - if not workdir_set and re.search(r"(?:\{\s*|,\s*)workdir\s*:", source): + if not workdir_set and re.search( + r'''(?:\{\s*|,\s*)(?:workdir|"workdir"|'workdir')\s*:''', source): return None if not workdir_set: workdir = None @@ -118,23 +155,101 @@ def _outer_call_spec(row, meta_cwd): keys.add(("argv", tuple(shlex.split(command)))) except ValueError: pass - return {"call_id": call_id, "cwd": cwd.as_posix(), "keys": keys} + return {"call_id": call_id, "cwd": cwd.as_posix(), "keys": keys, + "emits_exec_result": emits_exec_result} + +def _batch_launch_spec(row, meta_cwd): + """Identify one directly printed launch result among separate JS statements.""" + payload = row.get("payload", {}) + source = payload.get("input") + if (payload.get("type") != "custom_tool_call" or payload.get("name") != "exec" + or not isinstance(source, str)): + return None + statements, start = [], 0 + # Semicolons inside shell commands and other string values are not JS boundaries. + for token in re.finditer(_JS_STRING + "|;", source): + if token[0] == ";": + statements.append(source[start:token.start()]) + start = token.end() + statements.append(source[start:]) + matches = [] + for statement in statements: + call = _outer_call_spec({**row, "payload": {**payload, "input": statement}}, meta_cwd) + if call and call["emits_exec_result"]: + matches.append({**call, "batched_launch": True}) + return matches[0] if len(matches) == 1 else None -def _response_text(row): + +def _response_chunks(row, verified_text=None): + if verified_text is not None: + return [verified_text] payload = row.get("payload", {}) value = payload.get("output") if isinstance(payload, dict) else None if isinstance(value, str): - joined = value - elif isinstance(value, list): - joined = "".join( - part.get("text", "") for part in value + return [value] + if isinstance(value, list): + return [ + part["text"] for part in value if isinstance(part, dict) and part.get("type") == "input_text" and isinstance(part.get("text"), str) - ) - else: + ] + return None + + +def _response_text(row, verified_text=None): + chunks = _response_chunks(row, verified_text) + return None if chunks is None else "".join(chunks) + + +def _exec_result(row): + """Read the separate code-mode header and one serialized command result.""" + payload = row["payload"] + blocks = payload.get("output") + if (payload["type"] != "custom_tool_call_output" or not isinstance(blocks, list) + or len(blocks) != 2): + return None + chunks = _response_chunks(row) + if len(chunks) != 2 or not _TOOL_HEADER.fullmatch(chunks[0]): + return None + try: + result = json.loads(chunks[1]) + except (ValueError, RecursionError): + return None + if (not isinstance(result, dict) or not isinstance(result.get("chunk_id"), str) + or type(result.get("wall_time_seconds")) not in (int, float) + or not isinstance(result.get("output"), str)): + return None + return result + + +def _exec_result_text(row, exit_code): + result = _exec_result(row) + if (not result or type(result.get("exit_code")) is not int or result["exit_code"] != exit_code + or result.get("session_id") is not None): return None - return joined + return result["output"] + + +def _started_process(row, item, *, batched=False): + if batched: + blocks = row.get("payload", {}).get("output") + results = [] + if isinstance(blocks, list) and len(blocks) > 1: + for block in blocks[1:]: + candidate = {"payload": {**row["payload"], "output": [blocks[0], block]}} + result = _exec_result(candidate) + if result and str(result.get("session_id")) == str(item.get("process_id")): + results.append(result) + result = results[0] if len(results) == 1 else None + else: + result = _exec_result(row) + return (result is not None and "exit_code" not in result + and type(result.get("session_id")) is int + and str(result["session_id"]) == str(item.get("process_id")) + and item.get("source") == "unified_exec_startup" + and (item.get("status") == "completed" + or (item.get("status") == "failed" and item.get("exit_code") == 2))) def _truncation_marker(aggregate, response): @@ -151,12 +266,12 @@ def _truncation_marker(aggregate, response): return False -def _match_output_lines(aggregate, response): +def _match_output_lines(aggregate, response, *, tool_header=True): """Map only exact aggregate lines present in the outer call result.""" # Some producers prepend a tool header. Only remove a known envelope, # and leave an exact source body containing its own "Output:" intact. - if response != aggregate: - header = re.match(r"^(?:Script completed\nWall time[^\n]*\n)?Output:\n", response) + if tool_header and response != aggregate: + header = _TOOL_HEADER.match(response) if header: response = response[header.end():] if max(len(aggregate), len(response)) > _MAX_JOIN_CHARS: @@ -180,7 +295,8 @@ def _match_output_lines(aggregate, response): return indices, True, None if indices else "no_exact_output_lines" -def correlate_window(trace, commands, meta_cwd, window_lines): +def correlate_window(trace, commands, meta_cwd, window_lines, *, exec_returns=None, + submissions=False): """Join each command to one exact enclosing call/result pair in this window.""" first, last = window_lines command_rows, calls, outputs = [], [], {} @@ -205,7 +321,8 @@ def correlate_window(trace, commands, meta_cwd, window_lines): command_rows.append((line_number, item)) if row.get("type") != "response_item" or not isinstance(payload, dict): continue - call = _outer_call_spec(row, meta_cwd) + call = (_outer_call_spec(row, meta_cwd) + or (_batch_launch_spec(row, meta_cwd) if submissions else None)) if call: call["line"] = line_number calls.append(call) @@ -234,17 +351,21 @@ def correlate_window(trace, commands, meta_cwd, window_lines): if len(call_outputs) != 1: continue return_line, output_row = call_outputs[0] - if return_line < event_line: + pending = return_line < event_line + if pending and not (submissions and call["emits_exec_result"] + and _started_process(output_row, item, + batched=call.get("batched_launch", False))): continue covered = [] for line, candidate in command_rows: cwd = _path(candidate.get("cwd")) - if (call["line"] <= line <= return_line and cwd is not None - and cwd.as_posix() == signature[0] + in_call = (line > return_line and candidate.get("process_id") == item["process_id"] + if pending else call["line"] <= line <= return_line) + if (in_call and cwd is not None and cwd.as_posix() == signature[0] and _command_key(candidate) == signature[1]): covered.append(line) if len(covered) == 1 and covered[0] == event_line: - matching.append((call["line"], return_line, output_row)) + matching.append((call, return_line, output_row)) elif event_line in covered: ambiguous_command = True if len(matching) != 1: @@ -252,22 +373,37 @@ def correlate_window(trace, commands, meta_cwd, window_lines): joins[event_id] = {"state": "unknown", "runtime_truncated": None, "reason": reason} continue - call_line, return_line, output_row = matching[0] - response = _response_text(output_row) + call, return_line, output_row = matching[0] + call_line = call["line"] + if return_line < event_line: + # The process ID proves who started this command, not its output. + joins[event_id] = {"state": "unknown", "runtime_truncated": None, + "launch_line": call_line, "reason": "process_running_at_return"} + continue + structured = call["emits_exec_result"] + response = (_exec_result_text(output_row, signature[2]) if structured + else _response_text(output_row)) if response is None: joins[event_id] = {"state": "unknown", "runtime_truncated": None, "call_line": call_line, - "reason": "outer_result_has_no_text"} + "reason": ("exec_result_unverified" if structured + else "outer_result_has_no_text")} continue - indexes, truncated, reason = _match_output_lines(signature[3], response) + indexes, truncated, reason = _match_output_lines(signature[3], response, + tool_header=not structured) if reason is not None: joins[event_id] = {"state": "unknown", "runtime_truncated": truncated, "call_line": call_line, "reason": reason} + if submissions and reason == "output_bytes_do_not_match": + joins[event_id]["returned_text"] = (_TOOL_HEADER.sub("", response, count=1) + if not structured else response) continue joins[event_id] = { "state": "visible", "runtime_truncated": truncated, "line_indexes": indexes, "aggregate_lines": _output_lines(signature[3], keepends=True), "call_line": call_line, "return_line": return_line, } + if exec_returns is not None and structured and not truncated and signature[2] == 0: + exec_returns[return_line] = response return joins diff --git a/src/inferrsi/apps/views/comparison_report.py b/src/inferrsi/apps/views/comparison_report.py index a7997f3ab..d6c41c701 100644 --- a/src/inferrsi/apps/views/comparison_report.py +++ b/src/inferrsi/apps/views/comparison_report.py @@ -425,9 +425,21 @@ def table(headers, rows): if isinstance(trial.get("evidence"), str): evidence.append(("Evidence reference", trial["evidence"])) table(("Evidence field", "Value"), evidence) + required = trial.get("knowledge_delivery") or {} + if required.get("requests"): + legacy = required.get("budget_source") != "experiment_plan" + request_column = ("Requested bytes",) if legacy else () + table(("First-round search", "Frozen byte limit", *request_column, + "Delivered UTF-8 bytes", "Required card body receipt"), [ + (request["search_ref"], required["context_bytes"], + *((request["requested_bytes"],) if legacy else ()), + request["delivered_bytes"], (request["body_capture"] or {}).get("path") + or ", ".join(ref["path"] for ref in request.get("body_captures", ())) or None) + for request in required["requests"] + ]) deliveries = trial.get("knowledge_deliveries") or [] if deliveries: - table(("Delivered knowledge",), [ + table(("Knowledge receipts",), [ (entry.get("path") if isinstance(entry, dict) else entry,) for entry in deliveries ]) html.append("") diff --git a/src/inferrsi/apps/views/dashboard_data.py b/src/inferrsi/apps/views/dashboard_data.py index cf5e3b24d..50d5538b8 100644 --- a/src/inferrsi/apps/views/dashboard_data.py +++ b/src/inferrsi/apps/views/dashboard_data.py @@ -711,7 +711,7 @@ def _managed_diagnoses(state: dict, submissions: list) -> list[dict]: rounds_by_id[identity].add(number) for ref in state["contexts"]: identity, number = ref.get("diagnosis_id"), ref.get("round") - if (ref["kind"] == "delivered_context" and identity in rounds_by_id + if (ref["kind"] in ("delivered_context", "knowledge_search") and identity in rounds_by_id and type(number) is int and number > 0): rounds_by_id[identity].add(number) return [ diff --git a/src/inferrsi/apps/views/retrieval_projection.py b/src/inferrsi/apps/views/retrieval_projection.py index f0ae4b2eb..09b3fc271 100644 --- a/src/inferrsi/apps/views/retrieval_projection.py +++ b/src/inferrsi/apps/views/retrieval_projection.py @@ -353,6 +353,23 @@ def read_searches(root: Path, campaign_id, rows, retrievals): return results +def _join_scoped_read(query, record, path, targets): + """Attach one verified read or budget omission to the hit at its recorded revision.""" + resources = {(c["ref"], c["revision"]): c["resources"] for c in record["contexts"]} + omissions = {o["ref"]: o["reason"] for o in record["context_omissions"]} + for hit in query["items"]: + key = (hit["ref"], hit["revision"]) + if key not in targets: + continue + for resource in resources.get(key, ()): + hit["reads"].append({"path": path, "resource": resource["path"]}) + hit["delivered"] = True + if hit["ref"] in omissions: + display = record["retrieval"]["display"] + hit["reads"].append({"path": path, "resource": display.get("content_resource"), + "omission": omissions[hit["ref"]]}) + + def managed_knowledge(root, contexts, submissions=()): """Project managed deliveries and explicit citation targets without card bodies.""" # Older controllers froze cumulative references on submission without recording @@ -375,7 +392,7 @@ def managed_knowledge(root, contexts, submissions=()): if not isinstance(path, str) or Path(path).is_absolute(): continue external_record = kind in ("external_search", "external_read") - if kind != "delivered_context" and not external_record: + if kind not in ("knowledge_search", "delivered_context") and not external_record: continue if external_record and ( type(number) is not int or number < 1 @@ -385,22 +402,35 @@ def managed_knowledge(root, contexts, submissions=()): record, state, digest = _read(root, root / path) if state != "present" or digest != reference.get("sha256"): continue - if kind == "delivered_context": - delivered = {item["ref"] for item in record["contexts"] if item["resources"]} + if not external_record: + delivered = {(c["ref"], c["revision"]) for c in record["contexts"] if c["resources"]} items = [ {**{key: item.get(key) for key in ("ref", "title", "revision")}, - "delivered": item["ref"] in delivered} + "delivered": (item["ref"], item.get("revision")) in delivered} for item in record["items"] ] - if number is not None or path in submitted_rounds: - request = record["request"] + request = record["request"] + parent = reference.get("search_ref") + if parent is not None: + query = queries.get(parent) + if (query is None or query["round"] != number or parent != request.get("search_ref") + or query.get("kind") != "knowledge_search"): + continue + _join_scoped_read(query, record, path, {(i["ref"], i["revision"]) for i in items}) + elif number is not None or path in submitted_rounds: queries[path] = { "round": number, "path": path, "query": request.get("relevance") or request.get("query"), "items": items, } + if kind == "knowledge_search": + queries[path]["kind"] = kind + for item in items: + item["reads"] = [] if number is None: queries[path]["submitted_rounds"] = sorted(submitted_rounds[path]) + if kind == "knowledge_search" or (parent and not delivered): + continue citation = {"source": "local", "retrieval_round": number} citations[path] = {**citation, "ref": path} for item in items: diff --git a/src/inferrsi/apps/views/round_citations.py b/src/inferrsi/apps/views/round_citations.py index ce1e5918f..765841408 100644 --- a/src/inferrsi/apps/views/round_citations.py +++ b/src/inferrsi/apps/views/round_citations.py @@ -13,10 +13,11 @@ ) from .codex_knowledge import _ArgumentError, _parser, cli_arguments -from .codex_search import _recorded_argv +from .codex_search import _SHELL_OPERATORS, _recorded_argv from .codex_tool_returns import _MAX_JOIN_CHARS, _path, correlate_window _CITATION = re.compile(r"\[use ([^\s|\]]+) \| ([^\]\n]+)\]") +_PERSISTENCE_CUT = "\n... command output truncated for persistence ...\n" def _citations(reasons): @@ -30,6 +31,34 @@ def _citations(reasons): yield ref, quote, line.strip() +def submission_receipt(root, number, observation): + """Project the original round response to its retained observation identity.""" + return {"session": str(root), "completed_rounds": number, + "latest_observation": {key: observation[key] for key in ( + "path", "observation_sha256", + )}} + + +def read_round_receipt(root, number, *, project): + from inferrsi.harness.optimization import read_records + + plan, state, _ = read_records(root) + if plan.get("evaluation_mode") == "service_reuse": + raise ValueError("Round submission receipts require an AB/BA project or benchmark") + if plan["task_source"] != ("project" if project else "benchmark"): + raise ValueError("Use the status command for the session's project or benchmark") + if not 1 <= number <= len(state["rounds"]): + raise ValueError("Select a completed round by its one-based number") + return submission_receipt(root, number, state["rounds"][number - 1]) + + +def _round_args(row): + return {"hypothesis": row["hypothesis"], "strategy": row.get("strategy"), + "knowledge_ref": row.get("knowledge_refs") or None, + "alternative": row.get("alternatives") or None, + "selection_reason": row.get("selection_reason")} + + def _managed_citations(root, number): state, status = read_object(root / "state.json", root) rounds = state.get("rounds", []) if status == "present" else [] @@ -49,53 +78,110 @@ def _managed_citations(root, number): if observation["hypothesis"] == reason: notes["command"] = (("campaign", "round") if plan["task_source"] == "project" else ("benchmarks", "session", "round")) - notes["receipts"] = [{ - "session": str(root), "completed_rounds": number, - "latest_observation": {key: observation[key] for key in ( - "path", "hypothesis", "observation_sha256", - )}, - }] + compact = submission_receipt(root, number, observation) + if plan.get("evaluation_mode") != "service_reuse": + notes["status_receipt"] = compact + if observation["assessment"]["status"] == "infrastructure_failure": + notes["blocked_observation"] = { + key: observation[key] for key in ("candidate_sha256", "assessment") + } + notes["receipts"] = [{**compact, "latest_observation": { + **compact["latest_observation"], "hypothesis": reason, + }}] + notes["round_args"] = _round_args(observation) + notes["unique_round"] = sum(_round_args(row) == notes["round_args"] + for row in verified["rounds"]) == 1 except (OSError, ValueError, KeyError, TypeError, IndexError): pass return notes def _receipt_matches(expected, actual): - return isinstance(actual, dict) and all( - _receipt_matches(value, actual.get(key)) if isinstance(value, dict) - else actual.get(key) == value for key, value in expected.items() - ) + if type(expected) is not type(actual): + return False + if isinstance(expected, dict): + return all(key in actual and _receipt_matches(value, actual[key]) + for key, value in expected.items()) + return actual == expected def _submission(item, root, notes): - argv, compound = _recorded_argv(item) - if not argv or compound or item.get("exit_code") != 0: + argv, compound = _recorded_argv(item, submission=True) + code = item.get("exit_code") + # Unquoted shell boundaries have separator tokens. A quoted multiline hypothesis + # remains one argument and must still match the stored round byte for byte. + if (not argv or (compound and any(arg in _SHELL_OPERATORS for arg in argv)) + or type(code) is not int or code not in (0, 2)): return None command = notes["command"] args = cli_arguments(argv) output = item.get("aggregated_output") - if (not args or tuple(args[:len(command)]) != command or not isinstance(output, str) - or len(output) > _MAX_JOIN_CHARS): + if not args or not isinstance(output, str) or not output or len(output) > _MAX_JOIN_CHARS: + return None + operation = tuple(args[:len(command)]) + status = command[-1] == "round" and operation == (*command[:-1], "status") + if operation != command and not status: + return None + # The managed CLI returns 2 for a persisted blocked round as well as for + # argument errors. Only its matching retained observation can identify it. + if code and (status or command[-1] != "round" or "blocked_observation" not in notes): return None try: parsed = _parser().parse_args(args) - response = json.loads(output) - except (_ArgumentError, ValueError, RecursionError): + except _ArgumentError: return None cwd = _path(item.get("cwd")) directory = parsed.directory if command[-1] == "log" else parsed.session - if cwd is None or getattr(parsed, "hypothesis", None) != notes.get("hypothesis"): + if cwd is None or (cwd / directory).resolve() != root: + return None + if status: + expected = notes.get("status_receipt") + if not expected or getattr(parsed, "round_receipt", None) != expected["completed_rounds"]: + return None + elif command[-1] == "round" and any(getattr(parsed, name) != value + for name, value in notes["round_args"].items()): + return None + try: + response = json.loads(output) + except (ValueError, RecursionError): + # A later verified status can identify the observation whose full + # command output the host explicitly cut from the persisted rollout. + return ("round", None) if (not code and operation == command and command[-1] == "round" + and _PERSISTENCE_CUT in output) else None + if command[-1] == "round" and (not isinstance(response, dict) + or type(response.get("completed_rounds")) is not int): + return None + if status: + return ("status", expected) if response == expected else None + if code and not _receipt_matches( + {"state": "blocked", "latest_observation": notes["blocked_observation"]}, response, + ): return None receipt = next((value for value in notes["receipts"] if _receipt_matches(value, response)), None) - return receipt if receipt and (cwd / directory).resolve() == root else None + return (command[-1], receipt) if receipt else None + + +def _visible_summary(join, receipt, stdout): + # Older hosts retained full successful stdout but showed selected + # confirmation fields in the model-facing response. + if "returned_text" not in join: + return False + try: + summary = json.loads(join["returned_text"]) + full = json.loads(stdout) + except (ValueError, RecursionError): + return False + return (isinstance(summary, dict) and type(summary.get("completed_rounds")) is int + and summary["completed_rounds"] == receipt["completed_rounds"] + and _receipt_matches(summary, full)) def _submissions(trace, lines, root, notes): """Locate each authored command and its recorded receipt in the window.""" if not trace or not notes["receipts"]: return {} - commands, receipts = [], {} + commands, operations = [], {} first, last = lines with trace.open("rb") as stream: cwd = _path(json.loads(stream.readline())["payload"].get("cwd")) @@ -112,13 +198,38 @@ def _submissions(trace, lines, root, notes): item = payload.get("item") if (isinstance(item, dict) and item.get("type") == "CommandExecution" and isinstance(item.get("id"), str) - and (receipt := _submission(item, root, notes))): + and (operation := _submission(item, root, notes))): commands.append((number, item, item["id"])) - receipts[item["id"]] = receipt - joins = correlate_window(trace, commands, cwd, lines) if commands else {} - # The persisted round and command stdout establish acceptance. The join - # locates the authored input even when the host summarized its response. - return {join["call_line"]: receipts[key] for key, join in joins.items() if "call_line" in join} + operations[item["id"]] = operation + if not commands: + return {} + managed = notes["command"][-1] == "round" + joins = correlate_window(trace, commands, cwd, lines, submissions=managed) + submitted, starts, confirmations = {}, [], [] + for number, item, key in commands: + kind, receipt = operations[key] + join = joins[key] + visible = join["state"] == "visible" and not join["runtime_truncated"] + if kind == "status": + if visible: + confirmations.append(join["call_line"]) + elif kind == "log": + if "call_line" in join: + submitted[join["call_line"]] = receipt + else: + authored = join.get("launch_line") + summary = (not visible and receipt is not None + and _visible_summary(join, receipt, item["aggregated_output"])) + if join["state"] == "visible" or summary: + authored = join["call_line"] + if receipt and (visible or summary): + submitted[authored] = receipt + starts.append((authored, number)) + if not submitted and len(starts) == 1 and notes.get("unique_round"): + authored, finished = starts[0] + if authored is not None and any(at > finished for at in confirmations): + submitted[authored] = notes["receipts"][0] + return submitted def retained_round_citations(root, campaign, number, trace, lines): @@ -177,13 +288,15 @@ def round_reviews(citations, positions, events): for event in events: delivery = event["delivery"] if (event["action"] != "read" and "context_id" not in event - or delivery["state"] != "visible" or delivery.get("runtime_truncated")): + or delivery["state"] != "visible" or delivery.get("runtime_truncated") + or not delivery.get("passages")): continue line = next((at for at in decision_lines if delivery["return_line"] < at), None) if line is None: continue for p in delivery["passages"]: - if (p["ref"] != ref or quote not in p["text"] + matched = quote == p["text"] if p.get("quoted") else quote in p["text"] + if (p["ref"] != ref or not matched or p.get("redacted") or p.get("root_normalized")): continue revision = next((m.get("revision") for m in event["materials"] @@ -193,7 +306,7 @@ def round_reviews(citations, positions, events): matches[key] = { "ref": ref, "use": "used", "event_line": event["trace_line"], "passage_line": p["line"], "decision_line": line, - "decision_quote": reason, + "decision_quote": reason, "passage_text": p["text"], **({"passage_path": path} if path else {}), } if len(matches) == 1: diff --git a/src/inferrsi/apps/views/round_decision_view.html b/src/inferrsi/apps/views/round_decision_view.html index 1e78dade8..8b6a1f281 100644 --- a/src/inferrsi/apps/views/round_decision_view.html +++ b/src/inferrsi/apps/views/round_decision_view.html @@ -63,7 +63,13 @@ for(const entry of record.items){ const card=item(local,entry.title||entry.ref); field(card,tr('Reference','引用'),entry.ref); - field(card,tr('Delivery','交付'),entry.delivered?tr('Context prepared','已装配上下文'):tr('Context omitted','未装配上下文')); + if(Array.isArray(entry.reads)){ + if(!entry.reads.length)field(card,tr('Read receipts','读取凭据'),tr('No read recorded','暂无读取记录')); + for(const read of entry.reads){ + field(card,read.omission?tr('Read omitted','读取未交付'):tr('Read resource','已读资源'),[read.resource,read.omission].filter(Boolean).join(' · ')); + p(card,read.path,'rd-note'); + } + }else field(card,tr('Delivery','交付'),entry.delivered?tr('Context prepared','已装配上下文'):tr('Context omitted','未装配上下文')); } const result=record.external; if(!result)return; diff --git a/src/inferrsi/apps/views/search_archive.py b/src/inferrsi/apps/views/search_archive.py index 496d4c91b..672828982 100644 --- a/src/inferrsi/apps/views/search_archive.py +++ b/src/inferrsi/apps/views/search_archive.py @@ -13,6 +13,8 @@ ) from inferrsi.harness.records.optimization_log import _unique as _unique_pairs +from .codex_knowledge import mindie_unit_from_key + _REVISION = re.compile(r"[A-Fa-f0-9]{40}|[A-Fa-f0-9]{64}") @@ -71,7 +73,8 @@ def read_archive_review(path): if item["use"] not in ("used", "rejected"): raise ValueError(f"decisions[{index}].use must be used or rejected") ref = item["ref"] - if not isinstance(ref, str) or _relative_location(ref) != ref: + if not isinstance(ref, str) or (_relative_location(ref) != ref + and mindie_unit_from_key(ref) is None): raise ValueError(f"decisions[{index}].ref must be a portable source ref") for key in ("event_line", "decision_line"): if type(item[key]) is not int or item[key] < 1: @@ -131,6 +134,7 @@ def reviewed_uses(review, events, decisions): passages = [entry for entry in delivery.get("passages", []) if isinstance(entry, dict) and entry.get("ref") == item["ref"] and entry.get("line") == item["passage_line"] + and ("passage_text" not in item or entry["text"] == item["passage_text"]) and ("passage_path" not in item or entry.get("path") == item["passage_path"])] if item["passage_line"] is None and delivery.get("archive_omitted"): diff --git a/src/inferrsi/apps/views/search_attribution.py b/src/inferrsi/apps/views/search_attribution.py index 5279ee33f..1ffa4dbe0 100644 --- a/src/inferrsi/apps/views/search_attribution.py +++ b/src/inferrsi/apps/views/search_attribution.py @@ -478,22 +478,28 @@ def import_search(root: Path, *, number: int, trace=None, lines=None, knowledge_ capture_inputs = {key: load_campaign_capture(root, campaign_id, key) for key in capture_ids} capture_returns = dict(review["capture_returns"]) if review else {} + exec_returns = {} if trace and capture_inputs else None options = {} window, events, decisions, uncertain = None, [], {}, [] if trace: if capture_inputs: envelopes = managed_envelopes(capture_inputs) outputs = dict.fromkeys(((None, body) for body in envelopes.values()), root) + outputs.update({("reference", source, digest): root + for _, source, digest in capture_inputs.values()}) outputs.update(dict.fromkeys(capture_receipts(capture_inputs).items(), root)) options["capture_outputs"] = outputs + local_options = dict(options, exec_returns=exec_returns) if capture_inputs else options + window, events, decisions, uncertain, _ = read_window( + trace, lines, knowledge_root, archive=False, **local_options) + if capture_inputs: capture_returns.update(managed_return_lines( trace, lines, {key: body for key, body in envelopes.items() if key not in capture_returns}, - reserved=set(capture_returns.values()), + reserved=set(capture_returns.values()), exec_returns=exec_returns, )) - window, events, decisions, uncertain, _ = read_window( - trace, lines, knowledge_root, archive=False, **options) - return_texts = capture_return_texts(trace, lines, capture_returns, capture_ids) + return_texts = capture_return_texts(trace, lines, capture_returns, capture_ids, + exec_returns=exec_returns) captures = {key: capture_event(key, capture_inputs[key], return_chunks=return_texts.get(key), return_line=capture_returns.get(key)) for key in capture_ids} events.extend(captures.values()) diff --git a/src/inferrsi/apps/views/template.html b/src/inferrsi/apps/views/template.html index 2d865f49e..fa718de15 100644 --- a/src/inferrsi/apps/views/template.html +++ b/src/inferrsi/apps/views/template.html @@ -1232,8 +1232,10 @@

const request=retrieval.request||{}; const assemblyNotRequested=retrieval.retrieval?.assembly==='not_requested'; const budget=assemblyNotRequested?translated('Not requested'):Number.isFinite(request.context_bytes)?`${request.context_bytes} bytes`:translated('Not recorded'); + const scoped=['find','read'].includes(retrieval.retrieval?.entrypoint); + const budgetText=scoped&&!Object.hasOwn(request,'context_bytes')?'':` · ${scoped?'requested context budget':'context budget'} ${budget}`; const contextSize=assemblyNotRequested?translated('Assembly not requested'):Number.isFinite(retrieval.context_bytes_used)?`${retrieval.context_bytes_used} bytes of context`:translated('Context bytes not recorded'); - detailLine(grid,'Search request',[request.query?`query: ${request.query}`:'',request.relevance?`relevance: ${request.relevance}`:'',request.ids&&request.ids.length?`ids: ${request.ids.join(', ')}`:'',request.backend?`backend: ${request.backend}`:'',`limit ${request.limit ?? translated('Not recorded')} · context budget ${budget}`].filter(Boolean).join('\n'),true); + detailLine(grid,'Search request',[request.query?`query: ${request.query}`:'',request.relevance?`relevance: ${request.relevance}`:'',request.ids&&request.ids.length?`ids: ${request.ids.join(', ')}`:'',request.backend?`backend: ${request.backend}`:'',`limit ${request.limit ?? translated('Not recorded')}${budgetText}`].filter(Boolean).join('\n'),true); detailLine(grid,'Captured',`${retrieval.captured_at || 'Time not recorded'} · ${retrieval.captured_by || ''} · ${contextSize}`,true); const selectedBox=node('div',undefined,'detail-line');selectedBox.appendChild(node('strong','Selected by search')); const included=new Set(retrieval.contexts.map(context=>context.ref)); diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index a385a3e0e..f6cf792bb 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -190,11 +190,16 @@ def _freeze_knowledge_delivery(manifest, task): if "knowledge_delivery" not in manifest: return None requirement = manifest["knowledge_delivery"] - if (not isinstance(requirement, dict) or requirement.keys() != {"query", "scenario", "ref"} - or any(not isinstance(value, str) or not value.strip() - for value in requirement.values()) + fields = {"query", "scenario", "ref"} + if (not isinstance(requirement, dict) + or requirement.keys() not in (fields, fields | {"context_bytes"}) + or any(not isinstance(requirement[key], str) or not requirement[key].strip() + for key in fields) or not requirement["ref"].startswith("package:")): raise ValueError(f"{task}: knowledge_delivery requires a query, scenario and package ref") + limit = requirement.get("context_bytes", KNOWLEDGE_CONTEXT_BYTES) + if type(limit) is not int or limit < 0: + raise ValueError(f"{task}: knowledge_delivery.context_bytes must be a nonnegative integer") card = KnowledgeReader().read(requirement["ref"]).view() scenario = SCENARIO_ALIASES.get(requirement["scenario"], requirement["scenario"]) card_scenario = card.get("scenario") @@ -203,7 +208,7 @@ def _freeze_knowledge_delivery(manifest, task): raise ValueError(f"{task}: expected a package knowledge card for the declared scenario") return {**requirement, "scenario": scenario, "revision": card["revision"], "body_sha256": card["resources"]["record.json"], - "context_bytes": KNOWLEDGE_CONTEXT_BYTES} + "context_bytes": limit, "budget_source": "experiment_plan"} def _knowledge_requirement(plan, trial): @@ -271,7 +276,7 @@ def _prepare_at(config, sources, runtime, task_settings, root): "workspace": workspace.relative_to(root).as_posix()}) plan = {"schema_version": 1, "focus": "knowledge", "config": config, "metrics_policy": POLICY, - "diagnosis_required": True, + "diagnosis_required": True, "knowledge_command": "find", "parameter_sources": sources, "task_settings": task_settings, "runtime_files": {key: value for key, value in runtime_files.items() if key not in knowledge_files}, @@ -487,14 +492,28 @@ def _prompt(root, plan, trial, workspace): ) retrieval = "" requirement = _knowledge_requirement(plan, trial) + # Dispatch and retry also operate on experiments that froze an older runtime. + scoped_find = plan.get("knowledge_command") == "find" + lookup = "find with --session " if scoped_find else "benchmarks session knowledge" if requirement is not None: - knowledge = [*start[:6], "knowledge", "--session", str(campaign), - "--query", requirement["query"], "--scenario", requirement["scenario"], - "--context-bytes", str(requirement["context_bytes"])] + entry = ([*start[:4], "find", requirement["query"], "--session", str(campaign)] + if scoped_find else + [*start[:6], "knowledge", "--session", str(campaign), + "--query", requirement["query"]]) + knowledge = [*entry, "--scenario", requirement["scenario"]] + if requirement.get("budget_source") != "experiment_plan": + knowledge.extend(("--context-bytes", str(requirement["context_bytes"]))) retrieval = ( "After diagnosis, run the frozen knowledge request before the first round. " f"Knowledge argv (a JSON array, execute without a shell): {json.dumps(knowledge)}\n" ) + if requirement.get("budget_source") == "experiment_plan": + retrieval += (f"The first-round limit is {requirement['context_bytes']} UTF-8 resource " + "bytes from this search, including repeated reads.\n") + if scoped_find: + retrieval += (f"Select the hit whose material_ref equals {requirement['ref']} and " + "execute its read_args with the same runtime before the first round. " + "Retain the returned read receipt.\n") return ( f"Run complete RSI optimization: {trial['task']}, condition {trial['condition']}.\n" f"Work only in {workspace}. Set PYTHONPATH to {runtime}; disable bytecode. " @@ -508,7 +527,7 @@ def _prompt(root, plan, trial, workspace): "Preserve shared dependencies. " "Record actual model/effort from the host observation when available; " "requested settings alone do not establish actual settings.\n" - "The permitted optimization knowledge source is this runtime's session knowledge operation " + f"The permitted optimization knowledge source is this runtime's {lookup} " "when enabled. Other skill libraries, stores, external knowledge tools, web research " "and prior solutions are excluded in both. Public task/command operating instructions " "and target library APIs remain available to both. The off runtime omits the corpus. " @@ -520,7 +539,7 @@ def _prompt(root, plan, trial, workspace): f"Read frozen TASK.md. {diagnosis}{retrieval}" "Analyze feedback and choose a justified optimization each round. " "Submit candidate, --strategy and --hypothesis; cite delivered --knowledge-ref paths when " - "used and retain failures. When knowledge is enabled, use session knowledge for a " + f"used and retain failures. When knowledge is enabled, use {lookup} for a " "specific implementation question after diagnosing the bottleneck. Complete frozen " "rounds and independently retest the selected candidate " "using session final. Never replace final with a search score.\n" @@ -655,42 +674,164 @@ def _native_window(host, payload): "source": "caller_exported_terminal_native_receipt"}, None +def _verified_capture(snapshot, reference, campaign_id): + path = reference["path"] + source = snapshot.file(path, "knowledge", reference["sha256"], document=True) + if snapshot.verified([source]): + capture, _ = verify_capture(snapshot.documents[path]) + if (capture is not None and capture["campaign_id"] == campaign_id + and capture["assembled_text"] == assemble_context_text(capture["contexts"])): + return capture + return None + + +def _card_request(request, requirement): + scenario = request.get("scenario") + frozen = requirement["scenario"] + return (request.get("relevance") == requirement["query"] + and (not request.get("query") or request["query"] == requirement["query"]) + and SCENARIO_ALIASES.get(scenario, scenario) == SCENARIO_ALIASES.get(frozen, frozen)) + + +def _complete_card_pages(pages, body_sha256): + """Reconstruct bytes from verified intervals; keep the receipts that supplied them.""" + body = bytearray() + contributors = [] + total = pages[0][0]["total_bytes"] + for bounds, data, receipt in sorted(pages, key=lambda p: (p[0]["start"], -p[0]["end"])): + start, end = bounds["start"], bounds["end"] + if bounds["total_bytes"] != total or start > len(body): + return [] + overlap = min(end, len(body)) - start + if body[start:start + overlap] != data[:overlap]: + return [] + if end > len(body): + body.extend(data[overlap:]) + contributors.append(receipt) + if len(body) == total and hashlib.sha256(body).hexdigest() == body_sha256: + return contributors + return [] + + def _card_delivery(snapshot, campaign_id, references, requirement): - """Match the frozen request and card body against verified first-round inputs.""" - budget_problem = None - for reference in references: - if reference.get("kind") != "delivered_context": + """Account for all actual resources in each frozen query's verified first-round inputs.""" + limit = requirement["context_bytes"] + plan_budget = requirement.get("budget_source") == "experiment_plan" + result = {"ref": requirement["ref"], "revision": requirement["revision"], "capture": None, + "context_bytes": limit, "requests": []} + if plan_budget: + result["budget_source"] = "experiment_plan" + groups = {} + pages = {} + card_hits = set() + evidence_problem = False + unknown_totals = set() + for ref in references: + kind = ref.get("kind") + if kind not in ("knowledge_search", "delivered_context"): continue - path = reference["path"] - source = snapshot.file(path, "knowledge", reference["sha256"], document=True) - if not snapshot.verified([source]): - continue - capture, _ = verify_capture(snapshot.documents[path]) - if (capture is None or capture["campaign_id"] != campaign_id - or capture["request"].get("relevance") != requirement["query"] - or capture["request"].get("scenario") != requirement["scenario"]): + capture = _verified_capture(snapshot, ref, campaign_id) + request = capture["request"] if capture else {} + search_ref = ref.get("search_ref") or request.get("search_ref") + if search_ref: + group = groups.get(search_ref) + if group is None: + if capture and _card_request(request, requirement): + # A later valid query cannot account for this read's missing Find. + evidence_problem = True + continue + if capture is None: + evidence_problem = True + unknown_totals.add(search_ref) + continue + if (request.get("search_ref") != search_ref or not _card_request(request, requirement) + or request.get("context_bytes") != group.get("requested_bytes")): + evidence_problem = True + elif capture and _card_request(request, requirement): + # Older managed commands ranked and delivered in one receipt. + search_ref = ref["path"] + group = {"search_ref": search_ref} + if not plan_budget: + group["requested_bytes"] = request.get("context_bytes") + elif kind != "knowledge_search" or "context_bytes" in request: + evidence_problem = True + group.update(delivered_bytes=0, body_capture=None, omitted_for_budget=False) + groups[search_ref] = group + result["requests"].append(group) + if kind == "knowledge_search": + if any(hit.get("ref") == requirement["ref"] + and hit.get("revision") == requirement["revision"] + for hit in capture["items"]): + card_hits.add(search_ref) + continue + if (capture.get("retrieval") or {}).get("entrypoint") == "read": + evidence_problem = True + continue + card_hits.add(search_ref) + else: continue + # Historical tools declared their own cap; the current protocol measures + # delivered resource bytes directly against the frozen experiment plan. budget = capture.get("context_budget") - if (not isinstance(budget, dict) or type(budget.get("max_bytes")) is not int - or budget["max_bytes"] != requirement["context_bytes"] - or capture["request"].get("context_bytes") != requirement["context_bytes"]): - budget_problem = budget_problem or "context budget differs from the frozen plan" + if plan_budget and ("context_bytes" in request or budget is not None): + evidence_problem = True + if (not plan_budget and (budget is not None or search_ref == ref["path"]) + and (not isinstance(budget, dict) or type(budget.get("max_bytes")) is not int + or budget["max_bytes"] != group["requested_bytes"])): + evidence_problem = True + for context in capture["contexts"]: + for resource in context["resources"]: + data = resource["content"].encode("utf-8") + group["delivered_bytes"] += len(data) + if (context["ref"] != requirement["ref"] or search_ref not in card_hits + or context["revision"] != requirement["revision"] + or resource["path"] != "record.json"): + continue + bounds = resource.get("content_range") + if bounds is not None: + if (not request.get("search_ref") + or resource.get("source_sha256") != requirement["body_sha256"]): + continue + pages.setdefault(search_ref, []).append((bounds, data, ref)) + if bounds["start"] != 0 or bounds["end"] != bounds["total_bytes"]: + continue + if (resource["sha256"] == requirement["body_sha256"] + and group["body_capture"] is None): + group["body_capture"] = ref + if any(o.get("ref") == requirement["ref"] and o.get("reason") == "context_limit" + for o in capture["context_omissions"]): + group["omitted_for_budget"] = True + + for search_ref, received in pages.items(): + group = groups[search_ref] + if group["body_capture"] is None: + group["body_captures"] = _complete_card_pages(received, requirement["body_sha256"]) + if evidence_problem: + for search_ref in unknown_totals: + groups[search_ref]["delivered_bytes"] = None + return result, "First-round knowledge request or linked delivery could not be verified" + for group in groups.values(): + used = group["delivered_bytes"] + if (plan_budget or group["requested_bytes"] == limit) and used > limit: + return result, (f"Frozen knowledge context budget exceeded before the first round " + f"({used} UTF-8 resource bytes delivered, {limit} allowed)") + if not plan_budget and any(g["delivered_bytes"] and (type(g["requested_bytes"]) is not int + or g["requested_bytes"] != limit) for g in groups.values()): + return result, "First-round knowledge context budget differs from the frozen plan" + for group in groups.values(): + if not plan_budget and group["requested_bytes"] != limit: continue - if any(omission.get("ref") == requirement["ref"] - and omission.get("reason") == "context_limit" - for omission in capture["context_omissions"]): - budget_problem = "context budget exceeded" - matching_body = any( - resource["path"] == "record.json" and resource["sha256"] == requirement["body_sha256"] - for context in capture["contexts"] - if (context["ref"] == requirement["ref"] - and context["revision"] == requirement["revision"]) - for resource in context["resources"] - ) - if (matching_body - and capture["assembled_text"] == assemble_context_text(capture["contexts"])): - return reference, None - return None, budget_problem + if group["body_capture"]: + result["capture"] = group["body_capture"] + return result, None + if group.get("body_captures"): + result["captures"] = group["body_captures"] + return result, None + gap = ("Required knowledge card body was not delivered before the first round: " + + requirement["ref"]) + if any(g["omitted_for_budget"] for g in groups.values()): + gap += " (recorded context budget omission)" + return result, gap def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=None): @@ -772,7 +913,7 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non result["gaps"].append("Campaign runtime identity differs from the frozen runtime") result["knowledge_deliveries"] = control["contexts"] if trial["condition"] == "off" and control["contexts"]: - result["gaps"].append("Knowledge was delivered in the off condition") + result["gaps"].append("Knowledge retrieval was recorded in the off condition") requirement = _knowledge_requirement(plan, trial) if requirement is not None: # The verified observation pins the inputs snapshotted at round start. @@ -780,16 +921,9 @@ def _trial_result(root, plan, trial, host, payload, *, workspace, host_error=Non if (control["rounds"] and delivery["rounds"] and delivery["rounds"][0].get("record_verified")): first_inputs = control["rounds"][0]["contexts"] - matched, budget_problem = _card_delivery( + result["knowledge_delivery"], gap = _card_delivery( snapshot, delivery["campaign"]["id"], first_inputs, requirement) - result["knowledge_delivery"] = { - "ref": requirement["ref"], "revision": requirement["revision"], "capture": matched, - } - if matched is None: - gap = ("Required knowledge card body was not delivered before the first round: " - f"{requirement['ref']}") - if budget_problem: - gap += f" ({budget_problem})" + if gap: result["gaps"].append(gap) result["usage"].update(delivery["usage"]) result["benchmark_metrics"] = delivery.get("benchmark_metrics") diff --git a/src/inferrsi/apps/workflows/campaign.py b/src/inferrsi/apps/workflows/campaign.py index 3340eca2d..52f2fefea 100644 --- a/src/inferrsi/apps/workflows/campaign.py +++ b/src/inferrsi/apps/workflows/campaign.py @@ -12,7 +12,7 @@ from inferrsi import __version__ from inferrsi.harness.records import campaign_records, knowledge_capture -from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method +from inferrsi.knowledge._skill_selection import validate_relevance_method from inferrsi.knowledge.catalog import BACKENDS from inferrsi.knowledge.context_projection import ( PROVENANCE_FIELDS, @@ -41,20 +41,14 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "", sources: tuple[str, ...] = ("package",), ranking_policy=None, diagnosis_binding: dict | None = None) -> tuple[Path, str]: - """Run ``collect`` with a context budget and keep its complete envelope. - - The capture is produced by the same ``collect`` operation the agent uses, - not by a caller narrative. Returns the new campaign-relative file and its - SHA-256. - """ + """Save a bounded snapshot of explicit materials or a filtered inventory.""" if revisions and not ids: raise ValueError("Revision pins require explicit IDs (--id-ref)") validate_relevance_method(relevance_method) + if query.strip() or (relevance is not None and not ids): + raise ValueError("Use find QUERY --session DIR for discovery. " + "A snapshot accepts --relevance only with --id-ref.") campaign = knowledge_capture.capture_campaign(root, context_id) - if ids is None and (query.strip() or relevance): - relevance_method = FIND_RELEVANCE - if backend is None: - backend = campaign.get("backend") pins = {"revisions": revisions} if revisions else {} ranking = {"ranking_policy": ranking_policy} if ranking_policy is not None else {} result = reader.collect( diff --git a/src/inferrsi/apps/workflows/knowledge.py b/src/inferrsi/apps/workflows/knowledge.py index f6adedd1b..1878d5d2e 100644 --- a/src/inferrsi/apps/workflows/knowledge.py +++ b/src/inferrsi/apps/workflows/knowledge.py @@ -1,11 +1,89 @@ """Compose the standalone Apps knowledge operations through Knowledge ports.""" +import json +from hashlib import sha256 from pathlib import Path -from inferrsi.knowledge.knowledge_operations import KnowledgeReader, safe_path +from inferrsi.knowledge._skill_selection import INLINE_PAGE_BYTES, skill_procedure, text_page +from inferrsi.knowledge.knowledge_find import installed_skill_root +from inferrsi.knowledge.knowledge_operations import KnowledgeReader, resolve_resource_key from inferrsi.knowledge.knowledge_store import KnowledgeStore +def _character_bytes(raw, start): + end = start + 1 + while end < len(raw) and raw[end] & 0xc0 == 0x80: + end += 1 + return end - start + + +def read_page(view, requested, *, source_hash=None, source_ranges=None): + """Slice the UTF-8 material view; offsets always refer to the same pinned view.""" + if "content" not in view: + if requested is not None: + raise ValueError("--byte-range requires --material or --resource") + return + content = view["content"] + raw = content.encode("utf-8") + if requested is None: + if len(raw) <= INLINE_PAGE_BYTES: + serialized = json.dumps(content, ensure_ascii=False).encode("utf-8") + if len(serialized) <= INLINE_PAGE_BYTES: + return + requested = (0, INLINE_PAGE_BYTES) + start, length = requested + if start < 0 or length < 1 or start > len(raw) or (start == len(raw) and start != 0): + raise ValueError("--byte-range requires a valid start byte and a positive length") + if start < len(raw) and raw[start] & 0xc0 == 0x80: + raise ValueError("--byte-range must start at a UTF-8 character boundary") + text, stop = text_page(raw, start, length) + if stop == start and start < len(raw): + raise ValueError(f"--byte-range needs at least {_character_bytes(raw, start)} bytes " + "for the next UTF-8 character") + # Put the continuation coordinates before a potentially long stdout body. + del view["content"] + view["content_range"] = { + "start": start, "end": stop, "total_bytes": len(raw), + "first_line": raw.count(b"\n", 0, start) + 1, + } + if stop < len(raw): + view["next_byte_range"] = [stop, max(length, _character_bytes(raw, stop))] + if source_hash is not None or source_ranges is not None: + # A Skill procedure omits frontmatter. Map the selected view bytes back + # onto the already pinned source ranges, including pages crossing a gap. + original = view.get("content_view", {}) + ranges, offset = [], 0 + for lo, hi in original.get("source_byte_ranges", source_ranges or [(0, len(raw))]): + begin, end = max(start - offset, 0), min(stop - offset, hi - lo) + if begin < end: + ranges.append([lo + begin, lo + end]) + offset += hi - lo + view["content_view"] = {"locator": "byte-range", "source_byte_ranges": ranges} + if source_hash is not None: + view["content_view"].update(source_sha256=source_hash, + sha256=sha256(raw[start:stop]).hexdigest()) + view["content"] = text + + +def read_continuation(args, view): + """Return an executable next-page command for the same selected material.""" + if "next_byte_range" not in view: + return None + command = ["read", args.id, "--revision", view["revision"], "--omit-resources"] + if args.resource is not None: + command.extend(["--resource", args.resource]) + elif args.material: + command.append("--material") + for flag, value in (("--skill-root", args.skill_root), ("--store", args.store), + ("--session", args.session), ("--search-ref", args.search_ref)): + if value is not None: + command.extend([flag, str(value)]) + if args.installed_library: + command.append("--installed-library") + command.extend(["--byte-range", *map(str, view["next_byte_range"])]) + return command + + def open_knowledge_store( *, store_root: Path, skill_root: Path | None = None, writable: bool = False, ) -> KnowledgeStore: @@ -29,14 +107,55 @@ def knowledge_reader( def read( reader: KnowledgeReader, reference: str, *, revision: str | None = None, - material: bool = False, resource: str | None = None, + material: bool = False, resource: str | None = None, byte_range=None, ) -> tuple[str, str, dict]: """Return the qualified reference, actual revision, and public Bundle view.""" + if byte_range is not None and revision is None: + raise ValueError("--byte-range requires the exact --revision of the resource") qualified, bundle = reader.read_resolved(reference, revision=revision) view = bundle.view(material=material and resource is None) if resource is not None: - path = safe_path(resource) - if path not in bundle.content: - raise ValueError(f"Unknown resource: {path}") + body = view["entrypoint"] + if qualified.startswith("package:"): + body = view.get("skill_documents", {}).get("original", body) + path = resolve_resource_key(resource, body, bundle.content) + if path != resource: + view["body_resource"] = body view.update(content=bundle.content[path].decode("utf-8"), content_resource=path) + path = view.get("content_resource", view["entrypoint"]) + read_page(view, byte_range, source_hash=view["resources"][path]) return qualified, view["revision"], view + + +def read_selected_hit(hit: dict, *, resource: str | None = None) -> tuple[dict, dict]: + """Open a Find pin once. The tool response and the round receipt use the same bytes.""" + argv = hit["material_read_args"] + root = installed_skill_root() if "--installed-library" in argv else None + if "--skill-root" in argv: + root = Path(argv[argv.index("--skill-root") + 1]) + store = Path(argv[argv.index("--store") + 1]) if "--store" in argv else None + reader = knowledge_reader(skill_root=root, store_root=store) + ref, bundle = reader.read_resolved(hit["material_ref"], revision=hit["revision"]) + view = bundle.view() + body = hit["body_resource"] + path = resolve_resource_key(body if resource is None else resource, body, bundle.content) + if resource is not None and path != resource: + view["body_resource"] = body + raw = bundle.content[path] + data, locator = skill_procedure(path, raw) if resource is None else (raw, {}) + content = data.decode("utf-8") + digest = view["resources"][path] + role = "reference" if path != hit["body_resource"] else ( + "record" if path == "record.json" else "core" + ) + delivered = {"path": path, "role": role, "sha256": digest, "content": content} + if locator: + location = {**locator, "source_sha256": digest, "sha256": sha256(data).hexdigest()} + delivered.update(location) + view["content_view"] = location + context = {"ref": ref, "revision": view["revision"], "resources": [delivered], + "sources": view["sources"], "content_bytes": len(data), "omissions": []} + view.pop("resources") + view.pop("required_resources", None) + view.update(ref=ref, content=content, content_resource=path) + return view, context diff --git a/src/inferrsi/apps/workflows/session_knowledge.py b/src/inferrsi/apps/workflows/session_knowledge.py new file mode 100644 index 000000000..5205afa8f --- /dev/null +++ b/src/inferrsi/apps/workflows/session_knowledge.py @@ -0,0 +1,382 @@ +"""Find and read knowledge as separate, attributable operations in a campaign.""" + +from __future__ import annotations + +import json +import shutil +from contextlib import contextmanager +from pathlib import Path +from uuid import uuid4 + +from inferrsi import __version__ +from inferrsi.harness import optimization, project_service +from inferrsi.harness.atomic_json import atomic_write_json +from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.harness.records.evidence import bounded_record_bytes, sanitized_text +from inferrsi.harness.records.knowledge_capture import ( + MAX_CONTEXT_CAPTURE_BYTES, + capture_campaign, + scoped_response, + store_capture, +) +from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, skill_procedure +from inferrsi.knowledge.catalog import ( + SCENARIO_ALIASES, + _catalog_corpus, + knowledge_records, +) +from inferrsi.knowledge.channels import no_match_across_sources +from inferrsi.knowledge.context_projection import assemble_context_text +from inferrsi.knowledge.knowledge_find import rank +from inferrsi.knowledge.knowledge_operations import service_body, service_resources +from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, managed_ranking_policy + +from ..integrations.external_channels import round_provider +from .knowledge import read_continuation, read_page + +# Only portable Find data goes in an immutable capture. The installed launcher and +# session directory belong to this invocation, not the material's identity. +_HIT = ( + "material_ref", "revision", "body_resource", "material_read_args", "id", "authority", "kind", + "path", "title", "summary", "state", "score", "source", "source_location", "applicability", + "limitations", "limitations_withheld", "findings", "findings_withheld", + "next_read_content_bytes", "matched", "unreadable", + "repo", "backend", "scenario", "tier", "sources", "locally_verified", +) + + +@contextmanager +def _campaign(root): + manifest = capture_campaign(root, "find") + with optimization._locked(root): + if not manifest.get("managed_optimization"): + yield manifest, {}, None, None, DEFAULT_RANKING_POLICY + return + plan, state = optimization._load(root) + service = plan.get("evaluation_mode") == "service_reuse" + active = state if not service else { + **state, "deadline": optimization._service_deadline(state), + "state": "active" if state["state"] == "needs_baseline" else state["state"], + } + number = optimization._knowledge_round(plan, active) + binding = optimization._context_diagnosis(plan, state) + if not service and plan["runtime_identity"] != _runtime_identity(): + raise ValueError("Optimization runtime changed, use its frozen runtime to resume") + policy = optimization.resolve_frozen_ranking(plan, managed_ranking_policy) + yield manifest, plan, state, (number, binding), policy + + +def _save(root, campaign, state, step, *, context_id, action, request, items, display, contexts=()): + number, binding = step or (None, None) + service = campaign.get("evaluation_mode") == "service_reuse" + captured_by = f"inferrsi {action} {__version__}" + selection = {"method": FIND_RELEVANCE, "ranking_applied": action == "find", + "state": "applied" if action == "find" else "explicit_ids", + "ranking_policy": request["ranking_policy"]} + observation = {"schema_version": 1, "entrypoint": action, "calls": [action], + "request": request, "selection": selection, "display": display, + "counts": {"matched": display.get("matched"), "returned": len(items)}, + "items": [{k: row[k] for k in ("ref", "revision") if k in row} for row in items]} + facts = { + "request": request, "selection": selection, "items": items, "omissions": [], + "context_omissions": [], "context_budget": None, + "context_bytes_used": sum(c["content_bytes"] for c in contexts), + "contexts": list(contexts), "retrieval": observation, + } + kind = "knowledge_search" if action == "find" else "delivered_context" + path = f"knowledge/{context_id}.json" + reference = {"path": path, "kind": kind} + if service: + document = {**facts, "kind": "service_knowledge_context", "context_id": context_id, + "captured_by": captured_by, "prepared_not_consumed": True} + if action == "find": + document["source_snapshot"] = f"knowledge/sources/{context_id}" + if binding: + document["diagnosis_binding"] = binding + project_service.no_fingerprints(document) + (root / "knowledge").mkdir(exist_ok=True) + atomic_write_json(project_service.safe_path(root, path), document) + else: + target, digest = store_capture( + root, campaign_id=campaign["campaign_id"], context_id=context_id, + captured_by=captured_by, diagnosis_binding=binding, + assembled_text=assemble_context_text(list(contexts)), + **facts, + ) + reference["sha256"] = digest + document = json.loads(target.read_bytes()) + if state is not None: + retained = {**reference, "round": number} + if binding: + retained["diagnosis_id"] = binding["diagnosis_id"] + if action == "read": + retained["search_ref"] = request["search_ref"] + state["contexts"].append(retained) + return reference, document + + +def _retain_service_sources(root, context_id, selections): + """Publish only complete, byte-consistent source sets before their search receipt.""" + relative = f"knowledge/sources/{context_id}" + destination = project_service.safe_path(root, relative) + temporary = destination.with_name("." + context_id) + temporary.mkdir(parents=True) + try: + for record, document in selections: + resources = service_resources(record) + primary = record.get("skill_documents", {}).get("original") or "record.json" + if document.kind == "skill": + if (primary != "data/skill_library/" + document.path + or record["skill_metadata"]["name"] != document.identity + or record["backend"] != document.backend): + raise ValueError( + "Knowledge ownership changed while finding material; run Find again" + ) + raw = resources[primary].decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") + body, _ = skill_procedure(primary, raw.encode("utf-8")) + if body.decode("utf-8") != document.fields["body"]: + raise ValueError("Knowledge changed while finding material; run Find again") + directory = temporary / record["id"] + for path, content in resources.items(): + target = project_service.safe_path(directory, path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + target.chmod(target.stat().st_mode & ~0o222) + temporary.rename(destination) + finally: + if temporary.exists(): + shutil.rmtree(temporary) + + +def _service_find(args, policy, backend, root, context_id): + if not args.query: + raise ValueError("Service-reuse Find requires a question") + kinds = {item.strip() for item in args.kinds.split(",") if item.strip()} + if not kinds or kinds - {"case", "skill", "record"}: + raise ValueError("--kinds takes a subset of case,skill,record") + records = knowledge_records(file_fingerprints=False) + scenario = SCENARIO_ALIASES.get(args.scenario, args.scenario) + + def matches(record): + skill = record.get("index_type") == "packaged-skill" + declared = record.get("scenario", "") + applicable = (not scenario or declared == scenario + or (skill and declared == "skills.discovery") + or (declared.endswith(".*") and scenario.startswith(declared[:-1]))) + return (("skill" if skill else "record") in kinds + and (not backend or record["backend"] in ("common", backend)) + and (not args.tier or record.get("tier", "contribution") == args.tier) + and (not args.repo_type or record["repo"] == args.repo_type) + and applicable) + + records = [record for record in records if matches(record)] + corpus, records = _catalog_corpus(records, file_fingerprints=False) + _, _, ranked = rank(args.query, corpus, policy) + items = [] + selections = [] + for score, _, index, components in ranked[:args.limit]: + record = records[index] + selections.append((record, corpus.documents[index])) + ref = "package:" + record["id"] + revision = record["sources"][0]["commit"] + path = record.get("skill_documents", {}).get("original") or "record.json" + items.append({ + "id": record["id"], "authority": "package", "title": record["title"], + "kind": "skill" if record.get("index_type") == "packaged-skill" else "record", + "repo": record["repo"], "tier": record.get("tier", "contribution"), + "backend": record["backend"], "scenario": record["scenario"], + "score": round(score, 2), "material_ref": ref, "revision": revision, + "body_resource": path, "material_read_args": ["read", ref, "--revision", revision], + **({"matched": components} if args.explain else {}), + }) + _retain_service_sources(root, context_id, selections) + return {"query": args.query, "matched": len(ranked), "no_match": not ranked, "items": items, + "ranking_policy": policy.configuration(), "sources": ["package"]} + + +def _service_read(root, search, hit, resource): + snapshot = f"knowledge/sources/{search['context_id']}" + if search.get("source_snapshot") != snapshot: + raise ValueError("This Find has no retained source bytes; run Find again before reading") + source_root = project_service.safe_path(root, snapshot + "/" + hit["id"]) + record = project_service.read(project_service.safe_path(source_root, "record.json")) + if record.get("id") != hit["id"] or record["sources"][0]["commit"] != hit["revision"]: + raise ValueError("The retained source does not match this Find") + primary = hit["body_resource"] + path, data, locator = service_body(record, resource, source_root=source_root) + ref, revision = hit["material_ref"], hit["revision"] + selected = {"path": path, "role": "core" if path == primary else "reference", + "content": data.decode("utf-8"), **locator} + context = {"ref": ref, "revision": revision, "resources": [selected], + "content_bytes": len(data), "omissions": [], "sources": record["sources"]} + view = {"ref": ref, "id": hit["id"], "revision": revision, "entrypoint": primary, + "content_resource": path, "content": selected["content"], "sources": record["sources"]} + if resource is not None and path != resource: + view["body_resource"] = primary + if locator: + view["content_view"] = locator + return view, context + + +def find_in_session(args, find_local): + root = args.session.resolve() + if args.limit < 1: + raise ValueError("--limit must be positive") + if (args.decision_cards or args.input or args.external_source is not None + or args.platform + or args.searchspace_coordinate or args.show_searchspace_coordinates + or args.external_limit is not None or args.external_timeout != 8.0): + raise ValueError("Session Find provides body reads and uses its frozen external source") + with _campaign(root) as (campaign, plan, state, step, policy): + if state is not None and (args.skill_root or args.store or args.revisions): + raise ValueError("Managed Find uses the session's installed corpus") + query = args.query + backend = args.backend or campaign.get("backend") + settings = plan.get("external_knowledge") + external_enabled = (settings and not args.no_external + and (backend is None or backend == settings["backend"])) + if external_enabled: + if step[0] is None: + raise ValueError("Round budget consumed, run independent final evaluation") + query = sanitized_text(query, "", limit=None) + args.query = query + service = campaign.get("evaluation_mode") == "service_reuse" + context_id = "find-" + uuid4().hex + result = (_service_find(args, policy, backend, root, context_id) if service else + find_local(args, ranking_policy=policy, backend=backend, local_only=True)) + request = {"query": query, "relevance": query, "relevance_method": FIND_RELEVANCE, + "ranking_policy": result["ranking_policy"], + "backend": backend, "scenario": args.scenario, "limit": args.limit, + "kinds": args.kinds, "repo": args.repo_type, + "tier": args.tier, "sources": result["sources"]} + if args.no_external: + request["external_source"] = "none" + if args.revisions: + request["revisions"] = dict(pin.split("=", 1) for pin in args.revisions) + if plan: + optimization._check_context_ranking(plan, {"request": request}) + items = [{key: hit[key] for key in _HIT if key in hit} for hit in result["items"]] + # Some Find hits (for instance unavailable sources) have no material to open. + for item in items: + item["ref"] = item.get("material_ref") or f"{item['authority']}:{item['id']}" + argv = list(item.get("material_read_args", ())) + for flag in ("--skill-root", "--store"): + if flag in argv: + argv[argv.index(flag) + 1] = flag[2:].upper().replace("-", "_") + if argv: + item["material_read_args"] = argv + external = None + if external_enabled: + remaining = optimization._knowledge_time(plan, state) + external = (round_provider(plan).search(query, settings=settings, limit=args.limit, + timeout=remaining) if remaining > 0 else + {"state": "timeout", "items": [], "count": 0}) + result["no_match"] = no_match_across_sources(result["matched"], [external]) + display = {key: value for key, value in result.items() + if key not in ("items", "external", "searchspace_source")} + reference, document = _save( + root, campaign, state, step, context_id=context_id, + action="find", request=request, items=items, display=display, + ) + response = scoped_response(document, reference, str(args.session), + skill_root=args.skill_root, store=args.store) + if external is not None: + number = step[0] + search = {**external, **settings, "context_ref": reference["path"]} + extra = optimization._store_knowledge(root, "external_search", number, search) + state["contexts"].append(extra) + prefix = (["benchmarks", "session"] if plan["task_source"] == "benchmark" + else ["campaign"]) + read = [*prefix, "knowledge-read", "--session", str(args.session), + "--search-ref", extra["path"], "--locator"] + response["external"] = {**search, "reference": extra, "items": [ + {**hit, "read_args": [*read, hit["locator"]]} for hit in search["items"] + ]} + if state is not None: + atomic_write_json(root / "state.json", state) + return response + + +def _open_search(root, campaign, state, step, location): + path = Path(location) + if path.parent.as_posix() != "knowledge" or path.suffix != ".json": + raise ValueError("Supply a search reference from this campaign") + if state is not None: + number, binding = step + ref = next((entry for entry in state["contexts"] if entry["path"] == location + and entry["kind"] == "knowledge_search" and entry.get("round") == number + and entry.get("diagnosis_id") == (binding or {}).get("diagnosis_id")), None) + if ref is None: + raise ValueError("Supply a Find reference from the current round and diagnosis") + search = (project_service.read(project_service.safe_path(root, location)) + if campaign.get("evaluation_mode") == "service_reuse" else + optimization._read_context(root, ref)) + else: + from .campaign import verify_capture + + raw, _ = bounded_record_bytes(root, location, MAX_CONTEXT_CAPTURE_BYTES) + search = verify_capture(raw)[0] if raw else None + if not search or search["campaign_id"] != campaign["campaign_id"]: + raise ValueError("Supply a verified Find reference from this campaign") + if search.get("retrieval", {}).get("entrypoint") != "find": + raise ValueError("The reference must identify a Find result") + return search + + +def read_in_session(args, read_hit): + if not args.search_ref: + raise ValueError("A session read requires the --search-ref returned by Find") + if (args.layer or args.finding or args.compact or args.max_bytes is not None): + raise ValueError("Session Find supports a pinned body or --resource read") + root = args.session.resolve() + with _campaign(root) as (campaign, _, state, step, _): + search = _open_search(root, campaign, state, step, args.search_ref) + hit = next((item for item in search["items"] if item.get("material_ref") == args.id), None) + if not hit or not hit.get("revision") or hit["revision"] != args.revision: + raise ValueError("Read requires a hit and revision returned by this Find") + argv = list(hit["material_read_args"]) + for flag, value in (("--skill-root", args.skill_root), ("--store", args.store)): + if (flag in argv) != (value is not None): + raise ValueError("Use the source arguments returned by the original Find") + if value is not None: + argv[argv.index(flag) + 1] = str(value) + if args.installed_library != ("--installed-library" in argv): + raise ValueError("Use the source arguments returned by the original Find") + resource = args.resource + service = campaign.get("evaluation_mode") == "service_reuse" + view, context = (_service_read(root, search, hit, resource) if service else + read_hit({**hit, "material_read_args": argv}, resource=resource)) + delivered, = context["resources"] + read_page(view, args.byte_range, + source_hash=delivered.get("source_sha256", delivered.get("sha256")), + source_ranges=delivered.get("source_byte_ranges")) + if "content_range" in view: + delivered.update(content=view["content"], content_range=view["content_range"]) + delivered.update(view.get("content_view", {})) + context["content_bytes"] = len(view["content"].encode("utf-8")) + path = view["content_resource"] + request = {**search["request"], "search_ref": args.search_ref, "resource": path} + if args.byte_range is not None: + request["byte_range"] = args.byte_range + request.pop("context_bytes", None) # A manual campaign may reopen an earlier Find. + display = {key: view[key] for key in ( + "id", "ref", "revision", "kind", "title", "entrypoint", "content_resource", + "body_resource", "content_view", "content_range", "next_byte_range", + "sources", "limitations", "applicability", + ) if key in view} + if continuation := read_continuation(args, view): + for flag, replacement in (("--session", "."), ("--skill-root", "SKILL_ROOT"), + ("--store", "STORE")): + if flag in continuation: + continuation[continuation.index(flag) + 1] = replacement + display["next_read_args"] = continuation + material = {key: hit[key] for key in ("ref", "revision", "title", "kind") if key in hit} + prefix = "read-" + search["context_id"][:64] + "-" + reference, doc = _save( + root, campaign, state, step, context_id=prefix + uuid4().hex, action="read", + request=request, items=[material], display=display, contexts=[context], + ) + if state is not None: + atomic_write_json(root / "state.json", state) + return scoped_response(doc, reference, str(args.session), + skill_root=args.skill_root, store=args.store) diff --git a/src/inferrsi/benchmark/tasks/qwen21-denoise-npu/TASK.md b/src/inferrsi/benchmark/tasks/qwen21-denoise-npu/TASK.md index 335468e05..a3de7e26d 100644 --- a/src/inferrsi/benchmark/tasks/qwen21-denoise-npu/TASK.md +++ b/src/inferrsi/benchmark/tasks/qwen21-denoise-npu/TASK.md @@ -68,7 +68,8 @@ For a complete RSI optimization benchmark in the current Agent conversation, start a session with `inferrsi benchmarks session start qwen21-denoise-npu`. Supply its session directory, round and time budgets, condition label, allocator prefix and sampling arguments. The command returns the frozen task and editable -candidate paths. Use `session knowledge` for permitted RSI context, then repeat +candidate paths. When the session permits knowledge, use `find "" --session ` and +follow a selected hit's scoped `read` command. Then repeat `session round` with the changed candidate and hypothesis. Read each independent observation before the next change. Complete the frozen round budget and use `session final` to independently retest the selected source. Report the generated diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 31c0a4557..f31affa9c 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -11,7 +11,7 @@ from . import attempt_recovery, candidates from .artifact_primitives import digest, file_lock, sha256 from .atomic_json import atomic_write_json, durable_write_json -from .records.evidence import bounded_record_bytes, sanitized_text +from .records.evidence import bounded_record_bytes from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES from .task_protocol import TaskProtocolError from .usage import normalize_usage, usage_totals @@ -441,46 +441,6 @@ def _store_knowledge(root, kind, number, record): "kind": kind, "round": number} -def capture_context(root: Path, reader, *, retain_context, external_provider=None, - external_provider_for=None, **request) -> dict: - with _locked(root): - plan, state = _load(root) - number = _knowledge_round(plan, state) - settings = plan.get("external_knowledge") - if settings: - if number is None: - raise ValueError("Round budget consumed, run independent final evaluation") - if external_provider is None and external_provider_for is None: - raise ValueError("The frozen external knowledge provider is unavailable") - request["relevance"] = sanitized_text(request["relevance"], "", limit=None) - binding = _context_diagnosis(plan, state) - path, fingerprint = retain_context(root, context_id="context-" + uuid.uuid4().hex, - reader=reader, diagnosis_binding=binding, **request) - reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint, - "kind": "delivered_context"} - # Keep the local tool response compatible with stored Codex trace verification. - retained = {**reference, "round": number} if number is not None else reference - if binding: - retained = {**retained, "diagnosis_id": binding["diagnosis_id"]} - state["contexts"].append(retained) - response = {"reference": reference, "context": _read_context(root, reference)} - if settings: - remaining = _knowledge_time(plan, state) - if remaining > 0: - if external_provider_for is not None: - external_provider = external_provider_for(plan) - result = external_provider.search(request["relevance"], settings=settings, - limit=request["limit"], timeout=remaining) - else: - result = {"state": "timeout", "items": [], "count": 0} - search = {**result, **settings, "context_ref": reference["path"]} - search_ref = _store_knowledge(root, "external_search", number, search) - state["contexts"].append(search_ref) - response["external"] = {**search, "reference": search_ref} - atomic_write_json(root / "state.json", state) - return response - - def read_external_context(root: Path, provider, *, search_ref, locator, page, external_provider_for=None): with _locked(root): @@ -523,15 +483,15 @@ def _validate_knowledge_refs(root, contexts, refs): if len(set(refs)) != len(refs): raise ValueError("Cite unique delivered knowledge references") delivered = {entry["path"]: entry for entry in contexts - if entry["kind"] != "external_search"} + if entry["kind"] in ("delivered_context", "external_read")} for ref in refs: path, separator, item = ref.partition("#") reference = delivered.get(path) if reference is None or (separator and reference["kind"] != "delivered_context"): raise ValueError("Cite a delivered context or CANNBot read receipt from this session") - if separator: + if separator or reference.get("search_ref") is not None: capture = _read_context(root, reference) - if not any(entry["ref"] == item and entry["resources"] + if not any((not separator or entry["ref"] == item) and entry["resources"] for entry in capture["contexts"]): raise ValueError("Cite an item with delivered resources from this context") @@ -1526,7 +1486,7 @@ def _service_cleanup_receipt(root, state, path): atomic_write_json(root / "state.json", state) -def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=None): +def service_command(root, args, *, ranking_policy_for=None): """Service-mode operations inside the shared controller's lock and control record.""" from . import project_service as service from . import service_evidence @@ -1540,8 +1500,7 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non resolve_frozen_ranking(plan, ranking_policy_for) return service_backfill.run(root, args) plan, state = _load(root, read_only=action == "status") - ranking_policy = resolve_frozen_ranking(plan, ranking_policy_for, - read_only=action == "status") + resolve_frozen_ranking(plan, ranking_policy_for, read_only=action == "status") if getattr(args, "cleanup_receipt", None) is not None: _service_cleanup_receipt(root, state, args.cleanup_receipt) if action == "status": @@ -1599,41 +1558,6 @@ def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=Non ), ) return _service_settle(root, plan, state, pending, result) - if action == "knowledge": - _active( - { - **state, - "state": "active" if state["state"] == "needs_baseline" else state["state"], - "deadline": _service_deadline(state), - }, - reserve=plan["final_reserve_seconds"], - ) - if not plan["knowledge_allowed"] or knowledge_reader is None: - raise ValueError("Knowledge delivery is disabled or unavailable") - binding = _context_diagnosis(plan, state) - context = knowledge_reader.collect_service_context( - args.query, - relevance_method=args.relevance_method, - limit=args.limit, - context_bytes=args.context_bytes, - ranking_policy=ranking_policy, - ) - _check_context_ranking(plan, context) - if binding: - context["diagnosis_binding"] = binding - service.no_fingerprints(context) - relative = "knowledge/context-" + uuid.uuid4().hex + ".json" - (root / "knowledge").mkdir(exist_ok=True) - atomic_write_json(service.safe_path(root, relative), context) - reference = { - "path": relative, - "kind": "delivered_context", - "prepared_not_consumed": True, - } - state["contexts"].append( - {**reference, "diagnosis_id": binding["diagnosis_id"]} if binding else reference) - atomic_write_json(root / "state.json", state) - return {"reference": reference, "context": context} if action == "resume": if not args.reason.strip() or state["pending"] is not None: raise ValueError( diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 8a522793a..e1aed9df7 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -130,8 +130,7 @@ def _runtime_identity(): def session_command(args, *, ranking_policy_for, task_source: Path | None = None, - knowledge_reader=None, - retain_context=None, external_knowledge=None, external_provider=None, + external_knowledge=None, external_provider=None, external_project=None, external_provider_for=None, report_metadata=None) -> dict: """Run one operation; discovery and knowledge access are supplied by the caller.""" @@ -276,7 +275,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None operation = "campaign" if args.project_task else "benchmarks session" result["instructions"] = ( f"Read the frozen TASK.md. Record the measured bottleneck with {operation} " - f"diagnose first. Use {operation} knowledge when needed and permitted. " + "diagnose first. When knowledge is permitted, use find with --session, " + "then execute a selected hit's read_args to read and retain its body. " "Edit the returned working_candidate within its declared input scope. " f"Before each {operation} round, declare its hypothesis. " "Record other options you considered with --alternative and why you chose the " @@ -322,8 +322,7 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if getattr(args, "alternative", None) is not None or getattr( args, "selection_reason", None) is not None: raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") - return optimization.service_command(root, args, knowledge_reader=knowledge_reader, - ranking_policy_for=ranking_policy_for) + return optimization.service_command(root, args, ranking_policy_for=ranking_policy_for) if ( args.session_action in ("baseline", "refresh-references", "resume", "profile") or getattr(args, "retry_of", None) @@ -334,30 +333,13 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None raise ValueError("Service lifecycle/retry operations require a service-reuse campaign") if plan["runtime_identity"] != _runtime_identity(): raise ValueError("Optimization runtime changed, use its frozen runtime to resume") - ranking_policy = optimization.resolve_frozen_ranking( + optimization.resolve_frozen_ranking( plan, ranking_policy_for, read_only=args.session_action == "status", ) if args.session_action == "status": return optimization.status(root) if args.session_action == "diagnose": return optimization.record_diagnosis(root, args.bottleneck, args.evidence) - if args.session_action == "knowledge": - if knowledge_reader is None or retain_context is None: - raise ValueError("A knowledge reader and capture callback are required") - return optimization.capture_context( - root, - knowledge_reader, - retain_context=retain_context, - ranking_policy=ranking_policy, - external_provider=external_provider, - external_provider_for=external_provider_for, - query="", - relevance=args.query, - relevance_method=args.relevance_method, - scenario=getattr(args, "scenario", None), - context_bytes=args.context_bytes, - limit=args.limit, - ) if args.session_action == "knowledge-read": return optimization.read_external_context( root, external_provider, search_ref=args.search_ref, locator=args.locator, diff --git a/src/inferrsi/harness/records/campaign_records.py b/src/inferrsi/harness/records/campaign_records.py index 974725acc..b52b7f1d1 100644 --- a/src/inferrsi/harness/records/campaign_records.py +++ b/src/inferrsi/harness/records/campaign_records.py @@ -35,7 +35,8 @@ def _identifier(value: str, name: str) -> str: def require_manual_campaign(root: Path) -> None: manifest, _ = read_object(root / "campaign.json", root) if manifest.get("managed_optimization"): - raise ValueError("Managed campaigns use round/knowledge; manual record writes are disabled") + raise ValueError("Managed campaigns use campaign round and find --session; " + "manual record writes are disabled") def create_campaign(root: Path, campaign_id: str, *, target: float | None = None, diff --git a/src/inferrsi/harness/records/evidence.py b/src/inferrsi/harness/records/evidence.py index dd982b00a..0f2a11655 100644 --- a/src/inferrsi/harness/records/evidence.py +++ b/src/inferrsi/harness/records/evidence.py @@ -16,11 +16,34 @@ STAGES = ("diagnosis", "knowledge", "search", "execution", "validation", "review") +_JSON_CREDENTIAL = re.compile( + r'(? str: + pieces, end = [], 0 + for field in _JSON_CREDENTIAL.finditer(text): + if field.start() < end: + continue + pieces.extend((text[end:field.end()], '"[redacted]"')) + try: + _, end = json.JSONDecoder().raw_decode(text, field.end()) + except (ValueError, RecursionError): + # A clipped tool response can end halfway through a credential value. + newline = text.find("\n", field.end()) + end = len(text) if newline == -1 else newline + return "".join([*pieces, text[end:]]) if pieces else text + + def sanitized_text(value: object, default: str = "not_recorded", limit: int | None = 240) -> str: if not isinstance(value, str) or not value: return default - value = re.sub(r"https?://\S+", "[redacted-url]", value, flags=re.I) + if '"' in value: + value = _redact_json_credentials(value) + value = re.sub(r'https?://[^\s"<>]+', "[redacted-url]", value, flags=re.I) value = re.sub(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b", "[redacted-email]", value) value = re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", "[redacted-address]", value) value = re.sub(r"(?\"']+", "[redacted-path]", value) diff --git a/src/inferrsi/harness/records/knowledge_capture.py b/src/inferrsi/harness/records/knowledge_capture.py index caabd9d54..f5694ced5 100644 --- a/src/inferrsi/harness/records/knowledge_capture.py +++ b/src/inferrsi/harness/records/knowledge_capture.py @@ -39,6 +39,63 @@ def capture_campaign(root: Path, context_id: str) -> dict: return campaign +def ranking_identity(policy) -> dict | None: + """Project the recorded ranking identity without resolving its policy in this runtime.""" + if (not isinstance(policy, dict) or not isinstance(policy.get("id"), str) + or not _IDENTIFIER.fullmatch(policy["id"]) or type(policy.get("version")) is not int): + return None + identity = {"id": policy["id"], "version": policy["version"]} + if "config_sha256" in policy: + digest = policy["config_sha256"] + if not isinstance(digest, str) or not re.fullmatch("[0-9a-f]{64}", digest): + return None + identity["config_sha256"] = digest + return identity + + +def scoped_response(document: dict, reference: dict, session: str, *, skill_root=None, + store=None) -> dict: + """Render the Find or Read response from a retained session operation.""" + observation = document["retrieval"] + display = observation["display"] + if observation["entrypoint"] == "find": + hits = [] + for item in document["items"]: + hit = {key: value for key, value in item.items() if key != "material_read_args"} + if argv := item.get("material_read_args"): + argv = list(argv) + for flag, value in (("--skill-root", skill_root), ("--store", store)): + if value is not None and flag in argv: + argv[argv.index(flag) + 1] = str(value) + hit["read_args"] = [*argv, "--session", session, "--search-ref", reference["path"]] + hits.append(hit) + return {"reference": reference, **display, "items": hits} + response = {"reference": reference} + if "next_read_args" in display: + continuation = list(display["next_read_args"]) + for flag, value in (("--session", session), ("--skill-root", skill_root), + ("--store", store)): + if value is not None and flag in continuation: + continuation[continuation.index(flag) + 1] = str(value) + response["next_read_args"] = continuation + for key in ("ref", "revision", "content_resource"): + response[key] = display[key] + for key in ("content_range", "next_byte_range"): + if key in display: + response[key] = display[key] + if document["contexts"]: + resource, = document["contexts"][0]["resources"] + response["content"] = resource["content"] + else: + response["context_omissions"] = document["context_omissions"] + response.update(display) + if "next_read_args" in display: + response["next_read_args"] = continuation + response["search_ref"] = document["request"]["search_ref"] + response["ranking_policy"] = ranking_identity(document["request"]["ranking_policy"]) + return response + + def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dict, selection: object, items: list[dict], omissions: list[dict], context_omissions: list[dict], context_budget: object, @@ -81,6 +138,8 @@ def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dic payload = (json.dumps(document, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8") if len(payload) > MAX_CONTEXT_CAPTURE_BYTES: + if retrieval and retrieval.get("entrypoint") in ("find", "read"): + raise ValueError("captured context exceeds 4 MiB for one serialized record") raise ValueError("captured context exceeds 4 MiB; lower --context-bytes or --limit") directory = root / "knowledge" if directory.is_symlink() or directory.resolve() != directory: @@ -102,6 +161,17 @@ def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dic return target, hashlib.sha256(payload).hexdigest() +def valid_content_range(bounds, content): + """A returned interval describes exactly these bytes of the pinned UTF-8 view.""" + fields = ("start", "end", "total_bytes", "first_line") + if not isinstance(bounds, dict) or bounds.keys() != set(fields): + return False + start, end, total, line = (bounds[key] for key in fields) + return (all(type(i) is int for i in (start, end, total, line)) + and 0 <= start <= end <= total and (start < end or total == 0) + and 1 <= line <= start + 1 and end - start == len(content.encode("utf-8"))) + + def verify_capture(raw: bytes) -> tuple[dict | None, str]: """Check the stored bytes of a capture. @@ -143,6 +213,10 @@ def verify_capture(raw: bytes) -> tuple[dict | None, str]: actual = hashlib.sha256(resource["content"].encode("utf-8")).hexdigest() if resource["sha256"].lower() != actual: return None, "resource_hash_mismatch" + if "content_range" in resource and not valid_content_range( + resource["content_range"], resource["content"] + ): + return None, "invalid_format" for omission in context["omissions"]: if not isinstance(omission, dict) or not all( isinstance(omission.get(key), str) for key in ("path", "reason")): diff --git a/src/inferrsi/harness/session_runtime.py b/src/inferrsi/harness/session_runtime.py index e82a93299..3e00a06af 100644 --- a/src/inferrsi/harness/session_runtime.py +++ b/src/inferrsi/harness/session_runtime.py @@ -1,4 +1,4 @@ -"""Identify the installed session code and the two context capture entry points. +"""Identify the installed session code, including its knowledge capture, Find and Read paths. The identity pins previously retained contexts through their individual hashes. New captures may use the currently installed Knowledge internals. Version metadata @@ -16,6 +16,8 @@ _ROOTS = ( "inferrsi.harness.optimization_session", "inferrsi.apps.workflows.campaign", + "inferrsi.apps.workflows.session_knowledge", + "inferrsi.apps.workflows.knowledge", *_KNOWLEDGE_ROOTS, ) diff --git a/src/inferrsi/knowledge/_skill_selection.py b/src/inferrsi/knowledge/_skill_selection.py index 552db20e0..148fdd61a 100644 --- a/src/inferrsi/knowledge/_skill_selection.py +++ b/src/inferrsi/knowledge/_skill_selection.py @@ -10,6 +10,7 @@ from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy FIND_RELEVANCE = "find-lexical-v1" +INLINE_PAGE_BYTES = 6 * 1024 TASK_STOP_WORDS = frozenset({"a", "an", "and", "for", "in", "of", "on", "the", "to", "with"}) _BACKEND_TERMS = { @@ -22,6 +23,26 @@ class SkillIndexError(ValueError): pass +def text_page(raw: bytes, start: int, length: int) -> tuple[str, int]: + """Return a UTF-8 page whose JSON string fits an ordinary Agent tool response.""" + stop = min(start + length, start + INLINE_PAGE_BYTES, len(raw)) + while stop < len(raw) and raw[stop] & 0xc0 == 0x80: + stop -= 1 + text = raw[start:stop].decode("utf-8") + if len(json.dumps(text, ensure_ascii=False).encode("utf-8")) > INLINE_PAGE_BYTES: + low, high = 0, len(text) + while low < high: + middle = (low + high + 1) // 2 + encoded = json.dumps(text[:middle], ensure_ascii=False).encode("utf-8") + if len(encoded) <= INLINE_PAGE_BYTES: + low = middle + else: + high = middle - 1 + text = text[:low] + stop = start + len(text.encode("utf-8")) + return text, stop + + def validate_relevance_method(method: str | None) -> None: if method not in (None, FIND_RELEVANCE): raise ValueError( @@ -34,6 +55,14 @@ def named_backends(terms: set[str]) -> set[str]: return {backend for backend, names in _BACKEND_TERMS.items() if names & terms} +def declared_skill_references(metadata: dict) -> list[str]: + return [ + *metadata.get("references", []), *metadata.get("provenance_readsets", []), + *(source["third_party_notices"] for source in metadata.get("sources", []) + if "third_party_notices" in source), + ] + + def indexed_skill( record: dict, view: dict, content: dict[str, bytes], ) -> tuple[str, list[str], list[str]]: @@ -64,14 +93,7 @@ def indexed_skill( raise SkillIndexError("Stale packaged skill projection; rebuild with build_skill_index.py") required = [core] - metadata = record["skill_metadata"] - notices = [ - source["third_party_notices"] - for source in metadata.get("sources", []) if "third_party_notices" in source - ] - for relative in [ - *metadata.get("references", []), *metadata.get("provenance_readsets", []), *notices, - ]: + for relative in declared_skill_references(record["skill_metadata"]): path = posixpath.normpath(prefix + relative) if "\\" in relative or not path.startswith("data/skill_library/") or path not in content: raise SkillIndexError(f"Unavailable declared skill reference: {relative}") @@ -229,3 +251,45 @@ def include(path: str) -> None: "Follow omitted or other linked resources through the exact owner revision.", ], }, None + + +def candidate_contexts(entries, cue: str, budget: int, ranking_policy: RankingPolicy): + """Reserve complete pinned Find bodies before spending the remaining bytes on links.""" + reserved, contexts, omissions = [], [], [] + remaining = budget + for view, record, content, body in entries: + data, _ = skill_procedure(body, content[body]) + try: + data.decode("utf-8") + except UnicodeDecodeError: + omissions.append({"ref": view["ref"], "path": body, "reason": "not_utf8"}) + continue + if not budget or len(data) > remaining: + omissions.append({"ref": view["ref"], "path": body, "reason": "context_limit", + "required_bytes": len(data), "available_bytes": remaining}) + continue + remaining -= len(data) + reserved.append((view, record, content, body, len(data))) + + for view, record, content, body, size in reserved: + if record.get("index_type") == "packaged-skill": + _, declared, optional = indexed_skill(record, view, content) + paths = [*declared, *optional] + else: + paths = list(content) + links = [path for path in paths if path != body] + duplicate = (view["kind"] == "case" and "case.json" in links and any( + path != "case.json" and path.endswith(".json") and content[path] == content["case.json"] + for path in paths + )) + if duplicate: + links.remove("case.json") + context, _ = context_view((body, [body], links), view, content, cue, size + remaining, + ranking_policy) + if body == "record.json": + context["resources"][0]["role"] = "record" + if duplicate: + context["omissions"].append({"path": "case.json", "reason": "duplicate_resource"}) + remaining -= context["content_bytes"] - size + contexts.append(context) + return contexts, omissions, budget - remaining diff --git a/src/inferrsi/knowledge/catalog.py b/src/inferrsi/knowledge/catalog.py index 6313c5f9d..f92f2ace4 100644 --- a/src/inferrsi/knowledge/catalog.py +++ b/src/inferrsi/knowledge/catalog.py @@ -365,7 +365,9 @@ def _scoped_records( return eligible, excluded -def _catalog_corpus(records: list[dict[str, Any]]) -> tuple[Corpus, list[dict[str, Any]]]: +def _catalog_corpus( + records: list[dict[str, Any]], *, file_fingerprints: bool = True, +) -> tuple[Corpus, list[dict[str, Any]]]: from .knowledge_find import Corpus, installed_skill_projection, load_documents by_id = {record["id"]: record for record in records} @@ -373,7 +375,7 @@ def _catalog_corpus(records: list[dict[str, Any]]) -> tuple[Corpus, list[dict[st if any(record.get("index_type") == "packaged-skill" for record in records): kinds = ("skill", "record") documents, document_records = [], [] - for document in load_documents(kinds=kinds, records=records): + for document in load_documents(kinds=kinds, records=records, capture_sources=file_fingerprints): record = ( by_id[document.identity] if document.kind == "record" else installed_skill_projection(document, by_id) @@ -386,8 +388,7 @@ def _catalog_corpus(records: list[dict[str, Any]]) -> tuple[Corpus, list[dict[st return Corpus(documents), document_records -def search_knowledge( - query: str = "", +def list_knowledge( *, repo: str | None = None, tier: str | None = None, @@ -395,66 +396,48 @@ def search_knowledge( scenario: str | None = None, limit: int = 10, explain: bool = False, - ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, ) -> list[dict[str, Any]] | dict[str, Any]: - """List exact package records, using Find when a text query is supplied.""" + """List package records in stable ID order after applying inventory filters.""" if limit < 1: raise ValueError("limit must be positive") records, excluded = _scoped_records(repo=repo, tier=tier, backend=backend, scenario=scenario) - ranking = bool(query.strip()) - if ranking: - from .knowledge_find import rank - - corpus, document_records = _catalog_corpus(records) - _, _, scored = rank(query, corpus, ranking_policy) - matches = [ - (document_records[index], score, components) for score, _, index, components in scored - ] - else: - matches = [ - (record, None, None) for record in sorted(records, key=lambda record: record["id"]) - ] - - returned = matches[:limit] - items = [record for record, _, _ in returned] + items = sorted(records, key=lambda record: record["id"])[:limit] if not explain: return items - from ._skill_selection import FIND_RELEVANCE - observed = [] - for position, (record, score, components) in enumerate(returned, 1): + for position, record in enumerate(items, 1): data = json.dumps(record, sort_keys=True, ensure_ascii=False).encode() - item = {"ref": "package:" + record["id"], "rank": position, - "revision": "catalog-sha256:" + hashlib.sha256(data).hexdigest()} - if score is not None: - item.update(score=round(score, 2), components=components) - observed.append(item) + observed.append({"ref": "package:" + record["id"], "rank": position, + "revision": "catalog-sha256:" + hashlib.sha256(data).hexdigest()}) retrieval = observation( - entrypoint="knowledge search", - request={"query": query, "repo": repo, "tier": tier, "backend": backend, + entrypoint="knowledge list", + request={"query": "", "repo": repo, "tier": tier, "backend": backend, "scenario": SCENARIO_ALIASES.get(scenario, scenario), "limit": limit, "sources": ["package"]}, - selection={ - "method": FIND_RELEVANCE if ranking else None, "scope": "package-records", - "ranking_applied": ranking, "state": "applied" if ranking else "not_requested", - **({"ranking_policy": ranking_policy.receipt()} if ranking else {}), - "tie_break": "state_then_id_then_ref" if ranking else None, - }, + selection={"method": None, "scope": "package-records", "ranking_applied": False, + "state": "not_requested", "tie_break": None}, items=observed, - counts={ - "considered": len(records) + sum(excluded.values()), - "matched": len(matches), "returned": len(items), - "excluded": {**excluded, "query": len(records) - len(matches), - "item_limit": len(matches) - len(items)}, - }, + counts={"considered": len(records) + sum(excluded.values()), + "matched": len(records), "returned": len(items), + "excluded": {**excluded, "query": 0, "item_limit": len(records) - len(items)}}, assembly="not_requested", ) - if ranking: - retrieval["calls"].append("find") return {"items": items, "retrieval": retrieval} -def lookup_record(record_id: str) -> dict | None: +def search_knowledge(query: str = "", *, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, + **filters) -> list[dict[str, Any]] | dict[str, Any]: + """Historical spelling for filtered inventory. Use find(query, load_corpus(...)) for text.""" + if query.strip(): + raise ValueError("Use find(query, load_corpus(...)) to search for material.") + result = list_knowledge(**filters) + if isinstance(result, dict): + result["retrieval"].update(entrypoint="knowledge search", calls=["knowledge search"]) + result["retrieval"]["request"]["query"] = query + return result + + +def lookup_record(record_id: str, *, file_fingerprints: bool = True) -> dict | None: """Validate a single package owner without parsing unrelated records or skill sidecars.""" if not re.fullmatch(r"[a-z0-9][a-z0-9._-]*", record_id): return None @@ -462,12 +445,12 @@ def lookup_record(record_id: str) -> dict | None: item = root.joinpath("records", record_id + ".json") record = _authored_record(item) if item.is_file() else None if re.fullmatch(r"inferrsi\.[a-z0-9]+\.skills\.[a-z0-9_]+", record_id): - for view in skill_views(root, record_id=record_id): + for view in skill_views(root, record_id=record_id, file_fingerprints=file_fingerprints): if record is not None: raise ValueError(f"Duplicate knowledge ID: {record_id}") _validate_record(view, "inferrsi", (view["backend"], "skills", view["title"] + ".json")) record = view - return record + return record if file_fingerprints else without_file_fingerprints(record) def get_knowledge(record_id: str) -> dict[str, Any]: diff --git a/src/inferrsi/knowledge/channels.py b/src/inferrsi/knowledge/channels.py index 19b35cb40..46d300476 100644 --- a/src/inferrsi/knowledge/channels.py +++ b/src/inferrsi/knowledge/channels.py @@ -397,3 +397,13 @@ def explain_gate(registry: ChannelRegistry, backend: str | None) -> list[dict]: def external_view(results: list[ChannelResult], *, notes: list[str] | None = None) -> list[dict]: """Render channel results for `find`'s output, unchanged in shape when empty.""" return [result.view() for result in results] + + +def no_match_across_sources(local_matches: int, channels: list[dict]) -> bool | None: + """A hit settles the question. An attempted source with no answer leaves it open.""" + if local_matches or any(source.get("items") for source in channels): + return False + # Requests have a count even on failure. Sources excluded by the backend gate do not. + if any("count" in source and source["state"] != OK for source in channels): + return None + return True diff --git a/src/inferrsi/knowledge/context_projection.py b/src/inferrsi/knowledge/context_projection.py index 0c5660bce..c85d98c57 100644 --- a/src/inferrsi/knowledge/context_projection.py +++ b/src/inferrsi/knowledge/context_projection.py @@ -12,9 +12,12 @@ def assemble_context_text(contexts: list[dict]) -> str: for context in contexts: for resource in context["resources"]: content = resource["content"] + extent = "" + if bounds := resource.get("content_range"): + extent = f" [bytes {bounds['start']}..{bounds['end']} of {bounds['total_bytes']}]" lines.append( f"--- begin context {context['ref']} @ {context['revision']} " - f"{resource['path']} ---\n" + f"{resource['path']}{extent} ---\n" ) lines.append(content if content.endswith("\n") else content + "\n") lines.append(f"--- end context {resource['path']} ---\n") diff --git a/src/inferrsi/knowledge/data/skill_library/README.md b/src/inferrsi/knowledge/data/skill_library/README.md index c8d31b133..c6362df61 100644 --- a/src/inferrsi/knowledge/data/skill_library/README.md +++ b/src/inferrsi/knowledge/data/skill_library/README.md @@ -41,7 +41,7 @@ registered procedure through `skill_documents.original`. Core catalog reads do not require the optional YAML parser: ```bash -inferrsi knowledge search --repo-type inferrsi --backend ascend +inferrsi knowledge list --repo-type inferrsi --backend ascend inferrsi read inferrsi.ascend.skills.ascend_graph_mode --material ``` @@ -195,7 +195,7 @@ Catalog records link detailed procedures through `skill_documents.en`; `knowledge show` and `context` retain these package-relative pointers. ```bash -inferrsi knowledge search Radix --repo-type sglang +inferrsi find Radix --repo-type sglang inferrsi context --repo-type vllm --backend cuda --scenario llm.serving ``` diff --git a/src/inferrsi/knowledge/data/skill_library/records/README.md b/src/inferrsi/knowledge/data/skill_library/records/README.md index 0d2315255..25bc5fbc8 100644 --- a/src/inferrsi/knowledge/data/skill_library/records/README.md +++ b/src/inferrsi/knowledge/data/skill_library/records/README.md @@ -2,7 +2,7 @@ An engineering finding belongs in one `.json` file here. The ID encodes repository, backend, component and entry. Keep the source revision, applicability, verification state, limitations and negative results with the claim. The tier field expresses the source relationship (contribution, dependency or peer). Existing schema-1 contribution records may omit the tier. -Use `inferrsi knowledge search --tier peer --json` to browse a tier and `inferrsi knowledge show ` to open the complete record. A procedure belongs with its own SKILL.md, metadata and resources. The catalog builds packaged-skill views from those owners. No per-record navigation list needs editing. +Use `inferrsi knowledge list --tier peer --json` to browse a tier and `inferrsi knowledge show ` to open the complete record. A procedure belongs with its own SKILL.md, metadata and resources. The catalog builds packaged-skill views from those owners. No per-record navigation list needs editing. ## Adding or updating a record diff --git a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md index ba0b62e66..211264b15 100644 --- a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md @@ -144,7 +144,9 @@ Source-derived candidate for `antirez/h3.c` at `8974cc055ea9c02fcd14cc27dfda3e1027c05153`. Use for MiniMax-H3 text/image/video/audio conditioning, memory-fit diagnosis, kernel changes or a dedicated-engine design derived from this C/Metal runtime. Start with the -[source readset and architecture](references/source-notes.md). Native execution, +[source readset and architecture](references/source-notes.md). For the model's +aliases, component roles and input/output modalities, open the +[MiniMax-H3 profile](references/minimax-h3-profile.json) and its pinned model card. Native execution, media quality, performance and behavioral skill efficacy are **not_run**. ## Inputs and decision diff --git a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-apple.md b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-apple.md index 771e2dcb4..4a71c3881 100644 --- a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-apple.md +++ b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-apple.md @@ -26,9 +26,9 @@ Use independent catalog queries rather than requiring all these words in one record: ```bash -inferrsi knowledge search MiniMax-H3 --repo-type inferrsi --limit 100 -inferrsi knowledge search diffusion --repo-type vllm_omni --limit 100 -inferrsi knowledge search MLX --repo-type inferrsi --limit 100 +inferrsi find MiniMax-H3 --repo-type inferrsi --limit 100 +inferrsi find diffusion --repo-type vllm_omni --limit 100 +inferrsi find MLX --repo-type inferrsi --limit 100 inferrsi read inferrsi.common.skills.audit_h3_runtime_residency --material ``` @@ -42,7 +42,7 @@ lack of upstream support. For a legacy cited export, its existing required flags still apply: ```bash -inferrsi context diffusion --repo-type vllm_omni --backend cpu --scenario diffusion.video_generation +inferrsi context --repo-type vllm_omni --backend cpu --scenario diffusion.video_generation ``` The `cpu` filter retrieves common guidance here; it does not qualify an Apple diff --git a/src/inferrsi/knowledge/data/skill_library/config/research_profiles/minimax-h3.json b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json similarity index 100% rename from src/inferrsi/knowledge/data/skill_library/config/research_profiles/minimax-h3.json rename to src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json diff --git a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/validation.md b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/validation.md index 054b02538..c13b2e1a9 100644 --- a/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/validation.md +++ b/src/inferrsi/knowledge/data/skill_library/systems/engines/h3-c/audit-h3-runtime-residency/references/validation.md @@ -63,7 +63,7 @@ why available upstream evidence leaves that target unqualified. Use the existing readers independently of any research-preparation extension: ```bash -inferrsi knowledge search MiniMax-H3 --repo-type inferrsi --limit 100 +inferrsi find MiniMax-H3 --repo-type inferrsi --limit 100 inferrsi skills show audit-h3-runtime-residency inferrsi skills resource audit-h3-runtime-residency references/phase-residency.md inferrsi read inferrsi.common.skills.audit_h3_runtime_residency --material diff --git a/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/SKILL.md b/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/SKILL.md index 57771fb2b..5b9f02014 100644 --- a/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/SKILL.md +++ b/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/SKILL.md @@ -24,12 +24,14 @@ Use this collection to prepare a dedicated engine, compare architectures or desi ## Comparison procedure 1. Fix the model/checkpoint/tokenizer, tasks/modalities, component graph, target hardware/memory, software and quality contract. Ask only for missing facts that alter a decision; otherwise state reversible assumptions. Do not infer architecture from a family name. -2. Search model, framework, task, modality and mechanism dimensions independently and union the results. - Use `inferrsi knowledge research --framework ` with explicit `--task`, - `--modality` or `--mechanism` additions as needed. Known profiles supply grounded terms. - Inspect sources for unknown models. Each query uses Find's lexical ranking over the eligible - package records. Retain hard filters and record empty dimensions. Change the scope explicitly - if it is too restrictive. +2. Use ordinary `inferrsi find "QUESTION"` separately for each decision about the model, + framework, task, modality or mechanism. For MiniMax-H3, follow the hit for the + [h3.c audit](../../../systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md) to its + [model profile](../../../systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json). + For an unfamiliar model, derive the questions from its pinned model card and checkpoint. + Open relevant hits at their returned revisions. Merge repeated owners at the same revision, + retain each contributing question and note any unanswered ones. During an optimization round, + send every question through `find --session DIR` and use its scoped reads. 3. Compare eligible native implementations at pinned revisions. If the user requests the most-starred reference, record the candidate set, eligibility, observation date and counts; choose the largest count within that set, then check license and compatibility. Read that source directly or distill its relevant paths with an available repo-to-skill workflow before engine generation. Popularity is a reference-selection input, not a quality or hardware guarantee. 4. Inventory every selected encoder, denoiser, VAE/decoder, conditioning path, adapter and auxiliary asset. Reconcile tensor shapes, dtypes, quantization metadata, files and actual execution paths. Separate full checkpoint weights, required subsets, phase and cold-start peaks, activations/workspace, unified/host memory and storage. Do not count alternative task checkpoints twice or equate a DiT-only quant with a complete pipeline. Follow the [preparation procedure](references/model-aware-preparation.md) before deciding target feasibility. 5. Load the smallest relevant repository branches. Trace work units, state ownership, scheduling, memory, communication, output and cleanup. Produce supported settings, semantics-preserving implementation changes and research extensions as separate candidate classes, with explicit approximation budgets. diff --git a/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md b/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md index 99821e856..f6b41cf1b 100644 --- a/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md +++ b/src/inferrsi/knowledge/data/skill_library/workflows/research/inference-engine-research/references/model-aware-preparation.md @@ -15,43 +15,43 @@ diffusion pipeline does not make it a language-model serving task. Separate hosted-only services from locally released components. Unknown architecture facts remain unknown. -## 2. Discover along separate dimensions +## 2. Research each decision with an ordinary question -Run the public operation, adding dimensions established from the selected source: +For MiniMax-H3 on a 64 GiB Apple Silicon target, start with the model and its +total component inventory. ```bash -inferrsi knowledge research MiniMax-H3 --framework mlx --target-backend metal --target-device "M5 Mac Studio" --target-memory-gib 64 --limit 12 +inferrsi find "MiniMax-H3 component inventory on Apple Silicon" ``` -This emits JSON: the packaged profile and sources, independent query groups, -match counts, bounded deduplicated records with `matched_queries`, active filters, -component roles and target annotations. It searches the installed catalog only. -Round-robin selection lets different queries contribute; it is not an evidence -quality or engine ranking. Read the original records' applicability, sources, -negative results and verification state alongside their full linked procedures. - -- **Model:** canonical identity and aliases; preserve checkpoint/task variants. -- **Framework:** preferred runtime and its lazy evaluation, buffers and streams. -- **Task:** diffusion, autoregressive generation or the actual computation. -- **Modality:** video, audio, image and other required input/output contracts. -- **Mechanism:** relevant memory, residency, quantization, tiling, offload, - scheduling or reuse questions; query presence does not assert support. - -Known profiles supply only source-grounded discovery terms and component roles; -their linked repository skills own the detailed source map and inventories. The -MiniMax-H3 profile points to the [h3.c residency audit](../../../../systems/engines/h3-c/audit-h3-runtime-residency/SKILL.md). -For an unknown model, supply `--task` and `--modality` after inspecting its sources; -no architecture is guessed. Repeat dimensions to add queries. -A text query to `knowledge search` and each research query use the same Find -lexical ranking over the eligible package records. - -Tier/repository/backend/scenario flags remain hard catalog filters. An empty -dimension can mean missing or filtered knowledge: report it, inspect the missing -source and explicitly change scope when useful. Cross-platform records can -suggest mechanisms, but CUDA/Ascend evidence does not qualify Metal. The free-text -`--target-backend` describes the intended runtime; it does not add that backend to -InferRSI's experiment adapters. Avoid a CUDA-only filter when researching common -MLX procedures unless that restricted view is intentional. +Open the h3.c residency audit with the read command on its hit. Its +[model profile](../../../../systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-profile.json) +contains the model-card revision, aliases, tasks, modalities, component roles +and proposed research topics. Use the hit's owner and revision to read +`references/minimax-h3-profile.json`. The same owner has the +[weight inventory](../../../../systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-weight-inventory.json) +and [Apple feasibility comparison](../../../../systems/engines/h3-c/audit-h3-runtime-residency/references/minimax-h3-apple.md). +For a new model, get the corresponding facts from its card, configs and selected +checkpoint before choosing the next questions. + +```bash +inferrsi find "MLX lazy evaluation and buffer lifetime" +inferrsi find "video VAE temporal tiling and audio decoding" +inferrsi find "SSD streaming quantization and weight loading" +``` + +Pick further questions when the task, input modality or mechanism changes the +decision. Open each relevant source and record its owner, revision, applicability +and verification. Give each question a chance to contribute a source. When the +same owner and revision answer several questions, keep one source and list the +questions it answers. Record empty results and any change in scope. + +In an optimization round, add `--session DIR` to each Find call and follow that +call's scoped read arguments, including for linked resources. This retains each +query, its hits and the resources actually returned. Put the candidate machine, +available memory, software and required workload in the task or experiment plan. +Use source reports from other devices as leads and check their claims on the +specified target. ## 3. Choose and inspect an implementation reference diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index e5fec6f5e..f46530536 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -40,10 +40,18 @@ if TYPE_CHECKING: from .channels import ChannelRegistry from .knowledge_operations import Bundle + from .knowledge_store import KnowledgeStore from .searchspace_index import SearchspaceCoordinate, SearchspaceEntry, SearchspaceIndex from ._knowledge_errors import MissingSkillsExtra -from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends +from ._skill_selection import ( + INLINE_PAGE_BYTES, + TASK_STOP_WORDS, + indexed_skill, + named_backends, + skill_procedure, + text_page, +) from .catalog import BACKENDS, packaged_skill_id from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy @@ -193,6 +201,9 @@ class Document: locally_verified: bool | None = None backend: str | None = None ranked_sources: dict[str, bytes | None] = field(default_factory=dict) + stored_bundle: Bundle | None = None + store_args: tuple[str, ...] = () + package_record: dict | None = None def unverified(self) -> bool: return self.locally_verified is False or any( @@ -293,29 +304,34 @@ def view( record["findings_total"] = len(self.findings) if withheld: record["findings_withheld"] = withheld - scope = self.applicability - if isinstance(scope, dict): - scope = scope.get("scope") or _flatten(scope) - elif isinstance(scope, list): - scope = " · ".join(str(item) for item in scope) - if scope: - record["applicability"] = str(scope).strip()[:_MAX_SNIPPET] - if self.limitations: - shown = [] - for limitation in self.limitations[:_MAX_SHOWN_LIMITATIONS]: - preview = [*shown, limitation] - preview_bytes = json.dumps(preview, ensure_ascii=False).encode("utf-8") - if len(preview_bytes) > _MAX_LIMITATION_BYTES: - break - shown = preview - record["limitations"] = shown - if len(shown) < len(self.limitations): - record["limitations_withheld"] = len(self.limitations) - len(shown) + record.update(preview_bounds(self.applicability, self.limitations)) if self.unverified(): record["locally_verified"] = False return record +def preview_bounds(scope, limitations) -> dict: + """Summarize a hit's applicability and disclose how many limitations need a full read.""" + bounds = {} + if isinstance(scope, dict): + scope = scope.get("scope") or _flatten(scope) + elif isinstance(scope, list): + scope = " · ".join(str(item) for item in scope) + if scope: + bounds["applicability"] = str(scope).strip()[:_MAX_SNIPPET] + if limitations: + shown = [] + for limitation in limitations[:_MAX_SHOWN_LIMITATIONS]: + preview = [*shown, limitation] + if len(json.dumps(preview, ensure_ascii=False).encode("utf-8")) > _MAX_LIMITATION_BYTES: + break + shown = preview + bounds["limitations"] = shown + if len(shown) < len(limitations): + bounds["limitations_withheld"] = len(limitations) - len(shown) + return bounds + + def launcher() -> list[str]: """How to start this CLI from where the caller is. @@ -395,7 +411,7 @@ def _findings(record: dict, identity: str) -> tuple[Finding, ...]: return tuple(result) -def _case_documents(root: Path, *, source_location: str) -> list[Document]: +def _case_documents(root: Path, *, source_location: str, capture_sources: bool) -> list[Document]: """Cases owned by the registered skills of this root. Discovery is delegated to the reader that `read` uses, rather than globbing @@ -417,8 +433,8 @@ def _case_documents(root: Path, *, source_location: str) -> list[Document]: except (ValueError, OSError): body_path = None body, raw_body = _body_source(body_path) if body_path is not None else ("", None) - ranked_sources = {"case.json": _source_digest(declaration)} - if body_path is not None: + ranked_sources = {"case.json": _source_digest(declaration)} if capture_sources else {} + if capture_sources and body_path is not None: ranked_sources[record["content"]] = _source_digest(raw_body) findings = _findings(record, identity) backend = record.get("backend") @@ -480,6 +496,7 @@ def _skill_description(body: str) -> str: def _skill_documents( root: Path, *, source_location: str, searchspace_index: SearchspaceIndex | None = None, + capture_sources: bool, ) -> list[Document]: """Skills registered by this root, resolved the way `skills` and `read` do. @@ -555,13 +572,14 @@ def _skill_documents( }, applicability=applicability, limitations=tuple(metadata.get("limitations", [])), - ranked_sources={"SKILL.md": _source_digest(raw_body), - "metadata.json": _source_digest(raw_sidecar)}, + ranked_sources=({"SKILL.md": _source_digest(raw_body), + "metadata.json": _source_digest(raw_sidecar)} if capture_sources + else {}), )) return documents -def _record_documents(records: Iterable[dict]) -> list[Document]: +def _record_documents(records: Iterable[dict], *, capture_sources: bool) -> list[Document]: """Imported engine records. Skill projections are skipped: the checkout documents above already cover them, and counting both double-ranks one owner under two identities.""" @@ -602,7 +620,8 @@ def _record_documents(records: Iterable[dict]) -> list[Document]: }, applicability=record.get("applicability"), limitations=tuple(record.get("limitations", [])), - ranked_sources={"record.json": _source_digest(_json(record))}, + ranked_sources=({"record.json": _source_digest(_json(record))} + if capture_sources else {}), )) return documents @@ -612,8 +631,10 @@ class Corpus: def __init__( self, documents: list[Document], *, _searchspace_index: SearchspaceIndex | None = None, + sources: tuple[str, ...] = (), ): self.documents = documents + self.sources = sources self._searchspace_index = _searchspace_index total = len(documents) appearances = Counter() @@ -692,6 +713,7 @@ def load_documents( *, kinds: tuple[str, ...] = ("case", "skill", "record"), records: Iterable[dict] | None = None, + capture_sources: bool = True, _searchspace_index: SearchspaceIndex | None = None, ) -> list[Document]: documents: list[Document] = [] @@ -702,17 +724,19 @@ def load_documents( raise ValueError(f"Skill root is not a directory: {root}") source_location = "installed" if root == installed else "checkout" if "case" in kinds: - documents.extend(_case_documents(root, source_location=source_location)) + documents.extend(_case_documents(root, source_location=source_location, + capture_sources=capture_sources)) if "skill" in kinds: documents.extend(_skill_documents( root, source_location=source_location, searchspace_index=_searchspace_index, + capture_sources=capture_sources, )) if "record" in kinds: from .catalog import knowledge_records if records is None: records = knowledge_records(include_skill_views=False) - documents.extend(_record_documents(records)) + documents.extend(_record_documents(records, capture_sources=capture_sources)) identities = [document.qualified for document in documents] if len(set(identities)) != len(identities): duplicate = next(i for i, c in Counter(identities).items() if c > 1) @@ -723,16 +747,96 @@ def load_documents( def load_corpus( skill_root: Path | None = None, *, kinds: tuple[str, ...] = ("case", "skill", "record"), searchspace_index: SearchspaceIndex | None = None, + backend: str | None = None, repo: str | None = None, tier: str | None = None, + scenario: str | None = None, store: KnowledgeStore | None = None, + revisions: Mapping[str, str] | None = None, + unavailable_store_revisions: list[str] | None = None, ) -> Corpus: - """Build a rankable corpus, using the verified Skill inputs if explicitly supplied.""" - if searchspace_index is None: - return Corpus(load_documents(skill_root, kinds=kinds)) - if skill_root is not None and Path(skill_root).resolve() != searchspace_index.skill_root: - raise ValueError("SearchSpace coordinate and Find corpus require the same Skill root") + """Apply the caller's source and workload scope before computing ranking weights.""" + from .catalog import SCENARIO_ALIASES, knowledge_records + from .knowledge_operations import UnavailableRevision, _store_document + + if backend is not None and backend not in BACKENDS: + raise ValueError(f"Unknown knowledge backend {backend!r}. " + f"Choose one of {', '.join(BACKENDS)}.") + if searchspace_index is not None: + if skill_root is not None and Path(skill_root).resolve() != searchspace_index.skill_root: + raise ValueError("SearchSpace coordinate and Find corpus require the same Skill root") + skill_root = searchspace_index.skill_root + catalog_scope = any(value is not None for value in (repo, tier, scenario)) + custom = skill_root is not None and Path(skill_root).resolve() != installed_skill_root() + supplement = custom and not catalog_scope and searchspace_index is None and ( + "skill" in kinds and "record" in kinds + ) + if catalog_scope and (custom or store is not None): + raise ValueError("Package catalog filters (--repo-type, --tier, --scenario) cannot " + "select a custom --skill-root or --store") + records = ({r["id"]: r for r in knowledge_records()} + if catalog_scope or supplement or store else {}) documents = load_documents( - searchspace_index.skill_root, kinds=kinds, _searchspace_index=searchspace_index, + None if catalog_scope else skill_root, kinds=kinds, _searchspace_index=searchspace_index, + records=records.values() if records else None, ) - return Corpus(documents, _searchspace_index=searchspace_index) + sources = ["package"] if "record" in kinds else [] + if "case" in kinds or "skill" in kinds: + sources.append("checkout") + if supplement: + # A custom owner wins over its installed mirror. The package still supplies + # registered Skills missing from a mixed library-and-record search. + custom_ids = {doc.identity for doc in documents if doc.kind == "skill"} + for doc in load_documents(kinds=("skill",)): + if doc.identity in custom_ids: + continue + doc.package_record = installed_skill_projection(doc, records) + if doc.package_record is not None: + documents.append(doc) + if catalog_scope or (store and skill_root is None): + sources = ["package"] + scenario = SCENARIO_ALIASES.get(scenario, scenario) + eligible = [] + for document in documents: + record = (records.get(document.identity) if document.kind == "record" + else installed_skill_projection(document, records)) + if record is None or (repo and record["repo"] != repo): + continue + if tier and record.get("tier", "contribution") != tier: + continue + declared = record["scenario"] + if scenario and not ( + declared == scenario + or declared.endswith(".*") and scenario.startswith(declared[:-1]) + or record.get("index_type") == "packaged-skill" and declared == "skills.discovery" + ): + continue + if document.kind == "skill": + document.package_record = record + eligible.append(document) + documents = eligible + pins = dict(revisions or {}) + if store is not None and not catalog_scope: + sources.append("store") + source_args = ("--skill-root", str(skill_root.resolve())) if skill_root else () + for identity in sorted(store.identities()): + ref = f"store:{identity}" + revision = pins.pop(ref, None) + try: + bundle = store.read(identity, revision=revision) + except UnavailableRevision: + if unavailable_store_revisions is None or revision is None: + raise + unavailable_store_revisions.append(ref) + continue + document = _store_document(ref, bundle) + if document.kind in kinds: + document.stored_bundle = bundle + document.store_args = (*source_args, "--store", str(store.workspace)) + document.source_location = "store" + documents.append(document) + if pins: + raise ValueError("--revision on find requires a selected store:ID from --store") + if backend: + documents = [doc for doc in documents if doc.backend in (backend, "common")] + return Corpus(documents, _searchspace_index=searchspace_index, sources=tuple(sources)) @lru_cache(maxsize=1) @@ -815,25 +919,50 @@ class _ReadPreview: view: dict source_args: tuple[str, ...] + @property + def body_resource(self) -> str: + if "--resource" in self.args: + return self.args[self.args.index("--resource") + 1] + return self.view["entrypoint"] + + def session_pin(self) -> dict: + ref = self.args[1] + revision = self.view["revision"] + return {"material_ref": ref, "revision": revision, "body_resource": self.body_resource, + "material_read_args": ["read", ref, "--material", "--omit-resources", + "--revision", revision, *self.source_args]} -def _read_preview(document: Document, readers: dict) -> _ReadPreview | None: + +def _read_preview( + document: Document, readers: dict, package_skills: bool = False, +) -> _ReadPreview | None: """Validate a hit once and keep the exact material used for its preview.""" from .knowledge_operations import KnowledgeReader if not document.qualified: return None + if document.stored_bundle is not None: + bundle = document.stored_bundle + view = bundle.view(material=True) + args = ("read", document.qualified, "--material", "--omit-resources", + "--revision", view["revision"], *document.store_args) + size = text_page(view["content"].encode(), 0, INLINE_PAGE_BYTES)[1] + return _ReadPreview(args, size, bundle, view, document.store_args) reader = readers.get(document.root) if reader is None: reader = readers[document.root] = KnowledgeReader(skill_root=document.root) - try: - bundle = reader.read(document.qualified) - material = bundle.view(material=True) - except MissingSkillsExtra: - if document.source_location != "installed": - raise + record = document.package_record + if record is None and package_skills: record = installed_skill_projection(document, reader.record) - if record is None: - raise + if record is None: + try: + bundle = reader.read(document.qualified) + material = bundle.view(material=True) + except MissingSkillsExtra: + record = installed_skill_projection(document, reader.record) + if record is None: + raise + if record is not None: package_reader = readers.get(None) if package_reader is None: package_reader = readers[None] = KnowledgeReader() @@ -841,11 +970,14 @@ def _read_preview(document: Document, readers: dict) -> _ReadPreview | None: bundle = package_reader.read(ref) view = bundle.view() core, _, _ = indexed_skill(record, {**view, "authority": "package"}, bundle.content) - bundle.content[core].decode("utf-8") + data = bundle.content[core] + if package_skills: + data, _ = skill_procedure(core, data) + data.decode("utf-8") args = ( "read", ref, "--omit-resources", "--resource", core, "--revision", view["revision"], ) - return _ReadPreview(args, len(bundle.content[core]), bundle, view, ()) + return _ReadPreview(args, text_page(data, 0, INLINE_PAGE_BYTES)[1], bundle, view, ()) source_args = () if document.root is not None: @@ -853,14 +985,30 @@ def _read_preview(document: Document, readers: dict) -> _ReadPreview | None: source_args = ("--installed-library",) else: source_args = ("--skill-root", str(document.root)) - args = ("read", document.qualified, "--material", "--omit-resources", *source_args) - size = len(material["content"].encode("utf-8")) + args = ("read", document.qualified, "--material", "--omit-resources", + "--revision", material["revision"], *source_args) + size = text_page(material["content"].encode("utf-8"), 0, INLINE_PAGE_BYTES)[1] return _ReadPreview(args, size, bundle, material, source_args) _DECISION_SOURCE_UNAVAILABLE = "Source unavailable; repeat Find" +def _ranked_source_mismatch(document: Document, preview: _ReadPreview) -> str | None: + """Only offer a pinned read of the source that supplied the hit's searchable fields.""" + directory = PurePosixPath() + if document.kind == "skill": + body = preview.body_resource + prefix = "data/skill_library/" if preview.args[1].startswith("package:") else "" + if body != f"{prefix}{document.path}": + return "Skill location changed after ranking; repeat Find" + directory = PurePosixPath(body).parent + if any(_source_digest(preview.bundle.content.get(str(directory / name))) != expected + for name, expected in document.ranked_sources.items()): + return "Source changed after ranking; repeat Find" + return None + + def _decision_links( hit: dict, document: Document, preview: _ReadPreview | None, tokens: list[str], query_backend: str | None, @@ -872,24 +1020,16 @@ def _decision_links( if preview is None: return _DECISION_SOURCE_UNAVAILABLE if document.qualified else "missing qualified reference" source = DecisionSource.from_bundle(preview.args[1], preview.bundle, preview.view) - directory = PurePosixPath(source.body).parent if source.kind == "skill" else PurePosixPath() - if source.kind == "skill": - prefix = "data/skill_library/" if source.ref.startswith("package:") else "" - if source.body != f"{prefix}{document.path}": - return "Skill location changed after ranking; repeat Find" - # Checkout bundles cover the Skill directory. Its registration lives in the root. - if query_backend and source.ref.startswith("checkout:"): - registration = skill_registrations(document.root).get(document.identity) - if registration is None or ( - registration[0] / "SKILL.md" != document.root / document.path - or _backend_weight(registration[1], query_backend) - != _backend_weight(document.backend, query_backend) - ): - return "Skill registration changed after ranking; repeat Find" - if not document.ranked_sources or any( - _source_digest(preview.bundle.content.get(str(directory / name))) != expected - for name, expected in document.ranked_sources.items() - ): + # Checkout bundles cover the Skill directory. Its registration lives in the root. + if source.kind == "skill" and query_backend and source.ref.startswith("checkout:"): + registration = skill_registrations(document.root).get(document.identity) + if registration is None or ( + registration[0] / "SKILL.md" != document.root / document.path + or _backend_weight(registration[1], query_backend) + != _backend_weight(document.backend, query_backend) + ): + return "Skill registration changed after ranking; repeat Find" + if not document.ranked_sources and document.stored_bundle is None: return "Source changed after ranking; repeat Find" def link(selector: str | None = None) -> dict: @@ -951,6 +1091,8 @@ def find( limit: int = 5, explain: bool = False, decision_cards: bool = False, + pin_material: bool = False, + unreadable_hits: list[dict] | None = None, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, registry: "ChannelRegistry | None" = None, backend: str | None = None, @@ -960,7 +1102,11 @@ def find( searchspace_coordinate: SearchspaceCoordinate | None = None, show_searchspace_coordinates: bool = False, ) -> dict: - """Find local matches, optionally annotating them from the verified ranking source.""" + """Find local matches, optionally annotating them from the verified ranking source. + + A caller selecting a bounded delivery can collect unreadable hits separately + and count only readable material towards its item limit. + """ if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") query_tokens, applied, scored = rank(query, corpus, ranking_policy) @@ -989,22 +1135,36 @@ def find( ] items = [] readers: dict = {} - for value, _, position, detail in scored[:limit]: + for value, _, position, detail in scored: document = corpus.documents[position] + mismatch = None try: - preview = _read_preview(document, readers) - unreadable = None + preview = _read_preview(document, readers, pin_material) + if preview is not None and document.ranked_sources: + mismatch = _ranked_source_mismatch(document, preview) + if mismatch: + preview = None + unreadable = mismatch except (ValueError, KeyError, OSError, TypeError) as exc: preview, unreadable = None, str(exc) or type(exc).__name__ view = document.view( score=value, query_tokens=query_tokens, read_args=preview.args if preview else (), unreadable=unreadable, ) + if preview is None and unreadable_hits is not None: + unreadable_hits.append(view) + continue if preview: view["next_read_content_bytes"] = preview.size + if document.package_record is not None: + view.update(id=document.package_record["id"], authority="package") + if pin_material: + view.update(preview.session_pin()) if decision_cards: try: - reason = _decision_links(view, document, preview, query_tokens, query_backend) + reason = mismatch or _decision_links( + view, document, preview, query_tokens, query_backend, + ) except (ValueError, KeyError, OSError, TypeError): reason = _DECISION_SOURCE_UNAVAILABLE if reason is not None: @@ -1022,10 +1182,13 @@ def find( coverage["exclusion_reason"] = entry.exclusion_reason view["searchspace_coordinates"] = coverage items.append(view) + if len(items) == limit: + break result = { "query": query, "tokens": query_tokens, "corpus_size": len(corpus.documents), + **({"sources": list(corpus.sources)} if pin_material else {}), "ranking_policy": ranking_policy.receipt(), "matched": len(scored), "items": items, @@ -1075,7 +1238,7 @@ def _with_channels( """ if registry is None or not registry.channels: return result - from .channels import explain_gate, search_channels + from .channels import explain_gate, no_match_across_sources, search_channels declared = backend if backend is not None else registry.declared_backend results = search_channels( @@ -1089,6 +1252,8 @@ def _with_channels( gated = explain_gate(registry, declared) if gated: result.setdefault("external", []).extend(gated) + if "external" in result: + result["no_match"] = no_match_across_sources(result["matched"], result["external"]) if (results or gated) and all( getattr(channel, "navigation_only", False) for channel in registry.channels ): diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index 3b5af8a67..d8e7b82d1 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -2,8 +2,10 @@ import hashlib import json +import posixpath import re import sqlite3 +from collections.abc import Container from dataclasses import dataclass from datetime import date, datetime from importlib.resources import files @@ -13,7 +15,9 @@ from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import ( FIND_RELEVANCE, + candidate_contexts, context_view, + declared_skill_references, indexed_skill, record_context, skill_procedure, @@ -56,6 +60,25 @@ def safe_path(value: str) -> str: return value +def _resource_candidates(value: str, body: str): + yield value + target = value.partition("#")[0] + if not target or target.startswith("/") or "\\" in target or ":" in target: + raise ValueError(f"Unsafe bundle path: {value}") + directory = posixpath.dirname(safe_path(body)) + yield safe_path(posixpath.normpath(posixpath.join(directory, target))) + if target != value: + yield target + + +def resolve_resource_key(value: str, body: str, members: Container[str]) -> str: + """Resolve a bundle key or a local Markdown link against an already opened body.""" + for path in _resource_candidates(value, body): + if path in members: + return safe_path(path) + raise ValueError(f"Unknown resource: {value}") + + def case_resource_path(root: Path, record_path: Path, resource: object) -> Path: """Resolve a resource a case record names, refusing anything outside `root`. @@ -310,98 +333,67 @@ def _tree( return result -class KnowledgeReader: - def collect_service_context( - self, cue, *, relevance_method, limit, context_bytes, - ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, - ): - """Package knowledge for service campaigns; no Bundle/content identity path.""" - from .catalog import _catalog_corpus, without_file_fingerprints - from .context_projection import assemble_context_text - from .knowledge_find import rank - - validate_relevance_method(relevance_method) - if ( - not isinstance(cue, str) - or not re.search(r"\w", cue) - or type(limit) is not int - or limit < 1 - or type(context_bytes) is not int - or context_bytes < 1 +def _service_scope(record): + editions = record.get("skill_documents", {}) + primary = editions.get("original") or "record.json" + owner = posixpath.dirname(primary) + declared = set(editions.values()) + if owner: + declared.update(posixpath.normpath(posixpath.join(owner, link)) + for link in declared_skill_references(record.get("skill_metadata", {}))) + return primary, owner, declared + + +def _service_node(root, path): + parts = safe_path(path).split("/") + if not path.startswith("data/skill_library/") or parts[2] in {"records", "config", "_compiled"}: + raise ValueError(f"Unavailable service knowledge resource: {path}") + if any(part in INCIDENTAL or part.endswith(".pyc") for part in parts): + raise ValueError(f"Unavailable service knowledge resource: {path}") + node = root + for part in parts: + node = node.joinpath(part) + if isinstance(node, Path) and node.is_symlink(): + raise ValueError(f"Symbolic knowledge resource: {path}") + return node + + +def service_resources(record): + """Capture the exact owner and declared files this service hit can subsequently read.""" + root = files("inferrsi").joinpath("knowledge") + _, owner, declared = _service_scope(record) + resources = {"record.json": _json(record)} + if owner: + resources.update(_tree(_service_node(root, owner), owner)) + for path in sorted(declared): + if path not in resources: + node = _service_node(root, path) + if node.is_file(): + resources[path] = node.read_bytes() + return resources + + +def service_body(record, resource=None, *, source_root=None): + """Open one resource from the installed package or an already retained service source.""" + primary, owner, declared = _service_scope(record) + root = files("inferrsi").joinpath("knowledge") if source_root is None else source_root + requested = primary if resource is None else resource + for path in _resource_candidates(requested, primary): + if path == "record.json": + return path, _json(record), {} + if not path.startswith("data/skill_library/") or ( + path not in declared and not (owner and path.startswith(owner + "/")) ): - raise ValueError("Valid cue and positive limit/context budget required") - corpus, records = _catalog_corpus(knowledge_records(file_fingerprints=False)) - _, _, ranked = rank(cue, corpus, ranking_policy) - package = files("inferrsi").joinpath("knowledge") - contexts, omissions, used = [], [], 0 - for score, _, index, _ in ranked: - record = records[index] - ref = "package:" + record["id"] - documents = record.get("skill_documents", {}) - path = documents.get("original") if documents else None - if path is not None: - safe_path(path) - if not path.startswith("data/skill_library/"): - raise ValueError("Service knowledge resource must stay inside the library") - node = package.joinpath(*path.split("/")) - if isinstance(node, Path) and node.is_symlink(): - raise ValueError("Symbolic knowledge resource") - body = node.read_bytes() - else: - body = _json(record) - path = "record.json" - body, locator = skill_procedure(path, body) - if len(contexts) >= limit or used + len(body) > context_bytes: - omissions.append( - { - "ref": ref, - "reason": "context_limit" - if used + len(body) > context_bytes - else "item_limit", - } - ) - continue - sources = record["sources"] - contexts.append( - { - "ref": ref, - "revision": sources[0]["commit"], - "sources": sources, - "content_bytes": len(body), - "score": score, - "resources": [{"path": path, "role": "core", "content": body.decode("utf-8"), - **locator}], - "omissions": [ - {"path": target, "reason": "linked_document_not_loaded"} - for target in record.get("skill_metadata", {}).get("references", []) - ], - "limitations": [ - "Prepared source text; no content identity or model-consumption claim." - ], - } - ) - used += len(body) - if self.skill_root or self.store: - omissions.append({"reason": "checkout_and_store_require_content_identity_not_used"}) - return without_file_fingerprints( - { - "schema_version": 2, - "kind": "service_knowledge_context", - "request": { - "relevance": cue, - "relevance_method": FIND_RELEVANCE, - "ranking_policy": ranking_policy.configuration(), - "limit": limit, - "context_bytes": context_bytes, - }, - "contexts": contexts, - "omissions": omissions, - "context_bytes": used, - "assembled_text": assemble_context_text(contexts), - "prepared_not_consumed": True, - } - ) + continue + node = _service_node(root, path) + if node.is_file(): + raw = node.read_bytes() + data, locator = (raw, {}) if resource is not None else skill_procedure(path, raw) + return path, data, locator + raise ValueError(f"Unknown resource: {requested}") + +class KnowledgeReader: def __init__(self, *, skill_root: Path | None = None, store=None): self.skill_root = skill_root.resolve() if skill_root is not None else None if store is not None and store.skill_root != self.skill_root: @@ -701,82 +693,20 @@ def resource(self, identity: str, path: str, *, revision: str) -> bytes: raise ValueError(f"Unknown resource: {path}") return bundle.content[path] - def _search_order( - self, cue: str, matches, *, kind: str | None, package_only: bool, backend: str | None, - store_documents: list[Document], ranking_policy: RankingPolicy, - ) -> tuple[dict, int, dict[str, int]]: - from .knowledge_find import ( - Corpus, - installed_skill_projection, - installed_skill_root, - load_documents, - rank, + def pack_find_hits(self, hits, *, cue, limit, context_bytes, max_bytes=None, revisions=None, + ranking_policy=DEFAULT_RANKING_POLICY): + """Pack the complete bodies of already ranked pins, then their relevant attachments.""" + fixed = revisions or {} + pins = {hit["material_ref"]: fixed.get(hit["material_ref"], hit["revision"]) + for hit in hits} + if type(context_bytes) is not int or context_bytes < 0: + raise ValueError("A candidate context requires a nonnegative byte limit") + return self.collect( + ids=list(pins), revisions=pins, limit=limit, relevance=cue if pins else None, + max_bytes=max_bytes, context_bytes=context_bytes, ranking_policy=ranking_policy, + _found_bodies={hit["material_ref"]: hit["body_resource"] for hit in hits}, ) - kinds = { - None: ("case", "skill", "record"), - "case": ("case",), - "skill": ("skill",), - "knowledge": ("skill", "record"), - } - root = None if package_only else self.skill_root - records = self.records() - search_kinds = kinds[kind] - package_only_store = self.store is not None and self.skill_root is None - if package_only_store: - search_kinds = tuple(name for name in search_kinds if name != "case") - documents = load_documents(root, kinds=search_kinds, records=records.values()) - if root is not None and root != installed_skill_root() and kind is None: - # A selected custom library owns its registered skills. The package - # supplies missing skills and remains available for exact reads. - custom_skills = { - document.identity for document in documents if document.kind == "skill" - } - documents.extend( - document for document in load_documents(kinds=("skill",)) - if document.identity not in custom_skills - and installed_skill_projection(document, records) is not None - ) - documents.extend(store_documents) - - eligible, references = [], [] - excluded = {"filters": 0, "ranking_scope": 0} - considered = 0 - for document in documents: - authority, _, identity = document.qualified.partition(":") - projection = installed_skill_projection(document, records) - if projection is not None: - authority, identity = "package", projection["id"] - if package_only_store and authority == "checkout": - continue - considered += 1 - if authority == "package": - material_kind = "skill" if kind == "skill" else "knowledge" - metadata = {**records[identity], "kind": material_kind} - else: - metadata = { - "kind": "knowledge" if document.kind == "record" else document.kind, - "backend": document.backend, - } - if ( - backend and not package_only and document.kind == "case" - and document.backend is None - ): - excluded["ranking_scope"] += 1 - elif matches(metadata, authority): - eligible.append(document) - references.append(f"{authority}:{identity}") - else: - excluded["filters"] += 1 - - _, _, scored = rank(cue, Corpus(eligible), ranking_policy) - results = { - references[index]: {"score": round(score, 2), "components": components} - for score, _, index, components in scored - } - excluded["zero_score"] = len(eligible) - len(results) - return results, considered, excluded - def collect( self, query: str | None = "", @@ -796,6 +726,7 @@ def collect( ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, context_bytes: int | None = None, decision_cards: dict[str, str | None] | None = None, + _found_bodies: dict[str, str] | None = None, ) -> dict: if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") @@ -810,22 +741,15 @@ def collect( validate_relevance_method(relevance_method) if query is not None and not isinstance(query, str): raise ValueError("query must be a string or None") - if query and query.strip(): - if ids is not None: - raise ValueError( - "Remove query when using explicit IDs. Use relevance to guide context assembly." - ) - if relevance is not None: - raise ValueError("Find takes one query or relevance cue. Supply only one.") - cue = query - else: - cue = relevance + if (query and query.strip()) or (relevance is not None and not ids): + raise ValueError("Use find(query, load_corpus(...)) to search for material. " + "Collect uses relevance only for attachments of explicit IDs.") if relevance is not None and ( not isinstance(relevance, str) or not re.search(r"\w", relevance) ): raise ValueError("relevance requires at least one word") - find_ranking = cue is not None and ids is None - if context_bytes is not None and (type(context_bytes) is not int or context_bytes < 1): + if context_bytes is not None and (type(context_bytes) is not int + or context_bytes < (1 if _found_bodies is None else 0)): raise ValueError("context_bytes must be a positive integer") if revisions is None: revisions = {} @@ -848,14 +772,7 @@ def collect( raise ValueError(f"Decision card requires an exact revision for {ref}") if finding is not None and (not isinstance(finding, str) or not finding.strip()): raise ValueError("A finding must be a nonempty selector") - checkout = self owners = self.owners() - if find_ranking and self.skill_root is None and self.store is None: - from .knowledge_find import installed_skill_root - - checkout = KnowledgeReader(skill_root=installed_skill_root()) - for identity in checkout._checkout_identities(): - owners.setdefault(identity, []).append("checkout") requested = ids if ids is not None else sorted( f"{authority}:{identity}" for identity, values in owners.items() for authority in values ) @@ -882,21 +799,11 @@ def qualified(reference: str) -> str | None: if tier is not None and tier not in KNOWLEDGE_SCOPES: raise ValueError(f"Unknown knowledge tier: {tier}") scenario = SCENARIO_ALIASES.get(scenario, scenario) - package_filters = any( - value is not None for value in (repo, tier, scenario) - ) or (backend is not None and not find_ranking) + package_filters = any(value is not None for value in (repo, tier, scenario, backend)) def matches(metadata: dict, authority: str) -> bool: declared = metadata.get("scenario") declared = declared if isinstance(declared, str) else "" - # The catalog records skills.discovery as the discovery operation, - # not the workload served by a procedure. Let the task cue rank - # these procedures alongside records declaring the requested workload. - discovery_skill = ( - find_ranking and authority == "package" - and declared == "skills.discovery" - and metadata.get("index_type") == "packaged-skill" - ) return not ( (kind and metadata.get("kind") != kind) or (package_filters and authority != "package") @@ -907,7 +814,6 @@ def matches(metadata: dict, authority: str) -> bool: scenario is None or declared == scenario or (declared.endswith(".*") and scenario.startswith(declared[:-1])) - or discovery_skill ) ) @@ -916,37 +822,11 @@ def matches(metadata: dict, authority: str) -> bool: "item_limit": 0, "material_bytes": 0, } considered = len(requested) - found, store_revisions = {}, {} omitted = [] - if find_ranking: - store_documents = [] - for reference in requested: - if not reference.startswith("store:"): - continue - try: - bundle = self._read(reference, pinned.get(reference)) - store_revisions[reference] = bundle.revision - store_documents.append(_store_document(reference, bundle)) - except IdentityError as exc: - omitted.append({"id": reference, "reason": exc.code, "detail": str(exc)}) - except RevisionConflict as exc: - omitted.append({ - "id": reference, "reason": "unavailable_revision", "detail": str(exc), - }) - except (ValueError, KeyError, TypeError, OSError, sqlite3.Error) as exc: - omitted.append({"id": reference, "reason": "invalid", "detail": str(exc)}) - found, considered, rank_excluded = self._search_order( - cue, matches, kind=kind, backend=backend, - package_only=package_filters or kind == "knowledge", - store_documents=store_documents, ranking_policy=ranking_policy, - ) - considered += len(omitted) - requested = list(found) - excluded.update(rank_excluded) - cases = self._cases() if kind and not find_ranking else {} + cases = self._cases() if kind else {} selected, seen = [], set() used = 0 - contexts, context_omissions = [], [] + contexts, context_omissions, found_entries = [], [], [] delivered_bundles: dict[str, tuple[str, Bundle]] = {} context_used = 0 matched_count = 0 @@ -956,18 +836,9 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: packaged = view["authority"] == "package" record = ( self.records().get(view["id"], {}) - if packaged and (find_ranking or context_bytes is not None) else {} + if packaged and context_bytes is not None else {} ) is_skill = record.get("index_type") == "packaged-skill" - index = None - if find_ranking and is_skill: - try: - index = indexed_skill(record, view, bundle.content) - except (ValueError, KeyError, TypeError) as exc: - omitted.append({ - "id": reference, "reason": "index_unavailable", "detail": str(exc), - }) - return matched_count += 1 # Normal Bundle views were serialized while computing their revision. # Preserve custom subclasses' serialization/error behavior below. @@ -984,21 +855,23 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: used += size if context_bytes is None: return + if _found_bodies is not None: + found_entries.append((view, record, bundle.content, _found_bodies[view["ref"]])) + return pinned_item = ids is not None and view["ref"] in pinned checkout_context = ( view["authority"] == "checkout" and view["kind"] in ("case", "skill") - and (find_ranking or pinned_item) + and pinned_item ) - if not ((packaged and (is_skill or find_ranking or pinned_item)) or checkout_context): + if not ((packaged and (is_skill or pinned_item)) or checkout_context): context_omissions.append({"ref": view["ref"], "reason": "unsupported_context"}) return try: available = context_bytes - context_used if is_skill: - if index is None: - index = indexed_skill(record, view, bundle.content) + index = indexed_skill(record, view, bundle.content) context, omission = context_view( - index, view, bundle.content, cue, available, ranking_policy, + index, view, bundle.content, relevance, available, ranking_policy, ) else: context, omission = record_context(record, view, bundle.content, available) @@ -1016,33 +889,29 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: delivered_bundles[view["ref"]] = (view["ref"], bundle) for reference in requested: - if find_ranking and len(selected) >= limit: - excluded["item_limit"] += len(requested) - len(seen) - break try: qualified = self.resolve(reference, owners) if qualified in seen: raise IdentityError("duplicate_identity", f"Already selected: {qualified}") seen.add(qualified) authority, _, identity = qualified.partition(":") - if not find_ranking: - # Cheap metadata checks first, before loading bundle resources. - if authority == "package": - early = {**self.records()[identity], "kind": "knowledge"} - elif authority == "checkout": - early = {"kind": "case" if identity in cases else "skill"} - else: - early = None - if early is not None and not matches(early, authority): - excluded["filters"] += 1 - if ids is not None: - omitted.append({"id": reference, "reason": "filters"}) - continue - reader = checkout if authority == "checkout" else self - revision = store_revisions.get(qualified, pinned.get(qualified)) - bundle = reader._read(qualified, revision) + # Cheap metadata checks first, before loading bundle resources. + if authority == "package": + early = {**self.records()[identity], "kind": "knowledge"} + elif authority == "checkout": + early = {"kind": "case" if identity in cases else "skill"} + else: + early = None + if early is not None and not matches(early, authority): + excluded["filters"] += 1 + if ids is not None: + omitted.append({"id": reference, "reason": "filters"}) + continue + bundle = self._read(qualified, pinned.get(qualified)) view = {**bundle.view(material=material), "authority": authority, "ref": qualified} - if find_ranking and view["kind"] == "case": + # A Case selected by Find still includes its ranked title in the + # material-size limit when its exact pin is assembled later. + if _found_bodies is not None and view["kind"] == "case": view.setdefault("title", identity.removeprefix("case.")) except IdentityError as exc: omitted.append({"id": reference, "reason": exc.code, "detail": str(exc)}) @@ -1052,10 +921,7 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: {"id": reference, "reason": "unavailable_revision", "detail": str(exc)} ) continue - except MissingSkillsExtra as exc: - if find_ranking: - omitted.append({"id": reference, "reason": "invalid", "detail": str(exc)}) - continue + except MissingSkillsExtra: # The install cannot parse any checkout skill, not just this one. # As an omission it would return `no_match`, which reads as # "nothing found" rather than "install the skills extra". @@ -1063,12 +929,16 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: except (ValueError, KeyError, TypeError, AttributeError, OSError, sqlite3.Error) as exc: omitted.append({"id": reference, "reason": "invalid", "detail": str(exc)}) continue - if not find_ranking and not matches(view, authority): + if not matches(view, authority): excluded["filters"] += 1 if ids is not None: omitted.append({"id": reference, "reason": "filters"}) continue select(reference, bundle, view) + if found_entries: + contexts, context_omissions, context_used = candidate_contexts( + found_entries, relevance, context_bytes, ranking_policy, + ) result = { "items": selected, "omissions": omitted, @@ -1081,18 +951,7 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: "Read references must be resolved with their returned exact revision.", ], } - if find_ranking: - result["selection"] = { - "method": FIND_RELEVANCE, "cue": cue, - "scope": ("package-records-library-and-store" if self.store is not None - else "package-records-and-library"), - "ranking_applied": True, - "matched_count": len(found), "returned_count": len(selected), - } - result["limitations"][0] = ( - "Find ranks textual matches. Check each item's applicability and limitations." - ) - elif relevance is not None: + if relevance is not None: result["selection"] = { "method": FIND_RELEVANCE, "cue": relevance, "scope": "context-resources", "ranking_applied": False, @@ -1150,25 +1009,21 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: "backend": backend, "scenario": scenario, "limit": limit, "max_bytes": max_bytes, "context_bytes": context_bytes, **({"decision_cards": dict(decision_cards)} if decision_cards else {}), - "sources": ["package"] + (["checkout"] if checkout.skill_root else []) + "sources": ["package"] + (["checkout"] if self.skill_root else []) + (["store"] if self.store is not None else []), }, selection={ "method": selection.get("method"), "scope": selection.get("scope"), **({"ranking_policy": selection["ranking_policy"]} if selection else {}), - "ranking_applied": find_ranking, - "state": "applied" if find_ranking else "explicit_ids" if ids is not None - else "not_requested", - "tie_break": "state_then_id_then_ref" if find_ranking else None, - }, items=[{"ref": item["ref"], "revision": item["revision"], "rank": n, - **found.get(item["ref"], {})} + "ranking_applied": False, + "state": "explicit_ids" if ids is not None else "not_requested", + "tie_break": None, + }, items=[{"ref": item["ref"], "revision": item["revision"], "rank": n} for n, item in enumerate(selected, 1)], counts={ - "considered": considered, "matched": len(found) if find_ranking else matched_count, + "considered": considered, "matched": matched_count, "returned": len(selected), "excluded": excluded, }, assembly="not_requested" if context_bytes is None else "performed", ) - if find_ranking: - result["retrieval"]["calls"].append("find") return result diff --git a/src/inferrsi/knowledge/research.py b/src/inferrsi/knowledge/research.py index 280985e52..a72351610 100644 --- a/src/inferrsi/knowledge/research.py +++ b/src/inferrsi/knowledge/research.py @@ -1,134 +1,6 @@ -"""Read-only model-aware discovery; target annotations are not runtime support.""" - -from __future__ import annotations - -import json -import math -from collections.abc import Sequence -from importlib.resources import files - -from .catalog import _catalog_corpus, _scoped_records -from .knowledge_find import rank -from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy +"""Path to the published model preparation procedure.""" PROCEDURE = ( "data/skill_library/workflows/research/inference-engine-research/" "references/model-aware-preparation.md" ) - - -def _profile(model: str) -> dict | None: - config = files("inferrsi").joinpath("knowledge", "data", "skill_library", "config") - root = config.joinpath("research_profiles") - for resource in sorted(root.iterdir(), key=lambda path: path.name): - if resource.name.endswith(".json"): - profile = json.loads(resource.read_text(encoding="utf-8")) - if model.casefold() in {name.casefold() for name in profile["aliases"]}: - return profile - return None - - -def research_knowledge( - model: str, - *, - frameworks: Sequence[str] = (), - tasks: Sequence[str] = (), - modalities: Sequence[str] = (), - mechanisms: Sequence[str] = (), - repo: str | None = None, - tier: str | None = None, - backend: str | None = None, - scenario: str | None = None, - limit: int = 10, - target_backend: str | None = None, - target_device: str | None = None, - target_memory_gib: float | None = None, - ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, -) -> dict: - """Union separate research queries, preserving every package filter and record. - - Round-robin selection gives each query a turn before another result from the - same query. It is discovery ordering, not an engine or evidence-quality rank. - """ - if not model.strip(): - raise ValueError("model must be nonempty") - if limit < 1: - raise ValueError("limit must be positive") - if target_memory_gib is not None and ( - not math.isfinite(target_memory_gib) or target_memory_gib <= 0 - ): - raise ValueError("target memory must be positive and finite GiB") - model = model.strip() - profile = _profile(model) - defaults = profile or {} - groups = { - "model": [model, *([profile["model"]] if profile else [])], - "framework": frameworks, - "task": [*defaults.get("tasks", []), *tasks], - "modality": [*defaults.get("modalities", []), *modalities], - "mechanism": [*defaults.get("mechanisms", []), *mechanisms], - } - filters = {"repo": repo, "tier": tier, "backend": backend, "scenario": scenario} - queries, streams, matches = [], [], {} - scoped, _ = _scoped_records(**filters) - corpus, document_records = _catalog_corpus(scoped) - # Retain every query's matches before capping the union so overlapping - # records keep all their query attributions. - for group, terms in groups.items(): - seen = set() - for term in terms: - term = term.strip() - if not term: - raise ValueError(f"{group} query must be nonempty") - if term.casefold() in seen: - continue - seen.add(term.casefold()) - query = {"group": group, "query": term} - _, _, scored = rank(term, corpus, ranking_policy) - records = [document_records[index] for _, _, index, _ in scored] - queries.append({**query, "matches": len(records)}) - streams.append(records) - for record in records: - matches.setdefault(record["id"], []).append(query) - selected = {} - for position in range(max((len(stream) for stream in streams), default=0)): - for stream in streams: - if position < len(stream): - record = stream[position] - selected.setdefault(record["id"], record) - if len(selected) == limit: - break - if len(selected) == limit: - break - return { - "model": model, - "ranking_policy": ranking_policy.receipt(), - "profile": profile, - "queries": queries, - "filters": filters, - "items": [ - {"record": record, "matched_queries": matches[identity]} - for identity, record in selected.items() - ], - "no_match": not selected, - "target": { - "backend": target_backend, "device": target_device, "memory_gib": target_memory_gib, - }, - "target_validation": "unverified", - "components": defaults.get("components", []), - "procedure_resource": PROCEDURE, - "worked_example_resource": defaults.get("worked_example_resource"), - "warnings": [] if profile else [ - "No packaged model profile: supply --task/--modality and verify the full component " - "inventory from the selected checkpoint before judging feasibility." - ], - "limitations": [ - "Each query uses Find's lexical ranking over installed package records eligible " - "under the scope filters. Other sources require separate discovery.", - "Mechanism queries are research leads, not claims of model/backend support. " - "Retain each record's applicability, source revision and verification state.", - "Target annotations do not inspect hardware or add a runtime backend. Full weight " - "inventory, engine/format compatibility, peak residency and quality need evidence " - "under the linked preparation procedure; no engine is selected or executed.", - ], - } diff --git a/tests/apps/check_workswarm_installed.py b/tests/apps/check_workswarm_installed.py index 105161e99..ee0a4f66d 100644 --- a/tests/apps/check_workswarm_installed.py +++ b/tests/apps/check_workswarm_installed.py @@ -111,10 +111,10 @@ def invoke(*args: str, expected: int = 0): info = invoke("--plugin-info") assert info["runtime"] == "bundled" assert info["content_sha256"] == manifest["content_sha256"] - items = invoke("collect", "--relevance", "inference memory", "--limit", "1", - "--json")["items"] - assert items - item = items[0] + hit, = invoke("find", "inference memory", "--kinds", "record", "--limit", "1", + "--no-external", "--json")["items"] + item = invoke(*hit["read_args"]) + assert item["content"] material = invoke("read", item["ref"], "--revision", item["revision"], "--material") assert material["revision"] == item["revision"] invoke("read", item["ref"], "--revision", "sha256:" + "0" * 64, expected=2) diff --git a/tests/apps/test_apps_context_provider.py b/tests/apps/test_apps_context_provider.py index 70285d496..1c9b5fc73 100644 --- a/tests/apps/test_apps_context_provider.py +++ b/tests/apps/test_apps_context_provider.py @@ -1,12 +1,17 @@ """Check the Apps side of D023-3 against public Knowledge reads.""" +import json +import shutil from hashlib import sha256 -from pathlib import PurePosixPath +from pathlib import Path, PurePosixPath import pytest from inferrsi.apps.handoff.context_provider import ContextProvider from inferrsi.apps.workflows.knowledge import knowledge_reader +from inferrsi.knowledge.knowledge_find import find, installed_skill_root, load_corpus +from inferrsi.knowledge.knowledge_operations import Bundle, KnowledgeReader +from inferrsi.knowledge.knowledge_store import KnowledgeStore _CGROUP = "package:inferrsi.common.skills.cgroup_resource_controls" _H3 = "package:inferrsi.common.skills.audit_h3_runtime_residency" @@ -84,7 +89,16 @@ def test_unavailable_pin_never_falls_back_to_current_revision(): assert [entry["code"] for entry in draft.omissions] == ["unavailable_revision"] -def test_discovery_delegates_selection_to_knowledge(): +def test_find_selects_the_pin_before_exact_assembly(monkeypatch): + collect = KnowledgeReader.collect + + def assemble(self, query="", **options): + assert not query and options["ids"] == [_CGROUP] + assert options["revisions"] == {_CGROUP: self.read(_CGROUP).revision} + assert options["relevance"] == "cgroupv2" + return collect(self, query, **options) + + monkeypatch.setattr(KnowledgeReader, "collect", assemble) bounds = {"relevance": "cgroupv2", "limit": 1} draft = ContextProvider(knowledge_reader()).collect( _request(ids=[], selection_limits=bounds), @@ -96,6 +110,29 @@ def test_discovery_delegates_selection_to_knowledge(): assert draft.selection["tie_break"] == "state_then_id_then_ref" +def test_find_uses_the_question_to_select_optional_files_for_the_sealed_pin(): + provider = ContextProvider(knowledge_reader()) + query = "video diffusion temporal tiling" + request = _request(query=query, ids=[], selection_limits={"kind": "skill", "backend": "cuda", + "limit": 1}) + draft = provider.collect(request) + ref = "package:inferrsi.common.skills.video_diffusion_optimization" + revision = provider.reader.read(ref).revision + item, = draft.items + assert item["pin"] == {"reference": ref, "revision": revision} + assert item["delivered_roles"] == ["core"] + exact, = provider.reader.collect(ids=[ref], revisions={ref: revision}, relevance=query, + context_bytes=request["max_bytes"])["contexts"] + body, = exact["resources"] + assert draft.content == body["content"].encode("utf-8") + assert draft.sha256 == body["sha256"] + assert any(row["code"] == "not_relevant" and "campaign.template.json" in row["message"] + for row in draft.omissions) + + miss = provider.collect({**request, "query": "!!!"}) + assert miss.content == b"" and miss.items == [] and miss.selection["no_match"] + + def test_discovered_installed_case_can_be_replayed_at_its_exact_revision(): provider = ContextProvider(knowledge_reader()) discovered = provider.collect(_request( @@ -114,8 +151,122 @@ def test_discovered_installed_case_can_be_replayed_at_its_exact_revision(): assert replay.selection["state"] == "explicit_ids" +def test_query_reserves_both_diffusion_bodies_before_any_attachments(): + from inferrsi.knowledge._skill_selection import skill_procedure + from tests.apps.test_campaign_task_selection import BASELINE_CUE + + provider = ContextProvider(knowledge_reader()) + req = _request(query=BASELINE_CUE, ids=[], selection_limits={"backend": "cuda", "limit": 2}) + draft = provider.collect(req) + refs = ["package:inferrsi.common.skills.inference_benchmark_design", + "package:inferrsi.common.skills.video_diffusion_optimization"] + assert [item["pin"]["reference"] for item in draft.items] == refs + bodies = [] + for item in draft.items: + pin = item["pin"] + bundle = provider.reader.read(pin["reference"], revision=pin["revision"]) + body = bundle.metadata["skill_documents"]["original"] + bodies.append(skill_procedure(body, bundle.content[body])[0]) + assert all(body in draft.content for body in bodies) + assert len(draft.content) <= req["max_bytes"] and draft.omissions + exact = provider.collect({**req, "max_bytes": sum(map(len, bodies))}) + assert exact.content == b"".join(bodies) + assert all(item["delivered_roles"] == ["core"] for item in exact.items) + assert any(item["code"] == "context_limit" for item in exact.omissions) + + +def test_find_respects_separate_selection_and_sealed_byte_limits(tmp_path): + source = Path(__file__).resolve().parents[1] / "fixtures/indexer/ranking-corpus" + library = shutil.copytree(source, tmp_path / "library") + record = library / "demo/cases/alpha.json" + data = json.loads(record.read_text()) + data["limitations"] = ["x" * 10000] + record.write_text(json.dumps(data)) + provider = ContextProvider(knowledge_reader(skill_root=library)) + request = _request(query="qxrankprobe", ids=[], + selection_limits={"kind": "case", "limit": 1, "max_bytes": 2048}) + draft = provider.collect(request) + item, = draft.items + assert item["pin"]["reference"] == "checkout:case.alternate" + assert draft.content and draft.selection["matched_count"] == 2 + assert any(row["code"] == "output_limit" and "case.qxrankprobe" in row["message"] + for row in draft.omissions) + empty = provider.collect({**request, "max_bytes": 0}) + assert empty.content == b"" and empty.selection == draft.selection + assert any(row["code"] == "context_limit" for row in empty.omissions) + + +def test_ranked_case_title_counts_toward_selection_bytes_for_the_handoff(): + reader = knowledge_reader(skill_root=installed_skill_root()) + provider = ContextProvider(reader) + limits = {"kind": "case", "limit": 1, "max_bytes": 6000} + request = _request(query="drama3 rejected directions", ids=[], selection_limits=limits) + ranked = provider.collect(request) + first = "checkout:case.drama3-rejected-directions" + second = "checkout:case.qwen-b300-rejected-directions" + assert [row["pin"] for row in ranked.items] == [ + {"reference": second, "revision": reader.read(second).revision} + ] + assert any(row["code"] == "output_limit" and first in row["message"] + for row in ranked.omissions) + + # The caller who chooses the first Case directly is charged for its exact + # view, which fits without the title supplied by ranked discovery. + revision = reader.read(first).revision + exact = provider.collect(_request(ids=[first], pins=[{"name": first, "revision": revision}], + selection_limits=limits)) + assert [row["pin"] for row in exact.items] == [{"reference": first, "revision": revision}] + + +def test_first_unreadable_hit_does_not_consume_a_sealed_selection_slot(tmp_path): + source = Path(__file__).resolve().parents[1] / "fixtures/indexer/ranking-corpus" + library = shutil.copytree(source, tmp_path / "library") + record = library / "demo/cases/alpha.json" + data = json.loads(record.read_text()) + data["required_resources"] = ["missing.csv"] + record.write_text(json.dumps(data)) + + result = find("qxrankprobe", load_corpus(library, kinds=("case",)), limit=1) + first, = result["items"] + assert first["id"] == "case.qxrankprobe" and "missing.csv" in first["unreadable"] + provider = ContextProvider(knowledge_reader(skill_root=library)) + draft = provider.collect(_request(query="qxrankprobe", ids=[], + selection_limits={"kind": "case", "limit": 1})) + delivered, = draft.items + assert delivered["pin"]["reference"] == "checkout:case.alternate" + assert draft.selection["matched_count"] == 2 and draft.selection["returned_count"] == 1 + assert any(row["code"] == "invalid" and "case.qxrankprobe" in row["message"] + for row in draft.omissions) + + +def test_text_lookup_uses_the_requested_store_revision(tmp_path): + store = KnowledgeStore(tmp_path, skill_root=None) + metadata = {"id": "local-context", "kind": "knowledge", "state": "candidate", + "entrypoint": "note.md", "sources": [{"type": "unknown"}], "applicability": {}, + "limitations": [], "attribution": []} + old = store.create(Bundle(metadata, {"note.md": b"firstrevisionmarker"}, {})) + store.update(Bundle(metadata, {"note.md": b"latestrevisionmarker"}, {}), expected=old, + reason="new observation", evidence=[]) + provider = ContextProvider(knowledge_reader(store_root=tmp_path)) + request = _request(query="firstrevisionmarker", ids=[], selection_limits={"kind": "knowledge"}) + assert provider.collect(request).selection["no_match"] + draft = provider.collect({**request, "pins": [{"name": "local-context", "revision": old}]}) + assert draft.selection["returned_count"] == 1 and not draft.selection["no_match"] + assert draft.content == b"firstrevisionmarker" + assert draft.items[0]["pin"] == {"reference": "store:local-context", "revision": old} + assert not draft.omissions + missing = provider.collect({ + **request, "query": "cgroupv2", "selection_limits": {"limit": 1}, + "pins": [{"name": "local-context", "revision": "sha256:" + "0" * 64}], + }) + assert [item["pin"]["reference"] for item in missing.items] == [_CGROUP] + assert any(row["code"] == "unavailable_revision" and "store:local-context" in row["message"] + for row in missing.omissions) + + @pytest.mark.parametrize("overrides", [ {"max_bytes": False}, {"max_bytes": 2**53}, {"round_id": "../escape"}, + {"query": "cgroupv2"}, {"selection_limits": {"context_bytes": 1}}, {"selection_limits": {"limit": True}}, {"pins": [{"name": _CGROUP, "revision": "r1"}, {"name": _CGROUP, "revision": "r2"}]}, diff --git a/tests/apps/test_campaign_record_injection.py b/tests/apps/test_campaign_record_injection.py index ba0bba358..6c98cea44 100644 --- a/tests/apps/test_campaign_record_injection.py +++ b/tests/apps/test_campaign_record_injection.py @@ -53,14 +53,9 @@ def collect(self, query="", **options): # Each row checks the options that are passed to the reader and retained in the capture. SELECTION = { - "cue": ({"relevance": "decode launch"}, FIND_RELEVANCE, "cuda"), "cue-and-ids": ({"relevance": "decode launch", "ids": ["package:graphs"]}, None, None), - "query-only": ({"query": "decode"}, FIND_RELEVANCE, "cuda"), "inventory": ({}, None, None), - "explicit-backend": ({"relevance": "decode launch", "backend": "ascend"}, - FIND_RELEVANCE, "ascend"), - "explicit-find": ({"query": "decode", "relevance_method": FIND_RELEVANCE}, - FIND_RELEVANCE, "cuda"), + "explicit-backend": ({"ids": ["package:graphs"], "backend": "ascend"}, None, "ascend"), } @@ -95,17 +90,20 @@ def test_capture_rejects_legacy_ranking_methods_before_calling_reader(tmp_path, assert reader.calls == [] -def test_capture_rejects_a_query_and_relevance_together(tmp_path): +@pytest.mark.parametrize("options", [{"query": "decode"}, {"relevance": "launch"}, + {"query": "decode", "relevance": "launch"}]) +def test_capture_rejects_free_text_search_before_calling_the_reader(tmp_path, options): campaign.create_campaign(tmp_path, "selection") - with pytest.raises(ValueError, match="Find takes one query or relevance cue"): - campaign.capture_context(tmp_path, context_id="r1", reader=KnowledgeReader(), - query="decode", relevance="launch") + reader = Reader() + with pytest.raises(ValueError, match="find QUERY --session DIR"): + campaign.capture_context(tmp_path, context_id="r1", reader=reader, **options) + assert not reader.calls def test_capture_record_layout_is_unchanged(tmp_path): campaign.create_campaign(tmp_path, "layout") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=Reader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) assert list(document) == [ @@ -254,7 +252,7 @@ def collect(self, query="", **options): def test_capture_with_an_observation_keeps_its_retrieval_and_item_provenance(tmp_path): campaign.create_campaign(tmp_path, "layout") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=ObservedReader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) assert list(document) == [ @@ -267,7 +265,7 @@ def test_capture_with_an_observation_keeps_its_retrieval_and_item_provenance(tmp assert document["retrieval"]["entrypoint"] == "campaign capture-context" assert document["retrieval"]["calls"] == ["campaign capture-context", "collect", "find"] assert document["captured_by"] == "inferrsi campaign capture-context " + __version__ - assert document["request"]["ids"] is None + assert document["request"]["ids"] == ["package:graphs"] assert document["request"]["sources"] == ["package", "checkout"] assert list(document["items"][0]) == [ "ref", "revision", "title", "kind", "backend", "scenario", "authority", "sources", @@ -290,7 +288,7 @@ def collect(self, query="", **options): def test_item_provenance_without_an_observation_is_kept(tmp_path): campaign.create_campaign(tmp_path, "layout") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=ProvenanceReader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) assert "retrieval" not in document @@ -330,7 +328,7 @@ def test_harness_campaign_accepts_only_supplied_backends(tmp_path): def test_harness_checks_stored_bytes_and_apps_checks_the_projection(tmp_path): campaign.create_campaign(tmp_path, "verify") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=Reader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) def states(changed): @@ -361,7 +359,7 @@ def test_load_campaign_capture_rejects_consistent_digest_with_wrong_projection(t campaign.create_campaign(tmp_path, "verify") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=Reader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) text = document["assembled_text"] + "appended" consistent = {**document, "assembled_text": text, @@ -375,7 +373,7 @@ def test_load_campaign_capture_rejects_consistent_digest_with_wrong_projection(t def test_harness_keeps_invalid_format_when_assembled_text_is_not_utf8(tmp_path): campaign.create_campaign(tmp_path, "verify") path, _ = campaign.capture_context(tmp_path, context_id="r1", reader=Reader(), - relevance="decode launch") + ids=["package:graphs"], relevance="decode launch") document = json.loads(path.read_bytes()) document["assembled_text"] = "\ud800" raw = json.dumps(document, ensure_ascii=True).encode("utf-8") diff --git a/tests/apps/test_campaign_task_selection.py b/tests/apps/test_campaign_task_selection.py index 68492b8f1..95b4dcaee 100644 --- a/tests/apps/test_campaign_task_selection.py +++ b/tests/apps/test_campaign_task_selection.py @@ -7,62 +7,56 @@ from inferrsi.apps.workflows.campaign import capture_context, create_campaign, verify_capture from inferrsi.knowledge.knowledge_find import find, installed_skill_root, load_corpus from inferrsi.knowledge.knowledge_operations import KnowledgeReader +from tests.apps.test_codex_knowledge_search import _cli BASELINE_CUE = "reproducible diffusion baseline correctness fixed seed end to end benchmark" +def _scoped(root, query, *flags): + _, output = _cli(root, "find", query, "--session", str(root), + "--no-external", *flags) + found = json.loads(output) + doc, state = verify_capture((root / found["reference"]["path"]).read_bytes()) + assert state == "verified" + return found, doc + + def test_campaign_search_returns_portable_methods_and_records_counts(tmp_path): create_campaign(tmp_path, "diffusion", backend="cuda") - path, _ = capture_context(tmp_path, context_id="first", reader=KnowledgeReader(), - relevance=BASELINE_CUE, limit=2, context_bytes=14000) - document, state = verify_capture(path.read_bytes()) - assert state == "verified" - assert [item["title"] for item in document["items"]] == [ - "inference-benchmark-design", "video-diffusion-optimization", + found, doc = _scoped(tmp_path, BASELINE_CUE, "--limit", "2") + assert found["matched"] > len(found["items"]) == len(doc["items"]) == 2 + assert [h["material_ref"] for h in found["items"]] == [ + "package:inferrsi.common.skills.inference_benchmark_design", + "package:inferrsi.common.skills.video_diffusion_optimization", ] - assert document["selection"]["method"] == "find-lexical-v1" - assert document["selection"]["matched_count"] > document["selection"]["returned_count"] == 2 - assert document["context_omissions"][0]["reason"] == "context_limit" - assert document["contexts"][0]["resources"][0]["path"].endswith( - "video-diffusion-optimization/SKILL.md" - ) + for hit in found["items"]: + _, opened = _cli(tmp_path, *hit["read_args"]) + assert len(json.loads(opened)["content"].encode()) == hit["next_read_content_bytes"] def test_campaign_backend_routes_to_repository_evidence_and_can_be_overridden(tmp_path): create_campaign(tmp_path, "target", backend="cuda") - reader = KnowledgeReader() - path, _ = capture_context(tmp_path, context_id="cuda", reader=reader, - relevance="MiniMax H3 QK RMSNorm RoPE fusion", limit=3) - doc, state = verify_capture(path.read_bytes()) - assert state == "verified" + found, doc = _scoped(tmp_path, "MiniMax H3 QK RMSNorm RoPE fusion", "--limit", "3") assert doc["request"]["backend"] == "cuda" - assert all(item["backend"] in ("cuda", "common") for item in doc["items"]) - ctx = next(c for c in doc["contexts"] if c["ref"].endswith("minimax_h3_qk_norm_rope")) - resource, = ctx["resources"] - assert resource["role"] == "record" - assert json.loads(resource["content"])["scenario"] == "diffusion.video_generation" - assert resource["content"].encode() == reader.resource( - ctx["ref"], resource["path"], revision=ctx["revision"] + hit = next(h for h in found["items"] if h["material_ref"].endswith("minimax_h3_qk_norm_rope")) + _, output = _cli(tmp_path, *hit["read_args"]) + opened = json.loads(output) + assert json.loads(opened["content"])["scenario"] == "diffusion.video_generation" + assert opened["content"].encode() == KnowledgeReader().resource( + opened["ref"], opened["content_resource"], revision=opened["revision"], ) - path, _ = capture_context(tmp_path, context_id="ascend", reader=reader, backend="ascend", - relevance="Ascend video diffusion NPU optimization", limit=1) - doc, state = verify_capture(path.read_bytes()) - assert state == "verified" - assert doc["items"][0]["title"] == "ascend-video-diffusion-optimization" + other, _ = _scoped(tmp_path, "Ascend video diffusion NPU optimization", + "--backend", "ascend", "--limit", "1") + assert other["items"][0]["material_ref"].endswith(".skills.ascend_video_diffusion_optimization") def test_workload_scenario_discovers_skills_and_compatible_engine_records(): - reader = KnowledgeReader() - options = {"relevance": BASELINE_CUE, "backend": "cuda", - "scenario": "diffusion.t2i", "limit": 8} - items = reader.collect(**options)["items"] - ids = [i["id"] for i in items] - portable = "inferrsi.common.skills.video_diffusion_optimization" - assert portable in ids - assert "vllm_omni.common.diffusion.measurement_and_profiling" in ids - assert all(i["scenario"] in ("skills.discovery", "diffusion.*", "diffusion.image_generation") - and i["backend"] in ("cuda", "common") for i in items) - assert reader.collect(ids=[portable], **options)["omissions"] == [ + scope = {"backend": "cuda", "scenario": "diffusion.t2i"} + found = find(BASELINE_CUE, load_corpus(**scope), limit=8, pin_material=True) + refs = {hit["material_ref"] for hit in found["items"]} + portable = "package:inferrsi.common.skills.video_diffusion_optimization" + assert {portable, "package:vllm_omni.common.diffusion.measurement_and_profiling"} <= refs + assert KnowledgeReader().collect(ids=[portable], **scope)["omissions"] == [ {"id": portable, "reason": "filters"} ] @@ -73,43 +67,31 @@ def test_workload_scenario_discovers_skills_and_compatible_engine_records(): ]) def test_find_filters_cases_to_the_campaign_backend(tmp_path, backend, case): create_campaign(tmp_path, "target", backend=backend) - path, _ = capture_context( - tmp_path, context_id="r1", reader=KnowledgeReader(), kind="case", - relevance=case.replace("-", " "), limit=5, - ) - capture, state = verify_capture(path.read_bytes()) - assert state == "verified" - assert capture["items"] - assert all(item["ref"] != f"checkout:case.{case}" for item in capture["items"]) - counts = capture["retrieval"]["counts"] - assert counts["excluded"]["filters"] > 0 - assert counts["considered"] == ( - counts["matched"] + sum( - counts["excluded"][name] for name in ("filters", "ranking_scope", "zero_score") - ) - ) + found, doc = _scoped(tmp_path, case.replace("-", " "), "--kinds", "case", "--limit", "5") + assert doc["request"]["backend"] == backend + assert found["items"] and found["corpus_size"] >= found["matched"] >= len(found["items"]) + assert all(item["material_ref"] != f"checkout:case.{case}" for item in found["items"]) def test_find_with_custom_library_keeps_packaged_projections(tmp_path): create_campaign(tmp_path, "target") library = tmp_path / "custom" library.mkdir() - path, _ = capture_context( - tmp_path, context_id="r1", reader=KnowledgeReader(skill_root=library), - relevance="cgroupv2", limit=1, - ) - capture, state = verify_capture(path.read_bytes()) - assert state == "verified" - item, = capture["items"] - assert item["ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" + found, _ = _scoped(tmp_path, "cgroupv2", "--skill-root", str(library), "--limit", "1") + item, = found["items"] + assert item["material_ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" + with pytest.raises(ValueError, match="Package catalog filters"): + load_corpus(library, repo="inferrsi") def test_find_preserves_required_case_readset(tmp_path): create_campaign(tmp_path, "target") - path, _ = capture_context( - tmp_path, context_id="r1", reader=KnowledgeReader(), kind="case", - relevance="vllm gdn source contract", limit=1, - ) + found, _ = _scoped(tmp_path, "vllm gdn source contract", "--kinds", "case", "--limit", "1") + hit, = found["items"] + ref = hit["material_ref"] + reader = KnowledgeReader(skill_root=installed_skill_root()) + path, _ = capture_context(tmp_path, context_id="snapshot", reader=reader, ids=[ref], + revisions={ref: hit["revision"]}) capture, state = verify_capture(path.read_bytes()) assert state == "verified" context, = capture["contexts"] @@ -124,28 +106,22 @@ def test_find_preserves_required_case_readset(tmp_path): def test_find_collection_uses_the_case_only_corpus(): query = "cache per-step masks ran out of device memory" - discovery = find(query, load_corpus(kinds=("case",)), limit=3) - delivery = KnowledgeReader().collect( - query, kind="case", relevance_method="find-lexical-v1", limit=3, - ) - observed = delivery["retrieval"] - assert [(item["ref"], item["score"]) for item in observed["items"]] == [ - (f"checkout:{item['id']}", item["score"]) for item in discovery["items"] + result = find(query, load_corpus(kinds=("case",)), limit=3, pin_material=True) + reader = KnowledgeReader(skill_root=installed_skill_root()) + packed = reader.pack_find_hits(result["items"], cue=query, limit=3, context_bytes=65536) + assert [(item["ref"], item["revision"]) for item in packed["items"]] == [ + (hit["material_ref"], hit["revision"]) for hit in result["items"] ] - assert observed["counts"]["considered"] == discovery["corpus_size"] - assert observed["counts"]["excluded"]["filters"] == 0 + assert all(item["kind"] == "case" for item in packed["items"]) def test_find_collection_does_not_repeat_custom_skills_as_package_projections(tmp_path): library = tmp_path / "copy" shutil.copytree(installed_skill_root(), library) - reader = KnowledgeReader(skill_root=library) - result = reader.collect( - "weight loading optimization", relevance_method="find-lexical-v1", limit=6, - ) - refs = {item["ref"] for item in result["items"]} - assert "checkout:weight-loading-optimization" in refs - assert "package:inferrsi.common.skills.weight_loading_optimization" not in refs + hits = find("weight loading optimization", load_corpus(library), limit=6)["items"] + material = {hit["read_args"][1] for hit in hits} + assert "checkout:weight-loading-optimization" in material + assert "package:inferrsi.common.skills.weight_loading_optimization" not in material def test_find_does_not_infer_case_backend_from_applicability(tmp_path): @@ -166,16 +142,10 @@ def test_find_does_not_infer_case_backend_from_applicability(tmp_path): "limitations": [], "attribution": [], }), encoding="utf-8") - reader = KnowledgeReader(skill_root=tmp_path) - options = {"kind": "case", "relevance_method": "find-lexical-v1"} - result = reader.collect("B300", **options) - assert [item["ref"] for item in result["items"]] == ["checkout:case.legacy-b300"] - scoped = reader.collect("B300", backend="cuda", **options) - assert scoped["no_match"] - counts = scoped["retrieval"]["counts"] - assert counts["considered"] == 1 - assert counts["excluded"]["ranking_scope"] == 1 - assert counts["excluded"]["filters"] == 0 + result = find("B300", load_corpus(tmp_path, kinds=("case",)), pin_material=True) + assert [item["material_ref"] for item in result["items"]] == ["checkout:case.legacy-b300"] + scoped = find("B300", load_corpus(tmp_path, kinds=("case",), backend="cuda")) + assert scoped["no_match"] and scoped["corpus_size"] == 0 def test_task_skills_are_explicitly_readable_but_never_ranked_into_campaign(tmp_path): @@ -187,13 +157,9 @@ def test_task_skills_are_explicitly_readable_but_never_ranked_into_campaign(tmp_ task_refs = {f"package:inferrsi.common.skills.{task}" for task in tasks} cue = "inference-task-router day-0 model onboarding performance accuracy" options = {"context_bytes": 65536, "limit": 135, "repo": "inferrsi", "kind": "knowledge"} - path, _ = capture_context(tmp_path, context_id="ranked", reader=reader, - relevance=cue, **options) - ranked, state = verify_capture(path.read_bytes()) - assert state == "verified" and ranked["items"] - assert ranked["retrieval"]["counts"]["considered"] == 129 - for group in ("items", "contexts", "context_omissions"): - assert task_refs.isdisjoint(item.get("ref") for item in ranked[group]) + ranked, _ = _scoped(tmp_path, cue, "--repo-type", "inferrsi", "--limit", "135") + assert ranked["items"] and ranked["matched"] <= ranked["corpus_size"] + assert task_refs.isdisjoint(item["material_ref"] for item in ranked["items"]) refs = sorted(task_refs) path, _ = capture_context(tmp_path, context_id="explicit", reader=reader, ids=refs, **{**options, "context_bytes": 1024 * 1024}) diff --git a/tests/apps/test_cannbot_boundaries.py b/tests/apps/test_cannbot_boundaries.py index b502583ec..e4f99f856 100644 --- a/tests/apps/test_cannbot_boundaries.py +++ b/tests/apps/test_cannbot_boundaries.py @@ -167,11 +167,7 @@ def test_search_shape_is_rejected(upstream, mutation): assert error.value.state == "rejected" -@pytest.mark.parametrize("args", [ - ("cannbot", "search", "tiling", "--limit", "1"), - ("find", "tiling", "--external-limit", "1", "--json"), -]) -def test_source_cap_precedes_card_reads(upstream, args): +def test_source_cap_precedes_card_reads(upstream): _, script, card = upstream payload = search_payload(card) first = payload["results"][0] @@ -186,11 +182,9 @@ def test_source_cap_precedes_card_reads(upstream, args): f"print(json.dumps({discovery()!r} if sys.argv[1] == 'discover' " f"else {payload!r}))\n" ) - result = cli(*args) + result = cli("find", "tiling", "--external-limit", "1", "--json") assert result.returncode == 0, result.stderr - response = json.loads(result.stdout) - if args[0] == "find": - response = response["external"][0] + response = json.loads(result.stdout)["external"][0] assert response["state"] == "ok" assert [hit["locator"] for hit in response["items"]] == ["ops/card"] @@ -374,6 +368,8 @@ def test_platform_override_and_cuda_gate(upstream): ) result = cli("find", "synthetic", "--platform", "a3", "--json") assert json.loads(result.stdout)["external"][0]["state"] == "ok" + retired = cli("find", "tiling", "--external-source", "cannbot-knowledge") + assert retired.returncode == 2 and "invalid choice" in retired.stderr script.write_text("raise RuntimeError('must not be called')\n") for args in (("--backend", "cuda"), ("--no-external",)): result = cli("find", "tiling", *args, "--json") @@ -396,13 +392,17 @@ def test_public_find_displays_an_external_only_hit_and_managed_capture_stays_loc encoded = cli("find", query, "--backend", "ascend", "--json") assert encoded.returncode == 0, encoded.stderr result = json.loads(encoded.stdout) - assert result["no_match"] and result["items"] == [] + assert result["no_match"] is False and result["items"] == [] external, = result["external"] assert external["state"] == "ok" and external["count"] == 1 assert external["items"][0]["locator"] == "ops/card" rendered = cli("find", query, "--backend", "ascend") assert rendered.returncode == 0 and "ops/card" in rendered.stdout - for flags, output in ((["--json"], encoded.stdout), ([], rendered.stdout)): + assert rendered.stdout.startswith("local_no_match\t") + historical_json = json.dumps({**result, "no_match": True}) + historical_text = rendered.stdout.replace("local_no_match\t", "no_match\t", 1) + for flags, output in ((["--json"], encoded.stdout), ([], rendered.stdout), + (["--json"], historical_json), ([], historical_text)): call = invocation(["inferrsi", "find", query, "--backend", "ascend", *flags]) event, complete, _ = decode(call, 0, output) assert complete and event["materials"] == [{"ref": "cannbot-knowledge:ops/card"}] @@ -412,11 +412,11 @@ def test_public_find_displays_an_external_only_hit_and_managed_capture_stays_loc campaign = Path.cwd() / "campaign" created = cli("campaign", "init", "--directory", str(campaign), "--id", "local-lookup") assert created.returncode == 0, created.stderr - captured = cli("campaign", "capture-context", "--directory", str(campaign), - "--id", "lookup", "--backend", "ascend", query) + captured = cli("find", query, "--session", str(campaign), + "--backend", "ascend") assert captured.returncode == 0, captured.stderr - doc = json.loads((campaign / json.loads(captured.stdout)["context"]).read_text()) - assert doc["retrieval"]["calls"] == ["campaign capture-context", "collect", "find"] + doc = json.loads((campaign / json.loads(captured.stdout)["reference"]["path"]).read_text()) + assert doc["retrieval"]["calls"] == ["find"] assert doc["items"] == [] and doc["contexts"] == [] assert not invoked.exists() diff --git a/tests/apps/test_cannbot_channel_acceptance.py b/tests/apps/test_cannbot_channel_acceptance.py index 321900b04..415b20188 100644 --- a/tests/apps/test_cannbot_channel_acceptance.py +++ b/tests/apps/test_cannbot_channel_acceptance.py @@ -88,7 +88,7 @@ def test_undeclared_backend_reports_the_gate(): def test_local_corpus_is_unchanged_by_the_channel(): """The channel adds a column; it never re-ranks or trims the local list.""" for query in QUERIES: - before = _run("find", query, "--no-external") + before = _run("find", query, "--backend", "ascend", "--no-external") after = _run("find", query, "--backend", "ascend") assert before["matched"] == after["matched"], query assert [item["id"] for item in before["items"]] == [ @@ -125,7 +125,7 @@ def test_every_query_reaches_more_than_the_local_corpus(): """The point of the channel: each query gains upstream coverage.""" rows = [] for query in QUERIES: - before = _run("find", query, "--no-external") + before = _run("find", query, "--backend", "ascend", "--no-external") after = _run("find", query, "--backend", "ascend") external = sum( entry.get("count", 0) for entry in after["external"] if entry["state"] == "ok" diff --git a/tests/apps/test_cli_catalog.py b/tests/apps/test_cli_catalog.py index 384b408f7..3b602531e 100644 --- a/tests/apps/test_cli_catalog.py +++ b/tests/apps/test_cli_catalog.py @@ -29,8 +29,8 @@ } -def test_managed_knowledge_scenario_is_benchmark_only(capsys): - cli = parser() +def test_historical_parser_preserves_benchmark_scenario_spelling(capsys): + cli = parser(historical=True) knowledge = ["knowledge", "--session", "run", "--query", "denoise", "--context-bytes", "65536"] scenario = ["--scenario", "diffusion.image_generation"] assert cli.parse_args(["benchmarks", "session", *knowledge, *scenario]).scenario == scenario[1] @@ -91,7 +91,6 @@ def test_context_retains_conditions_and_source_verification(self): result = main( [ "context", - "MiniMax-H3", "--repo-type", "vllm_omni", "--backend", @@ -131,7 +130,6 @@ def test_ascend_image_context_preserves_provenance_and_scope(self): result = main( [ "context", - "Qwen-Image-2.1", "--repo-type", "vllm_omni", "--backend", diff --git a/tests/apps/test_codex_knowledge_search.py b/tests/apps/test_codex_knowledge_search.py index 1f6bf1768..11150a392 100644 --- a/tests/apps/test_codex_knowledge_search.py +++ b/tests/apps/test_codex_knowledge_search.py @@ -1,5 +1,6 @@ """Import real CLI results from a bounded synthetic Codex rollout.""" +import gzip import json import os import shlex @@ -9,6 +10,8 @@ import pytest +from tests.fixtures.knowledge_retrieval import install_legacy_capture, legacy_records + ROOT = Path(__file__).resolve().parents[2] LIBRARY = ROOT / "src/inferrsi/knowledge/data/skill_library" QUERY = "cache per-step masks ran out of device memory" @@ -22,6 +25,25 @@ def _cli(cwd, *args): return argv, _run(cwd, argv) +def _historical_capture(campaign, context_id, options): + """Build the original manual argv and path-only response from the capture API.""" + from inferrsi.apps.cli.arguments import parser + from inferrsi.apps.workflows.campaign import capture_context + from inferrsi.knowledge.knowledge_operations import KnowledgeReader + + words = ["campaign", "capture-context", "--directory", str(campaign), "--limit", "1", + "--id", context_id, *options] + args = parser(historical=True).parse_args(words) + if args.query or (args.relevance and not args.ids): + sample = "manual-query" if args.query else "manual-relevance" + path, digest = install_legacy_capture(campaign, sample, context_id) + else: + path, digest = capture_context(campaign, context_id=context_id, reader=KnowledgeReader(), + relevance=args.relevance, ids=args.ids, limit=1) + result = {"context": path.relative_to(campaign).as_posix(), "sha256": digest} + return [sys.executable, "-m", "inferrsi", *words], json.dumps(result, indent=2) + "\n" + + def _run(cwd, argv): env = dict(os.environ, PYTHONPATH=os.pathsep.join([str(ROOT / "src"), *sys.path])) env.update(HOME=str(cwd / "home"), USERPROFILE=str(cwd / "home")) @@ -119,15 +141,14 @@ def test_direct_find_and_read_import(tmp_path, json_output): _, reviewed = _import(tmp_path, rows, decisions=[review]) assert reviewed["counts"]["used"] == 1 assert reviewed["materials"][REF]["evidence"][0]["passage_text"] == PASSAGE - # The Find hit records no revision and the review names only the versioned - # Read, so the use is not credited to the hit; its denominator stays. + # Search and visible read now carry the same version, so the decision can be attributed. assert reviewed["materials"][REF]["evidence"][0]["event_id"] == read["id"] - assert "revision" not in reviewed["events"][0]["materials"][0] + assert reviewed["events"][0]["materials"][0]["revision"] == view["revision"] assert reviewed["adoption"] == { - "search_hits": {"adopted": 0, "unique_hits": 1, "state": "unknown"}, - "direct_reads": {"adopted": 0, "read_only": 0, "state": "unknown"}, + "search_hits": {"adopted": 1, "unique_hits": 1, "state": "complete"}, + "direct_reads": {"adopted": 0, "read_only": 0, "state": "not_applicable"}, "unverified_reads": {"adopted": 0, "refs": 0}, - "other_adopted": 0, "attribution_unknown": 1, "unique_hit_revisions": None} + "other_adopted": 0, "attribution_unknown": 0, "unique_hit_revisions": 1} @pytest.mark.parametrize("issue", ["missing_result", "truncated_result", "replaced_result"]) @@ -166,9 +187,63 @@ def test_no_match_and_unqualified_metadata_read_are_verified_without_content(tmp assert not record["events"][1]["delivery"].get("visible_resources") +@pytest.mark.parametrize("mode", ["catalog-text", "catalog-json"]) +def test_find_archive_uses_the_returned_owner_and_pin(tmp_path, mode): + options = ["inference benchmark design", "--repo-type", "inferrsi", "--no-external"] + argv, result = _cli(tmp_path, "find", *options, "--limit", "1", + *(["--json"] if mode.endswith("json") else [])) + if mode.endswith("text"): + opening = next(line for line in result.splitlines() if line.strip().startswith("open")) + args = shlex.split(opening.split(": ", 1)[1].removeprefix("& ")) + offset = args.index("read") + read_args = args[offset:] + else: + read_args = json.loads(result)["items"][0]["read_args"] + expected = {"ref": read_args[1], "revision": read_args[read_args.index("--revision") + 1]} + assert expected["ref"].startswith("package:") + _, archive = _import(tmp_path, _operation(tmp_path, argv, result, "find")) + assert archive["coverage"] == "complete" + material, = archive["events"][0]["materials"] + assert {key: material[key] for key in expected} == expected + + +@pytest.mark.parametrize("version", ["research", "model-find"]) +def test_archived_model_commands_keep_their_actual_hits_and_pins(tmp_path, version): + # Saved real CLI returns. Their original argv and generating revisions travel with them. + fixture = ROOT / "tests/fixtures/legacy/model_research_returns.json.gz" + samples = json.loads(gzip.decompress(fixture.read_bytes()))[version]["samples"] + rows = [] + for label, run in samples.items(): + rows.extend(_operation(tmp_path, run["argv"], run["stdout"], label)) + _, record = _import(tmp_path, rows) + assert record["coverage"] == "complete" + assert record["counts"] == {"searches": 2, "hits": 1, "unique_hits": 1, "used": 0} + hit, empty = record["events"] + assert hit["action"] == empty["action"] == "search" + assert hit["query"] == "MiniMax-H3" and empty["query"] == "zzcanaryunknownqx" + assert not empty["materials"] and not hit["delivery"].get("visible_resources") + item, = hit["materials"] + assert item["ref"] == "package:vllm_omni.ascend.diffusion.minimax_h3_reference_kv_reuse" + if version == "model-find": + returned, = json.loads(samples["hit"]["stdout"])["items"] + assert item["revision"] == returned["revision"] + else: + assert "revision" not in item + + run = samples["hit"] + clipped = "Warning: truncated output\n" + run["stdout"][:200] + other = tmp_path / "clipped" + other.mkdir() + _, partial = _import(other, _operation(other, run["argv"], run["stdout"], "clip", + received=clipped)) + assert partial["coverage"] == "partial" and partial["counts"] is None + assert partial["unresolved_command_lines"] and partial["observed"]["used"] == 0 + + def test_unarchived_compatibility_query_prevents_false_complete_coverage(tmp_path): - argv, output = _cli(tmp_path, "collect", "--relevance", QUERY, "--limit", "1", "--json") - assert json.loads(output)["items"] + argv = [sys.executable, "-m", "inferrsi", "collect", "--relevance", QUERY, "--limit", "1", + "--json"] + output = json.dumps(legacy_records()["samples"]["unarchived"], indent=2) for record in _import(tmp_path, _operation(tmp_path, argv, output, "collect")): assert record["coverage"] == "partial" and record["counts"] is None assert record["observed"]["searches"] == 1 @@ -181,7 +256,6 @@ def test_unarchived_compatibility_query_prevents_false_complete_coverage(tmp_pat def test_manual_capture_search_coverage_requires_the_matching_receipt(tmp_path, case): campaign = tmp_path / "campaign" _cli(tmp_path, "campaign", "init", "--directory", str(campaign), "--id", "capture-test") - command = ("campaign", "capture-context", "--directory", str(campaign), "--limit", "1") if case == "inventory": options = () elif case == "exact": @@ -191,12 +265,12 @@ def test_manual_capture_search_coverage_requires_the_matching_receipt(tmp_path, ) else: options = ("--relevance", QUERY) if case == "omitted" else (QUERY,) - argv, output = _cli(tmp_path, *command, "--id", "capture", *options) + argv, output = _historical_capture(campaign, "capture", options) context_ids = [] if case in ("matched", "clipped"): context_ids = ["capture"] elif case == "wrong_id": - _cli(tmp_path, *command, "--id", "other", *options) + _historical_capture(campaign, "other", options) context_ids = ["other"] rows = _operation(tmp_path, argv, output, "manual", received=( "Warning: truncated output\n" + output[:45] if case == "clipped" else True diff --git a/tests/apps/test_codex_plugin.py b/tests/apps/test_codex_plugin.py index bccdabf33..be2247afd 100644 --- a/tests/apps/test_codex_plugin.py +++ b/tests/apps/test_codex_plugin.py @@ -122,9 +122,14 @@ def test_isolated_runtime_and_exact_knowledge_reads(distribution, tmp_path): assert info.returncode == 0, info.stderr assert json.loads(info.stdout)["runtime"] == "bundled" assert not json.loads(info.stdout)["optional_skills_dependency"] - collected = invoke(distribution, tmp_path, "collect", "Qwen", "--limit", "1", "--json") - assert collected.returncode == 0, collected.stderr - item = json.loads(collected.stdout)["items"][0] + found = invoke(distribution, tmp_path, "find", "Qwen", "--kinds", "record", + "--limit", "1", "--no-external", "--json") + assert found.returncode == 0, found.stderr + hit, = json.loads(found.stdout)["items"] + opened = invoke(distribution, tmp_path, *hit["read_args"]) + assert opened.returncode == 0, opened.stderr + item = json.loads(opened.stdout) + assert item["content"] read = invoke( distribution, tmp_path, "read", item["ref"], "--revision", item["revision"], "--material", @@ -192,14 +197,17 @@ def test_entry_loads_the_required_primary_before_search(distribution, tmp_path): def test_entry_workflow_selects_packaged_skill_projections(distribution, tmp_path): result = invoke( - distribution, tmp_path, "collect", "--relevance", - "vLLM-Omni inference engine memory bottleneck", "--limit", "3", "--json", + distribution, tmp_path, "find", "vLLM-Omni inference engine memory bottleneck", + "--kinds", "skill", "--limit", "3", "--no-external", "--json", ) assert result.returncode == 0, result.stderr envelope = json.loads(result.stdout) assert envelope["items"] - assert all(item["authority"] == "package" for item in envelope["items"]) - assert all(item["kind"] == "knowledge" for item in envelope["items"]) + for hit in envelope["items"]: + assert hit["kind"] == "skill" and hit["source_location"] == "installed" + assert hit["read_args"][1].startswith("package:") + assert "--revision" in hit["read_args"] + assert "--resource" in hit["read_args"] @pytest.mark.parametrize(("action", "resource"), [ diff --git a/tests/apps/test_codex_search_delivery.py b/tests/apps/test_codex_search_delivery.py index de6ca077e..3cdbd8d93 100644 --- a/tests/apps/test_codex_search_delivery.py +++ b/tests/apps/test_codex_search_delivery.py @@ -1,7 +1,8 @@ """Model-visible file delivery must be traceable to exact tool output.""" import json -from pathlib import PureWindowsPath +import shlex +from pathlib import Path, PureWindowsPath import pytest @@ -13,12 +14,12 @@ def _meta(cwd): "payload": {"id": "synthetic-session", "cwd": str(cwd)}} -def _call(cwd, command, call_id): +def _call(cwd, command, call_id, *, emit="r.output"): source = ( "const r = await tools.exec_command({\n" f" cmd: {json.dumps(command)},\n" f" workdir: {json.dumps(str(cwd))}\n" - "});\ntext(r.output);" + f"}});\ntext({emit});" ) return {"type": "response_item", "payload": {"type": "custom_tool_call", "name": "exec", @@ -50,6 +51,17 @@ def _result(call_id, output): } +def _exec_result(call_id, output, *, exit_code=0): + result = {"chunk_id": "abcd12", "wall_time_seconds": 0.1, "exit_code": exit_code, + "original_token_count": 100, "output": output} + return {"type": "response_item", "payload": { + "type": "custom_tool_call_output", "call_id": call_id, "output": [ + {"type": "input_text", "text": "Script completed\nWall time 0.3 seconds\nOutput:\n"}, + {"type": "input_text", "text": json.dumps(result, ensure_ascii=False)}, + ], + }} + + def _message(text): return {"type": "response_item", "payload": {"type": "message", "role": "assistant", @@ -61,6 +73,147 @@ def _rollout(path, *rows): path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") +@pytest.mark.parametrize(("cmd_key", "workdir_key"), [ + ("cmd", '"workdir"'), ('"cmd"', "'workdir'"), ("'cmd'", "workdir"), +]) +def test_quoted_js_properties_keep_the_actual_command_workdir(tmp_path, cmd_key, workdir_key): + corpus = tmp_path / "knowledge" + corpus.mkdir() + call = _call(corpus, "cat note.md", "read") + source = call["payload"]["input"].replace("cmd:", cmd_key + ":") + call["payload"]["input"] = source.replace("workdir:", workdir_key + ":") + trace = tmp_path / "trace.jsonl" + _rollout(trace, _meta(tmp_path), call, _command(corpus, "cat note.md", "body\n", "event"), + _result("read", "body\n")) + _, events, _, uncertain, details = read_window(trace, (2, 4), corpus, archive=True) + assert events[0]["delivery"]["state"] == "visible" + assert not uncertain and not details + + +@pytest.mark.parametrize("issue", ["dynamic", "duplicate", "wrong"]) +def test_a_quoted_workdir_must_be_one_matching_literal(tmp_path, issue): + call = _call(tmp_path, "cat note.md", "read") + source = call["payload"]["input"].replace("workdir:", '"workdir":') + literal = json.dumps(str(tmp_path)) + if issue == "dynamic": + source = source.replace('"workdir": ' + literal, '"workdir": location') + elif issue == "duplicate": + source = source.replace('"workdir": ' + literal, + '"workdir": ' + literal + ', "workdir": ' + literal) + else: + source = source.replace('"workdir": ' + literal, + '"workdir": ' + json.dumps(str(tmp_path / "elsewhere"))) + call["payload"]["input"] = source + trace = tmp_path / "trace.jsonl" + _rollout(trace, _meta(tmp_path), call, _command(tmp_path, "cat note.md", "body\n", "event"), + _result("read", "body\n")) + _, events, _, uncertain, _ = read_window(trace, (2, 4), tmp_path, archive=True) + assert events[0]["delivery"]["state"] == "unknown" and uncertain == [3] + + +@pytest.mark.parametrize(("literal", "visible"), [ + ("""'cat "example.md"'""", True), ('`cat "example.md"`', True), + ('`cat "${file}"`', False), ("""'cat ' + '"example.md"'""", False), +]) +def test_single_quoted_and_static_template_command_receives_stdout(tmp_path, literal, visible): + trace = tmp_path / "trace.jsonl" + command = 'cat "example.md"' + call = _call(tmp_path, command, "read") + call["payload"]["input"] = call["payload"]["input"].replace(json.dumps(command), literal) + _rollout(trace, _meta(tmp_path), call, _command(tmp_path, command, "observed\n", "event"), + _result("read", "observed\n")) + _, events, _, uncertain, _ = read_window(trace, (2, 4), tmp_path, archive=True) + assert (events[0]["delivery"]["state"] == "visible") is visible + assert uncertain == ([] if visible else [3]) + + +@pytest.mark.parametrize("issue", [ + None, "truncated", "exit_code", "running", "multi_result", "multi_call", "summary", +]) +def test_single_serialized_exec_result_for_material_read(tmp_path, issue): + trace = tmp_path / "rollout.jsonl" + ref, revision = "package:example", "sha256:" + "a" * 64 + cmd = f"inferrsi read {ref} --revision {revision} --material --omit-resources" + body = 'Check the "baseline" first.\n保留精度对照。\n' + output = json.dumps({"ref": ref, "id": "example", "revision": revision, + "entrypoint": "SKILL.md", "content": body}, ensure_ascii=False) + "\n" + call = _call(tmp_path, cmd, "read", emit="JSON.stringify(r)") + result = _exec_result("read", output) + blocks = result["payload"]["output"] + if issue == "truncated": + result = _exec_result("read", "Warning: truncated output\n" + output[:80]) + elif issue == "exit_code": + result = _exec_result("read", output, exit_code=1) + elif issue == "running": + running = json.loads(blocks[1]["text"]) + del running["exit_code"] + blocks[1]["text"] = json.dumps({**running, "session_id": 123}) + elif issue == "multi_result": + blocks.append(dict(blocks[1])) + elif issue == "multi_call": + source = call["payload"]["input"] + call["payload"]["input"] = source.replace( + "text(JSON.stringify(r))", "await tools.exec_command(next); text(JSON.stringify(r))" + ) + elif issue == "summary": + blocks[1]["text"] = json.dumps({"output": output, "exit_code": 0}) + _rollout( + trace, _meta(tmp_path), call, _command(tmp_path, cmd, output, "read-event"), result, + ) + _, events, _, uncertain, details = read_window(trace, (2, 4), tmp_path, archive=True) + delivery = events[0]["delivery"] + if issue is None: + assert delivery["state"] == "visible" and delivery["return_line"] == 4 + assert delivery["visible_resources"] == [{"ref": ref, "path": "SKILL.md"}] + assert [p["text"] for p in delivery["passages"]] == body.splitlines() + assert not uncertain and not details + else: + assert delivery["state"] == "unknown" and not delivery["passages"] + assert not delivery.get("visible_resources") and uncertain == [3] + + +@pytest.mark.parametrize("explicit_returns", [False, True]) +def test_selected_captures_use_verified_serialized_cli_returns(tmp_path, explicit_returns): + from inferrsi.apps.views.search_attribution import import_search + from inferrsi.apps.workflows.campaign import create_campaign + from tests.apps.test_codex_knowledge_search import LIBRARY, QUERY, _cli + from tests.apps.test_search_capture_delivery import _review + + root, trace = tmp_path / "campaign", tmp_path / "trace.jsonl" + create_campaign(root, "example") + argv, found = _cli(tmp_path, "find", QUERY, "--session", str(root), + "--limit", "1", "--no-external") + result = json.loads(found) + find_id = Path(result["reference"]["path"]).stem + read_argv, opened = _cli(tmp_path, *result["items"][0]["read_args"]) + view = json.loads(opened) + read_id = Path(view["reference"]["path"]).stem + compound = shlex.join(argv) + "; printf done" + read = shlex.join(read_argv) + _rollout( + trace, _meta(tmp_path), + _call(tmp_path, compound, "find", emit="JSON.stringify(r)"), + _command(tmp_path, compound, found + "done", "compound"), + _exec_result("find", found + "done"), + _call(tmp_path, read, "read", emit="JSON.stringify(r)"), + _command(tmp_path, read, opened, "read-event"), _exec_result("read", opened), + ) + review = _review(tmp_path / "review.json", + capture_returns={find_id: 4, read_id: 7} if explicit_returns else {}) + archive = import_search(root, number=1, trace=trace, lines=(2, 7), knowledge_root=LIBRARY, + context_ids=[find_id, read_id], archive_review=review, complete=True) + for path in (root / "search/round-1.json", archive): + record = json.loads(path.read_bytes()) + assert record["coverage"] == "partial" and record["unresolved_command_lines"] == [3] + assert record["observed"]["used"] == 0 + search, read = record["events"] + assert search["context_id"] == find_id and search["delivery"]["return_line"] == 4 + assert read["context_id"] == read_id and read["delivery"]["return_line"] == 7 + assert read["delivery"]["visible_resources"] == [ + {"ref": view["ref"], "path": view["content_resource"]}, + ] + + def test_archive_keeps_multiple_exact_matches_and_legacy_materials(tmp_path): corpus = tmp_path / "knowledge" corpus.mkdir() @@ -249,7 +402,8 @@ def test_closed_window_ignores_later_duplicate_and_partial_trace_rows(tmp_path): assert uncertain == [] and details == [] -def test_truncated_result_keeps_only_exact_visible_lines_and_refs(tmp_path): +@pytest.mark.parametrize("structured", [False, True]) +def test_truncated_result_keeps_only_exact_visible_lines_and_refs(tmp_path, structured): corpus = tmp_path / "knowledge" corpus.mkdir() trace = tmp_path / "rollout.jsonl" @@ -259,9 +413,10 @@ def test_truncated_result_keeps_only_exact_visible_lines_and_refs(tmp_path): "Warning: truncated output (original token count exceeded)\n" "a.md:1:first\n[omitted]\nc.md:3:last\n" ) - _rollout(trace, _meta(corpus), _call(corpus, command, "call-search"), + _rollout(trace, _meta(corpus), + _call(corpus, command, "call-search", emit="r" if structured else "r.output"), _command(corpus, command, aggregate, "exec-search"), - _result("call-search", visible)) + (_exec_result if structured else _result)("call-search", visible)) _, events, _, uncertain, details = read_window(trace, (2, 4), corpus, archive=True) event = events[0] diff --git a/tests/apps/test_codex_search_shell_forms.py b/tests/apps/test_codex_search_shell_forms.py index 0ae748c14..6436eca11 100644 --- a/tests/apps/test_codex_search_shell_forms.py +++ b/tests/apps/test_codex_search_shell_forms.py @@ -74,6 +74,32 @@ def test_a_windows_recorded_tool_is_read_as_that_tool(tmp_path, tool): assert event is not None and event["tool"] == "rg" and complete +@pytest.mark.parametrize("script, complete", [ + ("rg -n -A15 'def relative_location' plugin/runtime/evidence.py", True), + ("rg -n -Aunknown needle plugin/runtime/evidence.py", False), + ("rg -n -A15 needle plugin/runtime/evidence.py && rg needle knowledge", False), +]) +def test_only_a_known_out_of_corpus_search_can_be_excluded(tmp_path, script, complete): + item = {"command": ["/bin/zsh", "-lc", script], "cwd": tmp_path.as_uri(), + "exit_code": 0, "aggregated_output": "1:def relative_location"} + assert _command(item, tmp_path / "knowledge") == (None, complete, None) + + +@pytest.mark.parametrize("option,scopes", [ + ("-A15", ["runtime/evidence.py", "knowledge/guide.md"]), + ("-B2", ["knowledge/guide.md"]), + ("-C0", ["knowledge/guide.md"]), +]) +def test_attached_context_preserves_only_the_recorded_corpus_hits(tmp_path, option, scopes): + output = "".join(f"{path}:2:needle\n" for path in scopes) + item = {"command": ["rg", "-nH", option, "needle", *scopes], "cwd": tmp_path.as_uri(), + "exit_code": 0, "aggregated_output": output} + event, complete, spec = _command(item, tmp_path / "knowledge") + assert complete and spec["mode"] == "numbered_context" + assert event["scope"] == ["guide.md"] and event["options"] == ["-nH", option] + assert event["materials"] == [{"ref": "guide.md", "match_line": 2}] + + def test_a_multi_line_script_keeps_its_line_boundaries(): assert _recorded_argv({"command": ["bash", "-lc", "cd docs\nrg -n needle ."]}) == ( ["cd", "docs", ";", "rg", "-n", "needle", "."], True) @@ -114,6 +140,52 @@ def test_a_compound_command_without_a_shell_or_tool_is_still_no_retrieval(tmp_pa assert _command(item, tmp_path) == (None, True, None) +@pytest.mark.parametrize(("script", "complete"), [ + ("cat profile/result.txt && git diff -- implementation.py && git status --short", True), + ("rg -n needle profile/result.txt && git status --short", True), + ("cat profile/result.txt && cat knowledge/card.md", False), + ("cat profile/result.txt && cat \"$DOCUMENT\"", False), + ("cd elsewhere && cat result.txt", False), + ("cat profile/result.txt | rg needle", False), + ("python - <<'PY'\nfrom pathlib import Path\n" + "p=Path('project/cache.pyc')\nif p.exists(): p.unlink()\nPY", True), + ("python - <<'PY'\nwith open('project/result.txt') as f: data=f.read()\n" + "print(data.find('passed'))\nPY", True), + ("python - <<'PY'\nimport inferrsi\nprint(inferrsi.__version__)\nPY", True), + ("python - <<'PY'\nfrom inferrsi import __version__\nprint(__version__)\nPY", True), + ("python - <<'PY'\nimport subprocess\nsubprocess.run(['rg','needle',scope])\nPY", False), + ("python - <<'PY'\nfrom inferrsi.apps.cli import main\nmain(['find','needle'])\nPY", False), + ("python - <<'PY'\nfrom inferrsi.apps import cli as app\n" + "app.main(['find','needle'])\nPY", False), + ("python - <<'PY'\nfrom inferrsi import knowledge\n" + "print(knowledge.knowledge_find.find('needle'))\nPY", False), + ("python - <<'PY'\nfrom pathlib import Path\n" + "print(Path('knowledge/card.md').read_text())\nPY", False), + ("python - < MAX_CONTEXT_CAPTURE_BYTES + store, revision, original = store_edition(tmp_path, body) + root = tmp_path / "campaign" + call(capsys, "campaign", "init", "--id", "paging", "--directory", str(root)) + result, _ = call(capsys, "find", "pagingdemo", "--store", str(store.workspace), + "--session", str(root), "--limit", "1") + search_ref = result["reference"]["path"] + item, = result["items"] + assert item["material_ref"] == "store:paging-demo" and item["revision"] == revision + argv = [*item["read_args"], "--resource", "pages.md"] + result, _ = call(capsys, *argv) + standalone, _ = call(capsys, "read", item["material_ref"], "--revision", revision, + "--store", str(store.workspace), "--resource", "pages.md", + "--omit-resources") + assert standalone["content"] == result["content"] + assert standalone["next_byte_range"] == result["next_byte_range"] + replacement = Bundle(original.metadata, {"note.md": b"updated", "pages.md": b"new"}, {}) + store.update(replacement, expected=revision, reason="new edition", evidence=[]) + received = bytearray() + while True: + span, data = result["content_range"], result["content"].encode() + assert span == {"start": len(received), "end": len(received) + len(data), + "total_bytes": len(body), "first_line": received.count(b"\n") + 1} + assert data == body[span["start"]:span["end"]] + assert result["revision"] == revision + assert result["search_ref"] == search_ref + saved = (root / result["reference"]["path"]).read_bytes() + assert len(saved) <= MAX_CONTEXT_CAPTURE_BYTES + document, state = verify_capture(saved) + assert state == "verified" and document["context_bytes_used"] == len(data) + resource, = document["contexts"][0]["resources"] + assert resource["content_range"] == span and resource["content"] == result["content"] + assert resource["sha256"] == hashlib.sha256(data).hexdigest() + assert resource["source_sha256"] == hashlib.sha256(body).hexdigest() + received.extend(data) + if "next_byte_range" not in result: + break + result, _ = call(capsys, *result["next_read_args"]) + assert bytes(received) == body + + +@pytest.mark.parametrize("body", [ + bytes(random.Random(686).choices(b"abcdefghijklmnopqrstuvwxyz0123456789+/", k=153_600)), + ("资料😀\t\r\n\u0001\\\"" * 2_000).encode(), +], ids=["entropy", "utf8-escaped"]) +def test_default_pages_and_explicit_large_ranges_return_bounded_executable_continuations( + tmp_path, capsys, body, +): + store, revision, _ = store_edition(tmp_path, body) + argv = ["read", "store:paging-demo", "--store", str(store.workspace), + "--revision", revision, "--resource", "pages.md"] + page, _ = call(capsys, *argv) + assert "resources" not in page and "required_resources" not in page + explicit, _ = call(capsys, *argv, "--byte-range", "0", str(len(body))) + assert explicit["content"] == page["content"] + received = bytearray() + while True: + raw = page["content"].encode() + assert len(json.dumps(page["content"], ensure_ascii=False).encode()) <= INLINE_PAGE_BYTES + assert page["content_range"]["start"] == len(received) + assert page["content_range"]["end"] == len(received) + len(raw) + received.extend(raw) + if "next_read_args" not in page: + break + continuation = page["next_read_args"] + assert continuation[:4] == ["read", "store:paging-demo", "--revision", revision] + for flag, value in (("--store", str(store.workspace)), ("--resource", "pages.md")): + assert continuation[continuation.index(flag) + 1] == value + assert "--omit-resources" in continuation + assert continuation[-3:] == ["--byte-range", *map(str, page["next_byte_range"])] + page, _ = call(capsys, *continuation) + assert received == body + + +def test_content_read_does_not_expand_the_package_inventory(tmp_path, capsys): + ref = "package:inferrsi.common.skills.inference_benchmark_design" + revision = KnowledgeReader().read(ref).revision + inventory, _ = call(capsys, "read", ref, "--revision", revision) + assert len(inventory["resources"]) > 100 + assert "content" not in inventory + page, _ = call(capsys, "read", ref, "--revision", revision, + "--resource", "references/benchmark-commands.md") + assert page["content"] and page["next_read_args"] + assert "resources" not in page and "required_resources" not in page + + +@pytest.mark.parametrize("scoped", [False, True]) +def test_archive_only_attributes_the_selected_bytes_and_their_source_line(tmp_path, capsys, scoped): + body = "一\nsecond line\nlast".encode() + store, revision, _ = store_edition(tmp_path, body) + root = tmp_path / "campaign" + call(capsys, "campaign", "init", "--id", "range", "--directory", str(root)) + argv = ["read", "store:paging-demo", "--store", str(store.workspace), "--revision", revision] + if scoped: + found, _ = call(capsys, "find", "pagingdemo", "--session", str(root), + "--store", str(store.workspace), "--limit", "1") + argv = found["items"][0]["read_args"] + argv = [*argv, "--resource", "pages.md", "--byte-range", "4", "11"] + result, output = call(capsys, *argv) + assert result["content"] == "second line" and result["next_byte_range"] == [15, 11] + rows = _operation(tmp_path, [sys.executable, "-m", "inferrsi", *argv], output, "read") + _, archive = _import(tmp_path, rows, campaign=root) + event, = archive["events"] + assert event["materials"][0]["content_range"] == result["content_range"] + resource, = event["delivery"]["visible_resources"] + assert resource["content_range"] == result["content_range"] + passage, = event["delivery"]["passages"] + assert (passage["line"], passage["text"]) == (2, "second line") + if scoped: + _, via_capture = _import(tmp_path, rows, campaign=root, + context_ids=[Path(result["reference"]["path"]).stem]) + event, = via_capture["events"] + assert event["materials"][0]["content_range"] == result["content_range"] + assert event["delivery"]["visible_resources"] == [resource] + + +def test_utf8_bounds_and_projected_skill_ranges(tmp_path, capsys): + ref = "package:inferrsi.common.skills.inference_benchmark_design" + bundle = KnowledgeReader().read(ref) + path = bundle.metadata["skill_documents"]["original"] + root = tmp_path / "campaign" + call(capsys, "campaign", "init", "--id", "cuda", "--directory", str(root), "--backend", "cuda") + result, _ = call(capsys, "find", "inference benchmark design", "--repo-type", "inferrsi", + "--session", str(root), "--limit", "1") + argv = result["items"][0]["read_args"] + full, _ = call(capsys, *argv) + split = full["content_view"]["source_byte_ranges"][0][1] + row, _ = call(capsys, *argv, "--byte-range", str(split - 1), "4") + proof = row["content_view"] + assert row["content"].encode() == full["content"].encode()[split - 1:split + 3] + assert len(proof["source_byte_ranges"]) == 2 + source_parts = [bundle.content[path][lo:hi] for lo, hi in proof["source_byte_ranges"]] + assert b"".join(source_parts) == row["content"].encode() + assert proof["sha256"] == hashlib.sha256(row["content"].encode()).hexdigest() + for requested in (["-1", "10"], ["0", "0"], [str(len(bundle.content[path])), "10"]): + with pytest.raises(SystemExit): + main(["read", ref, "--resource", path, "--revision", bundle.revision, + "--byte-range", *requested]) + with pytest.raises(SystemExit): + main(["read", ref, "--resource", path, "--byte-range", "0", "5"]) + + store, revision, _ = store_edition(tmp_path, "x😀 measurement".encode()) + argv = ["read", "store:paging-demo", "--store", str(store.workspace), "--revision", revision, + "--resource", "pages.md", "--byte-range"] + first, _ = call(capsys, *argv, "0", "1") + assert first["content"] == "x" and first["next_byte_range"] == [1, 4] + for start, size in (("1", "1"), ("2", "6")): + with pytest.raises(SystemExit): + main([*argv, start, size]) diff --git a/tests/apps/test_mindie_project.py b/tests/apps/test_mindie_project.py index 5b94b79d5..6dca96eff 100644 --- a/tests/apps/test_mindie_project.py +++ b/tests/apps/test_mindie_project.py @@ -2,6 +2,8 @@ import json from pathlib import Path +import pytest + from inferrsi.apps.cli import main from inferrsi.apps.integrations.mindie import mcp as mindie_mcp from inferrsi.apps.integrations.mindie import project as mindie_project @@ -37,6 +39,19 @@ def worker(grant, operation, raw): assert json.loads(capsys.readouterr().out)["available"] assert main(["mindie", "describe"]) == 0 assert json.loads(capsys.readouterr().out)["tools"] == ["knowledge_query", "knowledge_explain"] + request = {"query": "vector tail", "conditions": {"dtype": "fp16"}, "limit": 1, + "token_budget": 512, "include_unknown": True} + request_file = tmp_path / "request.json" + request_file.write_text(json.dumps(request)) + command = ["find", "--input", str(request_file)] + with pytest.raises(SystemExit) as rejected: + main([*command, "--external-source", "mindie-agent"]) + assert rejected.value.code == 2 + assert "native MindIE request" in capsys.readouterr().err + assert main(command) == 0 + receipt = Path(json.loads(capsys.readouterr().out)["receipt_directory"]) + assert json.loads((receipt / "input.json").read_text()) == request + assert json.loads((receipt / "receipt.json").read_text())["operation"] == "knowledge_query" assert {tool["name"] for tool in mindie_mcp._reply("tools/list", {})["tools"]} == { "knowledge_query", "knowledge_explain", } @@ -70,6 +85,9 @@ def worker(grant, operation, raw): assert json.loads((failed_path / "receipt.json").read_text())["exit_code"] == 1 monkeypatch.chdir(disabled) + with pytest.raises(SystemExit) as error: + main(command) + assert error.value.code == 2 assert mindie_mcp._reply("tools/list", {}) == {"tools": []} assert mindie_mcp._reply("tools/call", { "name": "knowledge_query", "arguments": {"query": "vector tail"}, @@ -84,4 +102,5 @@ def worker(grant, operation, raw): assert main(["mindie", "disable"]) == 0 assert mindie_mcp._reply("tools/list", {}) == {"tools": []} assert directory.is_dir() - assert reads == [("query", {"query": "vector tail"}), ("query", {"query": "read failure"})] + assert reads == [("query", request), ("query", {"query": "vector tail"}), + ("query", {"query": "read failure"})] diff --git a/tests/apps/test_mindie_runtime.py b/tests/apps/test_mindie_runtime.py index 056a7d3eb..fd76e105c 100644 --- a/tests/apps/test_mindie_runtime.py +++ b/tests/apps/test_mindie_runtime.py @@ -112,6 +112,28 @@ def query(self, query, *, navigation_only=False, **kwargs): "value": self.store.db.execute( "SELECT value FROM sentinel").fetchone()["value"]} self.observe_delivered(index, payload, delivery="query") + if query.startswith("archive-native"): + assert navigation_only and kwargs["conditions"] == {"dtype": "fp16"} + page = {"domain": "operators", "retrieval": "graded-bm25", + "results": [], "cards": [], "foundation_cards": [], + "usage": {"has_more": kwargs["token_budget"] == 1}} + if kwargs["token_budget"] == 1: + return page + prefix = "mindie://operators/units/" + if query == "archive-native-incomplete": + page.pop("cards") + return page + if query == "archive-native-invalid": + page["cards"] = [{"ref": prefix + "../private@2"}] + return page + found = {"ref": prefix + "unit-token-graph@3", "id": "unit-token-graph", + "revision": 3, "match_status": "matched", "ready_to_apply": True, + "excerpt": "private navigation preview"} + unknown = {"ref": prefix + "unit-unknown@2", "revision": 2, + "match_status": "condition_unknown", "ready_to_apply": False} + page.update(cards=[found], foundation_cards=[found], + unverified_cards=[unknown]) + return page if query.startswith("navigation-") or query == "graph mode": assert navigation_only assert kwargs == { @@ -233,6 +255,132 @@ def explain(self, refs, **kwargs): return {"python": str(python), "engine": str(engine), "domain": "operators"}, metadata +@pytest.fixture +def native_archive_project(reader, tmp_path): + from tests.apps.test_codex_knowledge_search import _cli + + grant, _ = reader + (tmp_path / ".git").mkdir() + adapter = tmp_path / "adapter.json" + adapter.write_text(json.dumps({"engine_config": grant["engine"], "python": grant["python"]})) + _cli(tmp_path, "mindie", "enable", "--adapter-config", str(adapter)) + return tmp_path + + +@pytest.mark.parametrize("case", [ + "hits", "legacy", "empty", "truncated", "incomplete", "malformed", "failed", +]) +def test_native_find_imports_only_the_observed_navigation(native_archive_project, case): + from tests.apps.test_codex_knowledge_search import _cli, _import, _operation + + tmp_path = native_archive_project + request = tmp_path / "private-query-input.json" + queries = {"legacy": "fixture", "malformed": "archive-native-invalid", "failed": "value-error", + "incomplete": "archive-native-incomplete"} + query = queries.get(case, "archive-native from /local/private/material") + request.write_text(json.dumps({"query": query, "conditions": {"dtype": "fp16"}, + "token_budget": 1 if case == "empty" else 8000})) + command = ["find", "--input", str(request)] + if case == "failed": + with pytest.raises(subprocess.CalledProcessError) as error: + _cli(tmp_path, *command) + rows = _operation(tmp_path, error.value.cmd, error.value.stderr, "native") + rows[1]["payload"]["item"]["exit_code"] = error.value.returncode + else: + argv, output = _cli(tmp_path, *command) + response = json.loads(output) + assert bool(response["result"]["results"]) == (case == "legacy") + Path(response["receipt_directory"]).rename(tmp_path / "moved-receipt") + if case == "legacy": + old_input = argv.index("--input") + argv[old_input:old_input] = ["--external-source", "mindie-agent"] + response.pop("query") # Earlier native Find printed just result and receipt_directory. + output = json.dumps(response, ensure_ascii=False, indent=2) + "\n" + received = "… 40 tokens truncated …" if case == "truncated" else True + rows = _operation(tmp_path, argv, output, "native", received=received) + request.unlink() + _cli(tmp_path, "mindie", "disable") + (tmp_path / "knowledge").rename(tmp_path / "moved-catalog") + + for record in _import(tmp_path, rows): + event, = record["events"] + assert (event["tool"], event["action"]) == ("find", "search") + text = json.dumps(record) + assert all(value not in text for value in ( + "private-query-input", "private navigation preview", str(tmp_path), "receipt_directory", + "/local/private/material", + )) + if case in ("truncated", "incomplete", "malformed", "failed"): + assert record["coverage"] == "partial" and record["counts"] is None + assert record["unresolved_command_lines"] and event["delivery"]["state"] == "unknown" + continue + assert record["coverage"] == "complete" and record["counts"]["searches"] == 1 + assert record["counts"]["used"] == 0 and not event["delivery"].get("visible_resources") + assert not event["delivery"].get("passages") + if case == "legacy": + assert "query" not in event + assert event["materials"] == [{ + "ref": "mindie-agent:operators/units/fixture@1", "revision": "1", + "navigation": [{"list": "results"}], + }] + assert record["counts"]["hits"] == 1 + continue + assert event["query"] == "archive-native from [redacted-path]" + if case == "empty": + assert not event["materials"] and record["counts"]["hits"] == 0 and event["has_more"] + continue + first, unknown = event["materials"] + assert first == {"ref": "mindie-agent:operators/units/unit-token-graph@3", "revision": "3", + "navigation": [{"list": group, "match_status": "matched", + "ready_to_apply": True} + for group in ("cards", "foundation_cards")]} + assert unknown["navigation"] == [{"list": "unverified_cards", + "match_status": "condition_unknown", + "ready_to_apply": False}] + assert record["counts"]["hits"] == record["counts"]["unique_hits"] == 2 + assert all(material["use"] == "unknown" and material["delivery_state"] == "ref_visible" + for material in record["materials"].values()) + + if case == "hits": + decision = "I will inspect the operator's graph prerequisites." + rows.append({"type": "response_item", "payload": { + "type": "message", "role": "assistant", "phase": "final_answer", + "content": [{"type": "output_text", "text": decision}], + }}) + review = {"ref": first["ref"], "use": "used", "event_line": 3, "passage_line": 1, + "passage_path": "unit.md", + "decision_line": 5, "decision_quote": decision} + with pytest.raises(subprocess.CalledProcessError) as error: + _import(tmp_path, rows, decisions=[review]) + assert "delivered" in error.value.stderr and "passage" in error.value.stderr + + +def test_text_and_json_find_archive_local_and_mindie_hits(native_archive_project): + from tests.apps.test_codex_knowledge_search import _cli, _import, _operation + + root = native_archive_project + command = ["find", "graph mode", "--backend", "ascend", "--external-source", "mindie-agent", + "--limit", "1"] + encoded = _cli(root, *command, "--json") + rendered = _cli(root, *command) + result = json.loads(encoded[1]) + local, = result["items"] + expected = [f"{local['authority']}:{local['id']}", + "mindie-agent:operators/units/unit-z@3", "mindie-agent:operators/units/unit-a@2"] + assert [hit["locator"] for hit in result["external"][0]["items"]] == [ + "mindie://operators/units/unit-z@3", "mindie://operators/units/unit-a@2", + ] + _cli(root, "mindie", "disable") + for argv, output in (encoded, rendered): + for record in _import(root, _operation(root, argv, output, "find")): + assert record["coverage"] == "complete" and record["counts"]["hits"] == 3 + event, = record["events"] + assert [material["ref"] for material in event["materials"]] == expected + assert [row["revision"] for row in event["materials"][1:]] == ["3", "2"] + assert event["delivery"]["visible_refs"] == expected + assert not event["delivery"].get("passages") and record["counts"]["used"] == 0 + + @pytest.mark.parametrize("extended_path", [ False, pytest.param(True, marks=pytest.mark.skipif(os.name != "nt", reason="Windows extended path")), diff --git a/tests/apps/test_mlx_discovery.py b/tests/apps/test_mlx_discovery.py index d82fb5cec..994ea59e3 100644 --- a/tests/apps/test_mlx_discovery.py +++ b/tests/apps/test_mlx_discovery.py @@ -149,7 +149,7 @@ def test_mlx_cards_are_source_scoped_and_readable(capsys): assert search_knowledge(repo="mlx", tier="peer", backend="mlx") == [] assert search_knowledge(repo="mlx", backend="cuda") == [] assert main([ - "knowledge", "search", "--tier", "dependency", "--repo-type", "mlx", + "knowledge", "list", "--tier", "dependency", "--repo-type", "mlx", "--backend", "mlx", "--json", "--limit", "100", ]) == 0 assert {item["id"] for item in json.loads(capsys.readouterr().out)} == IDS diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 28ad3d225..61b3d8bf5 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -915,30 +915,73 @@ def test_task_runner_does_not_expose_harness_as_top_level_modules(task, tmp_path assert json.loads(output.read_text())["isolated"] +def test_scoped_read_records_bytes_independently_of_the_experiment_limit(task, request, capsys): + from inferrsi.apps.views.dashboard import dashboard_snapshot + + query = "Qwen-Image-2.1 denoise NPU eager" + scenario = "diffusion.image_generation" + ref = "package:vllm_omni.ascend.diffusion.qwen_image_21_eager_t2i" + (task / "task.json").write_text(json.dumps({ + "knowledge_delivery": {"query": query, "scenario": scenario, + "ref": ref, "context_bytes": 1}, + })) + root = request.getfixturevalue("session") + for scope in ([], ["--scenario", "diffusion.t2i"]): + assert main(["find", query, "--session", str(root), *scope]) == 0 + found = json.loads(capsys.readouterr().out) + hits = {item["material_ref"]: item for item in found["items"]} + assert main(hits["package:inferrsi.ascend.skills.ascend_graph_mode"]["read_args"]) == 0 + assert json.loads(capsys.readouterr().out)["content"] + assert main(hits[ref]["read_args"]) == 0 + card = json.loads(capsys.readouterr().out) + receipt = json.loads((root / card["reference"]["path"]).read_bytes()) + size = hits[ref]["next_read_content_bytes"] + assert receipt["context_budget"] is None and not receipt["context_omissions"] + assert len(card["content"].encode("utf-8")) == receipt["context_bytes_used"] == size > 0 + search = json.loads((root / found["reference"]["path"]).read_bytes()) + assert "context_bytes" not in receipt["request"] + assert "context_bytes" not in search["request"] + visible = dashboard_snapshot(root)["data"]["managed_retrievals"] + observed = next(row for row in visible if row["path"] == found["reference"]["path"]) + card_hit = next(item for item in observed["items"] if item["ref"] == ref) + assert card_hit["delivered"] and card_hit["reads"] == [ + {"path": card["reference"]["path"], "resource": "record.json"}, + ] + + def test_knowledge_delivery_is_retained_and_bound_to_round(session, capsys): from inferrsi.apps.workflows.campaign import verify_capture from inferrsi.knowledge.knowledge_find import installed_skill_root from inferrsi.knowledge.knowledge_operations import KnowledgeReader assert main([ - "benchmarks", "session", "knowledge", "--session", str(session), - "--query", "cache per-step masks ran out of device memory", - "--limit", "1", "--context-bytes", "8192", + "find", "cache per-step masks ran out of device memory", "--session", str(session), + "--limit", "1", ]) == 0 + found = json.loads(capsys.readouterr().out) + hit, = found["items"] + assert "content" not in hit + wrong_pin = list(hit["read_args"]) + wrong_pin[wrong_pin.index("--revision") + 1] = "sha256:" + "0" * 64 + with pytest.raises(SystemExit): + main(wrong_pin) + assert "hit and revision" in capsys.readouterr().err + assert main(hit["read_args"]) == 0 delivered = json.loads(capsys.readouterr().out) assert set(delivered["reference"]) == {"path", "sha256", "kind"} path = session / delivered["reference"]["path"] capture, state = verify_capture(path.read_bytes()) assert state == "verified" assert capture["selection"]["method"] == "find-lexical-v1" - assert capture["retrieval"]["calls"] == ["campaign capture-context", "collect", "find"] + assert capture["retrieval"]["calls"] == ["read"] + assert capture["request"]["search_ref"] == found["reference"]["path"] item, = capture["items"] assert item["ref"] == "checkout:case.qwen-ascend-rejected-directions" context, = capture["contexts"] assert context["revision"] == item["revision"] - assert context["content_bytes"] <= 8192 + assert context["content_bytes"] > 0 and capture["context_budget"] is None assert {resource["path"] for resource in context["resources"]} == { - "qwen-ascend-rejected-directions.md", "qwen-ascend-rejected-directions.json", + "qwen-ascend-rejected-directions.md", } reader = KnowledgeReader(skill_root=installed_skill_root()) for resource in context["resources"]: @@ -947,8 +990,16 @@ def test_knowledge_delivery_is_retained_and_bound_to_round(session, capsys): ) result = submit(session, 2, capsys) observation = result["latest_observation"] + assert main(["benchmarks", "session", "status", "--session", str(session), + "--round-receipt", "1"]) == 0 + receipt = json.loads(capsys.readouterr().out) + assert receipt["completed_rounds"] == 1 and receipt["latest_observation"] == { + key: observation[key] for key in ("path", "observation_sha256") + } assert observation["contexts"] == [ - {**delivered["reference"], "round": 1, "diagnosis_id": observation["diagnosis_id"]} + {**found["reference"], "round": 1, "diagnosis_id": observation["diagnosis_id"]}, + {**delivered["reference"], "round": 1, "diagnosis_id": observation["diagnosis_id"], + "search_ref": found["reference"]["path"]}, ] from inferrsi.apps.views.dashboard import dashboard_snapshot @@ -957,21 +1008,24 @@ def test_knowledge_delivery_is_retained_and_bound_to_round(session, capsys): retrieval, = data["managed_retrievals"] assert retrieval["round"] == 1 and "external" not in retrieval assert data["candidates"][0]["knowledge_uses"] == [] + with pytest.raises(SystemExit): + main(hit["read_args"]) + assert "current round and diagnosis" in capsys.readouterr().err def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(session, capsys): from inferrsi.apps.views.dashboard import dashboard_snapshot + from inferrsi.harness import optimization + from tests.fixtures.knowledge_retrieval import install_legacy_capture - assert main([ - "benchmarks", "session", "knowledge", "--session", str(session), - "--query", "cache per-step masks ran out of device memory", - "--limit", "1", "--context-bytes", "1", - ]) == 0 - capture = json.loads(capsys.readouterr().out)["context"] + plan, state = optimization._load(session) + binding = optimization._context_diagnosis(plan, state) + path, digest = install_legacy_capture(session, "managed-omitted", "legacy", diagnosis=binding) + capture = json.loads(path.read_bytes()) state_path = session / "state.json" - state = json.loads(state_path.read_bytes()) - reference, = state["contexts"] - del reference["round"] + reference = {"path": path.relative_to(session).as_posix(), "sha256": digest, + "kind": "delivered_context", "diagnosis_id": binding["diagnosis_id"]} + state["contexts"].append(reference) state_path.write_text(json.dumps(state), encoding="utf-8") assert dashboard_snapshot(session)["data"]["managed_retrievals"] == [] @@ -1042,9 +1096,8 @@ def test_managed_knowledge_rejects_unverified_capture( from inferrsi.harness.records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES assert main([ - "benchmarks", "session", "knowledge", "--session", str(session), - "--query", "cache per-step masks ran out of device memory", - "--limit", "1", "--context-bytes", "8192", + "find", "cache per-step masks ran out of device memory", "--session", str(session), + "--limit", "1", ]) == 0 capsys.readouterr() state_path = session / "state.json" @@ -1104,13 +1157,15 @@ def track_read(path, limit): def test_cannbot_query_and_read_trace_to_candidate(tmp_path, task, capsys, monkeypatch): from inferrsi.apps.integrations.cannbot import project from inferrsi.apps.integrations.project_binding import checkout_identity + from inferrsi.apps.views.codex_knowledge import decode from inferrsi.apps.views.dashboard import dashboard_snapshot revision, digest = "a" * 40, "b" * 64 locator = "ops/ascendc/apis/synthetic" uncited = "ops/ascendc/apis/uncited" card_text = "synthetic external body" - search_query = "cache per-step masks ran out of device memory" + raw_query = "cache per-step masks ran out of device memory in /tmp/profile.json" + search_query = "cache per-step masks ran out of device memory in [redacted-path]" phase = {"state": "ok", "items": [locator, uncited]} approved = tmp_path / "approved" (approved / ".git").mkdir(parents=True) @@ -1167,8 +1222,7 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout, root, expect assert "external_knowledge_project" not in started monkeypatch.chdir(unrelated) - query_args = [*operation, "knowledge", *session_args, "--query", search_query, - "--context-bytes", "8192", "--limit", "2"] + query_args = ["find", raw_query, *session_args, "--limit", "2"] with pytest.raises(SystemExit): main(query_args) assert "Record measured bottleneck evidence" in capsys.readouterr().err @@ -1179,10 +1233,18 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout, root, expect "measurement_summary": "Synthetic workload: reference operation took 4 ms.", } assert main(query_args) == 0 - answer = json.loads(capsys.readouterr().out) + returned = capsys.readouterr().out + answer = json.loads(returned) + event, complete, recorded = decode(("find", query_args), 0, returned) + assert complete and recorded["capture"][0] == answer["reference"]["path"] + assert event["query"] == answer["query"] == search_query + assert any(item["ref"] == "cannbot-knowledge:" + locator for item in event["materials"]) + assert not decode(("find", [*query_args, "--no-external"]), 0, returned)[1] + assert not decode(("find", query_args), 0, json.dumps({**answer, "query": "other"}))[1] search_path = answer["external"]["reference"]["path"] - local_path = answer["reference"]["path"] - local_item = answer["context"]["contexts"][0]["ref"] + assert main(answer["items"][0]["read_args"]) == 0 + local_read = json.loads(capsys.readouterr().out) + local_path, local_item = local_read["reference"]["path"], local_read["ref"] before = dashboard_snapshot(root)["data"] assert before["managed_diagnoses"] == [{**diagnosis, "rounds": [1]}] query, = before["managed_retrievals"] @@ -1193,8 +1255,12 @@ def read(ref, *, expected_revision, expected_sha256, page, timeout, root, expect assert query["external"]["reads"] == [] assert not before["candidates"] - read_args = [*operation, "knowledge-read", *session_args, "--search-ref", search_path, - "--locator"] + ext_hit = next(hit for hit in answer["external"]["items"] if hit["locator"] == locator) + assert ext_hit["read_args"] == [ + *operation, "knowledge-read", *session_args, "--search-ref", search_path, + "--locator", locator, + ] + read_args = ext_hit["read_args"][:-1] with pytest.raises(SystemExit): main([*read_args, "ops/ascendc/not-from-search"]) assert "from the recorded search" in capsys.readouterr().err @@ -1399,10 +1465,9 @@ def legacy_plan(root, plan): capsys.readouterr() monkeypatch.chdir(unrelated) diagnose(root, capsys) - assert main([*args, "knowledge", *session_args, "--query", - "cache per-step masks ran out of device memory", "--context-bytes", "8192"]) == 0 + assert main(["find", "cache per-step masks ran out of device memory", *session_args]) == 0 result = json.loads(capsys.readouterr().out) - assert result["context"]["contexts"] + assert result["items"] and not any("content" in row for row in result["items"]) assert result["external"]["state"] == "not_enabled" and result["external"]["items"] == [] before = {path: path.read_bytes() for path in root.rglob("*.json")} @@ -1413,6 +1478,12 @@ def legacy_plan(root, plan): records = dashboard_snapshot(root)["data"]["managed_retrievals"] assert records[0]["external"]["state"] == "not_enabled" assert before == {path: path.read_bytes() for path in root.rglob("*.json")} + # A pinned Ascend grant cannot answer an explicitly CUDA-scoped Find. + assert main(["find", "implementation option", *session_args, "--backend", "cuda"]) == 0 + scoped = json.loads(capsys.readouterr().out) + assert "external" not in scoped + saved = json.loads((root / scoped["reference"]["path"]).read_bytes()) + assert saved["request"]["backend"] == "cuda" def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executor() -> None: @@ -1426,6 +1497,8 @@ def test_runtime_identity_covers_migrated_process_domain_and_not_removed_executo # #412 R3: the protocol child entry runs every task protocol operation. assert "harness/protocol_child.py" in identity assert "apps/workflows/campaign.py" in identity + assert "apps/workflows/session_knowledge.py" in identity + assert "apps/workflows/knowledge.py" in identity assert "knowledge/knowledge_find.py" in identity assert "knowledge/ranking_policy.py" in identity assert "apps/campaign.py" not in identity diff --git a/tests/apps/test_optimization_story.py b/tests/apps/test_optimization_story.py index 01a00c50c..48682a7a5 100644 --- a/tests/apps/test_optimization_story.py +++ b/tests/apps/test_optimization_story.py @@ -75,7 +75,7 @@ def campaign(tmp_path): _, digest = capture_context(tmp_path, context_id="r1", reader=FakeReader([ context("package:graphs", "Capture repeated decode launches.\n"), context("package:kv", "Tune the KV block size.\n")]), - relevance="decode launch", context_bytes=4096) + ids=["package:graphs", "package:kv"], relevance="decode launch", context_bytes=4096) make_run(tmp_path, "run-a", 4.0) make_run(tmp_path, "run-b", 3.0, quality="failed") record_candidate(tmp_path, candidate_id="a", run_id="run-a", round_number=1, title="A") @@ -151,7 +151,8 @@ def test_capture_keeps_exact_context_and_detects_tampering(tmp_path): def test_capture_matches_real_collect_output(tmp_path): create_campaign(tmp_path, "camp") reader = KnowledgeReader() - options = {"relevance": "kv cache block size", "context_bytes": 40000, "limit": 2} + options = {"ids": ["package:inferrsi.common.skills.cgroup_resource_controls"], + "relevance": "cpu quota", "context_bytes": 40000, "limit": 2} direct = reader.collect(**options, relevance_method=FIND_RELEVANCE) path, _ = capture_context(tmp_path, context_id="real", reader=reader, **options) document, state = verify_capture(path.read_bytes()) @@ -159,8 +160,8 @@ def test_capture_matches_real_collect_output(tmp_path): assert state == "verified" assert document["contexts"], "the installed library should supply a context" assert document["request"]["sources"] == direct["retrieval"]["request"]["sources"] - assert document["request"]["sources"] == ["package", "checkout"] - assert document["retrieval"]["calls"] == ["campaign capture-context", "collect", "find"] + assert document["request"]["sources"] == ["package"] + assert document["retrieval"]["calls"] == ["campaign capture-context", "collect"] assert document["selection"] == direct["selection"] assert [(item["ref"], item["revision"]) for item in document["items"]] == [ (item["ref"], item["revision"]) for item in direct["items"] @@ -200,8 +201,7 @@ def capture(context_id, pin): def test_capture_packaged_skills_does_not_repeat_bundle_manifest(tmp_path): create_campaign(tmp_path, "camp", noise=1.5) reader = KnowledgeReader() - options = {"relevance": "performance kernel optimization", "limit": 40, - "context_bytes": 65536, "kind": "knowledge"} + options = {"limit": 40, "context_bytes": 65536, "kind": "knowledge"} expected = reader.collect(**options) path, _ = capture_context(tmp_path, context_id="many-skills", reader=reader, **options) document, state = verify_capture(path.read_bytes()) @@ -539,8 +539,8 @@ def test_cli_capture_log_and_dashboard_escape_untrusted_text(tmp_path, capsys): def test_cli_capture_context_reports_relative_path(tmp_path, capsys): create_campaign(tmp_path, "camp") assert main(["campaign", "capture-context", "--directory", str(tmp_path), "--id", "r1", - "--relevance", "kv cache block size", "--context-bytes", "40000", - "--limit", "2"]) == 0 + "--id-ref", "package:vllm_omni.common.diffusion.step_state_and_output_validation", + "--context-bytes", "40000"]) == 0 output = json.loads(capsys.readouterr().out) assert output["context"] == "knowledge/r1.json" assert str(tmp_path) not in json.dumps(output) @@ -727,8 +727,9 @@ def test_search_import_keeps_omitted_use_claim_without_counting_it(tmp_path): from inferrsi.apps.views.search_attribution import import_search create_campaign(tmp_path, "camp") - capture, digest = capture_context(tmp_path, context_id="r1", reader=KnowledgeReader(), - relevance="casebook Qwen B300 RoPE", limit=1, context_bytes=1) + from tests.fixtures.knowledge_retrieval import install_legacy_capture + + capture, digest = install_legacy_capture(tmp_path, "omitted", "r1") context = json.loads(capture.read_bytes()) ref = context["items"][0]["ref"] assert context["contexts"] == [] diff --git a/tests/apps/test_optimization_trace.py b/tests/apps/test_optimization_trace.py index f60eccb68..f8796792f 100644 --- a/tests/apps/test_optimization_trace.py +++ b/tests/apps/test_optimization_trace.py @@ -94,7 +94,7 @@ def test_cli_preserves_full_reviewed_context_and_escapes_script(tmp_path, capsys def test_assembled_context_round_trips_from_actual_knowledge_command(tmp_path, capsys): setup_campaign(tmp_path) context_path = tmp_path / "reviewed-context.md" - assert main(["context", "decode", "--repo-type", "vllm", "--backend", "cuda", + assert main(["context", "--repo-type", "vllm", "--backend", "cuda", "--output", str(context_path)]) == 0 exact_context = context_path.read_bytes().decode("utf-8") assert exact_context.startswith("# InferRSI knowledge context") diff --git a/tests/apps/test_project_explanation.py b/tests/apps/test_project_explanation.py index d3a46329c..5fed8597e 100644 --- a/tests/apps/test_project_explanation.py +++ b/tests/apps/test_project_explanation.py @@ -608,13 +608,14 @@ def test_strategy_knowledge_refs_and_mechanism_are_kept_together(project, capsys """#501/#523 round declarations and the bound mechanism coexist on one round and final.""" repo, _, _, root = project assert start(project, capsys, "--decision", "paired", "--require-explanation") == 0 - assert main(["campaign", "knowledge", "--directory", str(root), - "--query", "cache per-step masks ran out of device memory", - "--limit", "1", "--context-bytes", "8192"]) == 0 + assert main(["find", "cache per-step masks ran out of device memory", + "--session", str(root), "--limit", "1", "--json"]) == 0 + found = json.loads(capsys.readouterr().out) + assert main(found["items"][0]["read_args"]) == 0 delivered = json.loads(capsys.readouterr().out) context = delivered["reference"]["path"] # Both citation forms: the whole delivered context and one delivered item (#523). - refs = [context, f"{context}#{delivered['context']['contexts'][0]['ref']}"] + refs = [context, f"{context}#{delivered['ref']}"] declaration = tmp_path / "mechanism.json" declaration.write_text(json.dumps(FUSION), encoding="utf-8") (repo / "config.json").write_text(json.dumps(FUSED), encoding="utf-8") diff --git a/tests/apps/test_project_optimization.py b/tests/apps/test_project_optimization.py index f4f2887d9..69ce128d1 100644 --- a/tests/apps/test_project_optimization.py +++ b/tests/apps/test_project_optimization.py @@ -76,6 +76,35 @@ def submit(project, capsys, metric): return code, json.loads(capsys.readouterr().out) +def test_read_verified_receipt_for_an_earlier_round(project, capsys): + _, _, _, root = project + start(project, capsys) + _, first = submit(project, capsys, 12) + _, second = submit(project, capsys, 14) + assert first["completed_rounds"] == 1 and second["completed_rounds"] == 2 + state = (root / "state.json").read_bytes() + args = ["campaign", "status", "--session", str(root), "--round-receipt"] + assert main([*args, "1"]) == 0 + receipt = json.loads(capsys.readouterr().out) + observation = first["latest_observation"] + assert receipt == { + "session": str(root), "completed_rounds": 1, + "latest_observation": {key: observation[key] for key in ( + "path", "observation_sha256", + )}, + } + assert (root / "state.json").read_bytes() == state + for invalid in ("0", "3"): + with pytest.raises(SystemExit): + main([*args, invalid]) + assert "Select a completed round" in capsys.readouterr().err + + (root / observation["path"] / "observation.json").write_text("{}") + with pytest.raises(SystemExit): + main([*args, "1"]) + assert "Retained assessment record changed" in capsys.readouterr().err + + def test_ab_ba_round_uses_target_dependencies(project, tmp_path, capsys, monkeypatch): python = target_python(tmp_path, monkeypatch, optimization_session) for name in ("measure.py", "quality.py"): @@ -134,7 +163,7 @@ def test_project_lifecycle_never_imports_benchmark(project): """Reject any Benchmark import in a fresh process, including the CLI entry.""" repo, _, _, root = project script = """ -import importlib.abc, json, sys +import contextlib, importlib.abc, io, json, sys from pathlib import Path class NoBenchmark(importlib.abc.MetaPathFinder): def find_spec(self, fullname, path=None, target=None): @@ -149,7 +178,13 @@ def find_spec(self, fullname, path=None, target=None): assert main(config['start']) == 0 Path(config['repo'], 'config.json').write_text('{"metric":20}', encoding='utf-8') for command in config['commands']: - assert main(command) == 0 + if command[0] == 'find': + output = io.StringIO() + with contextlib.redirect_stdout(output): + assert main(command) == 0 + assert main(json.loads(output.getvalue())['items'][0]['read_args']) == 0 + else: + assert main(command) == 0 plan, state, summary = read_records(Path(config['root'])) assert not any(name.startswith('benchmark/') for name in plan['runtime_identity']) assert state['final']['assessment']['verdict'] == 'PASS' @@ -158,8 +193,7 @@ def find_spec(self, fullname, path=None, target=None): """ commands = [ diagnosis_args(root, "campaign"), - ["campaign", "knowledge", "--directory", str(root), "--query", "cgroupv2", - "--context-bytes", "2048"], + ["find", "cgroupv2", "--session", str(root), "--limit", "1", "--json"], ["campaign", "round", "--directory", str(root), "--candidate", str(repo), "--hypothesis", "Synthetic configuration improvement"], ["campaign", "recover", "--directory", str(root)], @@ -310,7 +344,7 @@ def test_fixed_rounds_and_frozen_protocol_are_not_bypassed(project, capsys): @pytest.mark.parametrize("cannbot", [False, True]) -def test_project_knowledge_uses_find_and_records_budget_omission( +def test_project_find_returns_hits_and_reads_only_the_selected_body( project, capsys, monkeypatch, cannbot, ): from inferrsi.apps.integrations.cannbot import project as channel @@ -325,22 +359,35 @@ def unavailable(*args, **kwargs): start(project, capsys, extra=extra) root = project[3] assert main([ - "campaign", "knowledge", "--directory", str(root), - "--query", "cache per-step masks ran out of device memory", - "--limit", "1", "--context-bytes", "1", + "find", "cache per-step masks ran out of device memory", "--session", str(root), + "--limit", "1", "--json", ]) == 0 answer = json.loads(capsys.readouterr().out) if cannbot: assert answer["external"]["state"] == "not_enabled" else: assert "external" not in answer - capture = answer["context"] - assert capture["selection"]["method"] == "find-lexical-v1" - item, = capture["items"] - assert item["ref"] == "checkout:case.qwen-ascend-rejected-directions" - omission, = capture["context_omissions"] - assert (omission["ref"], omission["reason"]) == (item["ref"], "context_limit") - assert capture["contexts"] == [] + item, = answer["items"] + assert item["id"] == "case.qwen-ascend-rejected-directions" and "content" not in item + query, = dashboard_snapshot(root)["data"]["managed_retrievals"] + assert query["items"][0]["reads"] == [] and not query["items"][0]["delivered"] + assert main(item["read_args"]) == 0 + opened = json.loads(capsys.readouterr().out) + assert opened["ref"] == "checkout:case.qwen-ascend-rejected-directions" + capture = json.loads((root / opened["reference"]["path"]).read_bytes()) + context, = capture["contexts"] + body, = context["resources"] + assert body["content"] == opened["content"] + updated, = dashboard_snapshot(root)["data"]["managed_retrievals"] + assert updated["items"][0]["delivered"] and updated["items"][0]["reads"] == [ + {"path": opened["reference"]["path"], "resource": opened["content_resource"]} + ] + assert main([*item["read_args"], "--resource", "case.json"]) == 0 + extra = json.loads(capsys.readouterr().out) + receipt = json.loads((root / extra["reference"]["path"]).read_bytes()) + attachment, = receipt["contexts"][0]["resources"] + assert attachment["path"] == "case.json" and attachment["content"] == extra["content"] + assert extra["revision"] == opened["revision"] and receipt["context_budget"] is None def test_cannbot_timeout_keeps_local_ranking_and_final_budget(project, capsys, monkeypatch): @@ -364,8 +411,7 @@ def timeout_worker(*args, timeout, root, **kwargs): def search(session): assert main([ - "campaign", "knowledge", "--directory", str(session), "--query", query, - "--limit", "2", "--context-bytes", "8192", + "find", query, "--session", str(session), "--limit", "2", "--json", ]) == 0 return json.loads(capsys.readouterr().out) @@ -387,12 +433,13 @@ def search(session): assert 0 < timeout <= 6 - _WORKER_CLEANUP_SECONDS assert json.loads(state_path.read_bytes())["deadline"] == deadline assert opted_in["external"]["state"] == "timeout" - assert [item["ref"] for item in opted_in["context"]["items"]] == [ - item["ref"] for item in local["context"]["items"] + assert [item["id"] for item in opted_in["items"]] == [ + item["id"] for item in local["items"] ] - capture = opted_in["reference"]["path"] - ref = opted_in["context"]["contexts"][0]["ref"] + assert main(opted_in["items"][0]["read_args"]) == 0 + opened = json.loads(capsys.readouterr().out) + capture, ref = opened["reference"]["path"], opened["ref"] (source / "config.json").write_text('{"metric": 20}', encoding="utf-8") assert main([ "campaign", "round", "--directory", str(root), "--candidate", str(source), @@ -401,7 +448,7 @@ def search(session): ]) == 0 capsys.readouterr() snapshot = dashboard_snapshot(root)["data"] - retrieval, = snapshot["managed_retrievals"] + retrieval, = [r for r in snapshot["managed_retrievals"] if r.get("external")] candidate, = snapshot["candidates"] assert retrieval["external"]["state"] == "timeout" assert [use["ref"] for use in candidate["knowledge_uses"]] == [ref] @@ -415,14 +462,13 @@ def test_project_knowledge_off_and_manual_record_writes_are_rejected(project, ca start(project, capsys, extra=("--knowledge", "off")) root = project[3] with pytest.raises(SystemExit): - main(["campaign", "knowledge", "--directory", str(root), - "--query", "fusion", "--context-bytes", "100"]) + main(["find", "fusion", "--session", str(root)]) with pytest.raises(SystemExit): main(["campaign", "record", "--directory", str(root), "--candidate", "untracked", "--run-id", "missing", "--round", "1", "--title", "Bypass managed writes"]) with pytest.raises(SystemExit): main(["campaign", "capture-context", "--directory", str(root), "--id", "bypass", - "--relevance", "fusion", "--context-bytes", "100"]) + "--id-ref", "package:inferrsi.common.skills.inference_benchmark_design"]) def test_declared_paths_cannot_escape_project(project, capsys): diff --git a/tests/apps/test_project_service_reuse.py b/tests/apps/test_project_service_reuse.py index 1c99f94fe..d060bd609 100644 --- a/tests/apps/test_project_service_reuse.py +++ b/tests/apps/test_project_service_reuse.py @@ -19,11 +19,26 @@ from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints +def read_first_hit(campaign, question): + args = ["find", question, "--session", str(campaign["root"]), "--limit", "1", "--json"] + assert main(args) == 0 + result = json.loads(campaign["capsys"].readouterr().out) + project_service.no_fingerprints(result) + search = json.loads((campaign["root"] / result["reference"]["path"]).read_bytes()) + assert search["selection"]["method"] == "find-lexical-v1" and search["contexts"] == [] + hit, = result["items"] + assert "content" not in hit + assert main(hit["read_args"]) == 0 + delivery = json.loads(campaign["capsys"].readouterr().out) + assert delivery["content"] + project_service.no_fingerprints(delivery) + return json.loads((campaign["root"] / delivery["reference"]["path"]).read_bytes()) + + def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): assert call(campaign, "start")["next_action"] == "campaign_baseline" - lookup = ("--query", "前缀缓存", "--context-bytes", "65536", "--limit", "1") with pytest.raises(SystemExit) as error: - call(campaign, "knowledge", *lookup) + read_first_hit(campaign, "前缀缓存") assert error.value.code == 2 assert "Record measured bottleneck evidence" in campaign["capsys"].readouterr().err evidence = tmp_path / "measurement.txt" @@ -31,10 +46,9 @@ def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): result = call(campaign, "diagnose", "--bottleneck", "Service operation", "--evidence", evidence) assert result["diagnosis"]["reference_epoch"] == 0 assert call(campaign, "status")["diagnosis"] == result["diagnosis"] - delivery = call(campaign, "knowledge", *lookup) - assert delivery["context"]["contexts"] - assert delivery["context"]["request"]["relevance_method"] == "find-lexical-v1" - binding = delivery["context"]["diagnosis_binding"] + delivery = read_first_hit(campaign, "前缀缓存") + assert delivery["contexts"] + binding = delivery["diagnosis_binding"] assert binding["diagnosis_id"] == result["diagnosis"]["id"] assert binding["reference_epoch"] == 0 assert binding["started_at"] >= result["diagnosis"]["recorded_at"] @@ -46,12 +60,12 @@ def test_diagnosis_gate_applies_to_service_knowledge(campaign, tmp_path): "--reason", "Changed test runtime") assert refreshed["next_action"] == "record_bottleneck_diagnosis" with pytest.raises(SystemExit) as error: - call(campaign, "knowledge", *lookup) + read_first_hit(campaign, "前缀缓存") assert error.value.code == 2 assert "Record measured bottleneck evidence" in campaign["capsys"].readouterr().err new = call(campaign, "diagnose", "--bottleneck", "Different operation", "--evidence", evidence) assert new["diagnosis"]["reference_epoch"] == 1 - recent = call(campaign, "knowledge", *lookup)["context"]["diagnosis_binding"] + recent = read_first_hit(campaign, "前缀缓存")["diagnosis_binding"] assert recent["diagnosis_id"] == new["diagnosis"]["id"] assert recent["reference_epoch"] == 1 @@ -224,24 +238,52 @@ def test_service_mode_cli_does_not_require_legacy_metric_arguments(campaign): def test_service_knowledge_uses_find_without_file_fingerprints(campaign): call(campaign, "start") diagnose(campaign) - response = call( - campaign, "knowledge", "--query", "前缀缓存", "--context-bytes", "65536", "--limit", "1" - ) - retained = response["context"] - assert retained["request"]["relevance_method"] == "find-lexical-v1" + retained = read_first_hit(campaign, "前缀缓存") context, = retained["contexts"] assert context["ref"].startswith("package:") - path = campaign["root"] / response["reference"]["path"] - assert json.loads(path.read_bytes()) == retained - project_service.no_fingerprints(response) + assert context["resources"][0]["content"] + assert context["revision"] == context["sources"][0]["commit"] + project_service.no_fingerprints(retained) + from inferrsi.apps.views.dashboard import dashboard_snapshot + + snapshot = dashboard_snapshot(campaign["root"]) + project_service.no_fingerprints(snapshot) + assert snapshot["data"]["evaluation_mode"] == "service_reuse" + + +def test_service_read_follows_a_link_at_the_search_revision(campaign): + from tests.apps.test_campaign_task_selection import BASELINE_CUE + + call(campaign, "start") + diagnose(campaign) + root = campaign["root"] + assert main(["find", BASELINE_CUE, "--backend", "cuda", "--session", str(root), + "--limit", "2"]) == 0 + found = json.loads(campaign["capsys"].readouterr().out) + hit = found["items"][0] + assert hit["material_ref"] == "package:inferrsi.common.skills.inference_benchmark_design" + assert main(hit["read_args"]) == 0 + primary = json.loads(campaign["capsys"].readouterr().out) + link = "references/benchmark-commands.md" + assert f"]({link})" in primary["content"] + assert main([*hit["read_args"], "--resource", link]) == 0 + opened = json.loads(campaign["capsys"].readouterr().out) + assert opened["revision"] == primary["revision"] == hit["revision"] + retained = json.loads((root / opened["reference"]["path"]).read_bytes()) + context, = retained["contexts"] + selected, = context["resources"] + assert selected["role"] == "reference" + assert selected["path"] == opened["content_resource"] and selected["path"].endswith(link) + assert selected["content"] == opened["content"] + assert context["content_bytes"] == len(opened["content"].encode()) > 0 + assert retained["request"]["search_ref"] == found["reference"]["path"] + project_service.no_fingerprints(retained) def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign): begin(campaign) - context = call( - campaign, "knowledge", "--query", "optimization", "--context-bytes", "65536", "--limit", "1" - ) - assert context["context"]["contexts"] + context = read_first_hit(campaign, "optimization") + assert context["contexts"] project_service.no_fingerprints(context) submit(campaign, version="selected", a=90) from inferrsi.apps.views.dashboard import ( diff --git a/tests/apps/test_retrieval_projection.py b/tests/apps/test_retrieval_projection.py index b89844c1d..0901e4bd3 100644 --- a/tests/apps/test_retrieval_projection.py +++ b/tests/apps/test_retrieval_projection.py @@ -25,54 +25,30 @@ def campaign(tmp_path): return tmp_path -@pytest.mark.parametrize("question", [{"query": "launch"}, {"relevance": "launch"}]) -def test_execution_scores_and_exact_budget_preserve_payloads(tmp_path, question): - with FIXTURE["reader"](tmp_path) as reader: - result = reader.collect(**question, context_bytes=54) - # Observations cannot eject a result from the budgeted item bytes. - bounded = reader.collect(**question, context_bytes=54, max_bytes=result["material_bytes"]) - fewer = reader.collect(**question, limit=2) - assert len(result["items"]) == 5 and len(result["contexts"]) == 2 - assert len(result["context_omissions"]) == 3 and result["context_bytes"] == 54 - observation = result["retrieval"] +def test_recorded_scores_and_exact_budget_preserve_historical_payloads(campaign): + capture = json.loads((campaign / "knowledge/collect.json").read_bytes()) + observation = capture["retrieval"] + assert len(capture["items"]) == 5 and len(capture["contexts"]) == 2 + assert len(capture["context_omissions"]) == 3 and capture["context_bytes_used"] == 54 assert observation["calls"] == ["collect", "find"] assert observation["selection"]["method"] == "find-lexical-v1" - assert observation["counts"]["matched"] == 5 - assert observation["assembly"] == "performed" - assert [m["ref"] for m in observation["items"]] == [m["ref"] for m in result["items"]] + assert observation["counts"]["matched"] == 5 and observation["assembly"] == "performed" + assert [m["ref"] for m in observation["items"]] == [m["ref"] for m in capture["items"]] for item in observation["items"]: assert item["score"] == sum(item["components"].values()) assert len({m["score"] for m in observation["items"]}) == 1 - assert [m["ref"] for m in observation["items"]] == sorted(m["ref"] for m in result["items"]) - for field in ("items", "contexts", "context_omissions", "context_bytes", "material_bytes"): - assert result[field] == bounded[field] - assert fewer["retrieval"]["counts"]["excluded"]["item_limit"] == 3 - assert fewer["retrieval"]["assembly"] == "not_requested" -def test_catalog_observation_does_not_mutate_records_or_return_order(tmp_path, monkeypatch): +def test_catalog_inventory_preserves_records_and_return_order(tmp_path, monkeypatch): with FIXTURE["reader"](tmp_path) as reader: records = list(reader.records().values()) original = copy.deepcopy(records) monkeypatch.setattr("inferrsi.knowledge.catalog.knowledge_records", lambda: records) - observations = {} - for query in ("guidance missing", "missing", "guidance guidance", ""): - result = search_knowledge(query, limit=2, explain=True) - assert result["items"] == search_knowledge(query, limit=2) - observations[query] = result["retrieval"] - excluded = search_knowledge("guidance", repo="other", explain=True) - + result = search_knowledge(limit=2, explain=True) + assert result["items"] == search_knowledge(limit=2) + inventory = result["retrieval"] + excluded = search_knowledge(repo="other", explain=True) assert records == original - ranked = observations["guidance missing"] - assert ranked["calls"] == ["knowledge search", "find"] - assert ranked["selection"]["method"] == "find-lexical-v1" - assert ranked["counts"]["matched"] == 5 # "guidance" is only in the Skill bodies. - assert ranked["items"] == observations["guidance guidance"]["items"] - for item in ranked["items"]: - assert item["score"] == item["components"]["guidance"] - assert observations["missing"]["items"] == [] - inventory = observations[""] - assert inventory["calls"] == ["knowledge search"] assert inventory["selection"]["state"] == "not_requested" assert inventory["selection"]["method"] is None assert all("score" not in item for item in inventory["items"]) diff --git a/tests/apps/test_round_citations.py b/tests/apps/test_round_citations.py index 6d80e980f..637ea0f3f 100644 --- a/tests/apps/test_round_citations.py +++ b/tests/apps/test_round_citations.py @@ -1,7 +1,11 @@ """Round reasons prove use only through a delivered passage and authored choice.""" import json +import shlex import sys +from copy import deepcopy +from pathlib import Path +from types import SimpleNamespace import pytest @@ -14,11 +18,344 @@ from tests.apps.test_optimization_story import log_document from tests.apps.test_project_optimization import project as project from tests.apps.test_project_optimization import start +from tests.fixtures.knowledge_retrieval import install_legacy_capture QUOTE = "NPU OOM." REASON = f"Score each row immediately to avoid retaining all masks [use {REF} | {QUOTE}]." +def _historical_knowledge(root, command, query, *, limit=1, joint=False): + """Render the old one-step tool return from its persisted capture format.""" + argv = [sys.executable, "-m", "inferrsi", *command, "knowledge", "--session", str(root), + "--query", query, "--context-bytes", "8192", "--limit", str(limit)] + number = len(list((root / "knowledge").glob("legacy-*.json"))) + 1 + sample = {QUERY: "managed-query", "zzunmatchedcaptureqv": "managed-empty"}[query] + path, digest = install_legacy_capture(root, sample, f"legacy-{number}") + ref = {"path": path.relative_to(root).as_posix(), "sha256": digest, "kind": "delivered_context"} + output = {"reference": ref, "context": json.loads(path.read_bytes())} + if joint: + output["external"] = {"state": "not_enabled", "channel": "cannbot-knowledge", + "count": 0, "items": []} + return argv, json.dumps(output, ensure_ascii=False, indent=2) + "\n" + + +def _async_round(cwd, command, output, *, pid="17", code=0): + from tests.apps.test_codex_search_delivery import _call, _command, _exec_result + + call = _call(cwd, command, "round", emit="JSON.stringify(r)") + started = _exec_result("round", "") + block = started["payload"]["output"][1] + data = json.loads(block["text"]) + del data["exit_code"] + block["text"] = json.dumps({**data, "session_id": 17}) + finished = _command(cwd, command, output, "round", exit_code=code) + finished["payload"]["item"].update(process_id=pid, status="failed" if code else "completed", + source="unified_exec_startup") + return [call, started, finished] + + +@pytest.mark.parametrize(("body", "include_ids"), [ + ("unopened", False), ("full", False), ("full", True), ("clipped", True), +]) +def test_scoped_find_read_and_adoption_are_independent( + project, tmp_path, capsys, body, include_ids, +): + repo, _, _, root = project + start(project, capsys) + argv, found = _cli(tmp_path, "find", QUERY, "--kinds", "case", "--limit", "1", + "--session", str(root)) + search = json.loads(found) + hit, = search["items"] + assert hit["material_ref"] == REF + ids = [Path(search["reference"]["path"]).stem] + rows = _operation(tmp_path, argv, found, "find") + cite = [] + if body != "unopened": + argv, opened = _cli(tmp_path, *hit["read_args"]) + reference = json.loads(opened)["reference"]["path"] + ids.append(Path(reference).stem) + rows.extend(_operation(tmp_path, argv, opened, "read", + received=True if body == "full" else "Warning: truncated output\n")) + cite = ["--knowledge-ref", f"{reference}#{REF}"] + argv, outcome = _cli(tmp_path, "campaign", "round", "--session", str(root), "--candidate", + str(repo), "--hypothesis", REASON, *cite) + rows.extend(_operation(tmp_path, argv, outcome, "round")) + _, archive = _import(tmp_path, rows, context_ids=ids if include_ids else ()) + observed = archive["observed"] + assert (observed["searches"], observed["hits"], observed["used"]) == (1, 1, int(body == "full")) + find_event, = [event for event in archive["events"] if event["action"] == "search"] + policy = {k: search["ranking_policy"][k] for k in ("id", "version", "config_sha256")} + assert find_event["request"]["ranking_policy"] == policy + assert find_event["request"]["kinds"] == "case" + material = archive["materials"][REF] + assert archive["coverage"] == ("partial" if body == "clipped" else "complete") + if body == "full": + read_event, = [event for event in archive["events"] if event["action"] == "read"] + assert read_event["request"]["ranking_policy"] == policy + assert read_event["request"]["search_ref"] == search["reference"]["path"] + assert material["delivery_state"] == "visible" + assert QUOTE in material["evidence"][0]["passage_text"] + else: + assert material["use"] == "unknown" + + +@pytest.mark.parametrize("include_ids", [False, True]) +def test_cited_claims_share_a_json_line_with_source_urls(project, tmp_path, capsys, include_ids): + repo, _, _, root = project + start(project, capsys) + ref = "package:triton.common.kernel.bandwidth_fusion_resource_limits" + argv, found = _cli(tmp_path, "find", "bandwidth fusion resource limits softmax", + "--repo-type", "triton", "--session", str(root)) + result = json.loads(found) + hit = next(item for item in result["items"] if item["material_ref"] == ref) + rows = _operation(tmp_path, argv, found, "find") + read_argv, opened = _cli(tmp_path, *hit["read_args"]) + read = json.loads(opened) + body = read["content"] + assert "\n" not in body and "https://" in body + claims = json.loads(body)["claims"] + full = claims[0]["description"] + quotes = [full[:67], full] + hypotheses = [f"Apply the cited guidance [use {ref} | {quote}]." for quote in quotes] + rows.extend(_operation(tmp_path, read_argv, opened, "read")) + args, outcome = _cli(tmp_path, "campaign", "round", "--session", str(root), + "--candidate", str(repo), "--hypothesis", "\n".join(hypotheses), + "--knowledge-ref", read["reference"]["path"]) + rows.extend(_operation(tmp_path, args, outcome, "round")) + ids = [Path(row["reference"]["path"]).stem for row in (result, read)] if include_ids else [] + _, archive = _import(tmp_path, rows, context_ids=ids) + assert archive["observed"]["used"] == 1 and archive["declarations"] == [] + evidence = archive["materials"][ref]["evidence"] + assert len(evidence) == 2 + for item in evidence: + assert item["passage_text"] in quotes and item["passage_truncated"] + assert item["passage_path"] == "record.json" and item["passage_line"] == 1 + assert "https://" not in item["passage_text"] + + +def test_citation_cannot_extract_an_identifier_from_a_redacted_url_or_secret(): + from inferrsi.apps.views.capture_delivery import citation_excerpts + + text = "Use a stable reduction. See https://example.invalid/private-file and api_key=hidden." + assert citation_excerpts(text, ["stable reduction", "private-file", "hidden"]) == [ + "stable reduction", + ] + from inferrsi.harness.records.evidence import sanitized_text + + text = json.dumps({"description": "Keep this excerpt.", "api_key": "fixture-opaque", + "credentials": {"value": "fixture-nested"}, "token_budget": 1234}) + assert citation_excerpts(text, ["Keep this excerpt.", "fixture-opaque", "fixture-nested"]) == [ + "Keep this excerpt.", + ] + public = json.loads(sanitized_text(text, "", limit=None)) + assert public == {"description": "Keep this excerpt.", "api_key": "[redacted]", + "credentials": "[redacted]", "token_budget": 1234} + + +def test_a_source_url_leaves_the_adjacent_json_summary_citable(): + from inferrsi.apps.views.capture_delivery import citation_excerpts + from inferrsi.knowledge.knowledge_operations import KnowledgeReader + + bundle = KnowledgeReader().read("package:vllm.common.llm.bounded_serving_measurement") + text = bundle.content["record.json"].decode("utf-8") + summary = json.loads(text)["summary"] + assert citation_excerpts(text, [summary]) == [summary] + text = ('{"source":"https://example.invalid/private-file",' + '"description":"Use a stable reduction."}') + assert citation_excerpts(text, ["private-file", "Use a stable reduction."]) == [ + "Use a stable reduction.", + ] + + +def test_round_receipt_confirms_the_original_submission_position(project, tmp_path, capsys): + from inferrsi.apps.views.search_attribution import import_search + from tests.apps.test_codex_knowledge_search import LIBRARY + from tests.apps.test_codex_search_delivery import _meta, _rollout + from tests.apps.test_search_capture_delivery import _review + + repo, _, _, root = project + start(project, capsys) + _, found = _cli(tmp_path, "find", QUERY, "--kinds", "case", "--limit", "1", + "--session", str(root)) + read_argv, opened = _cli(tmp_path, *json.loads(found)["items"][0]["read_args"]) + read = _operation(tmp_path, read_argv, opened, "read") + source = json.loads(opened)["reference"]["path"] + argv, outcome = _cli(tmp_path, "campaign", "round", "--session", str(root), + "--candidate", str(repo), "--hypothesis", REASON, + "--knowledge-ref", f"{source}#{REF}") + status_argv, receipt = _cli(tmp_path, "campaign", "status", "--session", str(root), + "--round-receipt", "1") + status = _operation(tmp_path, status_argv, receipt, "status") + clipped = outcome[:65] + "\n... command output truncated for persistence ...\n" + outcome[-65:] + + def submit(command, pid="17"): + return _async_round(tmp_path, command, clipped, pid=pid) + + trace = tmp_path / "round.jsonl" + review = _review(tmp_path / "review.json") + + def archive(rows): + _rollout(trace, _meta(tmp_path), *rows) + result = import_search(root, number=1, trace=trace, lines=(2, len(rows) + 1), + knowledge_root=LIBRARY, archive_review=review, complete=True) + record = json.loads(result.read_bytes()) + # Each variant represents an independent trace for this test campaign. + result.unlink() + (root / "search/round-1.json").unlink() + return record + + command = shlex.join(argv) + submitted = submit(command) + confirmed = archive([*read, *submitted, *status]) + assert confirmed["observed"]["used"] == 1 + evidence, = confirmed["materials"][REF]["evidence"] + assert evidence["decision_line"] == 5 and evidence["event_id"] == "file-3" + assert evidence["decision_quote"] == REASON and QUOTE in evidence["passage_text"] + + # The host may emit a cleanup's plain output and the round's launch object + # in one code-mode call. The exact native process ID must still bind it. + from tests.apps.test_codex_search_delivery import _command + + batched = deepcopy(submitted) + options = json.dumps({"cmd": command, "workdir": str(tmp_path)}) + cleanup_options = json.dumps({"cmd": "true", "workdir": str(tmp_path)}) + batched[0]["payload"]["input"] = ( + f'text((await tools.exec_command({cleanup_options})).output);\n' + f'text((await tools.exec_command({options})));' + ) + batched[1]["payload"]["output"].insert(1, {"type": "input_text", "text": ""}) + cleanup = _command(tmp_path, "true", "", "cleanup") + batch_rows = [batched[0], cleanup, *batched[1:]] + confirmed = archive([*read, *batch_rows, *status]) + evidence, = confirmed["materials"][REF]["evidence"] + assert confirmed["observed"]["used"] == 1 and evidence["decision_line"] == 5 + wrong_process = deepcopy(batch_rows) + wrong_process[-1]["payload"]["item"]["process_id"] = "18" + duplicate_launch = deepcopy(batch_rows) + blocks = duplicate_launch[2]["payload"]["output"] + blocks.append(dict(blocks[-1])) + dynamic_command = deepcopy(batch_rows) + dynamic_command[0]["payload"]["input"] = batched[0]["payload"]["input"].replace( + json.dumps(command), "command" + ) + for invalid in (wrong_process, duplicate_launch, dynamic_command): + assert archive([*read, *invalid, *status])["observed"]["used"] == 0 + + full = json.loads(outcome) + summary = {"completed_rounds": 1, "session": full["session"]} + for shown, expected in ((summary, 1), ({**summary, "session": "another"}, 0), + ({**summary, "invented": None}, 0)): + returned = _operation(tmp_path, argv, outcome, "round", received=json.dumps(shown)) + assert archive([*read, *returned])["observed"]["used"] == expected + + changed = json.loads(receipt) + changed["latest_observation"]["observation_sha256"] = "0" * 64 + altered = _operation(tmp_path, status_argv, json.dumps(changed), "wrong-digest") + early = [*submitted[:2], *status, submitted[2]] + wrong_ref = submit(shlex.join([*argv[:-1], source + "#wrong"])) + wrong_round = _operation(tmp_path, [*status_argv[:-1], "2"], receipt, "wrong-round") + duplicate = deepcopy(submitted) + duplicate[0]["payload"]["call_id"] = duplicate[1]["payload"]["call_id"] = "second" + duplicate[2]["payload"]["item"]["id"] = "second" + for rows in ( + [*read, *submitted], [*read, *status], [*submitted, *read, *status], + [*read, *early], [*read, *submitted, *altered], + [*read, *submitted, *status[:-1]], + [*read, *submitted, *_operation(tmp_path, status_argv, receipt, "short-status", + received="Warning: truncated output\n")], + [*read, *submitted, *wrong_round], + [*read, *submit(command, pid="18"), *status], + [*read, submitted[0], submitted[2], *status], + [*read, *wrong_ref, *status], [*read, *submit(command + "; printf extra"), *status], + [*read, *submitted, *duplicate, *status], + ): + assert archive(rows)["observed"]["used"] == 0 + + # Once two verified rounds share all these authored fields, a later + # receipt for round 1 cannot disambiguate this clipped submission. + _cli(tmp_path, *argv[argv.index("campaign"):]) + assert archive([*read, *submitted, *status])["observed"]["used"] == 0 + + +def test_blocked_round_receipt_verifies_the_failed_candidate_reason(project, tmp_path, capsys): + from inferrsi.apps.views.round_citations import retained_round_citations + from tests.apps.test_codex_search_delivery import _meta, _rollout + + repo, protocol, _, root = project + (protocol / "quality.py").write_text("raise SystemExit(2)\n", encoding="utf-8") + start(project, capsys) + _, found = _cli(tmp_path, "find", QUERY, "--kinds", "case", "--limit", "1", + "--session", str(root)) + read_argv, opened = _cli(tmp_path, *json.loads(found)["items"][0]["read_args"]) + read = _operation(tmp_path, read_argv, opened, "read") + source = json.loads(opened)["reference"]["path"] + args = ["campaign", "round", "--session", str(root), "--candidate", str(repo), + "--hypothesis", REASON, "--knowledge-ref", source] + assert main(args) == 2 + result = capsys.readouterr().out + outcome = json.loads(result) + assert outcome["state"] == "blocked" and outcome["best"]["kind"] == "baseline" + observed = outcome["latest_observation"] + assert observed["assessment"]["status"] == "infrastructure_failure" + observation = root / observed["path"] / "observation.json" + frozen = observation.read_bytes() + + cmd = shlex.join(["env", "-u", "DEVICE", "OMP_NUM_THREADS=1", sys.executable, + "-m", "inferrsi", *args]) + status_args, receipt = _cli(tmp_path, "campaign", "status", "--session", str(root), + "--round-receipt", "1") + status = _operation(tmp_path, status_args, receipt, "status") + submitted = _async_round(tmp_path, cmd, result, code=2) + _, archive = _import(tmp_path, [*read, *submitted, *status], context_ids=[Path(source).stem]) + assert archive["observed"]["used"] == 1 + evidence, = archive["materials"][REF]["evidence"] + assert evidence["decision_line"] == 5 and evidence["decision_quote"] == REASON + assert QUOTE in evidence["passage_text"] and observation.read_bytes() == frozen + + campaign = json.loads((root / "campaign.json").read_bytes()) + trace = tmp_path / "submission.jsonl" + altered = deepcopy(outcome) + altered["latest_observation"]["observation_sha256"] = "0" * 64 + wrong_candidate = deepcopy(outcome) + wrong_candidate["latest_observation"]["candidate_sha256"] = "0" * 64 + for rows in ( + submitted, status, + [*_async_round(tmp_path, cmd, "Invalid argument\n", code=2), *status], + [*_async_round(tmp_path, cmd, json.dumps(altered), code=2), *status], + [*_async_round(tmp_path, cmd, json.dumps(wrong_candidate), code=2), *status], + [*_async_round(tmp_path, cmd, result, code=1), *status], + [*_async_round(tmp_path, cmd, result, pid="18", code=2), *status], + ): + _rollout(trace, _meta(tmp_path), *rows) + _, position = retained_round_citations(root, campaign, 1, trace, (2, len(rows) + 1)) + assert position is None + + +@pytest.mark.parametrize("include_id", [False, True]) +def test_selecting_a_scoped_find_receipt_keeps_visible_external_hits( + project, tmp_path, capsys, monkeypatch, include_id, +): + from inferrsi.apps.workflows import session_knowledge + + root = project[-1] + start(project, capsys, extra=("--cannbot-platform", "a3")) + remote = {"state": "ok", "revision": "a" * 40, "count": 1, + "items": [{"locator": "ops/card", "card_sha256": "b" * 64, "score": 1.0}]} + monkeypatch.setattr(session_knowledge, "round_provider", + lambda plan: SimpleNamespace(search=lambda *a, **kw: remote)) + args = ["find", "zzexternalarchiveonlyqv", "--session", str(root)] + assert main(args) == 0 + output = capsys.readouterr().out + result = json.loads(output) + assert result["items"] == [] and result["external"]["count"] == 1 + ids = [Path(result["reference"]["path"]).stem] if include_id else [] + rows = _operation(tmp_path, [sys.executable, "-m", "inferrsi", *args], output, "find") + for record in _import(tmp_path, rows, context_ids=ids): + assert record["coverage"] == "complete" + assert record["observed"] == {"searches": 1, "hits": 1, "unique_hits": 1, "used": 0} + assert set(record["materials"]) == {"cannbot-knowledge:ops/card"} + + @pytest.mark.parametrize("case", [ "read", "managed_context", "late_body", "clipped", "wrong_quote", "long_line", "grouped_context", "joint_context", "joint_context_clipped", @@ -32,9 +369,7 @@ def test_managed_round_resolves_citations_from_original_tool_outputs( context_ids = [] ref, quote, reason = REF, QUOTE, REASON if joint or case in ("managed_context", "grouped_context"): - read_args = ["campaign", "knowledge", "--directory", str(root), "--query", QUERY, - "--context-bytes", "8192", "--limit", "1"] - read_argv, read_output = _cli(tmp_path, *read_args) + read_argv, read_output = _historical_knowledge(root, ["campaign"], QUERY, joint=joint) answer = json.loads(read_output) context_ids = [answer["context"]["context_id"]] if joint: @@ -59,8 +394,7 @@ def test_managed_round_resolves_citations_from_original_tool_outputs( received = read_output.split('\n "external":', 1)[0] + '\n "external": {\n' read = _operation(tmp_path, read_argv, read_output, "read", received=received) if case == "grouped_context": - _, second = _cli(tmp_path, "campaign", "knowledge", "--directory", str(root), - "--query", "zzunmatchedcaptureqv", "--context-bytes", "8192") + _, second = _historical_knowledge(root, ["campaign"], "zzunmatchedcaptureqv") context_ids.append(json.loads(second)["context"]["context_id"]) read[-1]["payload"]["output"] += "\n" + second @@ -160,16 +494,14 @@ def test_managed_search_coverage_and_delivery_without_a_citation( if case == "no_query": argv, output = _cli(tmp_path, *command, "status", "--session", str(root)) else: - argv, output = _cli(tmp_path, *command, "knowledge", "--session", str(root), - "--query", QUERY, "--context-bytes", "8192", "--limit", "1") + argv, output = _historical_knowledge(root, command, QUERY) if case != "omitted": ids.append(json.loads(output)["context"]["context_id"]) rows = _operation(tmp_path, argv, output, "first", received=( "Warning: truncated output\n" + output[:250] if case == "unverified" else True )) if case == "second_omitted": - argv, output = _cli(tmp_path, *command, "knowledge", "--session", str(root), - "--query", "zzunmatchedcaptureqv", "--context-bytes", "8192") + argv, output = _historical_knowledge(root, command, "zzunmatchedcaptureqv") rows.extend(_operation(tmp_path, argv, output, "second")) verified = case in ("uncited", "second_omitted") complete = case in ("no_query", "uncited") diff --git a/tests/apps/test_round_decisions_browser.py b/tests/apps/test_round_decisions_browser.py index d4dd15029..acb0a282c 100644 --- a/tests/apps/test_round_decisions_browser.py +++ b/tests/apps/test_round_decisions_browser.py @@ -354,6 +354,14 @@ def test_managed_round_knowledge_and_measured_score(cpu_browser, tmp_path): {"round": 1, "query": "tile sizes", "items": [ {"ref": "package:tile", "title": "Tiling", "delivered": True}, ], "external": external}, + {"round": 1, "query": "workspace", "items": [ + {"ref": "package:worked", "reads": [ + {"resource": "SKILL.md", "path": "knowledge/read-body.json"}, + {"resource": "example.txt", "path": "knowledge/read-extra.json", + "omission": "context_limit"}, + ]}, + {"ref": "package:another", "reads": []}, + ]}, {"round": None, "submitted_rounds": [2], "query": "earlier snapshot", "items": []}, {"round": 2, "query": "empty query", "items": [], "external": {**external, "count": 0, "items": [], "reads": []}}, @@ -379,6 +387,9 @@ def test_managed_round_knowledge_and_measured_score(cpu_browser, tmp_path): analysis, retrieval, alternatives, choice, result = ( root.locator(f'[data-rd-stage="{i}"]') for i in range(1, 6)) expect(alternatives).to_contain_text("Submitted option · Reuse a table") + expect(retrieval).to_contain_text("Read resource · SKILL.md") + expect(retrieval).to_contain_text("Read omitted · example.txt · context_limit") + expect(retrieval).to_contain_text("No read recorded") expect(alternatives).to_contain_text("Cache across requests") expect(alternatives).not_to_contain_text(unused) expect(choice).to_contain_text("Submitted strategy · Share across layers") diff --git a/tests/apps/test_search_archive.py b/tests/apps/test_search_archive.py index eac2d82ed..97aee7f45 100644 --- a/tests/apps/test_search_archive.py +++ b/tests/apps/test_search_archive.py @@ -475,7 +475,8 @@ def _make_capture(tmp_path): campaign = tmp_path / "campaign" create_campaign(campaign, "example") capture, _ = capture_context(campaign, context_id="r1", reader=_Reader("Manual line.\n"), - relevance="manual", context_bytes=4096) + ids=["package:manual"], relevance="manual", + relevance_method=FIND_RELEVANCE, context_bytes=4096) document = json.loads(capture.read_text(encoding="utf-8")) output = assemble_context_text(document["contexts"]) return campaign, output @@ -485,7 +486,8 @@ def test_indexer_passage_lines_do_not_split_form_feeds(tmp_path): campaign = tmp_path / "campaign" create_campaign(campaign, "example") capture, _ = capture_context(campaign, context_id="r1", reader=_Reader("a\fb\nc\n"), - relevance="manual", context_bytes=4096) + ids=["package:manual"], relevance="manual", + relevance_method=FIND_RELEVANCE, context_bytes=4096) document = json.loads(capture.read_text()) trace = tmp_path / "rollout.jsonl" _capture_trace(trace, assemble_context_text(document["contexts"]), "I will use c.") diff --git a/tests/apps/test_search_attribution.py b/tests/apps/test_search_attribution.py index 8669db1ea..29d60eeaf 100644 --- a/tests/apps/test_search_attribution.py +++ b/tests/apps/test_search_attribution.py @@ -276,9 +276,9 @@ def test_logged_use_of_an_unreturned_capture_of_a_hit_is_not_search_adoption(tmp digests = {} with FIXTURE["reader"](tmp_path / "corpus") as source: ref = "package:" + next(iter(source.records())) - for key, options in (("search", {"relevance": "launch"}), ("explicit", {"ids": [ref]})): - _, digests[key] = capture_context(tmp_path, context_id=key, reader=source, - context_bytes=4096, **options) + _, digests["search"] = FIXTURE["install_legacy_capture"](tmp_path, "search", "search") + _, digests["explicit"] = capture_context(tmp_path, context_id="explicit", reader=source, + context_bytes=4096, ids=[ref]) log = {"schema_version": 2, "reviewed_by_caller": True, "campaign_id": "example", "goal": {"statement": "Example", "metric": "latency"}, "knowledge": [{"context_id": key, "sha256": digest, "stage": "knowledge", diff --git a/tests/apps/test_search_capture_delivery.py b/tests/apps/test_search_capture_delivery.py index 4a0bb77f7..c0ebf4d16 100644 --- a/tests/apps/test_search_capture_delivery.py +++ b/tests/apps/test_search_capture_delivery.py @@ -1,4 +1,6 @@ import json +import shutil +from pathlib import Path import pytest @@ -12,6 +14,7 @@ from inferrsi.knowledge.catalog import search_knowledge from inferrsi.knowledge.context_projection import assemble_context_text from inferrsi.knowledge.knowledge_operations import KnowledgeReader +from tests.fixtures.knowledge_retrieval import install_legacy_capture def _review(path, **fields): @@ -64,7 +67,7 @@ def test_round_counts_search_but_retains_exact_reads_and_inventory(tmp_path): capture_context(root, context_id="pin", reader=reader, ids=[record], revisions={record: revision}) save_retrieval(root, context_id="catalog", result=search_knowledge(limit=1, explain=True)) - capture_context(root, context_id="query", reader=reader, query="cgroupv2", limit=1) + install_legacy_capture(root, "manual-query", "query") archive = import_search( root, number=1, context_ids=["pin", "catalog", "query"], complete=True, @@ -98,9 +101,7 @@ def test_legacy_capture_remains_search_when_ranking_is_unknown_or_unrequested(ob def test_archive_accepts_complete_managed_json_at_the_matching_capture(tmp_path): root = tmp_path / "campaign" create_campaign(root, "managed-return") - path, digest = capture_context(root, context_id="r1", reader=KnowledgeReader(), - query="NPU OOM after caching per-step masks", - kind="case", limit=1) + path, digest = install_legacy_capture(root, "case-return", "r1") capture = json.loads(path.read_bytes()) context, = capture["contexts"] resource = next(item for item in context["resources"] if item["path"].endswith(".md")) @@ -153,3 +154,214 @@ def write_trace(output): assert evidence["passage_text"] == resource["content"].splitlines()[0] write_trace(exact.replace("\n", "\r\n")) assert json.loads(import_search(root, **inputs).read_bytes()) == saved + + +def test_manual_find_reads_body_and_each_requested_attachment_without_a_budget(tmp_path, capsys): + from inferrsi import __version__ + from inferrsi.apps.cli import main + from tests.apps.test_campaign_task_selection import BASELINE_CUE + + root = tmp_path / "campaign" + create_campaign(root, "diffusion", backend="cuda") + ref = "package:inferrsi.common.skills.inference_benchmark_design" + bundle = KnowledgeReader().read(ref) + links = ["references/benchmark-commands.md", "references/autotunebench-trial-validity.md"] + attachments = [next(path for path in bundle.content if path.endswith("/" + link)) + for link in links] + assert main(["find", BASELINE_CUE, "--session", str(root), + "--limit", "2"]) == 0 + found = json.loads(capsys.readouterr().out) + search = json.loads((root / found["reference"]["path"]).read_bytes()) + assert search["captured_by"] == f"inferrsi find {__version__}" + assert search["request"]["backend"] == "cuda" + assert search["request"]["sources"] == ["package", "checkout"] + assert "context_bytes" not in search["request"] and not search["contexts"] + first, _ = found["items"] + assert first["material_ref"] == ref and "content" not in first + assert main(first["read_args"]) == 0 + read = json.loads(capsys.readouterr().out) + assert len(read["content"].encode("utf-8")) == first["next_read_content_bytes"] + saved = json.loads((root / read["reference"]["path"]).read_bytes()) + assert saved["captured_by"] == f"inferrsi read {__version__}" + resource, = saved["contexts"][0]["resources"] + assert resource["content"] == read["content"] + body = read["content"] + page = read + while "next_read_args" in page: + assert main(page["next_read_args"]) == 0 + page = json.loads(capsys.readouterr().out) + body += page["content"] + from inferrsi.knowledge._skill_selection import skill_procedure + + expected, _ = skill_procedure(first["body_resource"], bundle.content[first["body_resource"]]) + assert len(expected) == 13_166 and body.encode() == expected + for link, path in zip(links, attachments, strict=True): + assert f"]({link})" in body + assert main([*first["read_args"], "--resource", link]) == 0 + result = json.loads(capsys.readouterr().out) + received = bytearray() + while True: + receipt = json.loads((root / result["reference"]["path"]).read_bytes()) + assert result["content_resource"] == receipt["request"]["resource"] == path + assert result["revision"] == first["revision"] + assert receipt["request"]["search_ref"] == found["reference"]["path"] + assert receipt["context_budget"] is None and not receipt["context_omissions"] + assert receipt["context_bytes_used"] == len(result["content"].encode()) + delivered, = receipt["contexts"][0]["resources"] + assert (delivered["path"], delivered["role"]) == (path, "reference") + received.extend(result["content"].encode()) + if "next_read_args" not in result: + break + assert main(result["next_read_args"]) == 0 + result = json.loads(capsys.readouterr().out) + assert received == bundle.content[path] + + archive = import_search(root, number=1, context_ids=[search["context_id"], saved["context_id"]], + archive_review=_review(tmp_path / "review.json")) + find_event, read_event = json.loads(archive.read_bytes())["events"] + identity = {k: search["request"]["ranking_policy"][k] + for k in ("id", "version", "config_sha256")} + assert find_event["request"]["kinds"] == "case,skill,record" + assert find_event["request"]["ranking_policy"] == identity + assert read_event["request"]["ranking_policy"] == identity + assert read_event["request"]["search_ref"] == found["reference"]["path"] + assert read_event["request"]["resource"] == resource["path"] + + +def test_manual_find_reopens_the_returned_checkout_without_archiving_local_paths(tmp_path, capsys): + from inferrsi.apps.cli import main + from tests.knowledge.test_knowledge_find import _plant_case + + root, library = tmp_path / "campaign", tmp_path / "separate library" + _plant_case(library, "casebook") + create_campaign(root, "manual") + assert main(["find", "mask caching ran out of device memory", "--kinds", "case", + "--skill-root", str(library), "--session", str(root), + "--limit", "1"]) == 0 + found = json.loads(capsys.readouterr().out) + hit, = found["items"] + assert hit["read_args"][hit["read_args"].index("--skill-root") + 1] == str(library) + assert str(library) not in (root / found["reference"]["path"]).read_text(encoding="utf-8") + assert found["sources"] == ["checkout"] + assert main(hit["read_args"]) == 0 + read = json.loads(capsys.readouterr().out) + assert read["revision"] == hit["revision"] and "910B1" in read["content"] + case = library / "casebook/cases/qwen-ascend-rejected-directions.md" + case.write_text(case.read_text(encoding="utf-8") + "\nUpdated.\n", encoding="utf-8") + with pytest.raises(SystemExit) as changed: + main(hit["read_args"]) + assert changed.value.code == 2 + + +@pytest.mark.parametrize("scoped", [False, True]) +def test_body_link_read_archives_the_resolved_attachment(tmp_path, scoped): + from tests.apps.test_campaign_task_selection import BASELINE_CUE + from tests.apps.test_codex_knowledge_search import _cli, _import, _operation + + root = tmp_path / "campaign" + create_campaign(root, "diffusion", backend="cuda") + scope = ["--session", str(root)] if scoped else [] + argv, output = _cli(tmp_path, "find", BASELINE_CUE, "--limit", "1", "--backend", "cuda", + "--no-external", "--json", *scope) + hit, = json.loads(output)["items"] + _, procedure = _cli(tmp_path, *hit["read_args"]) + link = "references/benchmark-commands.md" + assert f"]({link})" in json.loads(procedure)["content"] + read_argv, opened = _cli(tmp_path, *hit["read_args"], "--resource", link) + view = json.loads(opened) + assert view["revision"] == json.loads(procedure)["revision"] + path = view["body_resource"].removesuffix("/SKILL.md") + "/" + link + assert view["content_resource"] == path + + rows = [*_operation(tmp_path, argv, output, "find"), + *_operation(tmp_path, read_argv, opened, "attachment")] + for report in _import(tmp_path, rows, campaign=root): + assert report["coverage"] == "complete" and report["counts"]["used"] == 0 + read = report["events"][-1] + assert read["delivery"]["visible_resources"] == [ + {"ref": view["ref"], "path": path, "content_range": view["content_range"]}, + ] + + +@pytest.mark.parametrize(("case", "unresolved"), [ + ("matched", []), ("other_campaign", [3, 6]), ("clipped_read", [6]), ("changed_read", [6]), +]) +def test_selected_find_and_read_match_their_native_stdout_once(tmp_path, case, unresolved): + from tests.apps.test_codex_knowledge_search import _cli, _import, _operation + + root = tmp_path / "campaign" + create_campaign(root, "native-returns") + find_argv, found = _cli(tmp_path, "find", "cgroupv2", "--session", str(root), + "--no-external", "--limit", "1", "--json") + hit, = json.loads(found)["items"] + read_argv, opened = _cli(tmp_path, *hit["read_args"]) + rows, ids = [], [] + for tool, argv, output in (("find", find_argv, found), ("read", read_argv, opened)): + call, event, returned = _operation(tmp_path, argv, output, tool) + cmd = call["payload"]["arguments"]["cmd"].replace("\\", "\\\\").replace("'", "\\'") + call["payload"] = { + "type": "custom_tool_call", "name": "exec", "call_id": tool, + "input": f"const r=await tools.exec_command({{cmd:'{cmd}'}});text(r.output);", + } + visible = output + if tool == "read" and case == "clipped_read": + visible = "Warning: truncated output\n" + output[:120] + elif tool == "read" and case == "changed_read": + visible = output.replace('"content": "', '"content": "altered ', 1) + returned["payload"] = {"type": "custom_tool_call_output", "call_id": tool, "output": [ + {"type": "input_text", "text": "Script completed\nWall time 0.4 seconds\nOutput:\n"}, + {"type": "input_text", "text": visible}, + ]} + rows.extend((call, event, returned)) + ids.append(Path(json.loads(output)["reference"]["path"]).stem) + if case == "other_campaign": + # The exact captured bytes alone cannot bind a command issued in a different directory. + root = shutil.copytree(root, tmp_path / "different-campaign") + + local, archive = _import(tmp_path, rows, context_ids=ids, campaign=root) + for report in (local, archive): + assert [event["context_id"] for event in report["events"]] == ids + assert [event["action"] for event in report["events"]] == ["search", "read"] + assert report["observed"] == {"searches": 1, "hits": 1, "unique_hits": 1, "used": 0} + assert report["coverage"] == ("partial" if unresolved else "complete") + assert report["unresolved_command_lines"] == unresolved + assert [(d["trace_line"], d["action"], d["reason"]) for d in archive["unresolved_details"]] == [ + (line, "search" if line == 3 else "read", "capture_unverified") for line in unresolved + ] + if case == "matched": + search, read = archive["events"] + assert search["delivery"]["visible_refs"] == [hit["material_ref"]] + assert search["delivery"]["return_line"] == 4 + assert read["delivery"]["return_line"] == 7 + assert read["delivery"]["visible_resources"] == [ + {"ref": hit["material_ref"], "path": hit["body_resource"], + "content_range": json.loads(opened)["content_range"]}, + ] + elif case in ("clipped_read", "changed_read"): + assert archive["events"][1]["delivery"]["state"] == "unknown" + + +def test_scoped_find_records_the_catalog_filters_and_effective_store_scope(tmp_path, capsys): + from inferrsi.apps.cli import main + from inferrsi.knowledge.knowledge_store import KnowledgeStore + + root, store = tmp_path / "manual", tmp_path / "store" + store.mkdir() + KnowledgeStore(store, skill_root=None) + create_campaign(root, "filtered") + args = ["find", "diffusion", "--session", str(root), "--store", str(store), + "--kinds", "record", "--backend", "cuda", "--limit", "1"] + assert main(args) == 0 + found = json.loads(capsys.readouterr().out) + assert found["sources"] == ["package", "store"] + filters = ["--repo-type", "vllm_omni", "--tier", "contribution", "--scenario", "diffusion.t2i"] + with pytest.raises(SystemExit) as error: + main([*args, *filters]) + assert error.value.code == 2 and "--store" in capsys.readouterr().err + args = [word for word in args if word not in ("--store", str(store))] + assert main([*args, *filters]) == 0 + catalog = json.loads(capsys.readouterr().out) + request = json.loads((root / catalog["reference"]["path"]).read_bytes())["request"] + assert request["sources"] == catalog["sources"] == ["package"] + assert (request["repo"], request["tier"], request["scenario"], request["kinds"], + request["backend"]) == ("vllm_omni", "contribution", "diffusion.t2i", "record", "cuda") diff --git a/tests/apps/test_service_knowledge_snapshot.py b/tests/apps/test_service_knowledge_snapshot.py new file mode 100644 index 000000000..fc3b4cef0 --- /dev/null +++ b/tests/apps/test_service_knowledge_snapshot.py @@ -0,0 +1,170 @@ +"""A fingerprint-free search retains the actual bytes its reads can deliver.""" + +import json +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.apps.workflows import session_knowledge +from inferrsi.harness import optimization, project_service +from inferrsi.knowledge import knowledge_operations +from inferrsi.knowledge.catalog import lookup_record +from tests.apps.test_campaign_task_selection import BASELINE_CUE +from tests.fixtures.service_reuse import call, diagnose, rejected +from tests.fixtures.service_reuse import campaign as campaign +from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints + +IDENTITY = "inferrsi.common.skills.inference_benchmark_design" +LINK = "references/benchmark-commands.md" + + +@pytest.fixture +def installed_source(tmp_path, monkeypatch): + """Edit a real owner tree without changing this test checkout's package.""" + record = lookup_record(IDENTITY, file_fingerprints=False) + body = knowledge_operations.service_body(record)[1] + attachment = knowledge_operations.service_body(record, LINK)[1] + package = tmp_path / "installed-package" + root = package / "knowledge" + for path, content in knowledge_operations.service_resources(record).items(): + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + monkeypatch.setattr(knowledge_operations, "files", lambda name: package) + return {"root": root, "record": record, "body": body, "attachment": attachment, + "primary": root / record["skill_documents"]["original"]} + + +def find(campaign): + call(campaign, "start") + diagnose(campaign) + assert main(["find", BASELINE_CUE, "--backend", "cuda", "--session", + str(campaign["root"]), "--limit", "1"]) == 0 + found = json.loads(campaign["capsys"].readouterr().out) + assert found["items"][0]["material_ref"] == "package:" + IDENTITY + project_service.no_fingerprints(found) + return found + + +def read(campaign, argv): + assert main(argv) == 0 + opened = json.loads(campaign["capsys"].readouterr().out) + retained = project_service.read(campaign["root"] / opened["reference"]["path"]) + context, = retained["contexts"] + resource, = context["resources"] + assert resource["content"] == opened["content"] + assert context["content_bytes"] == len(opened["content"].encode()) + assert retained["request"]["search_ref"] in argv + project_service.no_fingerprints(opened) + return opened + + +def finish(campaign, first): + parts = [first["content"]] + opened = first + while "next_read_args" in opened: + previous = opened["content_range"]["end"] + opened = read(campaign, opened["next_read_args"]) + assert opened["content_range"]["start"] == previous + parts.append(opened["content"]) + return "".join(parts).encode() + + +def test_service_reads_and_continuations_keep_the_find_source(campaign, installed_source): + found = find(campaign) + hit, = found["items"] + primary = installed_source["primary"] + primary.write_bytes(primary.read_bytes() + b"\nEdited after Find.\n") + body = read(campaign, hit["read_args"]) + assert body["revision"] == hit["revision"] + assert "next_read_args" in body + assert finish(campaign, body) == installed_source["body"] + + attachment = read(campaign, [*hit["read_args"], "--resource", LINK, + "--byte-range", "0", "128"]) + original = installed_source["attachment"] + assert attachment["content"].encode() == original[:128] + target = primary.parent / LINK + target.write_bytes(b"Replaced after the first attachment page.\n") + assert finish(campaign, attachment) == original + assert attachment["revision"] == hit["revision"] + + declared = next(name for name in installed_source["record"]["skill_metadata"]["references"] + if name.startswith("../")) + path, raw, _ = knowledge_operations.service_body(installed_source["record"], declared) + (installed_source["root"] / path).write_bytes(b"Changed declared reference.\n") + linked = read(campaign, [*hit["read_args"], "--resource", declared + "#section"]) + assert finish(campaign, linked) == raw + _, state, _ = optimization.read_records(campaign["root"]) + assert any(item.get("search_ref") == found["reference"]["path"] + for item in state["contexts"]) + + +def test_service_search_does_not_publish_a_changed_ranked_body(campaign, installed_source, + monkeypatch): + original_rank = session_knowledge.rank + + def change_after_ranking(*args, **kwargs): + result = original_rank(*args, **kwargs) + primary = installed_source["primary"] + primary.write_bytes(primary.read_bytes() + b"\nChanged before retention.\n") + return result + + monkeypatch.setattr(session_knowledge, "rank", change_after_ranking) + call(campaign, "start") + diagnose(campaign) + assert rejected(["find", BASELINE_CUE, "--backend", "cuda", "--session", + str(campaign["root"]), "--limit", "1"]) == 2 + assert "Knowledge changed while finding material" in campaign["capsys"].readouterr().err + assert json.loads((campaign["root"] / "state.json").read_bytes())["contexts"] == [] + assert not list((campaign["root"] / "knowledge/sources").iterdir()) + + +def test_service_retains_a_records_declared_edition(tmp_path): + record = lookup_record("vllm.common.llm.bounded_serving_measurement", file_fingerprints=False) + edition = record["skill_documents"]["en"] + expected = knowledge_operations.service_body(record, edition) + source = tmp_path / "retained" + resources = knowledge_operations.service_resources(record) + assert set(resources) == {"record.json", edition} + for path, content in resources.items(): + target = source / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + assert knowledge_operations.service_body(record, edition, source_root=source) == expected + assert json.loads(knowledge_operations.service_body(record, source_root=source)[1]) == record + + +def test_service_old_search_keeps_history_but_cannot_claim_current_bytes(campaign): + found = find(campaign) + hit, = found["items"] + delivery = read(campaign, hit["read_args"]) + root = campaign["root"] + reference = root / found["reference"]["path"] + legacy = json.loads(reference.read_bytes()) + legacy.pop("source_snapshot") + reference.write_text(json.dumps(legacy), encoding="utf-8") + old_search = reference.read_bytes() + old_delivery = (root / delivery["reference"]["path"]).read_bytes() + before = (root / "state.json").read_bytes() + assert rejected(hit["read_args"]) == 2 + assert "run Find again before reading" in campaign["capsys"].readouterr().err + assert reference.read_bytes() == old_search + assert (root / delivery["reference"]["path"]).read_bytes() == old_delivery + assert (root / "state.json").read_bytes() == before + _, state, _ = optimization.read_records(root) + assert any(item["path"] == delivery["reference"]["path"] for item in state["contexts"]) + + +def test_missing_retained_attachment_never_falls_back_to_current_package(campaign): + found = find(campaign) + hit, = found["items"] + root = campaign["root"] + search = json.loads((root / found["reference"]["path"]).read_bytes()) + retained = root / search["source_snapshot"] / IDENTITY + primary = Path(hit["body_resource"]) + (retained / primary.parent / LINK).unlink() + assert rejected([*hit["read_args"], "--resource", LINK]) == 2 + assert "Unknown resource" in campaign["capsys"].readouterr().err + assert read(campaign, hit["read_args"])["content"] diff --git a/tests/apps/test_session_ranking_policy.py b/tests/apps/test_session_ranking_policy.py index 2b5b0b61a..e810b7644 100644 --- a/tests/apps/test_session_ranking_policy.py +++ b/tests/apps/test_session_ranking_policy.py @@ -56,9 +56,12 @@ def test_managed_policy_binds_delivery_and_guards_resume(lane, request, tmp_path plan_path = root / "plan.json" plan = read(plan_path) assert plan["ranking_policy"] == expected - assert main([*command, "knowledge", "--session", str(root), "--query", "cgroupv2", - "--limit", "1", "--context-bytes", "65536"]) == 0 - context = json.loads(capsys.readouterr().out)["context"] + assert main(["find", "cgroupv2", "--session", str(root), + "--limit", "1"]) == 0 + found = json.loads(capsys.readouterr().out) + assert main(found["items"][0]["read_args"]) == 0 + returned = json.loads(capsys.readouterr().out) + context = read(root / returned["reference"]["path"]) assert context["request"]["ranking_policy"] == expected assert context["contexts"] retained = read(root / read(root / "state.json")["contexts"][0]["path"]) diff --git a/tests/benchmark/test_benchmark_compare.py b/tests/benchmark/test_benchmark_compare.py index 7d98552ac..dd3c10ba6 100644 --- a/tests/benchmark/test_benchmark_compare.py +++ b/tests/benchmark/test_benchmark_compare.py @@ -1,5 +1,6 @@ """Real campaign subprocesses with synthetic host receipts; no Agent/device launch.""" +import hashlib import json import os import re @@ -16,6 +17,7 @@ from inferrsi.benchmark import registry from inferrsi.harness import agent_sessions from inferrsi.harness.optimization_session import _runtime_identity +from inferrsi.knowledge.knowledge_operations import KnowledgeReader @pytest.fixture @@ -44,7 +46,9 @@ def experiment(tmp_path, monkeypatch, capsys, request): card = "skill_library/records/" + requirement["ref"].split(":", 1)[1] + ".json" (corpus / card).parent.mkdir(parents=True) shutil.copyfile(actual / "knowledge/data" / card, corpus / card) - monkeypatch.setattr(compare, "KNOWLEDGE_CONTEXT_BYTES", card_budget) + if card_budget == "one-card": + card_budget = len(KnowledgeReader().read(requirement["ref"]).content["record.json"]) + requirement["context_bytes"] = card_budget (task / "task.json").write_text(json.dumps(manifest), encoding="utf-8") (task / "TASK.md").write_text("Synthetic task", encoding="utf-8") (task / "baseline.py").write_text("FACTOR = 1\n", encoding="utf-8") @@ -94,7 +98,8 @@ def finish(experiment, trial, *, factor=2, final=True, model="synthetic-model", final_score=None, legacy_session_id=None, python=None, environment_digest="a" * 64, knowledge=False, token_coverage=False, usage_counts=None, collect=True, session_id=None, host_state="completed", window=True, legacy_attempt=1, - card_timing=None, card_context_budgets=(None,), round_submit=main): + card_timing=None, search_count=1, card_scenario=None, extra_read=None, + card_ranges=None, round_submit=main): root, _, capsys = experiment opened = time.time() dispatch = operation(experiment, "dispatch", trial) @@ -126,24 +131,49 @@ def finish(experiment, trial, *, factor=2, final=True, model="synthetic-model", def deliver_required_cards(): planned = json.loads(re.search(r"Knowledge argv .*?: (\[.*\])\n", prompt).group(1)) - assert planned[:6] == command[:6] + assert planned[:5] == [*command[:4], "find"] + ref = re.search(r"material_ref equals ([\w:.-]+) and", prompt).group(1) assert Path(planned[planned.index("--session") + 1]) == campaign - for budget in card_context_budgets: + assert "--context-bytes" not in planned + for index in range(search_count): argv = planned.copy() - if budget is not None: - argv[argv.index("--context-bytes") + 1] = str(budget) + if card_scenario: + argv[argv.index("--scenario") + 1] = card_scenario assert main(argv[4:]) == 0 - capture = json.loads(capsys.readouterr().out)["context"] - assert capture["selection"]["method"] == "find-lexical-v1" - assert capture["diagnosis_binding"]["diagnosis_id"] == diagnosis["id"] - - if card_timing == "before_round": + found = json.loads(capsys.readouterr().out) + hit, = [item for item in found["items"] if item["material_ref"] == ref] + assert "content" not in hit + if card_timing == "find_only": + continue + for interval in card_ranges[index] if card_ranges else [None]: + args = hit["read_args"] + if interval: + args = [*args, "--byte-range", *map(str, interval)] + assert main(args) == 0 + read = json.loads(capsys.readouterr().out) + capture = json.loads((campaign / read["reference"]["path"]).read_bytes()) + assert capture["selection"]["method"] == "find-lexical-v1" + assert capture["diagnosis_binding"]["diagnosis_id"] == diagnosis["id"] + assert capture["contexts"][0]["resources"][0]["content"] == read["content"] + if extra_read: + arguments = hit["read_args"] + if extra_read == "attachment": + skill = next(item for item in found["items"] + if item["id"].endswith(".ascend_graph_mode")) + arguments = [*skill["read_args"], "--resource", + "references/torchair-graph-path.md"] + assert main(arguments) == 0 + assert json.loads(capsys.readouterr().out)["content"] + + if card_timing in ("before_round", "find_only"): deliver_required_cards() elif knowledge: - assert main(["benchmarks", "session", "knowledge", "--session", str(campaign), - "--query", "cache per-step masks ran out of device memory", - "--context-bytes", "8192", "--limit", "1"]) == 0 - capture = json.loads(capsys.readouterr().out)["context"] + assert main(["find", "cache per-step masks ran out of device memory", + "--session", str(campaign), "--limit", "1"]) == 0 + hit, = json.loads(capsys.readouterr().out)["items"] + assert main(hit["read_args"]) == 0 + path = json.loads(capsys.readouterr().out)["reference"]["path"] + capture = json.loads((campaign / path).read_bytes()) assert capture["contexts"] binding = capture["diagnosis_binding"] assert binding["diagnosis_id"] == diagnosis["id"] @@ -258,26 +288,25 @@ def test_metrics_summary_is_first_and_complete_token_ratio_has_explicit_directio @pytest.mark.parametrize( - "experiment,card_timing,expected_captures,expected_gap", + "experiment,card_timing,extra_read,scenario,expected_gap", [ - pytest.param(65536, "before_round", [(None, True)], None, id="body"), - pytest.param( - 1024, "before_round", [(None, False)], "context budget exceeded", id="over-budget", - ), - pytest.param(65536, None, [], "before the first round", id="missing"), - pytest.param(65536, "after_round", [(None, True)], "before the first round", id="late"), - pytest.param( - 1024, "before_round", [(65536, True)], "context budget differs", id="wrong-budget", - ), - pytest.param( - 1024, "before_round", [(None, False), (65536, True)], "context budget exceeded", - id="larger-budget-retry", - ), + pytest.param(65536, "before_round", None, None, None, id="body"), + pytest.param("one-card", "before_round", None, "diffusion.t2i", None, id="alias-exact-fit"), + pytest.param(1024, "before_round", None, None, "context budget exceeded", id="over-budget"), + pytest.param(0, "before_round", None, None, "context budget exceeded", id="zero-budget"), + pytest.param(65536, None, None, None, "before the first round", id="missing"), + pytest.param(65536, "find_only", None, None, "before the first round", + id="hit-without-read"), + pytest.param(65536, "after_round", None, None, "before the first round", id="late"), + pytest.param("one-card", "before_round", "repeat", None, "context budget exceeded", + id="repeat-after-body"), + pytest.param("one-card", "before_round", "attachment", None, "context budget exceeded", + id="attachment-after-body"), ], indirect=["experiment"], ) def test_required_card_delivery_controls_pair_eligibility( - experiment, card_timing, expected_captures, expected_gap + experiment, card_timing, extra_read, scenario, expected_gap ): root, initial, _ = experiment on, off = [trial["id"] for trial in initial["trials"]] @@ -286,7 +315,7 @@ def test_required_card_delivery_controls_pair_eligibility( assert requirement["scenario"] == "diffusion.image_generation" campaign, result = finish( experiment, on, card_timing=card_timing, - card_context_budgets=tuple(budget for budget, _ in expected_captures), + card_scenario=scenario, extra_read=extra_read, ) _, off_result = finish(experiment, off) assert off_result["eligible"] and "knowledge_delivery" not in off_result @@ -296,45 +325,254 @@ def test_required_card_delivery_controls_pair_eligibility( assert result["status"] == "completed" assert result["final"]["assessment"]["verdict"] == "PASS" eligible = expected_gap is None - for reference, (budget, has_body) in zip( - result["knowledge_deliveries"], expected_captures, strict=True, - ): + searches = [r for r in result["knowledge_deliveries"] if r["kind"] == "knowledge_search"] + reads = [r for r in result["knowledge_deliveries"] if r["kind"] == "delivered_context"] + assert len(searches) == int(card_timing is not None) + assert len(reads) == int(card_timing in ("before_round", "after_round")) + int(bool(extra_read)) + assert requirement["budget_source"] == delivery["budget_source"] == "experiment_plan" + expected_sizes = dict.fromkeys([search["path"] for search in searches], 0) + for reference in reads: assert (reference in result["trace"][0]["available_contexts"]) == ( card_timing == "before_round") capture = json.loads((campaign / reference["path"]).read_text(encoding="utf-8")) assert capture["request"]["relevance"] == requirement["query"] - assert capture["request"]["scenario"] == requirement["scenario"] - expected_bytes = budget if budget is not None else requirement["context_bytes"] - assert capture["request"]["context_bytes"] == expected_bytes - assert capture["context_budget"]["max_bytes"] == expected_bytes - assert any(item["ref"] == delivery["ref"] for item in capture["items"]) - matching = [item for item in capture["contexts"] if item["ref"] == delivery["ref"]] - if has_body: - card, = matching + assert capture["request"]["scenario"] == (scenario or requirement["scenario"]) + assert capture["context_budget"] is None and not capture["context_omissions"] + card, = capture["contexts"] + body, = card["resources"] + actual = len(body["content"].encode("utf-8")) + expected_sizes[reference["search_ref"]] += actual + assert actual == capture["context_bytes_used"] + assert body["content"] in capture["assembled_text"] + if card["ref"] == delivery["ref"]: + assert body["path"] == "record.json" assert card["revision"] == requirement["revision"] - body, = [item for item in card["resources"] if item["path"] == "record.json"] assert body["sha256"] == requirement["body_sha256"] - assert body["content"] in capture["assembled_text"] assert json.loads(body["content"])["verification"]["locally_verified"] is False else: - assert not matching - assert any( - item["ref"] == delivery["ref"] and item["reason"] == "context_limit" - for item in capture["context_omissions"] - ) - if eligible: - assert delivery["capture"] == reference + assert extra_read == "attachment" and body["role"] == "reference" + groups = delivery["requests"] + if card_timing in ("before_round", "find_only"): + assert {g["search_ref"]: g["delivered_bytes"] for g in groups} == expected_sizes + assert all("requested_bytes" not in group for group in groups) + assert all(bool(g["body_capture"]) == (card_timing == "before_round") for g in groups) + else: + assert groups == [] + if eligible: + assert delivery["capture"] == reads[0] assert result["eligible"] == result["metrics_comparable"] == eligible if not eligible: assert delivery["capture"] is None gap, = result["gaps"] - assert "Required knowledge card body was not delivered" in gap assert expected_gap in gap report = operation(experiment, "report") assert report["assessment"]["counts"]["eligible_pairs"] == int(eligible) performance = report["benchmark_metrics"]["tasks"][0]["metrics"]["performance_benefit_ratio"] assert performance["eligible_pairs"] == int(eligible) assert _document(report)["trials"][0]["knowledge_delivery"] == delivery + if groups: + for fmt in ("markdown", "html"): + text = Path(report["reports"][fmt]).read_text(encoding="utf-8") + assert "Delivered UTF-8 bytes" in text and "Requested bytes" not in text + + +def test_single_capture_verifies_the_original_body_or_budget_omission(tmp_path): + from inferrsi.apps.delivery.snapshot import Snapshot + from inferrsi.apps.workflows.campaign import capture_context, create_campaign + + create_campaign(tmp_path, "single-delivery") + task = "qwen21-denoise-npu" + manifest = json.loads((compare.task_resources(task) / "task.json").read_bytes()) + frozen = compare._freeze_knowledge_delivery(manifest, task) + reader = KnowledgeReader() + for budget in (frozen["context_bytes"], 1024): + path, digest = capture_context( + tmp_path, context_id=f"capture-{budget}", reader=reader, ids=[frozen["ref"]], + revisions={frozen["ref"]: frozen["revision"]}, relevance=frozen["query"], + scenario="diffusion.t2i", context_bytes=budget, + ) + reference = {"kind": "delivered_context", "path": path.relative_to(tmp_path).as_posix(), + "sha256": digest, "round": 1} + requirement = {**frozen, "context_bytes": budget} + del requirement["budget_source"] # The single-capture protocol predates plan-only budgets. + snapshot = Snapshot(tmp_path, "test") + report, gap = compare._card_delivery(snapshot, "single-delivery", [reference], requirement) + request, = report["requests"] + if budget == 1024: + assert gap and "recorded context budget omission" in gap + assert request["omitted_for_budget"] and not request["delivered_bytes"] + assert request["body_capture"] is None and report["capture"] is None + else: + assert not gap and report["capture"] == request["body_capture"] == reference + body = reader.read(frozen["ref"]).content["record.json"] + assert request["delivered_bytes"] == len(body) + for field in ("revision", "body_sha256", "query", "scenario"): + failed, gap = compare._card_delivery(snapshot, "single-delivery", [reference], + {**requirement, field: "different"}) + assert gap and failed["capture"] is None + + +@pytest.mark.parametrize(("limit", "declared", "expected_gap"), [ + (65536, [65536], None), (65536, [None], "differs"), + (1024, [65536], "differs"), (1024, [1024, 65536], "exceeded"), + (65536, [65536, 131072], "differs"), +]) +def test_historical_find_keeps_retry_limits(tmp_path, limit, declared, expected_gap): + from inferrsi.apps.delivery.snapshot import Snapshot + from inferrsi.harness.records.knowledge_capture import store_capture + from inferrsi.knowledge.context_projection import assemble_context_text + + manifest = json.loads((compare.task_resources("qwen21-denoise-npu") / "task.json").read_bytes()) + frozen = compare._freeze_knowledge_delivery(manifest, "qwen21-denoise-npu") + del frozen["budget_source"] + frozen["context_bytes"] = limit + item = {"ref": frozen["ref"], "revision": frozen["revision"]} + body = KnowledgeReader().read(item["ref"]).content["record.json"] + context = {**item, "omissions": [], "resources": [{"path": "record.json", "role": "record", + "sha256": frozen["body_sha256"], "content": body.decode("utf-8")}]} + + def retain(name, action, request, contexts): + path, digest = store_capture( + tmp_path, context_id=name, campaign_id="legacy", selection={}, request=request, + items=[item], omissions=[], context_omissions=[], context_budget=None, + context_bytes_used=len(body) if contexts else 0, contexts=contexts, + assembled_text=assemble_context_text(contexts), retrieval={"entrypoint": action}, + ) + return {"kind": "knowledge_search" if action == "find" else "delivered_context", + "path": path.relative_to(tmp_path).as_posix(), "sha256": digest} + + references = [] + for index, budget in enumerate(declared): + request = {"query": frozen["query"], "relevance": frozen["query"], + "scenario": "diffusion.t2i", "context_bytes": budget} + found = retain(f"find-{index}", "find", request, []) + read_request = {**request, "search_ref": found["path"]} + opened = retain(f"read-{index}", "read", read_request, [context]) + references.extend((found, {**opened, "search_ref": found["path"]})) + result, gap = compare._card_delivery(Snapshot(tmp_path, "test"), "legacy", references, frozen) + assert [g["requested_bytes"] for g in result["requests"]] == declared + assert all(g["delivered_bytes"] == len(body) and g["body_capture"] for g in result["requests"]) + assert bool(result["capture"]) == (expected_gap is None) + if expected_gap is None: + assert gap is None + else: + assert expected_gap in gap + + +@pytest.mark.parametrize("experiment", [1024], indirect=True) +def test_handoff_uses_the_frozen_runtime_knowledge_syntax(experiment): + root, initial, _ = experiment + trial = initial["trials"][0] + plan = json.loads((root / "experiment.json").read_bytes()) + frozen = compare._knowledge_requirement(plan, trial) + workspace = root / trial["workspace"] + + def knowledge_argv(): + prompt = compare._prompt(root, plan, trial, workspace) + return json.loads(re.search(r"Knowledge argv .*?: (\[.*\])\n", prompt).group(1))[4:] + + current = knowledge_argv() + assert current[:2] == ["find", frozen["query"]] and "--context-bytes" not in current + del frozen["budget_source"] + assert knowledge_argv() == [*current, "--context-bytes", "1024"] + del plan["knowledge_command"] + legacy = knowledge_argv() + assert legacy[:3] == ["benchmarks", "session", "knowledge"] + assert legacy[legacy.index("--query") + 1] == frozen["query"] + assert legacy[-2:] == ["--context-bytes", "1024"] + + +@pytest.mark.parametrize("bad", [-1, True, 2.5, None, "1024"]) +def test_declared_card_budget_must_be_a_nonnegative_byte_count(bad): + manifest = {"knowledge_delivery": {"query": "card", "scenario": "diffusion.t2i", + "ref": "package:card", "context_bytes": bad}} + with pytest.raises(ValueError, match="context_bytes must be a nonnegative integer"): + compare._freeze_knowledge_delivery(manifest, "test-work") + + +@pytest.mark.parametrize("experiment", [65536], indirect=True) +def test_retry_cannot_replace_an_unverified_first_round_input(experiment): + from inferrsi.apps.delivery.snapshot import Snapshot + + root, initial, _ = experiment + trial = initial["trials"][0] + campaign, _ = finish(experiment, trial["id"], collect=False, card_timing="before_round", + search_count=2) + state = json.loads((campaign / "state.json").read_bytes()) + campaign_id = json.loads((campaign / "campaign.json").read_bytes())["campaign_id"] + plan = json.loads((root / "experiment.json").read_bytes()) + requirement = compare._knowledge_requirement(plan, trial) + find, read, retry_find, retry_read = state["rounds"][0]["contexts"] + wrong_scenario, gap = compare._card_delivery( + Snapshot(campaign, "test"), campaign_id, [find, read], + {**requirement, "scenario": "diffusion.t2v"}, + ) + assert gap and wrong_scenario["requests"] == [] and wrong_scenario["capture"] is None + for inputs in ([read, retry_find, retry_read], + [find, {**read, "sha256": "0" * 64}, retry_find, retry_read]): + report, gap = compare._card_delivery(Snapshot(campaign, "test"), campaign_id, + inputs, requirement) + assert gap and "could not be verified" in gap + assert report["capture"] is None and report["requests"][-1]["body_capture"] == retry_read + if inputs[0] == find: + assert report["requests"][0]["delivered_bytes"] is None + + +@pytest.mark.parametrize("experiment,case,eligible", [ + ("one-card", "three-pages", True), ("one-card", "missing-middle", False), + ("one-card", "different-searches", False), (65536, "overlap-and-repeat", True), + ("one-card", "overlap-and-repeat", False), +], indirect=["experiment"]) +def test_frozen_card_reconstructed_from_actual_scoped_reads(experiment, case, eligible): + root, initial, _ = experiment + trial = initial["trials"][0] + plan = json.loads((root / "experiment.json").read_bytes()) + requirement = compare._knowledge_requirement(plan, trial) + card = KnowledgeReader().read(requirement["ref"]).content["record.json"] + + def boundary(at): + while card[at] & 0xc0 == 0x80: + at -= 1 + return at + + a, b = boundary(len(card) // 3), boundary(2 * len(card) // 3) + first, middle, last = (0, a), (a, b - a), (b, len(card) - b) + if case == "overlap-and-repeat": + earlier = boundary(a - 1) + ranges = [[(earlier, b - earlier), last, first, last]] + elif case == "missing-middle": + ranges = [[first, last]] + elif case == "different-searches": + ranges = [[first, last], [middle]] + else: + ranges = [[middle, last, first]] + _, result = finish(experiment, trial["id"], card_timing="before_round", + search_count=len(ranges), card_ranges=ranges) + assert result["eligible"] == result["metrics_comparable"] == eligible + report = result["knowledge_delivery"] + assert report["capture"] is None + for group, requested in zip(report["requests"], ranges, strict=True): + assert group["body_capture"] is None + assert group["delivered_bytes"] == sum(length for _, length in requested) + if case in ("missing-middle", "different-searches"): + assert not group["body_captures"] + else: + assert len(group["body_captures"]) == 3 + if eligible: + assert report["captures"] == report["requests"][0]["body_captures"] + else: + assert "captures" not in report + assert any(("context budget exceeded" if case == "overlap-and-repeat" + else "not delivered") in gap for gap in result["gaps"]) + + +def test_conflicting_or_wrong_page_bytes_cannot_prove_the_frozen_hash(): + left = ({"start": 0, "end": 2, "total_bytes": 3}, b"ab", {"path": "first"}) + right = ({"start": 1, "end": 3, "total_bytes": 3}, b"bc", {"path": "second"}) + digest = hashlib.sha256(b"abc").hexdigest() + assert compare._complete_card_pages([right, left], digest) == [left[2], right[2]] + assert not compare._complete_card_pages([left, (right[0], b"xc", right[2])], digest) + assert not compare._complete_card_pages([left, right], hashlib.sha256(b"abd").hexdigest()) def test_new_metrics_missing_tokens_does_not_remove_valid_performance(experiment): @@ -708,8 +946,7 @@ def test_round_cannot_cite_undelivered_knowledge(experiment): capsys.readouterr() round_args = ["benchmarks", "session", "round", "--session", str(campaign), "--candidate", str(campaign / "work/candidate.py"), "--hypothesis", "Test"] - knowledge_args = ["benchmarks", "session", "knowledge", "--session", str(campaign), - "--query", "implementation option", "--context-bytes", "1024"] + knowledge_args = ["find", "implementation option", "--session", str(campaign)] for arguments in (knowledge_args, round_args): with pytest.raises(SystemExit) as error: main(arguments) diff --git a/tests/fixtures/knowledge_retrieval.py b/tests/fixtures/knowledge_retrieval.py index 18c2f1c48..ba1aae1ed 100644 --- a/tests/fixtures/knowledge_retrieval.py +++ b/tests/fixtures/knowledge_retrieval.py @@ -5,6 +5,8 @@ from __future__ import annotations +import gzip +import hashlib import json import sys from contextlib import contextmanager @@ -13,12 +15,11 @@ from inferrsi.apps.views.dashboard import write_dashboard from inferrsi.apps.views.search_attribution import import_search -from inferrsi.apps.workflows.campaign import capture_context, create_campaign, save_retrieval +from inferrsi.apps.workflows.campaign import create_campaign from inferrsi.harness.records.campaign_records import record_candidate from inferrsi.harness.records.optimization_log import record_log from inferrsi.knowledge import knowledge_find from inferrsi.knowledge._source_snapshot import source_entry -from inferrsi.knowledge.catalog import search_knowledge from inferrsi.knowledge.knowledge_operations import KnowledgeReader, _hash, _json @@ -70,38 +71,38 @@ def write(path, value): ) +def legacy_records(): + """Receipts recorded before free-text collection retired, including the original bodies.""" + with gzip.open(Path(__file__).with_name("pre_find_read_captures.json.gz"), "rt", + encoding="utf-8") as source: + return json.load(source) + + +def install_legacy_capture(root, sample, context_id, *, collection="samples", diagnosis=None): + """Place a recorded response into the synthetic campaign used by an importer test.""" + doc = legacy_records()[collection][sample] + doc["campaign_id"] = json.loads((root / "campaign.json").read_bytes())["campaign_id"] + doc["context_id"] = context_id + if diagnosis is not None: + doc["diagnosis_binding"] = diagnosis + raw = (json.dumps(doc, ensure_ascii=False, indent=2) + "\n").encode("utf-8") + path = root / "knowledge" / (context_id + ".json") + path.parent.mkdir(exist_ok=True) + with path.open("xb") as file: + file.write(raw) + return path, hashlib.sha256(raw).hexdigest() + + def build(root, *, runs=DEFAULT_RUNS): root = Path(root) create_campaign(root, "synthetic-retrieval") manifest = json.loads((root / "campaign.json").read_text()) write(root / "campaign.json", {**manifest, "synthetic": True}) - budget = 2 * len(b"Synthetic launch guidance.\n") captures = {} - with reader(root / "corpus") as source: - path, captures["capture"] = capture_context( - root, context_id="capture", reader=source, relevance="launch", context_bytes=budget, - ) - captured = json.loads(path.read_text()) - with patch("inferrsi.knowledge.catalog.knowledge_records", - return_value=list(source.records().values())): - _, captures["catalog"] = save_retrieval( - root, context_id="catalog", result=search_knowledge("launch", explain=True), - ) - for name, options in { - "collect": {"relevance": "launch", "context_bytes": budget}, - "explicit": {"ids": list(reversed(source.records())), "relevance": "launch"}, - "no-ranking": {}, "empty": {"query": "no-such-term"}, - }.items(): - result = source.collect(**options) - _, captures[name] = save_retrieval(root, context_id=name, result=result) - - # Keep a synthetic pre-observation capture in the dashboard fixture. Its - # payload is fixed by ID and its recorded selection is historical metadata. - legacy = source.collect(ids=list(source.records())) - legacy.pop("retrieval") - legacy["selection"] = {"method": "weighted-lexical-v1", "cue": "launch", - "scope": "generated-packaged-skills", "ranking_applied": True} - _, captures["legacy"] = save_retrieval(root, context_id="legacy", result=legacy) + with reader(root / "corpus"): + for name in ("capture", "catalog", "collect", "explicit", "no-ranking", "empty", "legacy"): + _, captures[name] = install_legacy_capture(root, name, name, collection="example") + captured = json.loads((root / "knowledge/capture.json").read_bytes()) for candidate, run, number, verdict, gain, quality in runs: directory = root / "runs" / run write(directory / "run.lock.json", {"workload_id": "synthetic", "scenario": "http"}) diff --git a/tests/fixtures/legacy/model_research_returns.json.gz b/tests/fixtures/legacy/model_research_returns.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..f4600efa2cdef049382286760e16b71f3affbdc9 GIT binary patch literal 4399 zcmV+~5zy`*iwFP!00002|Lt4bk{h=XefL+OwknmRisamQ8A?x5EX68Iu_DQS@v2yu z84L;UT<8IYyR=GGdCCVQ5BZ?{NxmfA0Orc!ijsE~CE<%!1Ta9O(U;SW#=EZwxhR-m zvdJ6ZM?XwBfS#6B=l--a*TcbqlodEM`R^xS7YaUS;`p!lE_nHrJGQT3_&t zzo0kcZ@g~%cpMirW!HIe)$K@=oBl`%v@tmjXn4i4s5hKRnjHBc0+xk6DqqaV3mTHw zvW$3sGi)W6;~9T!4I zd5K4K@$NDsD*3tkVmT3nb^AVeNAteXE9%|#D==Fx!$SgMT=k>&6bWw7r}B#=bq2(fHH># z@xl*6e-(0AuP_1tMdr<8fK%L|ji}6iI$S(T+zf@2pBu zXAWoJ*|wCcqw`31BRkXZl&)E)<>aM6C2n2oYoa`k zlblAKHf<;lXAkpqn`bPO-Pvn>QW~3UnL@?PaxPfWnp*2EOklL3Eg$5koM)1#ty*e( zG|_D%e?Uq&&Qto7z}N} zcPt_a&DJFxuBBZSF%vx`Jlny?z$-=CSZrCyV;;gLL`f5}rE(((%_6f2m?|!l#F9ms zg%p3Xn{8fv%tjP@Ry)d0<*NFC{P5_>2&fH{5)BnmqOG@qKaoN$f+S+P?ITE1XZ0~8 z>BH@jR50+#KoL8YtiEt+JaLO;mW4528!5Nqfn}|^+?2rtq}r;ed-Tj|2(^MF53I;_ z+^G}WbQ*Xx3<7T&E*BAH(?v|D&LUXY^BJ3ZzV+(Kqpx2)nWRyV4=_J?N23!bPS%@( zhOjfiq7^msxVAeVJNDT1Zs7=+ag;`*^BupJW)Y$SPsG z%JQ#E9#LqkR&D&1f&gl%zUg_hVZ=BaB1&|KOb~rq<8_gjSp|rD?NDku^{vq0|5hf&9IfgBNI6%`rgGg>gE@9_0njUqpnz`dF-IG+Ml8n>A1|1l{M7IYVS*4PYS3=Jh( zirPLHn9|mau4ys0$5I*rJSf=DB`;WtR{0@`az#uCTm_O6U{VIO?iiZVmgN*gUIT=j z9GZA>#gk-JVJp;BIo^0IGe*mtpn!H~adi3)EXTjMD1Y%Mjvla&U6Y_o`aCyP|b_z2G&vk3lqYZM3k z9++X#iL)@iHpg6r)GhUg0HDC$46tI|XtD$c?IL6uEqGpav~`xFX&Bbn0^COtbx=V& zsIJMHP+TCI)KWh&WWG_@?*_pe=5D;ZWWp6~AH7&iJXbin(uu5Mpd%^$Z#iNGWaZPOqumEt7 zWF+P{0A?r=Nq!BKZVNUx)FR{oe6rs%671oNaD%=a;eTuY0-U!p#$*d$D^Nx@3~&d8 z{Y7N9|0qeuG9SaAhh}|n_mpP>0Ep7>v0$0t%FQEQsc;+N0;8s}*yM83KNyq8__1kJ zvRt2SXS^1e*xk{CW;l4<8$0MI2M$f89e9?3lRZ$RI$u)cHwe%A=c17`_%mRgcF+y- zZQ#Q3P@oqMd^jXP6&M3GKLIe)KTsd69#M*!aL9U^aw}xPXu3iLFXX`3b}%rH*pfQ_ zY~cpfa~&rRJujXvLZ8h7Mj7=Ze>r1Ie_)!F0iscrO6EwF&L&h6o}v(tQ;*q%DWW3Lv&o~E&j8eGyHKcwI(xaM0^@`_ z{JEW13Ym#PPPK8_ZBv9f7{0?8uj>B(^~ybt?wg`UZTUJ3>yO9^5W&7PXhD|UIVCp;y!smYQFdjOdkL1 zuYX&@`7Irig7~?@aAvw#%pDs#=Zl%`+NyI_buQi6eCa`_<1TD_hM!KzYvbRvKNDn4 z!AF%DgD|7T+}ht;-?(2BpkDH@%AQSnW@vOGpL&*4W zCgiaRQ_xtcG^H9K_P{=H%qG?)G%Rx1&Fhy+@WmksuNfvX)xH}SrWq51C=4E_kpl}@ z3Ph%gj3U48N_zK{8ZfhhJ!Au?^gSL0s1zVXl_MIr^Qp)_62KP1O`Tm#`HfQf8cLDP z5YjS=so_x<)2Kc`0|=LD`VLw2s>}>1Vo^5^L%t*Xl7uBnfjSw}%7oVVp#lwHQsD0h zQ{4&1k7^z`q5!kd5c9!CvIuPMdVm(CaN3mVkiU%&Fd3y2#*!oe2qfAq#=AMjjY3RzGz4Dg}Vx-GLH*auew##LJh;0WqZ z%d#}NKebMUt<>E*=H!j!{9O{_jpRPA3*BU zWBnY<(L1J7@0pI@H4Q+x7LGo=o~%-F(dsZ)ect#@}T#f6<3YGcI zMH*jJiN>uP7%I-VztW6bNf|22xZjeDj~u*i2oOHp$lZtBCE;+f2=q(jG!(ro*=+fR*IAu>pz9C z6vJkAqmm+~Ad+AlhY_Yk2#i=byuyG;U+X~Flkl|y@K{|@D6}rZe2W(r>NaXZzJs>H z;4V>B5r7hypro$Hn6%8&i^{B4r4OnoqB!IpZQoawwigf!$o*%jg#P6h0N0>BWrm++Ki}L>aqz)1 z=NjS9S|eQFFx^op$g%T0TCj2IoqFeX{2s2-hwvbvh11|*XT1gqcAC53uTRJ)gTMb8 z*W8k{j_0iS^QXLWcaiokRdwM5U0%2+_~JoaS>tgP#Wb#C-z2M>^1=oqs>FlxmX*nE zFl?0{`KgT7>MoyAVH`kZjL*LP?A!0nw|`artGv9nu48m7x4x-j0a$q_o-gPAV!8Ag zi#-<2JU8_1c@R+B^QNI2JK_DjsZ!+i@PH!x{F>@sUQ^vxYk7Wab$)Agert7pYju8W zb$)Agert7pYju8Wb$)Agert7pYju8Wb$)Agerxq>6U3(WM3FZC@cXNCsmi%jR+ks=E-zb;rY^N%xIFEt6bySiBKW6%7u8H~ z53iwMR=wO8^$4orf_d@O@StTJn^CPtP0h$pe#%tyN?!#apj$))9ci8se zPL2d`N_x?--lhpvJA0)dLdE*freROdB-|m9I2~TBRh;gYt=~DztK}+|9K3@%;|!!GK61;M5?3w47kQ0Sxa>KK52c1Ji3z88EFSG$c0|fn-=%7a!QIK6v0m z#l~`I2i|+oow28rbwE?Zk6r8%kDlK_4T*@ZxiUz*pRd?WeEwE>TJkK&pt z%K+&cA{T{qQMWk7q|uR)U|~QJsNJnKGINQd2aS?Z$b=BV9Lq_TaBG(i z`ObyS)AAN6IWUziGUAF964{K8!{NC$WOGU#l3;t{KX)-6lYRc8?P&}n`Q(pVE{01x zjpvj_O?lVhtWlUDf1gpF9HB>SjtCY?YZpx1h-ts+A;$?)^{>zx0jVSajjWrjYXi+x zh0K&)^b~&c15-TX9ucm;hx8Wuv43dOkFDTva7piWU+;#cb)*9u0DxOhb+q#pSjJf6 z>XwzFwmBwZvDsVpG)inWkWi9YkfYS#!p2kyUIcrZ9)5=xX%qQ<=rq=f4yCpu9hOsG zxIaEk5>5dw+BlICyF@J%&QCc+WW}jTX1JL{^tW6&6`o|$VRj6si%P-0Ub2X&y7tJP z&y&7i?iDS>#`Ta&q=|=uO&1yUepQewE z_l}bAXbJY&mBm4+!Ot|&as%ciP$IX`W%w$4B{Z8Nl&7oG3mi0qym#23CXCY<36^8| zNaArM-8}ZID#phR-ov1&dz8hIxNjnlp>#i0EtpORFy(ZJ?mP0esi%WEyEyjB=K zmpf_Z8nzp7^c2BwMN{j!gwTeAdO#45AS+*SMluN0qN8lFGU`1AA%`{d;NdbRI`ORBe=MqP*>el|p*9o!Z9H@Nrw4!X*iy$Q3qn8Q_a1In z3bvJ1NzmBL8l1R25;3%<{Pb{`*KpNUm>$Bz2xTS)9?SdhiwLst{TdH#{{%DlzUhTG zGk4Ai74|Me3ulo`5~c-;%uSXi+kfCN)nCZ5lu8iGO#uC)O#Ak{T8gXC=NTKdqM}7N znq#L-l7+4IVVzmS_t7LXy5@TfQ}vvQQO&e+5Zzxr?g2LCV=D@A@*T60{@= z&oHN>rW}bAJ57-0ggo(V843Qi3WMqjR*be^Ic6EOT4#ug4j>7-ibB=Yn@rnUcI95* zl1udEljo`)sxy$>8P|QKR7gh_8 zWAsvraHExd6(TgRbvw0X#OkOH`?&q1m8{h;4-~);uMYslGt59X)=ehdVjh>)00;H_ z79f0B=?qvc4gEaa7x$>xEZqXX>twHmQ4UG=n>cnbEKH}yMu=gBVfdCJiPsFP3~d}X zL>Kid73(4%(g@dJtSEG&4E`|CO%?@NIlHX+32_`iK0fGs=jcZv;eYJ-f45Ax$_J7h z*>AM1dga@>L2bUZpn~Juv)z41FFInD){QNX!M!7H(Ye(YfJ$u5U#S9CcW&uU)2E&% zaKT*-CQgJ^oKr@@UgOv}(TZZrbmk}KPM{*eM?XyOB!q53m5{9lkNT{cve$BqP_JY< zdchDEo`DJUM4rbU$uSG|*{IXA5r4P9UapCO;;|pY-G8swnx#~c01O+B z_$59rxD(aSs^z3pwE?DtB|I9dO^%*m#H%H8&X@R%EBWKV!U>CAr*iAmy**aVgGk}p zU9oGuLiK;iW(L$;nple|xg%IX~Z`@ZTcV?>)8`f|DUpMAPdWi<*y(n^!PFB`4e zXbur_iZZ{H_`2&T*hq|_4{zR6hFwF207GLa)MYB0w5zHk+ktbP%OJ0X34No<3EX)^^+yNvOI(EkYPvJBl{nM_+>GvjTi}PCg&8q@Uw#Zf_~;T z%KoJE1j8F<>yTjC*h!3H8+m5>e8#x8e>z8dC2D{0GOiMl!NiEqa$F28rX}Xutw5Af z;!fvubJuQ75cKm zV;r8XKlS|v|j7kw0d${J8B#E^sU;(EhhrS0EF;OGTIqMYL%;|@tTy8 z9@o%_H8n(-azh-e7K9CRa+Pxc<+=$=moiodBzh_ifqTOyP>lO6}y zi>zUyt6Juy%c^=g%9dpjdbd_t`Rj?q!2JD**mtD+7W{;tXai`ME#s@QijG z63m#eS-OkT#qvk^@h@ch3(0*ce9|K9YUH#~s!S56E272z0jfA5Rrs1C{Z>HSjNU9> z^+it@7^+dK6i!?s`>DRtMtm1jv5}HL5dlhgsZf@wuaQZ)l~r&U{mQuw6^1M8het%B?zxhicbIg2ALwZ{ z=6h=RFY~+TNLxccORL6Z^7w`e2c^;Vy4UQKkbz|>jf29koaQ{68 zk%=O0=9sTe=|*}j{4T`$981cWL|%=%8e_SOC+(sKEr6|Fgb%N_ELidf4?o`GK_RPrIgIqm2c6lDp3q&HkSN zenAMAO}Z{hwr@8#Q~qX{=GiO{%YM>4wf0OOqx~<^`4u@j_zznki=Quddr-BTAPq%s z=DfnTx28a&olSH~t^nbH+Y3q(rG*&A&?s0&fbsOEuDCnt7fhOO7E$S<`~yZu7~$b~ z7#1sd-dQ8~T)&7KAwL`QH~i%8`Oa$D@3y-B*mFZ-%UCS5$t@8$pQ& z6Ok)%)f-j!BpaSmOQcam7}yg;^~Gr1VFzpU6+^FRBq|o8^40qYEqRI-S#;VEL~fNm z9SE9K_NBzZC~uk2A0_oQOf2d#wx@DSh5w3+i*Ci*5$cIjKcp+D5w;}7z-z>4WZq>! zzfiksT)e**y!`|{NeLo2&Wn|ZPfboi#tGk2cPI*Qdxt9FRpI)QjuxJXGq=Yn$%kB2 zJ6U~q2&_uwkh9V1nQw4GEh1u|tD`lA55_oN`Jonk*~YS{WVKlR;W-`l5%I3|{Mee< z7N0R-bxLd&QUcY3EfaeU=iqP+=Z`__XsA-CH;Be;Tz=cDthTpVjdiK-vMRS^b?093 z?0j5s+%eRK+q4!`VUfrRCR+CBea@5elY#Wp+BPQj*dDQ;^N=^%Av&~j;HikoZh-h6 ztd-kxU7ccza#@h1u>HJl70fqFVxb^~7XM_^qw?I=dykuO>uF^rPw&C4Ein`C`l= z;N^Cm%-`$wqHY^CmyAxCW{aN#LA~GRkz|ICyj}duJKQ9M9>FMu<1W*%qT_Zfs@WUj zADEhN24g1z{4h&XD^~5$jc}$AYSusk=mt1e364vhA+Fb)cO*EHw79zW{lbSpsZ&(=P*>){c|V5P z>P;6G0&e%(Fhsvl$s9i)9AEFyJV>E>L*}Som)%g}?~ITI_*+vlJe|#s2yhYNw+1f0 zpjnY6(}vONFDj$HK-Y0hF5Os$QD@*Isg&mRA zU>(HA%`*jj7xud?KkxfEQo#W#hj4HGahs&u#@!}%A=kQ+H8q-nJF;)8G1f-fpIBBGVYRG(0AeOiEdLr68h!SWBd zGXUQ=nB$`UMw|1Wm>f(-P_c%K?V)05;cy(47JQ$kw)Ib*Oyo=g*qbPwNXZwPKNCHYhp{Ybl9Q8} z!N=4~)RBV3*mE&0@{AnL1deePp%QOGdQD<>=jbfZV5a;W>`Bw!wxi!~^=fBscqrj8?!Q zAQg{mt4822G0XZBckRPcJr6BmhYOL~PW>+311IgsY%B|HSzWU=or3k#bsXqr=4=I{ zv`_V(&DEcDN@q6bNBEtokyyX4ZSmOOfPV2>a%MtUuA6&@1XnNOuSna${ty&)WQI0p zx;@8`ZEnC1$Mhd^@jY(q`*ZsRM7UgqJ2)MgAp1uI8=`zs@Mo(T14;dw0Xk8mxMKXl_+k4JAht`;7%{Z)d&OOf591CL`zbjR z1w;&h`lkEaA^Rj0dj9ktqgEx^#I&W!7kj?|Eq;(z-FU5c`pq@B+J{!1LvQHn)t=3z zdG=$Lz!BG_5cb^;(6ElYkj+O*C-Ek8ogb^wa1nCdjjH<*HO=*YZfG~)wWpQBFc<^UK<8@euoHn47^j9Fd)$?^aO8{ws)@WeA2(`o2;eLc)1jx|>HUQX z=6Co)zT$@M(kL~YpDK~s5dUHuYo6P1wp`)8JU#>q_i7qb1LWU)X(r)9G7F}*KhcSP zZr-STXTX+S)F4pMG_!f-?273M)pgj`o-uUQYwOn);bj&muX%295*k>bQ>!A-kRoZ> zIH<~E>?fA~yyoE3xp>&}oHe`c`;PlE4>NJ;tj$wIlD5!*lu;yxuKEN$&| zg{^Gj^~(IHOMs*tg;x?ky5VGs=&d~k;SvqMDI=pBpb-GYKqYZZ0QV<`ah1)9R=YB% zjTZuj)x!-CBbpdBLPQd`U;X<8SSwgkZTHfed<*6&c@5W+@BUsQCUMLc{)+6DQ+PYN zvi^g>rgkN;c(Y$Vu3*)fi0d%OTLCAHD4L|2-z#79wu~w0?|+L0n(T247pxdxTeqtl zP#SGX>#_D(o~Rc{g$I163IKBe?G9a+&Wq)ji5M8%Pc!-yQ%4rH6Tgucur)p~;j7nc z(vEx~W9|w}g)8m%OZ<4v{{ZS#v!Yx5He_pT|4AcNQ~INE@)^IjC`5J%=&51!;A&!x zt}$JrAW_XW;!YDOkTE#-?9VQKw)PVDP_IuJ;i5jG*1qP)sgYS}g}DN)?k?Fm zkkKZ&CeNY5QV0?j=Hpd5P>SAC!MI;S9}JWO*~Km|_Ek-ES9Umj4$O@64?k0wQ5G; zOGe8=cqmlQt(-1|VZAv$$I7XFZcal(j*OoX0V6=B)IM2%$x2fFl7^JRpP3t92}}Zm8ANh6F-36frZoeSU*B$hIT_%*@1|%DEI-pw+&ilG0b+d?8+$OAuTU@<;$tcirEwx0X z%>eZY<7Fu=3Z5vkI>P3wh@E>pzeD(^b0NsXIAdB zgK?SM#c>JaKe{{VMQoo2N?V74HseYpUC(~4wzX64981fF56B27uG9rT(?s-Jus1Ak ze=5G3_~t|)gOA3N5ws=h34@m~YQl}UV5%u}Q3tI5p|aq#n_g^k)<;wFRX)WUhZSZT z@x%P2$Uqx#MJSVCB?&&oP>lFDDwie$R4a8SHPI1v`)!6l*UrMK!}8oJuiDuqL_uU< zJlu;Au@s9%hZLOo+XQz)GR%q4xzsrmu3=gtl}4{b64WR-<%jc`fIS@5cC=_wBrW_^ z*@Mo;rbFr!HZE?+jQ!%HKJ$RKRcbyQv>BKs9C>ZGEy58xD8^(xee!!G{cy7n4^{jo5yDPRmPxDMirT~i9dhR-rbj>B`(nmsMt}a|) zfHm?}H@n5L3XgN{3zuo_6^IzV8?f=7OoO|0Y6L)WzyjG4Qlbwhz z)5b!gXJK&s5{XNP&R#iKuVgDDVVUTDn6dmH&wS(Jd2gfWvk?%g&h6cxsCoE zf!U=)5D|Mq98|&Z55B<;%_si@vs?b3735%;4!Ut6u`5Jpl|-N54eW!wf1&=fx7#T7 ze?|QN@d*6yphN+rBQ6?U;nkk zPSCk!9il*uRDy*@g#lTEo1z*j#MlCo^u>4B&R*Duw^y3@*1M6j5JT3-bLjVYm}v01 zE9XygwrbvXl{LRQ^L5%bLn zW85Cbb;q;9@U$LS9uz8j%}T}iwXgQB9XHelPvD+N2eVfreI-_1u7Cm*=0sFDwqArn z{r*R^&u0x)t~FM@Km2HQH~5$}bQQC_5jB^moC*Ytz6-EjQgp2+;+x}tg8da44zlpr zwAHR@E9Q)8835HiHfr%L~O0MUFhTXe!5Y;S9nB- zW7#aNP0tp+%f83|r`RhB@MO+36QjK2guhRsRzpMPxiKk(DhvKByD*Gif{@HAr%QPM zPqCMfh=tzEr;&3MtxXFTd&C|i_j3#Z;xM1E^#WGyNM}&CYWlkh-pu?$%FQmP`PX^1 zGUxD2d7JAw$PkeQP~8D15j%C<=Cl$XTucp9VlD(e?U%CNok_pR(}E&RRSq%1Z@h}WBT^Sq zYDWs0mh8ylAa!!CJ@WWPttdLlWOkhJSj!CuIdHse=Y}l*u;!$aAd7ltEKY=M^s}Ji zhTz>GwduD}x$zEl);>u#L^kabD6$QTVW40XAkFn7vc!@|ZZ-vBe_VxkR=k7-ttW?p z!kL`G$ZN8_y78CGehNJEEQcx{&!ENZAmGR6rnKKXktNkLs4bf?pB1P`M?2sF2z#;> zyxMw%pYvdI*wPMJnYL#`ep!0$(9h2L&gC&;C0aC>M0^GKJ5-UlV_nu~TSmMduUn{key&wQaw9~O zqa4+61LD->3iXy};dCT&0L!mgMK^@(Y_Ziezl_H*Pg7~Tu}q6su;4z2wtL=|TZ;S% zq)VBdyiS_FO4sYmpN>Dek+T3#DPGYv6-)6`H@%vtUH*k(p8vqIPIiH5bZ|z|(8N^w zG&;|_?d<-T21DO!h>sajK!fE9#KBhn^~68=mH5BwS1`nX^{Z0ulj>?|GGuW+R36t( zFE`c^k@B6h0w_hfK)QrxG9+gYw2psvN11aK9l! z%Q2%72uqRCF)iLJI@Ef2mjzgtM^u6w66hc*Haa08qwyg&y03rr zEuG_wlm7VOoD0WkwcIjRpH56mnPW%lqZ+h&0vtelUaU!dDl;=74w$hQ*V&Jt=seRQL$yogE(i*pZ$APZ)hdN&)9OiWyG(KF5AE~LN5swN5s@tkXu z7_U@UX3xg3#RP*r7`e&Dz{arx*t>R_*141rqPDVV`Y!l;^6FRJD>pC*5`3l`0^suT z>Z|3cI(=B_Tecg z8KLK?vXWIISMDQ+m4Nb+Pua@mL|EAN8Z7x<0g1)jx2*eUZ{)W%YvmYtp<-e7OK0ve z%%Ju$Tau9Y@jSW3yfT~!?&xYi;~f(QtmeR}H^bl4okE7qn{A?@R}>C!`^g3dyt;Vl zG(uJz^No}_U+dD`{CI~R85yh_E76h9hN>8C`*5C`hc!{Amn{~waP5j#n$7x@zpQ6O z&X$u+b}r{gA*bL7>7}MDV@|b$EQcN1{1kVZoVdPzO;9TMvaWce$}A0(b50F>&$|x+(zM$T^sEQ7|xnInBc6% zhC-EvR}Xu4U*xA^5~_X{66)8OO0+VL)!1EKtX6fjH3RN@HCp(_uNxe+p74?Z zCRK_;Uvs?r3lqZxsszw{tQboCXjf3@nIGQ;6wGOQ1_kPf9{D43h?^pR;|&yS7%LhJ^zhub>q;T- zBIjirhRpjd&qv1|uc@9$@eXqIDj6B>400m4zBZxFI1`+4_3VrNM(yjLzg?-WoTMoH zJq_-izCZ2C6|+UhWR52m78gm`Tr_)oD&%|ipp8?z0G|%;9=q;2>Y%&ikedKW5|hAPR1Q^;6UeEGABN@cO&>$wFE_b)I+^$0e`ICq@!E&YO_HBX||PbHN`!zZzfe&EiS<)|ql!6$S7+uE|N*TFe-Z*wS3Dys6Pq^;XV0@)Dy zo`MLewEY3y)kId*r43-VV+218GT#rmWxtA!OS^a{C^&+J&Xd<&f_pNA>`nDqk8!~c zS>tQqvNp-I5G<#72ni}`tIw&|Wiw^8{aCAA*ZFN)?wSed^J3-YfU+H#@Smv span["start"] + + def test_enter_rejects_a_primary_with_no_instructions(tmp_path): owner = tmp_path / "task-accuracy" owner.mkdir() @@ -70,39 +92,82 @@ def test_collect_inventory_defaults_to_package_with_limit(): assert not envelope["retrieval"]["selection"]["ranking_applied"] -def test_catalog_and_collect_share_package_rank_with_the_same_filters(): - query = "graph mode dynamic shapes" - filters = ("--repo-type", "inferrsi", "--backend", "ascend", "--limit", "4") - code, stdout, stderr = run_cli("knowledge", "search", query, *filters, "--explain") - assert code == 0 and "Find ranking" in stderr - catalog = json.loads(stdout) - code, stdout, stderr = run_cli("collect", "--kind", "knowledge", query, *filters, "--json") - assert code == 0 and "Find ranking" in stderr - collect = json.loads(stdout) - expected = [(item["ref"], item["score"]) for item in catalog["retrieval"]["items"]] - assert len(expected) == 4 - assert [(item["ref"], item["score"]) for item in collect["retrieval"]["items"]] == expected - assert catalog["retrieval"]["calls"] == ["knowledge search", "find"] - assert collect["retrieval"]["calls"] == ["collect", "find"] - - -def test_collect_accepts_find_as_an_explicit_ranking_method(): - query = "cache per-step masks ran out of device memory" - method = ("--relevance-method", "find-lexical-v1") - code, stdout, _ = run_cli("collect", query, *method, "--kind", "case", "--json") +def test_catalog_list_explains_an_unranked_inventory(): + code, stdout, _ = run_cli("knowledge", "list", "--repo-type", "mlx", + "--limit", "1", "--explain") assert code == 0 result = json.loads(stdout) - assert result["selection"]["method"] == "find-lexical-v1" - assert result["items"][0]["ref"] == "checkout:case.qwen-ascend-rejected-directions" - code, stdout, stderr = run_cli("collect", "--relevance", query, "--kind", "case", "--json") - assert code == 0 and "Find ranking" in stderr - assert json.loads(stdout)["items"] == result["items"] - stderr = run_cli_error("collect", query, *method, "--id", f"package:{SOURCE}") - assert "explicit IDs" in stderr - stderr = run_cli_error("collect", query, *method, "--relevance", "cache") - assert "one" in stderr and "relevance" in stderr - stderr = run_cli_error("collect", query, "--relevance-method", "weighted-lexical-v1") - assert "find-lexical-v1" in stderr + observation = result["retrieval"] + assert observation["calls"] == ["knowledge list"] + assert observation["selection"]["state"] == "not_requested" + assert observation["counts"]["matched"] == 3 and observation["counts"]["returned"] == 1 + assert result["items"][0]["id"] in observation["items"][0]["ref"] + + +@pytest.mark.parametrize("argv", [ + ("knowledge", "search", "graph mode"), ("knowledge", "research", "Model"), + ("collect", "graph mode"), ("collect", "--relevance", "graph mode"), + ("context", "graph mode", "--repo-type", "inferrsi", "--backend", "ascend"), + ("campaign", "capture-context", "--directory", ".", "--id", "r1", "--relevance", "graph"), + ("campaign", "capture-context", "--directory", "absent-directory", "--id", "r1", + "--relevance", "graph", "--relevance-method", "find-lexical-v1"), + ("campaign", "knowledge", "--session", ".", "--query", "graph mode"), + ("benchmarks", "session", "knowledge", "--session", ".", "--query", "graph mode"), + ("cannbot", "search", "graph mode"), ("mindie", "query", "--input", "query.json"), +]) +def test_retired_text_queries_point_to_find(argv): + assert "find" in run_cli_error(*argv).splitlines()[-1] + + +def test_collect_attachment_cue_keeps_the_explicit_owner(): + identity = "package:inferrsi.common.skills.calibrate_serving_simulation" + code, stdout, _ = run_cli("collect", "--id", identity, "--relevance", "serving", + "--context-bytes", "65536", "--json") + assert code == 0 + result = json.loads(stdout) + assert [item["ref"] for item in result["items"]] == [identity] + assert result["selection"]["scope"] == "context-resources" + assert not result["selection"]["ranking_applied"] + + +def test_exact_capture_keeps_the_pinned_owner_and_its_selected_attachments(tmp_path): + from inferrsi.apps.workflows.campaign import verify_capture + + ref = "package:inferrsi.common.skills.video_diffusion_optimization" + revision = KnowledgeReader().read(ref).revision + options = ["--revision", f"{ref}={revision}", "--context-bytes", "65536", + "--relevance-method", "find-lexical-v1"] + cue = ["--relevance", "numerical parity"] + + def resources(argv): + _, output, _ = run_cli("collect", "--id", ref, *options, *argv, "--json") + context, = json.loads(output)["contexts"] + assert (context["ref"], context["revision"]) == (ref, revision) + return context["resources"] + + complete = resources([]) + selected = resources(cue) + assert [Path(item["path"]).name for item in complete] == ["SKILL.md", "campaign.template.json"] + assert selected == complete[:1] + + run_cli("campaign", "init", "--directory", str(tmp_path), "--id", "manual") + _, output, _ = run_cli("campaign", "capture-context", "--directory", str(tmp_path), + "--id", "one", "--id-ref", ref, *options, *cue) + receipt = json.loads(output) + raw = (tmp_path / receipt["context"]).read_bytes() + assert receipt["sha256"] == hashlib.sha256(raw).hexdigest() + capture, state = verify_capture(raw) + assert state == "verified" + assert capture["request"]["revisions"] == {ref: revision} + assert capture["request"]["relevance"] == "numerical parity" + assert capture["request"]["relevance_method"] == "find-lexical-v1" + assert capture["retrieval"]["selection"]["state"] == "explicit_ids" + assert capture["selection"]["ranking_applied"] is False + context, = capture["contexts"] + assert (context["ref"], context["revision"]) == (ref, revision) + body, = context["resources"] + assert body["content"] == selected[0]["content"] + assert {"path": complete[1]["path"], "reason": "not_relevant"} in context["omissions"] def test_collect_reports_explicit_no_match_with_omission_reason(): @@ -145,43 +210,49 @@ def test_material_delivers_procedure_and_exact_resource_preserves_raw_source(aut KnowledgeStore(tmp_path, skill_root=SKILLS).create(local_candidate(source)) identity = f"store:{LOCAL}" source_args += ["--store", str(tmp_path)] - code, stdout, stderr = run_cli("read", identity, "--material", "--omit-resources", *source_args) - assert code == 0, stderr - view = json.loads(stdout) - code, stdout, stderr = run_cli( + procedure_pages = read_pages("read", identity, "--material", "--omit-resources", *source_args) + view = procedure_pages[0] + raw_pages = read_pages( "read", identity, "--revision", view["revision"], "--resource", view["entrypoint"], "--omit-resources", *source_args, ) - assert code == 0, stderr - raw = json.loads(stdout)["content"].encode("utf-8") - delivered = view["content"].encode("utf-8") + assert raw_pages[0]["revision"] == view["revision"] + raw = b"".join(page["content"].encode("utf-8") for page in raw_pages) + delivered = b"".join(page["content"].encode("utf-8") for page in procedure_pages) assert b" inferrsi: |" in raw and b" inferrsi: |" not in delivered assert raw.split(b"---", 2)[2] == delivered.split(b"---", 2)[2] - proof = view["content_view"] - assert proof["locator"] == "skill-procedure" - assert proof["source_sha256"] == hashlib.sha256(raw).hexdigest() - assert proof["sha256"] == hashlib.sha256(delivered).hexdigest() - assert delivered == b"".join(raw[start:end] for start, end in proof["source_byte_ranges"]) + source_digest = hashlib.sha256(raw).hexdigest() + for page in procedure_pages: + proof = page["content_view"] + content = page["content"].encode("utf-8") + assert proof["locator"] == ("byte-range" if "content_range" in page else "skill-procedure") + assert proof["source_sha256"] == source_digest + assert proof["sha256"] == hashlib.sha256(content).hexdigest() + assert content == b"".join(raw[start:end] for start, end in proof["source_byte_ranges"]) @pytest.mark.parametrize("identity", [ "package:vllm_omni.common.diffusion.step_state_and_output_validation", "package:inferrsi.common.skills.calibrate_serving_simulation", ]) -def test_read_can_omit_inventory_without_changing_material_or_revision(identity): - args = ("read", identity, "--material") - code, stdout, stderr = run_cli(*args) +def test_read_lists_inventory_separately_from_material(identity): + pages = read_pages("read", identity, "--material") + assert all("resources" not in page and "required_resources" not in page for page in pages) + pinned = ("read", identity, "--revision", pages[0]["revision"]) + code, stdout, stderr = run_cli(*pinned) assert code == 0, stderr - full = json.loads(stdout) - assert "record.json" in full["resources"] - assert "content_view" not in full - assert full["resources"]["record.json"] == hashlib.sha256(full["content"].encode()).hexdigest() - assert full["required_resources"] - - code, stdout, stderr = run_cli(*args, "--omit-resources", "--revision", full["revision"]) + inventory = json.loads(stdout) + assert inventory["revision"] == pages[0]["revision"] + assert "content" not in inventory + assert inventory["entrypoint"] == "record.json" + content = b"".join(page["content"].encode("utf-8") for page in pages) + assert inventory["resources"]["record.json"] == hashlib.sha256(content).hexdigest() + assert inventory["required_resources"] + + code, stdout, stderr = run_cli(*pinned, "--omit-resources") assert code == 0, stderr assert json.loads(stdout) == { - key: value for key, value in full.items() + key: value for key, value in inventory.items() if key not in ("resources", "required_resources") } @@ -290,11 +361,13 @@ def test_malformed_revision_pairs_are_input_errors(): def test_collect_material_appears_in_text_and_json_modes(): - code, stdout, _ = run_cli("collect", "Qwen", "--limit", "1", "--material") + args = ("collect", "--id", "package:inferrsi.common.skills.calibrate_serving_simulation", + "--material") + code, stdout, _ = run_cli(*args) assert code == 0 assert "--- begin content package:" in stdout assert "--- end content package:" in stdout - _, json_stdout, _ = run_cli("collect", "Qwen", "--limit", "1", "--material", "--json") + _, json_stdout, _ = run_cli(*args, "--json") envelope = json.loads(json_stdout) assert envelope["items"][0]["content"] @@ -310,9 +383,9 @@ def _escaped(value: str) -> str: def test_collect_text_lines_match_the_json_envelope(): - code, stdout, _ = run_cli("collect", "Qwen", "--limit", "2") + code, stdout, _ = run_cli("collect", "--limit", "2") assert code == 0 - _, json_stdout, _ = run_cli("collect", "Qwen", "--limit", "2", "--json") + _, json_stdout, _ = run_cli("collect", "--limit", "2", "--json") items = json.loads(json_stdout)["items"] assert len(items) >= 1 # Item lines are the ones whose second field is the content revision. @@ -337,7 +410,7 @@ def test_collect_text_lines_match_the_json_envelope(): def test_collect_reports_no_match_omissions_and_collisions_in_text_mode(tmp_path): - code, stdout, _ = run_cli("collect", "zzcollectnomatchqvf") + code, stdout, _ = run_cli("collect", "--kind", "case", "--repo-type", "mlx") assert code == 0 assert stdout.strip() == ( "no_match\tnothing selected from the requested sources; " diff --git a/tests/knowledge/test_knowledge_compatibility_shells.py b/tests/knowledge/test_knowledge_compatibility_shells.py index a854b7336..2ad404b74 100644 --- a/tests/knowledge/test_knowledge_compatibility_shells.py +++ b/tests/knowledge/test_knowledge_compatibility_shells.py @@ -58,6 +58,8 @@ def test_retired_root_name_fails_and_moved_exports_match_current_contract(item): "RELEVANCE_METHODS", "TASK_RELEVANCE", "words", "lexical_score", "raw_string_lexical_score", "skill_score", "task_score", } + if item["importer"] == "research": + retired_rankers = {"research_knowledge"} assert retired_rankers <= set(names) for name in names: assert hasattr(moved, name) == (name not in retired_rankers), name diff --git a/tests/knowledge/test_knowledge_find.py b/tests/knowledge/test_knowledge_find.py index fd5aa78d4..579fc2811 100644 --- a/tests/knowledge/test_knowledge_find.py +++ b/tests/knowledge/test_knowledge_find.py @@ -136,14 +136,14 @@ def test_catalog_ranks_find_documents_over_the_filtered_package_scope(corpus, qu _, _, scored = rank(query, Corpus(eligible)) assert scored - result = search_knowledge(query, **filters, limit=5, explain=True) - assert result["items"] == [ - by_find_ref[eligible[index].qualified] for _, _, index, _ in scored[:5] + result = find(query, Corpus(eligible), limit=5, explain=True) + assert [(item["id"], item["score"], item["matched"]) for item in result["items"]] == [ + (eligible[index].identity, round(score, 2), detail) + for score, _, index, detail in scored[:5] ] - assert [(item["score"], item["components"]) for item in result["retrieval"]["items"]] == [ - (round(score, 2), detail) for score, _, _, detail in scored[:5] - ] - assert result["retrieval"]["counts"]["matched"] == len(scored) + assert result["matched"] == len(scored) + with pytest.raises(ValueError, match="Use find"): + search_knowledge(query, **filters, limit=5) def test_repeated_query_terms_contribute_once(corpus): @@ -340,6 +340,17 @@ def test_reference_survives_a_root_whose_path_has_spaces(tmp_path, capsys): assert shlex.split(item["ref"]) == item["open_argv"] +@pytest.mark.parametrize(("args", "message"), [ + (["question", "--backend", "cdua"], "backend"), + (["--model", ""], "unrecognized arguments: --model"), + (["question", "--repo-type", "inferrsi", "--skill-root", "custom"], "custom --skill-root"), +]) +def test_invalid_find_scope_is_reported(args, message, capsys): + with pytest.raises(SystemExit) as error: + main(["find", *args, "--no-external"]) + assert error.value.code == 2 and message in capsys.readouterr().err + + def test_finding_order_is_not_decided_by_corpus_common_terms(corpus): """"the" occurring three times in a one-line finding must not outrank the term the caller asked about.""" @@ -674,7 +685,7 @@ def test_find_bounds_caveats_and_sizes_the_opened_content(tmp_path, capsys, limi assert f"{len(limitations) - len(shown)} more recorded limitation(s)" in out -def test_find_size_hint_allows_a_later_unpinned_checkout_edit(tmp_path, capsys): +def test_find_size_and_read_command_belong_to_the_selected_checkout_revision(tmp_path, capsys): _plant_custom_case(tmp_path, { "id": "case.demo", "kind": "case", "content": "demo.md", "state": "historical_observation", "attribution": "Local demo", @@ -687,9 +698,13 @@ def test_find_size_hint_allows_a_later_unpinned_checkout_edit(tmp_path, capsys): path = tmp_path / "demo/cases/demo.md" assert hit["next_read_content_bytes"] == path.stat().st_size revised = "新修订的较长证据。\n".encode("utf-8") - path.write_bytes(revised) assert main(hit["read_args"]) == 0 - assert json.loads(capsys.readouterr().out)["content"].encode("utf-8") == revised + original = json.loads(capsys.readouterr().out) + assert original["revision"] in hit["read_args"] + path.write_bytes(revised) + with pytest.raises(SystemExit) as error: + main(hit["read_args"]) + assert error.value.code == 2 and "revision" in capsys.readouterr().err.lower() assert len(revised) > hit["next_read_content_bytes"] @@ -847,8 +862,13 @@ def test_cli_reports_findings_and_path(capsys): def test_cli_json_mode_states_its_limits(capsys): - assert main(["find", "ascend device health", "--limit", "1", "--json"]) == 0 + argv = ["find", "ascend device health", "--limit", "1", "--json", "--no-external"] + assert main(argv) == 0 payload = json.loads(capsys.readouterr().out) + with pytest.raises(SystemExit) as error: + main([*argv, "--context-bytes", "0"]) + assert error.value.code == 2 + assert "unrecognized arguments: --context-bytes" in capsys.readouterr().err item, = payload["items"] assert item["id"] == "ascend-device-health" assert item["source_location"] == "installed" diff --git a/tests/knowledge/test_knowledge_install.py b/tests/knowledge/test_knowledge_install.py index 95c5ba7b6..a0de39c8e 100644 --- a/tests/knowledge/test_knowledge_install.py +++ b/tests/knowledge/test_knowledge_install.py @@ -60,16 +60,13 @@ def test_package_only_commands_work_without_pyyaml(without_yaml): assert json.loads(result.stdout)["id"] == items[0]["id"] query = "ascend graph mode" - catalog = _run(["knowledge", "search", query, "--limit", "1", "--explain"], env) + catalog = _run(["knowledge", "list", "--repo-type", "inferrsi", "--limit", "1", "--json"], env) assert catalog.returncode == 0, catalog.stderr - searched = json.loads(catalog.stdout) + assert json.loads(catalog.stdout)[0]["repo"] == "inferrsi" target = "inferrsi.ascend.skills.ascend_graph_mode" - assert searched["items"][0]["id"] == target - assert searched["retrieval"]["selection"]["method"] == "find-lexical-v1" - - research = _run(["knowledge", "research", query, "--limit", "1"], env) + research = _run(["find", query, "--repo-type", "inferrsi", "--limit", "1", "--json"], env) assert research.returncode == 0, research.stderr - assert json.loads(research.stdout)["items"][0]["record"]["id"] == target + assert json.loads(research.stdout)["items"][0]["id"] == target def test_packaged_skill_search_and_resource_work_without_pyyaml(without_yaml, tmp_path): @@ -83,7 +80,7 @@ def test_packaged_skill_search_and_resource_work_without_pyyaml(without_yaml, tm assert opened.returncode == 0, opened.stderr read = json.loads(opened.stdout) - collected = _run(["collect", "--relevance", query, "--limit", "1", "--material", "--json"], env) + collected = _run(["collect", "--id", read["ref"], "--limit", "1", "--material", "--json"], env) assert collected.returncode == 0, collected.stderr packaged, = json.loads(collected.stdout)["items"] assert packaged["authority"] == "package" @@ -92,8 +89,15 @@ def test_packaged_skill_search_and_resource_work_without_pyyaml(without_yaml, tm assert read["id"] == packaged["id"] assert read["revision"] == packaged["revision"] assert read["content_resource"] == original - assert read["content"].encode("utf-8") == expected - assert hit["next_read_content_bytes"] == len(expected) + assert hit["next_read_content_bytes"] == len(read["content"].encode()) + received = read["content"].encode() + page = read + while "next_read_args" in page: + opened = _run(page["next_read_args"], env) + assert opened.returncode == 0, opened.stderr + page = json.loads(opened.stdout) + received += page["content"].encode() + assert received == expected output = tmp_path / "packaged-skill.md" fetched = _run([ @@ -110,26 +114,47 @@ def test_capture_scope_skill_delivers_packaged_text_without_pyyaml(without_yaml, created = _run(["campaign", "init", "--directory", str(campaign), "--id", "lean"], env) assert created.returncode == 0, created.stderr result = _run([ - "campaign", "capture-context", "--directory", str(campaign), "--id", "r1", - "--kind", "skill", "--limit", "1", "ascend graph mode", + "find", "ascend graph mode", "--session", str(campaign), + "--kinds", "skill", "--limit", "1", ], env) assert result.returncode == 0, result.stderr - capture = json.loads((campaign / json.loads(result.stdout)["context"]).read_bytes()) + hit, = json.loads(result.stdout)["items"] + opened = _run(hit["read_args"], env) + assert opened.returncode == 0, opened.stderr + read = json.loads(opened.stdout) + capture = json.loads((campaign / read["reference"]["path"]).read_bytes()) item, = capture["items"] context, = capture["contexts"] assert item["ref"] == "package:inferrsi.ascend.skills.ascend_graph_mode" assert context["revision"] == item["revision"] original = context["resources"][0] - assert original["path"] == item["skill_documents"]["original"] + assert original["path"] == hit["body_resource"] == read["content_resource"] source = ( SKILLS / Path(original["path"]).relative_to("data/skill_library") ).read_bytes() - assert original["locator"] == "skill-procedure" + assert original["locator"] == "byte-range" assert hashlib.sha256(source).hexdigest() == original["source_sha256"] procedure = b"".join(source[start:end] for start, end in original["source_byte_ranges"]) - assert original["content"].encode() == procedure + assert original["content"].encode() == read["content"].encode() == procedure assert hashlib.sha256(procedure).hexdigest() == original["sha256"] assert capture["omissions"] == [] + received = procedure + page = read + while "next_read_args" in page: + opened = _run(page["next_read_args"], env) + assert opened.returncode == 0, opened.stderr + page = json.loads(opened.stdout) + capture = json.loads((campaign / page["reference"]["path"]).read_bytes()) + resource, = capture["contexts"][0]["resources"] + assert resource["content_range"]["start"] == len(received) + data = b"".join(source[start:end] for start, end in resource["source_byte_ranges"]) + assert data == resource["content"].encode() == page["content"].encode() + assert hashlib.sha256(source).hexdigest() == resource["source_sha256"] + assert hashlib.sha256(data).hexdigest() == resource["sha256"] + received += data + from inferrsi.knowledge._skill_selection import skill_procedure + + assert received == skill_procedure(original["path"], source)[0] def test_custom_skill_does_not_open_the_installed_projection_without_pyyaml(without_yaml, tmp_path): diff --git a/tests/knowledge/test_knowledge_operations.py b/tests/knowledge/test_knowledge_operations.py index 260953c7d..81796f868 100644 --- a/tests/knowledge/test_knowledge_operations.py +++ b/tests/knowledge/test_knowledge_operations.py @@ -10,12 +10,36 @@ IdentityError, KnowledgeReader, RevisionConflict, + resolve_resource_key, safe_path, + service_body, ) ROOT = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" +def test_service_attachments_belong_to_the_source_record_or_a_declared_edition(): + from inferrsi.knowledge.catalog import lookup_record + + record = lookup_record("vllm.common.llm.bounded_serving_measurement", file_fingerprints=False) + primary, metadata, _ = service_body(record) + assert primary == "record.json" and json.loads(metadata)["id"] == record["id"] + edition = record["skill_documents"]["en"] + assert service_body(record, edition)[:2] == ( + edition, (ROOT / edition.removeprefix("data/skill_library/")).read_bytes(), + ) + skill = lookup_record("inferrsi.common.skills.inference_benchmark_design", + file_fingerprints=False) + link = next(name for name in skill["skill_metadata"]["references"] if name.startswith("../")) + path, raw, _ = service_body(skill, link + "#section") + assert raw == (ROOT / path.removeprefix("data/skill_library/")).read_bytes() + with pytest.raises(ValueError, match="Unknown resource"): + service_body(skill, "data/skill_library/systems/frameworks/mlx/" + "lazy-evaluation-stream-lifetimes/SKILL.md") + with pytest.raises(ValueError, match="Unsafe bundle path"): + service_body(skill, "") + + def test_normalized_sources_and_original_catalog_identity(): reader = KnowledgeReader(skill_root=ROOT) repository = reader.read("audit-vllm-kv-lifetimes") @@ -153,7 +177,9 @@ def test_incidental_files_and_hashes_do_not_affect_reads(tmp_path): (directory / "__pycache__" / "x.pyc").write_bytes(b"\0") reader = KnowledgeReader(skill_root=tmp_path) assert reader.read("selected").revision == before - assert reader.collect("sha256", kind="skill")["no_match"] + from inferrsi.knowledge.knowledge_find import find, load_corpus + + assert find("sha256", load_corpus(tmp_path, kinds=("skill",)))["no_match"] def test_qualified_identity_rules(tmp_path): @@ -261,6 +287,20 @@ def test_unsafe_resource_paths_fail(path): safe_path(path) +def test_body_links_respect_exact_keys_and_the_bundle_boundary(): + body = "guide/SKILL.md" + members = {body, "guide/note.md", "note.md", "cases/case.md"} + assert resolve_resource_key("note.md", body, members) == "note.md" + assert resolve_resource_key("./note.md", body, members) == "guide/note.md" + assert resolve_resource_key("note.md#setup", body, members) == "guide/note.md" + assert resolve_resource_key("guide/note.md#setup", body, members) == "guide/note.md" + assert resolve_resource_key("../cases/case.md#setup", body, members) == "cases/case.md" + with pytest.raises(ValueError, match="Unsafe bundle path"): + resolve_resource_key("../../note.md", body, members) + with pytest.raises(ValueError, match="Unknown resource"): + resolve_resource_key("missing.md", body, members) + + def _skill(root: Path, name: str = "sk", **frontmatter) -> Path: directory = root / name directory.mkdir(parents=True) diff --git a/tests/knowledge/test_knowledge_store.py b/tests/knowledge/test_knowledge_store.py index 5296bba49..10fd695be 100644 --- a/tests/knowledge/test_knowledge_store.py +++ b/tests/knowledge/test_knowledge_store.py @@ -1,4 +1,5 @@ import hashlib +import json import os import sqlite3 import subprocess @@ -11,6 +12,7 @@ import pytest import inferrsi +from inferrsi.knowledge.knowledge_find import find, load_corpus from inferrsi.knowledge.knowledge_operations import ( Bundle, IdentityError, @@ -70,7 +72,9 @@ def test_duplicate_stale_update_and_immutable_resources(tmp_path): assert item["ref"] == f"store:{LOCAL}" -def test_store_find_searches_the_delivered_revision(tmp_path): +def test_store_find_searches_the_delivered_revision(tmp_path, capsys): + from inferrsi.apps.cli import main + store = KnowledgeStore(tmp_path, skill_root=None) ref = "store:local-budget-notes" metadata = { @@ -88,46 +92,41 @@ def test_store_find_searches_the_delivered_revision(tmp_path): successor = Bundle(metadata, {"note.md": b"alpinecapacitymarker"}, {}) old_revision = store.create(original) new_revision = store.update(successor, expected=old_revision, reason="amend", evidence=[]) - options = {"kind": "knowledge", "material": True} - - assert store.collect("borealcapacitymarker", **options)["no_match"] - current = store.collect("alpinecapacitymarker", **options) - item, = current["items"] - assert (item["ref"], item["revision"], item["content"]) == ( - ref, new_revision, "alpinecapacitymarker", - ) - assert current["retrieval"]["calls"] == ["collect", "find"] - - retained = store.collect( - relevance="borealcapacitymarker", revisions={ref: old_revision}, **options, - ) - item, = retained["items"] - assert (item["ref"], item["revision"], item["content"]) == ( - ref, old_revision, "borealcapacitymarker", - ) - assert not retained["omissions"] - assert store.collect("alpinecapacitymarker", revisions={ref: old_revision}, **options)[ - "no_match" - ] + current = load_corpus(store=store, kinds=("record",)) + archived = load_corpus(store=store, kinds=("record",), revisions={ref: old_revision}) + assert find("borealcapacitymarker", current)["no_match"] + assert find("alpinecapacitymarker", archived)["no_match"] + for corpus, query, revision in ((current, "alpinecapacitymarker", new_revision), + (archived, "borealcapacitymarker", old_revision)): + item, = find(query, corpus, pin_material=True)["items"] + assert (item["material_ref"], item["revision"]) == (ref, revision) + assert store.reader().read(ref, revision=revision).view(material=True)["content"] == query + for query, expected in (("alpinecapacitymarker", new_revision), + ("borealcapacitymarker", old_revision)): + flags = [] if expected == new_revision else ["--revision", f"{ref}={expected}"] + argv = ["find", query, "--store", str(tmp_path), "--no-external", + "--json", *flags] + assert main(argv) == 0 + hit, = json.loads(capsys.readouterr().out)["items"] + assert main(hit["read_args"]) == 0 + opened = json.loads(capsys.readouterr().out) + assert (opened["ref"], opened["revision"], opened["content"]) == (ref, expected, query) def test_package_only_store_find_respects_its_reserved_sources(tmp_path): query = "cache per-step masks ran out of device memory" - options = {"kind": "case", "limit": 1} - ordinary = KnowledgeReader().collect(query, **options) + ordinary = find(query, load_corpus(kinds=("case",)), limit=1) assert ordinary["items"][0]["authority"] == "checkout" - store = KnowledgeStore(tmp_path, skill_root=None) - result = store.collect(query, **options) - assert result["no_match"] - assert result["retrieval"]["request"]["sources"] == ["package", "store"] - assert result["retrieval"]["counts"]["considered"] == 0 - - reader = store.reader() - result = reader.collect("cgroupv2", kind="skill", limit=1) + result = find(query, load_corpus(kinds=("case",), store=store), limit=1, pin_material=True) + assert result["no_match"] and result["corpus_size"] == 0 + assert result["sources"] == ["package", "store"] + result = find("cgroupv2", load_corpus(kinds=("skill",), store=store), + limit=1, pin_material=True) item, = result["items"] - assert item["ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" - assert reader.read(item["ref"], revision=item["revision"]).revision == item["revision"] + assert item["material_ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" + opened = store.reader().read(item["material_ref"], revision=item["revision"]) + assert opened.revision == item["revision"] def test_store_cannot_shadow_read_only_identities(tmp_path): @@ -422,7 +421,7 @@ def test_operations_leave_sources_evidence_and_matrices_unchanged(tmp_path): revision = store.create(adaptation()) store.update(changed(adaptation(), b"amend"), expected=revision, reason="r", evidence=[]) store.collect(limit=500, material=True) - store.reader().collect("calibration", material=True) + find("calibration", load_corpus(store=store, skill_root=store.skill_root), limit=1) store.read(LOCAL, revision=revision) assert _digest(watched) == before assert sorted(p.name for p in tmp_path.iterdir()) == ["knowledge.sqlite3"] diff --git a/tests/knowledge/test_knowledge_tiers.py b/tests/knowledge/test_knowledge_tiers.py index 56f572e3b..82434d3da 100644 --- a/tests/knowledge/test_knowledge_tiers.py +++ b/tests/knowledge/test_knowledge_tiers.py @@ -52,7 +52,7 @@ def test_filters_intersect_before_limit_without_downstream_inheritance(): def test_cli_preserves_tier_scope_and_transfer_cautions(capsys): - assert main(["knowledge", "search", "--tier", "peer", "--json", "--limit", "100"]) == 0 + assert main(["knowledge", "list", "--tier", "peer", "--json", "--limit", "100"]) == 0 assert all(r["tier"] == "peer" for r in json.loads(capsys.readouterr().out)) assert main(["context", "--repo-type", "xdit", "--backend", "cuda", "--tier", "peer"]) == 0 output = capsys.readouterr().out diff --git a/tests/knowledge/test_mlx_knowledge.py b/tests/knowledge/test_mlx_knowledge.py index ded72bedd..234ef8518 100644 --- a/tests/knowledge/test_mlx_knowledge.py +++ b/tests/knowledge/test_mlx_knowledge.py @@ -2,9 +2,10 @@ import pytest -from inferrsi.knowledge.catalog import get_knowledge, search_knowledge +from inferrsi.knowledge.catalog import get_knowledge from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import skill_metadata, skill_resource +from tests.knowledge._catalog_find import find_package_records LIBRARY = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" @@ -52,7 +53,7 @@ def test_mlx_candidate_preserves_source_state_and_owner_resources( ) def test_mlx_packaged_guidance_is_discoverable_and_complete(query, identity, resources, marker): record = get_knowledge(identity) - assert record in search_knowledge(query, repo="inferrsi", limit=100) + assert record in find_package_records(query, repo="inferrsi", limit=100) assert record["backend"] == "common" assert record["verification"]["locally_verified"] is False bundle = KnowledgeReader(skill_root=LIBRARY).read(identity) diff --git a/tests/knowledge/test_qwen3_tts_knowledge.py b/tests/knowledge/test_qwen3_tts_knowledge.py index 3134d86d4..8b89033a9 100644 --- a/tests/knowledge/test_qwen3_tts_knowledge.py +++ b/tests/knowledge/test_qwen3_tts_knowledge.py @@ -5,10 +5,11 @@ from inferrsi.apps.cli import main from inferrsi.knowledge.catalog import get_knowledge, search_knowledge from inferrsi.resources.repository_packs import repository_pack +from tests.knowledge._catalog_find import find_package_records def test_qwen_tts_peer_scope_and_runtime_boundary(): - records = search_knowledge( + records = find_package_records( "Qwen3-TTS", tier="peer", repo="qwen3_tts_engine", backend="ascend", scenario="audio.tts", limit=10, ) @@ -26,7 +27,7 @@ def test_qwen_tts_peer_scope_and_runtime_boundary(): def test_qwen_tts_cli_retains_source_and_unverified_status(capsys): assert main([ - "knowledge", "search", "Qwen3-TTS", "--tier", "peer", + "find", "Qwen3-TTS", "--tier", "peer", "--repo-type", "qwen3_tts_engine", "--backend", "ascend", "--scenario", "audio.tts", "--limit", "10", "--json", ]) == 0 diff --git a/tests/knowledge/test_ranking_policy.py b/tests/knowledge/test_ranking_policy.py index d8ac3e2b7..45898378f 100644 --- a/tests/knowledge/test_ranking_policy.py +++ b/tests/knowledge/test_ranking_policy.py @@ -3,9 +3,7 @@ import pytest -from inferrsi.knowledge._skill_selection import FIND_RELEVANCE from inferrsi.knowledge.knowledge_find import Corpus, Document, rank -from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy @@ -57,27 +55,26 @@ def test_default_preserves_body_length_idf_backend_and_all_tie_breaks(): def test_packaged_service_uses_same_weights_without_content_fingerprints(): - reader = KnowledgeReader() - args = {"relevance_method": FIND_RELEVANCE, "limit": 1, "context_bytes": 65536} - implicit = reader.collect_service_context("cgroupv2", **args) - explicit = reader.collect_service_context( - "cgroupv2", **args, ranking_policy=DEFAULT_RANKING_POLICY, - ) - assert implicit == explicit - context, = implicit["contexts"] - assert context["ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" - assert implicit["request"]["ranking_policy"] == DEFAULT_RANKING_POLICY.configuration() + from inferrsi.apps.cli.arguments import parser + from inferrsi.apps.workflows.session_knowledge import _service_find + + args = parser().parse_args(["find", "cgroupv2", "--limit", "1"]) + selected = _service_find(args, DEFAULT_RANKING_POLICY, None) + hit, = selected["items"] + assert hit["material_ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" + assert selected["ranking_policy"] == DEFAULT_RANKING_POLICY.configuration() zero = RankingPolicy("zero", dict.fromkeys(DEFAULT_RANKING_POLICY.weights, 0)) - other = reader.collect_service_context("cgroupv2", **args, ranking_policy=zero) - assert other["request"]["ranking_policy"] == zero.configuration() - assert other["contexts"] == [] + other = _service_find(args, zero, None) + assert other["ranking_policy"] == zero.configuration() + assert other["items"] == [] def test_service_rejects_finite_weights_that_overflow_a_score(): + from inferrsi.apps.cli.arguments import parser + from inferrsi.apps.workflows.session_knowledge import _service_find + + args = parser().parse_args(["find", "cgroupv2", "--limit", "1"]) weights = dict.fromkeys(DEFAULT_RANKING_POLICY.weights, sys.float_info.max) policy = RankingPolicy("large", weights) with pytest.raises(ValueError, match="Ranking score overflow for policy 'large'"): - KnowledgeReader().collect_service_context( - "cgroupv2", relevance_method=FIND_RELEVANCE, limit=1, - context_bytes=65536, ranking_policy=policy, - ) + _service_find(args, policy, None) diff --git a/tests/knowledge/test_raw_string_selection.py b/tests/knowledge/test_raw_string_selection.py index 999be76c3..761600bf4 100644 --- a/tests/knowledge/test_raw_string_selection.py +++ b/tests/knowledge/test_raw_string_selection.py @@ -53,8 +53,8 @@ def synthetic_reader(entries): ({"relevance_method": "task-lexical-v1", "ids": ["owner"]}, "find-lexical-v1"), ({"relevance_method": "unknown"}, "Unsupported relevance_method"), ({"relevance_method": []}, "Unsupported relevance_method"), - ({"query": "filtered", "relevance": "cue"}, "Find takes one query or relevance cue"), - ({"query": "filtered", "ids": ["owner"]}, "Remove query when using explicit IDs"), + ({"query": "filtered", "relevance": "cue"}, "Use find"), + ({"query": "filtered", "ids": ["owner"]}, "Use find"), ]) def test_retired_selectors_and_ambiguous_inputs_fail_before_reader_access( monkeypatch, options, message, diff --git a/tests/knowledge/test_research.py b/tests/knowledge/test_research.py index 81dda5291..f680cf3fb 100644 --- a/tests/knowledge/test_research.py +++ b/tests/knowledge/test_research.py @@ -1,229 +1,104 @@ -"""Research discovery broadens queries without qualifying engines or hardware.""" +"""Model research uses the ordinary per-question Find and pinned Read workflow.""" import json -import math from importlib.resources import files import pytest from inferrsi.apps.cli import main -from inferrsi.knowledge import catalog as knowledge_catalog -from inferrsi.knowledge.catalog import get_knowledge, search_knowledge -from inferrsi.knowledge.research import research_knowledge - - -def test_h3_retrieves_framework_and_task_knowledge_with_source_boundaries(): - result = research_knowledge( - "MiniMax-H3", frameworks=["mlx"], target_backend="metal", - target_device="M5 Mac Studio", target_memory_gib=64, limit=12, - ) - queries = {(item["group"], item["query"]) for item in result["queries"]} - assert ("model", "MiniMax-H3") in queries - assert ("framework", "mlx") in queries - assert ("task", "diffusion") in queries - assert ("modality", "video") in queries - assert ("modality", "audio") in queries - assert any(group == "mechanism" for group, _ in queries) - items = result["items"] - identities = [item["record"]["id"] for item in items] - assert len(identities) == len(set(identities)) <= 12 - # Corpus additions can reorder matches; the independent framework query still contributes. - framework_first = search_knowledge("mlx", limit=1)[0]["id"] - assert any( - item["record"]["id"] == framework_first - and {"group": "framework", "query": "mlx"} in item["matched_queries"] - for item in items - ) - assert set(result["profile"]["knowledge_ids"]) <= set(identities) - task_first = search_knowledge("diffusion", limit=1)[0]["id"] - assert any( - item["record"]["id"] == task_first - and {"group": "task", "query": "diffusion"} in item["matched_queries"] - for item in items - ) - assert any( - match["group"] == "modality" and match["query"] == "video" - for item in items for match in item["matched_queries"] - ) - for item in items: - assert item["record"] == get_knowledge(item["record"]["id"]) - assert item["record"]["verification"]["locally_verified"] is False - assert result["target"]["memory_gib"] == 64 - assert result["target"]["backend"] == "metal" - assert result["target_validation"] == "unverified" - assert "metal" not in knowledge_catalog.BACKENDS - assert {part["role"] for part in result["components"]} == { +from inferrsi.apps.cli.arguments import parser +from inferrsi.knowledge.research import PROCEDURE + +H3_QUESTION = "MiniMax-H3 component inventory on Apple Silicon" +MLX_QUESTION = "MLX lazy evaluation and buffer lifetime" +PROFILE = "references/minimax-h3-profile.json" +QUESTIONS = ( + (H3_QUESTION, "audit_h3_runtime_residency"), + (MLX_QUESTION, "lazy_evaluation_stream_lifetimes"), +) +RETIRED = { + "--model": "MiniMax-H3", "--framework": "mlx", "--task": "diffusion", "--modality": "video", + "--mechanism": "memory", "--target-backend": "metal", "--target-device": "Apple Silicon", + "--target-memory-gib": "64", +} + + +def _run(capsys, *argv): + assert main(list(argv)) == 0 + return json.loads(capsys.readouterr().out) + + +def test_model_research_options_are_only_in_the_historical_parser(capsys): + with pytest.raises(SystemExit) as help_exit: + main(["find", "--help"]) + assert help_exit.value.code == 0 + help_text = capsys.readouterr().out + for flag, value in RETIRED.items(): + assert flag not in help_text + with pytest.raises(SystemExit) as error: + main(["find", H3_QUESTION, flag, value]) + assert error.value.code == 2 and "unrecognized arguments" in capsys.readouterr().err + + old = parser(historical=True) + dimensions = [word for flag, value in RETIRED.items() if flag != "--model" + for word in (flag, value)] + for words in (["find", "--model"], ["knowledge", "research"]): + archived = old.parse_args([*words, "MiniMax-H3", *dimensions]) + assert archived.model == "MiniMax-H3" and archived.framework == ["mlx"] + assert archived.target_memory_gib == 64 + + +def test_model_profile_opens_at_the_advertised_revision(capsys): + found = _run(capsys, "find", H3_QUESTION, "--limit", "1", "--json") + hit, = found["items"] + read_args = hit["read_args"] + body = _run(capsys, *read_args) + assert PROFILE in body["content"] + # A base install can use a package projection with an explicit SKILL.md resource. + args = read_args[:] + if "--resource" in args: + del args[args.index("--resource"):args.index("--resource") + 2] + opened = _run(capsys, *args, "--resource", PROFILE) + assert opened["revision"] == body["revision"] == read_args[read_args.index("--revision") + 1] + assert opened["ref"] == body["ref"] and opened["content_resource"].endswith("/" + PROFILE) + profile = json.loads(opened["content"]) + assert profile["model"] == "MiniMax-H3" and "MiniMax-H3" in profile["aliases"] + assert {row["role"] for row in profile["components"]} == { "denoiser", "text_encoder", "video_vae", "audio_vae", } - assert result["profile"]["input_modalities"] == ["text", "image", "video", "audio"] - assert result["profile"]["output_modalities"] == ["video", "audio"] - - -def test_scoped_mlx_research_retains_the_lifecycle_resource(): - result = research_knowledge( - "MiniMax-H3", frameworks=["mlx"], mechanisms=["lazy evaluation"], - repo="inferrsi", scenario="skills.discovery", limit=12, - ) - lifecycle = next( - item for item in result["items"] - if item["record"]["id"] == "inferrsi.common.skills.lazy_evaluation_stream_lifetimes" - ) - assert lifecycle["record"]["skill_documents"]["original"] == ( - "data/skill_library/systems/frameworks/mlx/lazy-evaluation-stream-lifetimes/SKILL.md" - ) - assert {"group": "framework", "query": "mlx"} in lifecycle["matched_queries"] - assert {"group": "mechanism", "query": "lazy evaluation"} in lifecycle["matched_queries"] - - -def _synthetic_record(identity, summary): - return { - "id": identity, "repo": "vllm_omni", "backend": "common", "scenario": "diffusion.*", - "summary": summary, "status": "imported", "verification": {"locally_verified": False}, - } - - -def test_independent_find_queries_are_unioned_fairly(monkeypatch): - records = [ - _synthetic_record(name, summary) - for name, summary in ( - ("a-model", "ExampleModel"), - ("b-framework", "mlx"), - ("c-task", "diffusion"), - ("d-modality", "video"), - ("e-mechanism", "offload"), - ("f-overlap", "ExampleModel mlx diffusion video offload"), - ) - ] - monkeypatch.setattr(knowledge_catalog, "knowledge_records", lambda: records) - compound = search_knowledge("ExampleModel mlx diffusion video offload") - assert compound[0]["id"] == "f-overlap" - assert {record["id"] for record in compound} == {record["id"] for record in records} - result = research_knowledge( - "ExampleModel", frameworks=["mlx", "MLX"], tasks=["diffusion"], - modalities=["video"], mechanisms=["offload"], limit=6, - ) - assert len(result["queries"]) == 5 # same-dimension duplicates are case insensitive - assert {item["record"]["id"] for item in result["items"]} == { - record["id"] for record in records - } - overlap = next(item for item in result["items"] if item["record"]["id"] == "f-overlap") - assert len(overlap["matched_queries"]) == 5 - limited = research_knowledge( - "ExampleModel", frameworks=["mlx"], tasks=["diffusion"], - modalities=["video"], mechanisms=["offload"], limit=5, - ) - assert len(limited["items"]) == 5 - assert {item["record"]["id"] for item in limited["items"]} == { - "a-model", "b-framework", "c-task", "d-modality", "e-mechanism", - } - - -def test_query_attribution_survives_the_shared_output_limit(monkeypatch): - records = [ - _synthetic_record("model", "SyntheticModel mlx"), - _synthetic_record("framework", "mlx mlx"), - ] - monkeypatch.setattr(knowledge_catalog, "knowledge_records", lambda: records) - result = research_knowledge("SyntheticModel", frameworks=["mlx"], limit=1) - assert result["items"] == [{ - "record": records[0], - "matched_queries": [ - {"group": "model", "query": "SyntheticModel"}, - {"group": "framework", "query": "mlx"}, - ], - }] - assert [query["matches"] for query in result["queries"]] == [1, 2] - - -def test_research_retains_all_package_filters_and_no_match(): - result = research_knowledge( - "MiniMax-H3", frameworks=["mlx"], repo="vllm_omni", tier="contribution", - backend="ascend", scenario="diffusion.t2v", limit=100, - ) - assert result["items"] - allowed = { - item["id"] for item in search_knowledge( - repo="vllm_omni", tier="contribution", backend="ascend", - scenario="diffusion.video_generation", limit=100, - ) - } - assert {item["record"]["id"] for item in result["items"]} <= allowed - assert result["filters"]["backend"] == "ascend" - assert any(item["matches"] == 0 for item in result["queries"]) - empty = research_knowledge("MiniMax-H3", repo="vllm_rlt") - assert empty["items"] == [] - assert empty["no_match"] is True - - -def test_unknown_model_never_invents_tasks_or_components(): - result = research_knowledge("UnknownSyntheticModel") - assert [(item["group"], item["query"]) for item in result["queries"]] == [ - ("model", "UnknownSyntheticModel"), - ] - assert result["profile"] is None - assert result["components"] == [] - assert result["warnings"] - explicit = research_knowledge( - "UnknownSyntheticModel", tasks=["diffusion"], modalities=["video"] - ) - assert {item["group"] for item in explicit["queries"]} == {"model", "task", "modality"} - - -@pytest.mark.parametrize("alias", ["MiniMax-H3", "minimax h3", "MiniMax_H3"]) -def test_model_profile_links_packaged_resources_at_the_repository_owner(alias): - result = research_knowledge(alias) - # Returned resource keys stay logical "data/..."; K02 moved the physical - # corpus under the Knowledge module without changing that spelling. - package = files("inferrsi").joinpath("knowledge") - profile = result["profile"] - assert profile["model"] == "MiniMax-H3" - assert package.joinpath(result["procedure_resource"]).read_text(encoding="utf-8") - assert result["worked_example_resource"] == profile["worked_example_resource"] - for key in ("skill_resource", "worked_example_resource", "inventory_resource"): - resource = profile[key] - assert resource.startswith("data/skill_library/systems/engines/h3-c/") - assert package.joinpath(resource).read_text(encoding="utf-8") - record = get_knowledge(profile["knowledge_ids"][0]) - assert record["skill_documents"]["original"] == profile["skill_resource"] - - -@pytest.mark.parametrize("memory", [0, -1, math.inf, math.nan]) -def test_target_memory_must_be_positive_and_finite(memory): - with pytest.raises(ValueError, match="memory"): - research_knowledge("MiniMax-H3", target_memory_gib=memory) - - -def test_public_cli_exposes_model_profile_and_keeps_filters(capsys): - assert main([ - "knowledge", "research", "minimax-h3", "--framework", "mlx", - "--target-backend", "metal", "--target-device", "M5 Mac Studio", - "--target-memory-gib", "64", "--limit", "12", - ]) == 0 - result = json.loads(capsys.readouterr().out) - assert result["profile"]["model"] == "MiniMax-H3" - assert result["profile"]["sources"] - assert result["target"]["device"] == "M5 Mac Studio" - assert result["target_validation"] == "unverified" - framework_first = search_knowledge("mlx", limit=1)[0]["id"] - assert any( - item["record"]["id"] == framework_first - and {"group": "framework", "query": "mlx"} in item["matched_queries"] - for item in result["items"] - ) - assert main([ - "knowledge", "research", "MiniMax-H3", "--repo-type", "vllm_rlt", - ]) == 0 - assert json.loads(capsys.readouterr().out)["no_match"] is True - with pytest.raises(SystemExit) as error: - main(["knowledge", "research", "MiniMax-H3", "--target-memory-gib", "-1"]) - assert error.value.code == 2 - with pytest.raises(SystemExit) as error: - main(["knowledge", "research", "MiniMax-H3", "--backend", "metal"]) - assert error.value.code == 2 - - -@pytest.mark.parametrize("model,kwargs", [("", {}), ("Example", {"frameworks": [" "]}), - ("Example", {"limit": 0})]) -def test_invalid_research_inputs_fail_explicitly(model, kwargs): - with pytest.raises(ValueError): - research_knowledge(model, **kwargs) + assert profile["input_modalities"] == ["text", "image", "video", "audio"] + assert profile["output_modalities"] == ["video", "audio"] + assert all(source["commit"] in source["url"] for source in profile["sources"]) + assert not profile["verification"]["locally_verified"] + resources = files("inferrsi.knowledge") + for key in ("skill_resource", "inventory_resource", "worked_example_resource"): + assert resources.joinpath(*profile[key].split("/")).is_file() + assert resources.joinpath(*PROCEDURE.split("/")).is_file() + missing = _run(capsys, "find", "zzcanaryunknownqx", "--json") + assert missing["no_match"] and not missing["items"] + + +def test_session_keeps_each_research_question_and_selected_read(tmp_path, capsys): + root = tmp_path / "campaign" + _run(capsys, "campaign", "init", "--directory", str(root), "--id", "research") + searches = [] + for query, skill in QUESTIONS: + found = _run(capsys, "find", query, "--session", str(root), "--limit", "1") + search = found["reference"] + searches.append(search["path"]) + assert search["kind"] == "knowledge_search" + capture = json.loads((root / search["path"]).read_bytes()) + assert capture["request"]["query"] == found["query"] == query + assert capture["contexts"] == [] + hit, = found["items"] + assert hit["material_ref"] == "package:inferrsi.common.skills." + skill + opened = _run(capsys, *hit["read_args"]) + assert opened["search_ref"] == search["path"] + assert opened["ref"] == hit["material_ref"] and opened["revision"] == hit["revision"] + assert opened["reference"]["kind"] == "delivered_context" and opened["content"] + if query == H3_QUESTION: + resource = _run(capsys, *hit["read_args"], "--resource", PROFILE) + assert resource["search_ref"] == search["path"] + assert resource["revision"] == hit["revision"] + assert json.loads(resource["content"])["model"] == "MiniMax-H3" + assert len(set(searches)) == 2 diff --git a/tests/knowledge/test_skill_index.py b/tests/knowledge/test_skill_index.py index 82a2d942f..3c69f7ddf 100644 --- a/tests/knowledge/test_skill_index.py +++ b/tests/knowledge/test_skill_index.py @@ -292,7 +292,7 @@ def test_package_index_and_checkout_skill_have_distinct_read_boundaries(): def test_index_cli_search_show_context_and_execution_boundary(capsys): assert main([ - "knowledge", "search", "profiling", "--repo-type", "inferrsi", "--json", + "knowledge", "list", "--repo-type", "inferrsi", "--json", ]) == 0 records = json.loads(capsys.readouterr().out) assert records and all(record["repo"] == "inferrsi" for record in records) @@ -300,7 +300,7 @@ def test_index_cli_search_show_context_and_execution_boundary(capsys): assert main(["knowledge", "show", identity]) == 0 shown = json.loads(capsys.readouterr().out) assert shown["skill_metadata"]["license"] == "UNKNOWN" - assert main(["context", identity, "--repo-type", "inferrsi", "--backend", "ascend"]) == 0 + assert main(["context", "--id", "package:" + identity]) == 0 context = capsys.readouterr().out assert identity in context and "not the original skill" in context assert "locally_verified\": false" in context diff --git a/tests/knowledge/test_skill_library.py b/tests/knowledge/test_skill_library.py index 095b9f59a..8000a5878 100644 --- a/tests/knowledge/test_skill_library.py +++ b/tests/knowledge/test_skill_library.py @@ -21,7 +21,7 @@ def test_imported_repository_cli_and_scope_boundaries(repo, capsys, tmp_path): imported = [record for record in records if "skill_documents" in record] assert len(imported) == 3 assert all(record["repo"] == repo and record["backend"] == "common" for record in records) - assert main(["knowledge", "search", "--repo-type", repo, "--backend", "cpu", "--json"]) == 0 + assert main(["knowledge", "list", "--repo-type", repo, "--backend", "cpu", "--json"]) == 0 assert json.loads(capsys.readouterr().out) == records for record in imported: @@ -42,15 +42,8 @@ def test_imported_repository_cli_and_scope_boundaries(repo, capsys, tmp_path): main( [ "context", + "--id", record["id"], - "--repo-type", - repo, - "--backend", - "cpu", - "--scenario", - scenario, - "--limit", - "1", "--output", str(destination), ] diff --git a/tests/knowledge/test_vllm_ascend_skills.py b/tests/knowledge/test_vllm_ascend_skills.py index 7399fed58..7c1ecc4f2 100644 --- a/tests/knowledge/test_vllm_ascend_skills.py +++ b/tests/knowledge/test_vllm_ascend_skills.py @@ -9,9 +9,9 @@ import pytest -from inferrsi.knowledge.catalog import search_knowledge from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.skill_catalog import skill_instructions, skill_metadata, skill_resource +from tests.knowledge._catalog_find import find_package_records LIBRARY = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/data/skill_library" NAME = "vllm-ascend" @@ -49,7 +49,7 @@ def test_batch1_skills_are_discoverable_for_representative_queries( query, expected_skill_id ): - results = search_knowledge(query, repo="inferrsi", backend="ascend", limit=5) + results = find_package_records(query, repo="inferrsi", backend="ascend", limit=5) skill_ids = [item["id"] for item in results] assert expected_skill_id in skill_ids, ( f"Query {query!r} expected {expected_skill_id} in {skill_ids}" @@ -97,7 +97,7 @@ def test_distilled_skill_metadata_and_contracts(skill, notes_terms, instruction_ ("DSA-CP FlashComm1 Fused-MC2", "communication-config.md"), ]) def test_release_skill_is_discoverable_and_its_routes_ship(query, route): - results = search_knowledge(query, repo="inferrsi", backend="ascend", limit=3) + results = find_package_records(query, repo="inferrsi", backend="ascend", limit=3) assert any(item["id"] == "inferrsi.ascend.skills.vllm_ascend" for item in results) relative = f"references/{route}" assert f"]({relative})" in skill_instructions(LIBRARY, NAME) diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 99c3055d9..0f43a8ac1 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -21,7 +21,13 @@ from inferrsi.benchmark.skill_eval_engineering import REQUEST from inferrsi.contracts import RunSpec, claim, evidence, json_v1 from inferrsi.knowledge._source_snapshot import BUNDLE_LIBRARY, LIBRARY -from inferrsi.knowledge.catalog import _split_skill_metadata, knowledge_records, search_knowledge +from inferrsi.knowledge.catalog import ( + _split_skill_metadata, + get_knowledge, + knowledge_records, + search_knowledge, +) +from inferrsi.knowledge.knowledge_find import find, load_corpus from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.resources import repository_packs from inferrsi.resources.repository_packs import REPO_TYPES, repository_pack @@ -44,6 +50,13 @@ ) +def find_records(query, *, limit=10, **scope): + hits = find(query, load_corpus(kinds=("skill", "record"), **scope), + limit=limit, pin_material=True) + return [get_knowledge(hit["material_ref"].removeprefix("package:")) + for hit in hits["items"] if hit.get("material_ref", "").startswith("package:")] + + def bundle_key(logical): """Return the package-relative bundle key for a bundle or pinned-record key. @@ -234,13 +247,16 @@ def resource(logical): ("MiniMax-H3", h3_identity, None), ("AFD", afd_identity, "cuda"), ("WGMMA", hopper_identity, "cuda"), ): - assert any(item["id"] == identity for item in search_knowledge( + assert any(item["id"] == identity for item in find_records( query, repo="inferrsi", backend=backend, limit=100, )) selection_reader = KnowledgeReader() -selection = selection_reader.collect( - "cgroupv2 cpu.stat.local", kind="knowledge", context_bytes=65536, limit=1, -) +found = find("cgroupv2 cpu.stat.local", load_corpus(repo="inferrsi"), limit=1, + pin_material=True) +pin, = found["items"] +selection = selection_reader.collect(ids=[pin["material_ref"]], + revisions={pin["material_ref"]: pin["revision"]}, + context_bytes=65536, limit=1) assert selection["items"][0]["id"] == "inferrsi.common.skills.cgroup_resource_controls" assert not selection["context_omissions"] selection_context = selection["contexts"][0] @@ -263,7 +279,7 @@ def resource(logical): imported = search_knowledge(tier=tier, limit=100) assert len(imported) >= count, f"Missing installed {tier} records" assert all(item["tier"] == tier for item in imported) -qwen_tts = search_knowledge( +qwen_tts = find_records( "Qwen3-TTS", tier="peer", repo="qwen3_tts_engine", backend="ascend", scenario="audio.tts", limit=10, ) @@ -349,7 +365,7 @@ def resource(logical): assert resource(reference).is_file(), reference output = io.StringIO() with contextlib.redirect_stdout(output): - assert main(["context", imported[0]["id"], "--repo-type", repo, "--backend", "cpu"]) == 0 + assert main(["context", "--id", imported[0]["id"]]) == 0 assert '"skill_documents"' in output.getvalue() assert '"locally_verified": false' in output.getvalue() assert router.joinpath("SKILL.md").is_file() @@ -392,7 +408,7 @@ def resource(logical): assert model_sol.joinpath("references", name).is_file() inference_modules = {"torch", "vllm", "sglang", "sglang_omni", "vllm_omni", "transformers", "mlx"} assert not inference_modules & sys.modules.keys() -ascend_image = search_knowledge( +ascend_image = find_records( "Qwen-Image-2.1", repo="vllm_omni", backend="ascend", scenario="diffusion.image_generation" ) assert ascend_image[0]["id"] == "vllm_omni.ascend.diffusion.qwen_image_21_eager_t2i" @@ -408,48 +424,36 @@ def resource(logical): assert main(["skills", "resource", "audit-h3-runtime-residency", "references/phase-residency.md"]) == 0 assert Path(json.loads(output.getvalue())["path"]).is_file() -output = io.StringIO() -with contextlib.redirect_stdout(output): - assert main([ - "knowledge", "research", "MiniMax-H3", "--framework", "mlx", - "--target-backend", "metal", "--target-device", "M5 Mac Studio", - "--target-memory-gib", "64", "--limit", "12", - ]) == 0 -research = json.loads(output.getvalue()) -assert research["profile"]["model"] == "MiniMax-H3" -assert research["target_validation"] == "unverified" -assert research["target"]["device"] == "M5 Mac Studio" -framework_first = search_knowledge("mlx", limit=1)[0]["id"] -assert any( - item["record"]["id"] == framework_first - and {"group": "framework", "query": "mlx"} in item["matched_queries"] - for item in research["items"] -) -assert {item["group"] for item in research["queries"]} == { - "model", "framework", "task", "modality", "mechanism", -} -for key in ("procedure_resource", "worked_example_resource"): - assert resource(research[key]).read_text(encoding="utf-8") -for key in ("skill_resource", "inventory_resource"): - assert resource(research["profile"][key]).read_text(encoding="utf-8") -assert set(research["profile"]["knowledge_ids"]) <= { - item["record"]["id"] for item in research["items"] -} -output = io.StringIO() -with contextlib.redirect_stdout(output): - assert main([ - "knowledge", "research", "MiniMax-H3", "--framework", "mlx", - "--mechanism", "lazy evaluation", "--repo-type", "inferrsi", - "--scenario", "skills.discovery", "--limit", "12", - ]) == 0 -mlx_research = json.loads(output.getvalue()) -mlx_lifecycle = next( - item for item in mlx_research["items"] - if item["record"]["id"] == "inferrsi.common.skills.lazy_evaluation_stream_lifetimes" -) -assert mlx_lifecycle["record"]["skill_documents"]["original"] == mlx_document -assert {"group": "framework", "query": "mlx"} in mlx_lifecycle["matched_queries"] -assert {"group": "mechanism", "query": "lazy evaluation"} in mlx_lifecycle["matched_queries"] + + +def cli_json(*words): + output = io.StringIO() + with contextlib.redirect_stdout(output): + assert main(list(words)) == 0 + return json.loads(output.getvalue()) + + +h3_hit, = cli_json("find", "MiniMax-H3 component inventory on Apple Silicon", + "--repo-type", "inferrsi", "--limit", "1", "--json")["items"] +profile_key = "references/minimax-h3-profile.json" +h3_read = cli_json(*h3_hit["read_args"]) +assert profile_key in h3_read["content"] +h3_args = h3_hit["read_args"][:] +if "--resource" in h3_args: + at = h3_args.index("--resource") + del h3_args[at:at + 2] +h3_profile_read = cli_json(*h3_args, "--resource", profile_key) +assert h3_profile_read["revision"] == h3_read["revision"] +assert h3_read["revision"] == h3_args[h3_args.index("--revision") + 1] +profile = json.loads(h3_profile_read["content"]) +assert profile["model"] == "MiniMax-H3" and h3_hit["id"] in profile["knowledge_ids"] +for key in ("skill_resource", "inventory_resource", "worked_example_resource"): + assert resource(profile[key]).read_text(encoding="utf-8") +mlx_hit, = cli_json("find", "MLX lazy evaluation and buffer lifetime", "--repo-type", "inferrsi", + "--limit", "1", "--json")["items"] +assert mlx_hit["id"] == "inferrsi.common.skills.lazy_evaluation_stream_lifetimes" +mlx_read = cli_json(*mlx_hit["read_args"]) +assert mlx_read["content_resource"] == mlx_document and mlx_read["content"] assert not inference_modules & sys.modules.keys() print(f"Installed package: {inferrsi.__file__}; {len(records)} source-grounded records available.") diff --git a/tools/evaluate_indexer.py b/tools/evaluate_indexer.py index 0b435b7eb..b634b6656 100644 --- a/tools/evaluate_indexer.py +++ b/tools/evaluate_indexer.py @@ -1,7 +1,8 @@ """Read-only, CPU-only retrieval evidence runner; no model or hardware invocation. Use --help. Baseline/candidate paths and frozen protocol are explicit inputs. -This tool measures real packaged retrieval, not a synthetic workload or CI gate. +Each checkout runs its own evaluator against its published interfaces. Cross-version +comparisons retain unpaired measurements and compare only shared operations. """ from __future__ import annotations @@ -35,7 +36,7 @@ def write(path, value): def identity(root): groups = {} for name, paths in ( - ("python", sorted((root / "src").rglob("*.py"))), + ("python", [*sorted((root / "src").rglob("*.py")), root / "tools/evaluate_indexer.py"]), ("corpus", sorted((root / "src/inferrsi/knowledge/data").rglob("*")) + sorted((root / "src/inferrsi/harness/data").rglob("*"))), ): @@ -54,42 +55,24 @@ def identity(root): return groups -def options(case, context=False): - value = {"query": case.get("query", ""), "limit": case.get("limit", 5)} - value.update(case.get("filters", {})) - if case.get("relevance") is not None: - if value["query"].strip(): - raise ValueError("Supply one Find question or use the pinned legacy runner.") - value["relevance"] = case["relevance"] - if context: - value["context_bytes"] = case.get("context_bytes", 262144) - return value - - def child(root, action, payload): env = {"PATH": os.defpath, "PYTHONPATH": str(root / "src"), "PYTHONDONTWRITEBYTECODE": "1"} + runner = root / "tools/evaluate_indexer.py" + if not runner.is_file(): + raise ValueError("Use the retained frozen evaluator for a checkout without its own worker.") run = subprocess.run( - [sys.executable, str(Path(__file__).resolve()), "--worker", str(root), action], + [sys.executable, str(runner), "--worker", str(root), action], input=json.dumps(payload), text=True, capture_output=True, env=env, check=True, timeout=180, ) return json.loads(run.stdout) -def cli(root, mode, case): - args = [sys.executable, "-m", "inferrsi"] - if mode == "search": - args += ["knowledge", "search", "cgroupv2", "--limit", "5", "--json"] - else: - selection = options(case) - args += ["collect", "--limit", str(selection["limit"]), "--json"] - if selection.get("relevance") is not None: - args += ["--relevance", selection["relevance"]] - elif selection["query"]: - args += [selection["query"]] - for field in ("repo", "tier", "backend", "scenario", "kind"): - if field in selection: - flag = "--repo-type" if field == "repo" else "--" + field - args += [flag, selection[field]] +def cli(root, query, limit, scope): + args = [sys.executable, "-m", "inferrsi", "find", query, "--no-external", + "--limit", str(limit), "--json"] + for name, value in scope.items(): + flag = "--repo-type" if name == "repo" else "--" + name + args.extend((flag, ",".join(value) if name == "kinds" else value)) start = time.perf_counter_ns() run = subprocess.run(args, capture_output=True, check=True, timeout=180, env={ "PATH": os.defpath, "PYTHONPATH": str(root / "src"), "PYTHONDONTWRITEBYTECODE": "1", @@ -102,9 +85,31 @@ def cli(root, mode, case): "output_sha256": digest(encode(result))} +def find_options(case): + query = case.get("query", "") + if case.get("relevance") is not None: + if query.strip(): + raise ValueError("Supply one Find question or use the pinned legacy runner.") + query = case["relevance"] + scope = dict(case.get("filters", {})) + kind = scope.pop("kind", None) + if kind: + scope["kinds"] = ("record", "skill") if kind == "knowledge" else (kind,) + return query, case.get("limit", 5), scope + + +def measure(call): + start = time.perf_counter_ns() + value = call() + elapsed = time.perf_counter_ns() - start + data = encode(value) + return {"ns": elapsed, "bytes": len(data), "output_sha256": digest(data)} + + def worker(root, action, payload): sys.path.insert(0, str(root / "src")) - from inferrsi.knowledge.catalog import search_knowledge + from inferrsi.apps.workflows.knowledge import read_selected_hit + from inferrsi.knowledge.knowledge_find import find, installed_skill_root, load_corpus from inferrsi.knowledge.knowledge_operations import KnowledgeReader if action == "identity": @@ -112,40 +117,24 @@ def worker(root, action, payload): if action == "bench": rows = {} for case in payload["queries"]: - reader = KnowledgeReader() - args = options(case) - reader.collect(**args) - start = time.perf_counter_ns() - value = reader.collect(**args) - elapsed = time.perf_counter_ns() - start - rows["hot_relevance/" + case["id"]] = { - "ns": elapsed, "bytes": len(encode(value)), "output_sha256": digest(encode(value))} + query, limit, scope = find_options(case) + corpus = load_corpus(**scope) + find(query, corpus, limit=limit) + rows["hot_find/" + case["id"]] = measure(lambda: find(query, corpus, limit=limit)) case = payload["queries"][0] - for mode in ("fresh_relevance", "default", "context", "search"): - args = options(case, context=mode == "context") - if mode == "search": - args = {"query": "cgroupv2", "limit": 5} - elif mode == "default": - args.pop("relevance", None) - args["query"] = "cgroupv2" - reader = KnowledgeReader() - call = search_knowledge if mode == "search" else reader.collect - if mode != "fresh_relevance": - call(**args) - start = time.perf_counter_ns() - if mode == "fresh_relevance": - value = KnowledgeReader().collect(**args) - else: - value = call(**args) - elapsed = time.perf_counter_ns() - start - rows[mode] = {"ns": elapsed, "bytes": len(encode(value)), - "output_sha256": digest(encode(value))} - for mode in ("relevance", "search"): - rows["cli_" + mode] = cli(root, mode, case) - for api, cli_name in (("hot_relevance/" + case["id"], "cli_relevance"), - ("search", "cli_search")): - if rows[api]["output_sha256"] != rows[cli_name]["output_sha256"]: - raise ValueError("API/CLI payload mismatch: " + api) + query, limit, scope = find_options(case) + rows["fresh_find"] = measure(lambda: find(query, load_corpus(**scope), limit=limit)) + hits = find(query, load_corpus(**scope), limit=limit, pin_material=True) + if hits["items"]: + hit = hits["items"][0] + rows["pinned_read"] = measure(lambda: read_selected_hit(hit)[0]) + for name, probe in (("cli_find_relevance", case), + ("cli_find_search", {"query": "cgroupv2", "limit": 5})): + query, limit, scope = find_options(probe) + rows[name] = cli(root, query, limit, scope) + result = find(query, load_corpus(**scope), limit=limit) + if digest(encode(result)) != rows[name]["output_sha256"]: + raise ValueError("Find API/CLI payload mismatch: " + name) return rows if action == "contracts": from inferrsi.knowledge._skill_selection import SkillIndexError, indexed_skill @@ -155,9 +144,9 @@ def worker(root, action, payload): rows = [] def check(name, passed, output): rows.append({"id": name, "passed": bool(passed), "output": output}) - result = reader.collect(relevance="floristry orchid") + result = find("floristry orchid", load_corpus()) check("no_match", result["no_match"], result) - result = reader.collect(relevance="P2pNccl", backend="ascend") + result = find("P2pNccl", load_corpus(backend="ascend")) check("incompatible_filter", result["no_match"], result) result = reader.collect(ids=[cgroup], relevance="unrelated orchid") check("explicit_id_unrelated", [x["id"] for x in result["items"]] == [cgroup], result) @@ -185,9 +174,14 @@ def check(name, passed, output): if action == "cases": rows = [] for case in payload: - reader = KnowledgeReader() - result = reader.collect(**options(case, context=True)) - ids = [item["id"] for item in result["items"]] + query, limit, scope = find_options(case) + found = find(query, load_corpus(**scope), limit=limit, pin_material=True) + reader = KnowledgeReader(skill_root=installed_skill_root()) + hits = [hit for hit in found["items"] if "revision" in hit] + result = reader.pack_find_hits(hits, cue=query, limit=limit, + context_bytes=case.get("context_bytes", 262144)) + ids = [hit["material_ref"].partition(":")[2] if "material_ref" in hit else hit["id"] + for hit in found["items"]] ranks = [ids.index(i) + 1 for i in case["relevant_ids"] if i in ids] selected = [i for i in case["relevant_ids"] if i in ids] complete = [] @@ -196,10 +190,14 @@ def check(name, passed, output): if c["ref"] == "package:" + target), None) checks = [] if context: - bundle = reader.read(target, revision=context["revision"]) + bundle = reader.read(context["ref"], revision=context["revision"]) # Read the exact revision once; verify every complete emitted resource. for resource in context["resources"]: data = bundle.content[resource["path"]] + if resource.get("locator") == "skill-procedure": + checks.append(digest(data) == resource["source_sha256"]) + data = b"".join(data[start:end] for start, end + in resource["source_byte_ranges"]) checks.append(data == resource["content"].encode() and digest(data) == resource["sha256"]) paths = [r["path"] for r in context["resources"]] @@ -207,11 +205,12 @@ def check(name, passed, output): for s in case.get("required_resource_suffixes", [])) checks.append(bundle.revision == context["revision"]) complete.append(bool(context) and all(checks)) + returned = {"find": found, "candidate_input": result} rows.append({"id": case["id"], "split": case["split"], "hit_at_5": bool(ranks), "rr_at_5": 1 / min(ranks) if ranks else 0, "retrieved_relevant": len(selected), "complete_relevant": sum(complete), "forbidden_hits": sorted(set(ids) & set(case.get("forbidden_ids", []))), - "output_sha256": digest(encode(result)), "result": result}) + "output_sha256": digest(encode(returned)), "result": returned}) return rows raise ValueError(action) @@ -221,7 +220,8 @@ def percentile(values, q): def summarize(groups): - names = list(groups[0]["A"]) + first = groups[0] + names = [name for name in first["A"] if name in first["B"]] rows = {} for name in names: arms = {arm: [g[arm][name]["ns"] / 1e6 for g in groups] for arm in ("A", "B")} @@ -234,13 +234,21 @@ def summarize(groups): 100 * (rows[name]["B"][stat] / rows[name]["A"][stat] - 1)) rows[name]["output_parity"] = all( g["A"][name]["output_sha256"] == g["B"][name]["output_sha256"] for g in groups) - gains = [statistics.median([ - 100 * (g["A"][name]["ns"] - g["B"][name]["ns"]) / g["A"][name]["ns"] - for name in names if name.startswith("hot_relevance/")]) for g in groups] - rng = random.Random(255) - bootstrap = [statistics.median(rng.choices(gains, k=len(gains))) for _ in range(10000)] - return {"paths": rows, "primary_reduction_percent": statistics.median(gains), - "primary_95ci": [percentile(bootstrap, .025), percentile(bootstrap, .975)]} + primary = [name for name in names if name.startswith(("hot_find/", "hot_relevance/"))] + summary = {"paths": rows, "primary_reduction_percent": None, "primary_95ci": None} + if primary: + gains = [statistics.median( + 100 * (g["A"][name]["ns"] - g["B"][name]["ns"]) / g["A"][name]["ns"] + for name in primary + ) for g in groups] + rng = random.Random(255) + bootstrap = [statistics.median(rng.choices(gains, k=len(gains))) for _ in range(10000)] + summary.update(primary_reduction_percent=statistics.median(gains), + primary_95ci=[percentile(bootstrap, .025), percentile(bootstrap, .975)]) + unpaired = {arm: sorted(first[arm].keys() - rows.keys()) for arm in ("A", "B")} + if any(unpaired.values()): + summary["unpaired_paths"] = unpaired + return summary def main(): @@ -282,12 +290,13 @@ def main(): result["summary"] = summarize(result["groups"]) summary = result["summary"] failed = [] - if summary["primary_reduction_percent"] < protocol["primary"]["gain_min_percent"]: + if (summary["primary_reduction_percent"] is not None and + summary["primary_reduction_percent"] < protocol["primary"]["gain_min_percent"]): failed.append("primary practical gain") - if summary["primary_95ci"][0] <= 0: + if summary["primary_95ci"] is not None and summary["primary_95ci"][0] <= 0: failed.append("primary confidence interval") for name, row in summary["paths"].items(): - primary = name.startswith("hot_relevance/") + primary = name.startswith(("hot_find/", "hot_relevance/")) p50_limit = (protocol["primary"]["each_query_p50_max_regression_percent"] if primary else protocol["secondary_limits"][ "each_path_p50_max_regression_percent"]) @@ -301,16 +310,31 @@ def main(): result["failed_gates"] = failed result["verdict"] = "FAIL" if failed else "PASS" result["verdict_scope"] = "Timing only; accuracy and contracts reported separately" + if "unpaired_paths" in summary: + if not failed: + result["verdict"] = "INCONCLUSIVE" + result["verdict_scope"] = ( + "The runtimes expose different measurement contracts. Shared operations have " + "paired timings and output parity. Each arm retains all of its measurements." + ) contracts = {arm: child(root, "contracts", {}) for arm, root in roots.items()} write(args.output / "contracts.json", contracts) - result["contracts_pass"] = (contracts["A"] == contracts["B"] and - all(r["passed"] for r in contracts["A"])) + measured = result["groups"][0] + same_api = (any(name.startswith("hot_find/") for name in measured["A"]) + == any(name.startswith("hot_find/") for name in measured["B"])) + result["contract_checks_by_arm"] = { + arm: all(row["passed"] for row in checks) for arm, checks in contracts.items() + } + if not all(result["contract_checks_by_arm"].values()): + result["contracts_pass"] = False + else: + result["contracts_pass"] = contracts["A"] == contracts["B"] if same_api else None if args.cases: cases = [c for path in args.cases for c in json.loads(path.read_text())["cases"]] outcomes = {arm: child(root, "cases", cases) for arm, root in roots.items()} for arm, rows in outcomes.items(): write(args.output / (arm + "-cases.json"), rows) - result["accuracy_output_parity"] = outcomes["A"] == outcomes["B"] + result["accuracy_output_parity"] = outcomes["A"] == outcomes["B"] if same_api else None result["cases_sha256"] = {path.name: digest(path.read_bytes()) for path in args.cases} except Exception as exc: result["error"] = type(exc).__name__ + ": " + str(exc) From 0ddfce1b87c704560977783c509ff42ee324e1e7 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 15:59:39 +0800 Subject: [PATCH 2/7] Pin the compiled catalog to the published skill sources Agent-assisted-by: Codex / unknown [effort=unknown] (author) Signed-off-by: Zhou ziheng --- .../data/skill_library/_compiled/_provenance.json | 2 +- .../knowledge/data/skill_library/_compiled/inputs.json | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 3abf1a04e..02db973e7 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "bf14fec0bd909efcfeb2bc02d69fe227d0c51ce6", + "source_revision": "cbeb57eb5232b2a61ab21395c1b2f31745503f56", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index 93037ddac..7a754774f 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -193,15 +193,16 @@ }, "files": { "LICENSE": "663e51edcd9a3a8f858018ce6924ad2895a24c269c26c39ad75325bcd0f7e5bc", - "SKILL.md": "dd9539c5189582df0ffac7cf24461e377298507566cec44ca3bb9dec1def4b8d", + "SKILL.md": "b04be48d0e4621f6cb11236dfd4ebd19eb69b31cccd2d1f98a1f6b9f5c090c2c", "references/THIRD_PARTY_NOTICES.md": "a0d77db7d2aca0eda811ab3c386cc32b3143f2c2609a042cf4642954f0f6fb09", - "references/minimax-h3-apple.md": "9e11b867fd7e3dede66e73de7410558bcb6b5015a0a218bed376b4b24bebad76", + "references/minimax-h3-apple.md": "0f880d76cdc8baff7b9b54d3ba9bb21a07d0411aa478b9e76241ad9163713481", + "references/minimax-h3-profile.json": "f399fe156568dc83571cd880c045eddf1c6df2d23b1c4455c96efe6576f5627c", "references/minimax-h3-weight-inventory.json": "fbaacaeec340d3ce893556ee864405a0746af4d13530a38cb3d5aa9d60929271", "references/phase-residency.md": "2836a550eb2be7f5a862f51ec7b135ebd9715bf3c4faa84a7ecbc9d9c11f5d8d", "references/precision-and-streaming.md": "7e166c89193f4c7aed852ec95346a2de2b5008dac002e2e1862be1b3e57f6093", "references/source-identity.json": "730f8dd23648a3f8f47b9726cc613d893a79d1817d515eec609a9b06d8a9ff90", "references/source-notes.md": "7304bf9369efc157dc7aa40686dd828cc14db45c49442e908b3d3cc4b329eb86", - "references/validation.md": "0754873a758e048480938314894e25b504ae0c269549312e7f8e6020d83fe294" + "references/validation.md": "c0190b63689f6c71fb439d9ea6a0205e356dcdec1fb47b5b32d9cdb13b4b2430" } }, "audit-llama-runtime-state": { From 48b6314e8b8a07347785f82385a95e3b951bb233 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 16:53:15 +0800 Subject: [PATCH 3/7] Update knowledge CI checks for scoped and paginated reads Follow published read continuations in the wheel and decision-card checks. Exercise service ranking with a session root, record the retired research helper in the compatibility test, and regenerate the coverage digest. Agent-assisted-by: Codex / gpt-6.2-sol [effort=max] (author) Signed-off-by: Zhou ziheng --- docs/skill-coverage.md | 2 +- tests/knowledge/test_decision_cards.py | 10 +++++++++- .../knowledge/test_knowledge_compatibility_shells.py | 12 ++++++------ tests/knowledge/test_ranking_policy.py | 12 +++++++----- tests/repository/check_installed.py | 9 ++++++++- 5 files changed, 31 insertions(+), 14 deletions(-) diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index 4d92f1500..b31be5ebd 100644 --- a/docs/skill-coverage.md +++ b/docs/skill-coverage.md @@ -4,7 +4,7 @@ Generated from the registry, SKILL.md frontmatter and the two maintained matrices. **Do not edit by hand**; regenerate after any registry, skill, matrix or frozen-plan change. -- Input digest: `sha256:b1f3b477729a45ae923a5365d905c2715c5aac9d08a09d2dde92017c7aea2a09` +- Input digest: `sha256:3128dfeab8cdbbddb2afa7156f3887b255fbcb3001a35ba49d351936c7e242cc` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` diff --git a/tests/knowledge/test_decision_cards.py b/tests/knowledge/test_decision_cards.py index 13d6f1ddd..cfa635175 100644 --- a/tests/knowledge/test_decision_cards.py +++ b/tests/knowledge/test_decision_cards.py @@ -280,8 +280,16 @@ def test_real_case_finding_links_follow_visible_order_and_reopen_original(capsys assert card["declared"]["empirical_validation"] == "not_run" source = cli(capsys, read["source_read_args"]) assert source["revision"] == link["revision"] + source_parts = [source["content"]] + page = source + while continuation := page.get("next_read_args"): + page = cli(capsys, continuation) + assert page["revision"] == link["revision"] + assert page["content_resource"] == source["content_resource"] + source_parts.append(page["content"]) assert cli(capsys, read["next_read_args"])["revision"] == link["revision"] - assert card["declared"]["finding"] == json.loads(source["content"])["findings"][position] + source_findings = json.loads("".join(source_parts))["findings"] + assert card["declared"]["finding"] == source_findings[position] compact = compact_read(capsys, link, read)["card"] assert compact["finding_context"]["scope"] == card["declared"]["finding"]["scope"] assert compact["declared"]["origin"] == card["declared"]["origin"] diff --git a/tests/knowledge/test_knowledge_compatibility_shells.py b/tests/knowledge/test_knowledge_compatibility_shells.py index 2ad404b74..711377db1 100644 --- a/tests/knowledge/test_knowledge_compatibility_shells.py +++ b/tests/knowledge/test_knowledge_compatibility_shells.py @@ -51,18 +51,18 @@ def test_retired_root_name_fails_and_moved_exports_match_current_contract(item): names = [*item["exports"]["public"], *item["exports"]["private_used"]] assert len(names) == len(set(names)) # The manifest records the interface at the time of the move. The Find - # migration explicitly retires these scoring APIs and keeps the readers. - retired_rankers = set() + # migration retires the old rankers and model research helpers. + retired_exports = set() if item["importer"] == "_skill_selection": - retired_rankers = { + retired_exports = { "RELEVANCE_METHODS", "TASK_RELEVANCE", "words", "lexical_score", "raw_string_lexical_score", "skill_score", "task_score", } if item["importer"] == "research": - retired_rankers = {"research_knowledge"} - assert retired_rankers <= set(names) + retired_exports = {"research_knowledge", "_profile"} + assert retired_exports <= set(names) for name in names: - assert hasattr(moved, name) == (name not in retired_rankers), name + assert hasattr(moved, name) == (name not in retired_exports), name # A pickle that names a class or function by the retired root path no longer loads. with pytest.raises(ModuleNotFoundError): pickle.loads(f"c{retired}\n{names[0]}\n.".encode("ascii")) diff --git a/tests/knowledge/test_ranking_policy.py b/tests/knowledge/test_ranking_policy.py index 45898378f..48e6e0026 100644 --- a/tests/knowledge/test_ranking_policy.py +++ b/tests/knowledge/test_ranking_policy.py @@ -54,22 +54,24 @@ def test_default_preserves_body_length_idf_backend_and_all_tie_breaks(): assert [r[0] for r in rows] == pytest.approx([idf] * 4 + [idf / 2]) -def test_packaged_service_uses_same_weights_without_content_fingerprints(): +def test_packaged_service_uses_same_weights_without_content_fingerprints(tmp_path): from inferrsi.apps.cli.arguments import parser from inferrsi.apps.workflows.session_knowledge import _service_find + from inferrsi.harness.project_service import no_fingerprints args = parser().parse_args(["find", "cgroupv2", "--limit", "1"]) - selected = _service_find(args, DEFAULT_RANKING_POLICY, None) + selected = _service_find(args, DEFAULT_RANKING_POLICY, None, tmp_path, "find-default") + no_fingerprints(selected) hit, = selected["items"] assert hit["material_ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" assert selected["ranking_policy"] == DEFAULT_RANKING_POLICY.configuration() zero = RankingPolicy("zero", dict.fromkeys(DEFAULT_RANKING_POLICY.weights, 0)) - other = _service_find(args, zero, None) + other = _service_find(args, zero, None, tmp_path, "find-zero") assert other["ranking_policy"] == zero.configuration() assert other["items"] == [] -def test_service_rejects_finite_weights_that_overflow_a_score(): +def test_service_rejects_finite_weights_that_overflow_a_score(tmp_path): from inferrsi.apps.cli.arguments import parser from inferrsi.apps.workflows.session_knowledge import _service_find @@ -77,4 +79,4 @@ def test_service_rejects_finite_weights_that_overflow_a_score(): weights = dict.fromkeys(DEFAULT_RANKING_POLICY.weights, sys.float_info.max) policy = RankingPolicy("large", weights) with pytest.raises(ValueError, match="Ranking score overflow for policy 'large'"): - _service_find(args, policy, None) + _service_find(args, policy, None, tmp_path, "find-overflow") diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 0f43a8ac1..876d7b4fe 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -437,7 +437,14 @@ def cli_json(*words): "--repo-type", "inferrsi", "--limit", "1", "--json")["items"] profile_key = "references/minimax-h3-profile.json" h3_read = cli_json(*h3_hit["read_args"]) -assert profile_key in h3_read["content"] +h3_body = [h3_read["content"]] +page = h3_read +while continuation := page.get("next_read_args"): + page = cli_json(*continuation) + assert page["revision"] == h3_read["revision"] + assert page["content_resource"] == h3_read["content_resource"] + h3_body.append(page["content"]) +assert profile_key in "".join(h3_body) h3_args = h3_hit["read_args"][:] if "--resource" in h3_args: at = h3_args.index("--resource") From 6ac25149d53c6a84b2e27d56b23d71ea8fbee98c Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 18:19:46 +0800 Subject: [PATCH 4/7] Exclude empty historical captures from delivery evidence Check returned resources for every cited local receipt. Preserve archived captures while showing empty receipts separately in session summaries and excluding them from dashboard citation targets. Agent-assisted-by: Codex / gpt-6.2-sol [effort=max] (author) Signed-off-by: Zhou ziheng --- .../apps/views/retrieval_projection.py | 8 ++--- src/inferrsi/harness/optimization.py | 25 +++++++++++---- .../harness/records/knowledge_capture.py | 6 ++++ tests/apps/test_optimization_session.py | 31 +++++++++++++++++-- 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/src/inferrsi/apps/views/retrieval_projection.py b/src/inferrsi/apps/views/retrieval_projection.py index 09b3fc271..01fe50116 100644 --- a/src/inferrsi/apps/views/retrieval_projection.py +++ b/src/inferrsi/apps/views/retrieval_projection.py @@ -14,7 +14,7 @@ relative_location, sanitized_text, ) -from inferrsi.harness.records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES +from inferrsi.harness.records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES, delivered_contexts from inferrsi.harness.records.optimization_log import _IDENTIFIER, _unique from ..integrations.cannbot.round_knowledge import read_metadata, search_metadata @@ -355,7 +355,7 @@ def read_searches(root: Path, campaign_id, rows, retrievals): def _join_scoped_read(query, record, path, targets): """Attach one verified read or budget omission to the hit at its recorded revision.""" - resources = {(c["ref"], c["revision"]): c["resources"] for c in record["contexts"]} + resources = {(c["ref"], c["revision"]): c["resources"] for c in delivered_contexts(record)} omissions = {o["ref"]: o["reason"] for o in record["context_omissions"]} for hit in query["items"]: key = (hit["ref"], hit["revision"]) @@ -403,7 +403,7 @@ def managed_knowledge(root, contexts, submissions=()): if state != "present" or digest != reference.get("sha256"): continue if not external_record: - delivered = {(c["ref"], c["revision"]) for c in record["contexts"] if c["resources"]} + delivered = {(c["ref"], c["revision"]) for c in delivered_contexts(record)} items = [ {**{key: item.get(key) for key in ("ref", "title", "revision")}, "delivered": (item["ref"], item.get("revision")) in delivered} @@ -429,7 +429,7 @@ def managed_knowledge(root, contexts, submissions=()): item["reads"] = [] if number is None: queries[path]["submitted_rounds"] = sorted(submitted_rounds[path]) - if kind == "knowledge_search" or (parent and not delivered): + if kind == "knowledge_search" or not delivered: continue citation = {"source": "local", "retrieval_round": number} citations[path] = {**citation, "ref": path} diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index f31affa9c..45e644cb4 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -12,7 +12,7 @@ from .artifact_primitives import digest, file_lock, sha256 from .atomic_json import atomic_write_json, durable_write_json from .records.evidence import bounded_record_bytes -from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES +from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES, delivered_contexts from .task_protocol import TaskProtocolError from .usage import normalize_usage, usage_totals @@ -489,10 +489,10 @@ def _validate_knowledge_refs(root, contexts, refs): reference = delivered.get(path) if reference is None or (separator and reference["kind"] != "delivered_context"): raise ValueError("Cite a delivered context or CANNBot read receipt from this session") - if separator or reference.get("search_ref") is not None: + if reference["kind"] == "delivered_context": capture = _read_context(root, reference) - if not any((not separator or entry["ref"] == item) and entry["resources"] - for entry in capture["contexts"]): + if not any(not separator or entry["ref"] == item + for entry in delivered_contexts(capture)): raise ValueError("Cite an item with delivered resources from this context") @@ -522,6 +522,16 @@ def _token_totals(records): return {name: totals[name] for name in fields} +def _knowledge_summary(contexts, read_capture): + """Project empty legacy receipts without changing their archived references.""" + return [ + {**ref, "kind": "empty_context"} + if (ref["kind"] == "delivered_context" and ref.get("search_ref") is None + and not any(delivered_contexts(read_capture(ref)))) else ref + for ref in contexts + ] + + def _summary(root, plan, state): if plan.get("evaluation_mode") == "service_reuse": return _service_summary(root, plan, state) @@ -545,7 +555,8 @@ def _summary(root, plan, state): "wall_elapsed_seconds": state.get("settled_at", time.time()) - state["started_at"], "usage": _token_totals(rounds), "usage_scope": "caller_round_exports", "session_usage_export": final.get("observations") if final else None, - "knowledge_deliveries": state["contexts"], + "knowledge_deliveries": _knowledge_summary( + state["contexts"], lambda ref: _read_context(root, ref)), "curve": [ {"round": index + 1, "hypothesis": item["hypothesis"], "assessment": item["assessment"], "best_score": item["best_after"]["score"], @@ -1156,6 +1167,7 @@ def _service_status(root, plan, state): def _service_summary(root, plan, state, *, attempts=None, budget_time=None): + from . import project_service as service from . import service_observations if attempts is None: @@ -1184,7 +1196,8 @@ def _service_summary(root, plan, state, *, attempts=None, budget_time=None): "comparison_parent": state["comparison_parent"], "accepted_attempt_ids": state["accepted_attempt_ids"], "attempts": state["attempts"], - "knowledge_deliveries": state["contexts"], + "knowledge_deliveries": _knowledge_summary( + state["contexts"], lambda ref: service.read(service.safe_path(root, ref["path"]))), "stagnation": state["stagnation"], "usage": _token_totals([item for item in state["attempts"] if item["kind"] == "round"]), "usage_scope": "caller_round_attempt_exports", diff --git a/src/inferrsi/harness/records/knowledge_capture.py b/src/inferrsi/harness/records/knowledge_capture.py index f5694ced5..3ae97f01b 100644 --- a/src/inferrsi/harness/records/knowledge_capture.py +++ b/src/inferrsi/harness/records/knowledge_capture.py @@ -172,6 +172,12 @@ def valid_content_range(bounds, content): and 1 <= line <= start + 1 and end - start == len(content.encode("utf-8"))) +def delivered_contexts(capture): + """Yield contexts with returned resource content.""" + return (context for context in capture["contexts"] + if any(resource["content"] for resource in context["resources"])) + + def verify_capture(raw: bytes) -> tuple[dict | None, str]: """Check the stored bytes of a capture. diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 61b3d8bf5..59f37d5db 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1021,7 +1021,9 @@ def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(sessio plan, state = optimization._load(session) binding = optimization._context_diagnosis(plan, state) path, digest = install_legacy_capture(session, "managed-omitted", "legacy", diagnosis=binding) - capture = json.loads(path.read_bytes()) + raw = path.read_bytes() + capture = json.loads(raw) + assert capture["context_bytes_used"] == 0 and not capture["contexts"] state_path = session / "state.json" reference = {"path": path.relative_to(session).as_posix(), "sha256": digest, "kind": "delivered_context", "diagnosis_id": binding["diagnosis_id"]} @@ -1029,10 +1031,21 @@ def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(sessio state_path.write_text(json.dumps(state), encoding="utf-8") assert dashboard_snapshot(session)["data"]["managed_retrievals"] == [] + refs = [reference["path"], reference["path"] + "#" + capture["items"][0]["ref"]] + args = round_arguments(session, 2) + for ref in refs: + with pytest.raises(SystemExit) as error: + main([*args, "--knowledge-ref", ref]) + assert error.value.code == 2 + assert "delivered resources" in capsys.readouterr().err + _, state, summary = optimization.read_records(session) + assert state["contexts"] == [reference] and not state["rounds"] + assert summary["knowledge_deliveries"] == [{**reference, "kind": "empty_context"}] + submit(session, 2, capsys) state = json.loads(state_path.read_bytes()) submitted, = state["rounds"] - state["pending"] = {**submitted, "candidate_id": "candidate-002"} + state["pending"] = {**submitted, "candidate_id": "candidate-002", "knowledge_refs": refs} state_path.write_text(json.dumps(state), encoding="utf-8") data = dashboard_snapshot(session)["data"] query, = data["managed_retrievals"] @@ -1045,6 +1058,20 @@ def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(sessio state["pending"]["contexts"] = [{**reference, "sha256": "0" * 64}] state_path.write_text(json.dumps(state), encoding="utf-8") assert dashboard_snapshot(session)["data"]["managed_retrievals"][0]["submitted_rounds"] == [1] + assert path.read_bytes() == raw + + +def test_nonempty_legacy_capture_allows_both_reference_forms(session): + from inferrsi.harness import optimization + from tests.fixtures.knowledge_retrieval import install_legacy_capture + + path, digest = install_legacy_capture(session, "managed-query", "legacy-delivered") + relative = path.relative_to(session).as_posix() + context, = json.loads(path.read_bytes())["contexts"] + reference = {"path": relative, "sha256": digest, "kind": "delivered_context"} + optimization._validate_knowledge_refs( + session, [reference], [relative, relative + "#" + context["ref"]], + ) def test_round_declarations_follow_the_candidate_through_assessment(session, capsys, monkeypatch): From ecf60ecb210b1cb6df64bd71511bfb4667f52788 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 19:27:35 +0800 Subject: [PATCH 5/7] Verify scoped round citations after reading a CUDA skill Exercise the search-only rejection before reading the paged body and citing its delivery. Clarify the session, MindIE and explicit bundle boundaries in CLI help and the operation guide. Agent-assisted-by: Codex / gpt-6.2-sol [effort=max] (author) Signed-off-by: Zhou ziheng --- docs/knowledge-operations.md | 4 ++- src/inferrsi/apps/cli/arguments.py | 13 ++++---- tests/apps/test_optimization_session.py | 40 +++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 7 deletions(-) diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index f3e53595e..2dca2051d 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -233,7 +233,9 @@ Its manifest identifies the bytes delivered and the omissions. Manual This explicit bundle operation has its own byte cap. The published context for an indexed Skill includes its declared references, notices and licenses. -Its `record.json` package entrypoint remains available with `--material`. +If the body and required files together exceed the cap, `collect` reports +`context_limit` for that bundle. Its `record.json` package entrypoint remains +available with `--material`. | Additional result | Meaning | | --- | --- | diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index b373d7de0..3a64e3f71 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -259,7 +259,8 @@ def _optimization_actions(stages, *, project=False, historical=False): stage.add_argument("--selection-reason", help="Why this candidate was chosen to try (benchmark or AB/BA)") stage.add_argument("--knowledge-ref", action="append", - help="Delivered path, path#item-ref, or CANNBot receipt; repeatable") + help="Cite a read receipt in a benchmark or AB/BA campaign round " + "(path, path#item-ref, or CANNBot receipt; repeatable)") stage.add_argument("--mechanism-file", type=Path, help="JSON mechanism with expected region/counter directions") if project: @@ -762,14 +763,14 @@ def parser(*, parser_class=argparse.ArgumentParser, historical=False) -> argpars find = commands.add_parser( "find", - help="Rank packaged skills, imported records and checkout cases for one " - "question; returns corpus paths with optional pinned decision card reads", + help="Find knowledge for a question and return commands to read the hits", ) find.add_argument("query", nargs="?", help="Describe the problem in your own words") if historical: find.add_argument("--model") _historical_model_dimensions(find) - find.add_argument("--session", type=Path, help="Find under this session's knowledge policy") + find.add_argument("--session", type=Path, + help="Apply this session's knowledge policy and record the search") if historical: find.add_argument("--capture-id") find.add_argument("--context-bytes", type=int) @@ -780,7 +781,7 @@ def parser(*, parser_class=argparse.ArgumentParser, historical=False) -> argpars find.add_argument("--revision", action="append", dest="revisions", metavar="store:ID=REV", help="Search a retained store revision") find.add_argument("--input", type=Path, - help="Run a native MindIE JSON request under the project grant") + help="Run a standalone MindIE JSON request under the project grant") find.add_argument("--decision-cards", action="store_true", help="Add pinned L1 read commands and their UTF-8 card sizes") find.add_argument("--limit", type=int, default=5 if historical else None) @@ -853,7 +854,7 @@ def parser(*, parser_class=argparse.ArgumentParser, historical=False) -> argpars collect.add_argument("query", nargs="?", default="") collect.add_argument( "--context-bytes", type=int, - help="UTF-8 budget for context bodies and any explicitly requested L1 cards", + help="UTF-8 cap for assembled bodies, attachments, and requested L1 cards", ) collect.add_argument( "--decision-card", action="append", metavar="REF[=FINDING]", diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index c54530ea6..f6ed3fc35 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1022,6 +1022,46 @@ def test_knowledge_delivery_is_retained_and_bound_to_round(session, capsys): assert "current round and diagnosis" in capsys.readouterr().err +def test_round_cites_the_cuda_skill_read_and_rejects_the_search(session, capsys): + from tests.apps.test_campaign_task_selection import BASELINE_CUE + + assert main(["find", BASELINE_CUE, "--session", str(session), + "--backend", "cuda", "--limit", "2"]) == 0 + found = json.loads(capsys.readouterr().out) + hit = found["items"][0] + assert hit["material_ref"] == "package:inferrsi.common.skills.inference_benchmark_design" + search = found["reference"] + assert search["kind"] == "knowledge_search" + + args = round_arguments(session, 2) + with pytest.raises(SystemExit) as error: + main([*args, "--knowledge-ref", search["path"]]) + assert error.value.code == 2 + assert "Cite a delivered context" in capsys.readouterr().err + _, state, _ = optimization.read_records(session) + assert not state["rounds"] and state["pending"] is None + + paths, body = [], bytearray() + read_args = hit["read_args"] + while read_args is not None: + assert main(read_args) == 0 + opened = json.loads(capsys.readouterr().out) + assert opened["content_resource"] == hit["body_resource"] + assert opened["revision"] == hit["revision"] + assert opened["reference"]["kind"] == "delivered_context" + paths.append(opened["reference"]["path"]) + body.extend(opened["content"].encode("utf-8")) + read_args = opened.get("next_read_args") + assert len(body) == 13_166 + + citation = f"{paths[0]}#{hit['material_ref']}" + assert main([*args, "--knowledge-ref", citation]) == 0 + assert json.loads(capsys.readouterr().out)["completed_rounds"] == 1 + _, state, _ = optimization.read_records(session) + completed, = state["rounds"] + assert completed["knowledge_refs"] == [citation] + + def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(session, capsys): from inferrsi.apps.views.dashboard import dashboard_snapshot from inferrsi.harness import optimization From bf3204b9327b21c513969915ee1868a469de8616 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 21:08:00 +0800 Subject: [PATCH 6/7] Register scoped knowledge delivery through the Harness Delegate discovery and exact resource reads to the KnowledgeReader. Register the observed bytes under the session lock and reserve historical or empty receipts for audit. Agent-assisted-by: Codex / gpt-6.2-sol [effort=max] (author) Signed-off-by: Zhou ziheng --- docs/guides/operations.md | 6 +- docs/knowledge-operations.md | 17 +- src/inferrsi/apps/cli/__init__.py | 55 +-- src/inferrsi/apps/views/capture_delivery.py | 9 +- src/inferrsi/apps/views/codex_knowledge.py | 8 +- .../apps/views/retrieval_projection.py | 3 +- src/inferrsi/apps/workflows/knowledge.py | 95 +--- .../apps/workflows/session_knowledge.py | 404 ++---------------- src/inferrsi/harness/optimization.py | 308 ++++++++++++- src/inferrsi/harness/optimization_session.py | 2 + .../harness/records/knowledge_capture.py | 5 +- .../knowledge/knowledge_operations.py | 242 ++++++++++- tests/apps/test_knowledge_read_ranges.py | 34 ++ tests/apps/test_optimization_session.py | 33 +- tests/apps/test_service_knowledge_snapshot.py | 7 +- tests/fixtures/knowledge_retrieval.py | 5 +- 16 files changed, 711 insertions(+), 522 deletions(-) diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 29812cdf3..8e5b182ac 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -421,8 +421,10 @@ CLI. Update installed plugin bundles to get the matching instructions and runtim | `cannbot search QUERY` | `find QUERY --backend ascend` with the project grant. Set the upstream cap with `--external-limit N` and use the returned locator for a card read. | | `mindie query --input FILE` | `find --input FILE` with the same native request and project grant. | -Python callers use `find(question, load_corpus(...))` from -`inferrsi.knowledge.knowledge_find`. For a filtered inventory use +Python callers can use `KnowledgeReader.find(question, ...)` for discovery +and `KnowledgeReader.read_hit(...)` for a pinned body or resource page. +The lower-level `find(question, load_corpus(...))` remains available. +For a filtered inventory use `catalog.list_knowledge(...)`. The existing query-free `search_knowledge` spelling and explicit-ID `KnowledgeReader.collect` remain available. Catalog filters select packaged records. A custom Skill root or store combined with a diff --git a/docs/knowledge-operations.md b/docs/knowledge-operations.md index 2dca2051d..53e8c3d6e 100644 --- a/docs/knowledge-operations.md +++ b/docs/knowledge-operations.md @@ -179,8 +179,14 @@ inferrsi find "fixed seed diffusion baseline" --session ``` Run the emitted scoped `read` for the relevant hit. The session records the -ordered hits, then the read it actually served. Each operation returns its -campaign-relative receipt in `reference.path`. To follow a link in the primary body, +ordered hits, then the read it actually served. Find reports zero delivered +bytes even when it returns hits. Each operation returns its campaign-relative +receipt in `reference.path`. An empty resource produces an `empty_context` +receipt for audit. A round can cite a scoped read that returned content. +Historical captures remain available for reviewing and replaying old rounds. +New rounds require a scoped read receipt. + +To follow a link in the primary body, append the path as printed, for example `--resource references/benchmark-commands.md`, to the hit's read arguments. Keep the original `--session` and `--search-ref`. Read resolves the link inside the pinned bundle and the receipt names the full @@ -193,8 +199,11 @@ and search reference. Pages limit their JSON content string to 6 KiB so the normal Agent tool response can carry the content and its receipt together. This is a per-response size limit; it does not limit how much of the file you can read. `next_byte_range` also exposes the continuation coordinates for -callers using `--byte-range START LENGTH`. Each receipt identifies only the -byte range it delivered; one page does not prove receipt of the whole file. +callers using `--byte-range START LENGTH`. Use `--byte-range 0 3900` to +request at most the first 3,900 UTF-8 bytes. Each receipt identifies the +bytes in that page. A scoped read serves one selected body or linked resource. +For an exact L1 decision card use standalone `read --layer L1`. Use explicit +bundle assembly when the required files need to be delivered as a group. Content responses omit the full resource inventory. To inspect that inventory, run `read ID --revision REVISION` without `--material` or `--resource`. diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index b90010f21..474c21fe8 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -13,7 +13,6 @@ from ...contracts.runspec import revision_matches as _revision_matches from ...knowledge.catalog import BACKENDS, get_knowledge, list_knowledge from ...knowledge.knowledge_operations import KnowledgeReader -from ...knowledge.ranking_policy import DEFAULT_RANKING_POLICY from ..host.prepared_environment import inspect_environment from ..legacy.reporting import write_report from ..workflows.campaign import capture_context, create_campaign @@ -26,17 +25,14 @@ def _print(value: object) -> None: print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False)) -def run_find(args, *, ranking_policy=DEFAULT_RANKING_POLICY, backend=None, local_only=False): - """Run Find over the selected sources, using the session policy when supplied.""" - from ...knowledge.knowledge_find import find, load_corpus - +def run_find(args): + """Run standalone Find over the selected sources.""" if (args.query is None) == (args.input is None): raise ValueError("Supply a question or --input FILE for a native MindIE request") if args.input is not None: from ..integrations.mindie.project import query_input - if (local_only or args.no_external or args.external_source is not None - or args.backend or args.platform): + if args.no_external or args.external_source is not None or args.backend or args.platform: raise ValueError("Use find --input FILE for a native MindIE request. " "The file and project grant specify its source and conditions.") if (args.store or args.skill_root or args.revisions or args.repo_type or args.tier @@ -48,7 +44,7 @@ def run_find(args, *, ranking_policy=DEFAULT_RANKING_POLICY, backend=None, local kinds = tuple(k.strip() for k in args.kinds.split(",") if k.strip()) if not kinds or set(kinds) - {"case", "skill", "record"}: raise ValueError("--kinds takes a subset of case,skill,record") - backend = args.backend or backend + backend = args.backend if args.external_source == "mindie-agent" and not args.no_external: if backend != "ascend": raise ValueError("--external-source mindie-agent requires --backend ascend") @@ -67,23 +63,35 @@ def run_find(args, *, ranking_policy=DEFAULT_RANKING_POLICY, backend=None, local index = load_searchspace_index_for_skill_root( args.skill_root, option="--show-searchspace-coordinates", ) - reader = knowledge_reader(skill_root=args.skill_root, store_root=args.store) - corpus = load_corpus( - args.skill_root, kinds=kinds, searchspace_index=index, repo=args.repo_type, tier=args.tier, - scenario=args.scenario, backend=backend, store=reader.store, - revisions=_revisions(args.revisions or []), - ) - return find( - args.query, corpus, limit=args.limit, explain=args.explain, - decision_cards=args.decision_cards, pin_material=args.session is not None, - ranking_policy=ranking_policy, - registry=None if local_only or args.no_external else _channels(source=args.external_source), - backend=backend, platform=args.platform, external_limit=args.external_limit, + return _knowledge_reader(args).find( + args.query, kinds=kinds, repo=args.repo_type, tier=args.tier, scenario=args.scenario, + backend=backend, revisions=_revisions(args.revisions or []), searchspace_index=index, + limit=args.limit, explain=args.explain, decision_cards=args.decision_cards, + registry=None if args.no_external else _channels(source=args.external_source), + platform=args.platform, external_limit=args.external_limit, external_timeout=args.external_timeout, searchspace_coordinate=coordinate, show_searchspace_coordinates=args.show_searchspace_coordinates, ) +def _session_find(args): + from ..workflows.session_knowledge import find_in_session + + if args.query is None or ( + args.decision_cards or args.input or args.external_source is not None or args.platform + or args.searchspace_coordinate or args.show_searchspace_coordinates + or args.external_limit is not None or args.external_timeout != 8.0 + ): + raise ValueError("Session Find requires a question and uses its frozen external source") + options = { + "query": args.query, "backend": args.backend, "scenario": args.scenario, + "limit": args.limit, "kinds": args.kinds, "repo": args.repo_type, "tier": args.tier, + "explain": args.explain, "no_external": args.no_external, + "revisions": _revisions(args.revisions or []), + } + return find_in_session(args, _knowledge_reader(args), options) + + def _round_provider(plan): from ..integrations.external_channels import round_provider @@ -697,9 +705,7 @@ def main(argv: list[str] | None = None) -> int: if args.limit is None: args.limit = 5 if args.session is not None: - from ..workflows.session_knowledge import find_in_session - - result = find_in_session(args, run_find) + result = _session_find(args) else: result = run_find(args) if args.json or args.session or args.input: @@ -780,10 +786,9 @@ def main(argv: list[str] | None = None) -> int: return 0 if args.command == "read": if args.session is not None: - from ..workflows.knowledge import read_selected_hit from ..workflows.session_knowledge import read_in_session - _print(read_in_session(args, read_selected_hit)) + _print(read_in_session(args, _knowledge_reader(args))) return 0 if args.search_ref is not None: raise ValueError("--search-ref requires --session") diff --git a/src/inferrsi/apps/views/capture_delivery.py b/src/inferrsi/apps/views/capture_delivery.py index 486981393..c0bb9414f 100644 --- a/src/inferrsi/apps/views/capture_delivery.py +++ b/src/inferrsi/apps/views/capture_delivery.py @@ -66,9 +66,10 @@ def capture_return_texts(trace, lines, references, context_ids, *, exec_returns= def _managed_envelope(doc, reference): action = (doc.get("retrieval") or {}).get("entrypoint") if action in ("find", "read") and "display" in doc["retrieval"]: - ref = {"path": reference["path"], "kind": ("knowledge_search" if action == "find" - else "delivered_context"), - "sha256": reference["sha256"]} + kind = doc["retrieval"].get( + "receipt_kind", "knowledge_search" if action == "find" else "delivered_context", + ) + ref = {"path": reference["path"], "kind": kind, "sha256": reference["sha256"]} return json.dumps(scoped_response(doc, ref, "."), ensure_ascii=False, indent=2) return json.dumps({"reference": reference, "context": doc}, ensure_ascii=False, indent=2) @@ -164,6 +165,8 @@ def visible_capture_resources(doc, texts): chunks = ["\n" + text + "\n" for text in texts] for context in doc["contexts"]: for resource in context["resources"]: + if not resource["content"]: + continue block = assemble_context_text([{ **context, "resources": [resource], "omissions": [], }]) diff --git a/src/inferrsi/apps/views/codex_knowledge.py b/src/inferrsi/apps/views/codex_knowledge.py index 2f88c41eb..6eb08a65e 100644 --- a/src/inferrsi/apps/views/codex_knowledge.py +++ b/src/inferrsi/apps/views/codex_knowledge.py @@ -344,7 +344,7 @@ def _read_result(args, output): or end - start > args.byte_range[1])): raise ValueError("read returned inconsistent byte range") material["content_range"] = bounds - return material, (path, body) + return material, (path, body) if body else None def decode(call, code, output): @@ -413,8 +413,10 @@ def decode(call, code, output): if getattr(args, "session", None) is not None and tool in ("find", "read"): returned = json.loads(output) reference = returned["reference"] - kind = "knowledge_search" if tool == "find" else "delivered_context" - if (reference["kind"] != kind or not isinstance(reference["path"], str) + kinds = ("knowledge_search",) if tool == "find" else ("delivered_context",) + if tool == "read" and returned.get("content") == "": + kinds += ("empty_context",) + if (reference["kind"] not in kinds or not isinstance(reference["path"], str) or relative_location(reference["path"]) != reference["path"]): raise ValueError("invalid scoped receipt") if "sha256" in reference: diff --git a/src/inferrsi/apps/views/retrieval_projection.py b/src/inferrsi/apps/views/retrieval_projection.py index 01fe50116..321d7416c 100644 --- a/src/inferrsi/apps/views/retrieval_projection.py +++ b/src/inferrsi/apps/views/retrieval_projection.py @@ -392,7 +392,8 @@ def managed_knowledge(root, contexts, submissions=()): if not isinstance(path, str) or Path(path).is_absolute(): continue external_record = kind in ("external_search", "external_read") - if kind not in ("knowledge_search", "delivered_context") and not external_record: + if (kind not in ("knowledge_search", "delivered_context", "empty_context") + and not external_record): continue if external_record and ( type(number) is not int or number < 1 diff --git a/src/inferrsi/apps/workflows/knowledge.py b/src/inferrsi/apps/workflows/knowledge.py index 1878d5d2e..94e16a223 100644 --- a/src/inferrsi/apps/workflows/knowledge.py +++ b/src/inferrsi/apps/workflows/knowledge.py @@ -1,70 +1,11 @@ """Compose the standalone Apps knowledge operations through Knowledge ports.""" -import json -from hashlib import sha256 from pathlib import Path -from inferrsi.knowledge._skill_selection import INLINE_PAGE_BYTES, skill_procedure, text_page -from inferrsi.knowledge.knowledge_find import installed_skill_root -from inferrsi.knowledge.knowledge_operations import KnowledgeReader, resolve_resource_key +from inferrsi.knowledge.knowledge_operations import KnowledgeReader, read_page, resolve_resource_key from inferrsi.knowledge.knowledge_store import KnowledgeStore -def _character_bytes(raw, start): - end = start + 1 - while end < len(raw) and raw[end] & 0xc0 == 0x80: - end += 1 - return end - start - - -def read_page(view, requested, *, source_hash=None, source_ranges=None): - """Slice the UTF-8 material view; offsets always refer to the same pinned view.""" - if "content" not in view: - if requested is not None: - raise ValueError("--byte-range requires --material or --resource") - return - content = view["content"] - raw = content.encode("utf-8") - if requested is None: - if len(raw) <= INLINE_PAGE_BYTES: - serialized = json.dumps(content, ensure_ascii=False).encode("utf-8") - if len(serialized) <= INLINE_PAGE_BYTES: - return - requested = (0, INLINE_PAGE_BYTES) - start, length = requested - if start < 0 or length < 1 or start > len(raw) or (start == len(raw) and start != 0): - raise ValueError("--byte-range requires a valid start byte and a positive length") - if start < len(raw) and raw[start] & 0xc0 == 0x80: - raise ValueError("--byte-range must start at a UTF-8 character boundary") - text, stop = text_page(raw, start, length) - if stop == start and start < len(raw): - raise ValueError(f"--byte-range needs at least {_character_bytes(raw, start)} bytes " - "for the next UTF-8 character") - # Put the continuation coordinates before a potentially long stdout body. - del view["content"] - view["content_range"] = { - "start": start, "end": stop, "total_bytes": len(raw), - "first_line": raw.count(b"\n", 0, start) + 1, - } - if stop < len(raw): - view["next_byte_range"] = [stop, max(length, _character_bytes(raw, stop))] - if source_hash is not None or source_ranges is not None: - # A Skill procedure omits frontmatter. Map the selected view bytes back - # onto the already pinned source ranges, including pages crossing a gap. - original = view.get("content_view", {}) - ranges, offset = [], 0 - for lo, hi in original.get("source_byte_ranges", source_ranges or [(0, len(raw))]): - begin, end = max(start - offset, 0), min(stop - offset, hi - lo) - if begin < end: - ranges.append([lo + begin, lo + end]) - offset += hi - lo - view["content_view"] = {"locator": "byte-range", "source_byte_ranges": ranges} - if source_hash is not None: - view["content_view"].update(source_sha256=source_hash, - sha256=sha256(raw[start:stop]).hexdigest()) - view["content"] = text - - def read_continuation(args, view): """Return an executable next-page command for the same selected material.""" if "next_byte_range" not in view: @@ -125,37 +66,3 @@ def read( path = view.get("content_resource", view["entrypoint"]) read_page(view, byte_range, source_hash=view["resources"][path]) return qualified, view["revision"], view - - -def read_selected_hit(hit: dict, *, resource: str | None = None) -> tuple[dict, dict]: - """Open a Find pin once. The tool response and the round receipt use the same bytes.""" - argv = hit["material_read_args"] - root = installed_skill_root() if "--installed-library" in argv else None - if "--skill-root" in argv: - root = Path(argv[argv.index("--skill-root") + 1]) - store = Path(argv[argv.index("--store") + 1]) if "--store" in argv else None - reader = knowledge_reader(skill_root=root, store_root=store) - ref, bundle = reader.read_resolved(hit["material_ref"], revision=hit["revision"]) - view = bundle.view() - body = hit["body_resource"] - path = resolve_resource_key(body if resource is None else resource, body, bundle.content) - if resource is not None and path != resource: - view["body_resource"] = body - raw = bundle.content[path] - data, locator = skill_procedure(path, raw) if resource is None else (raw, {}) - content = data.decode("utf-8") - digest = view["resources"][path] - role = "reference" if path != hit["body_resource"] else ( - "record" if path == "record.json" else "core" - ) - delivered = {"path": path, "role": role, "sha256": digest, "content": content} - if locator: - location = {**locator, "source_sha256": digest, "sha256": sha256(data).hexdigest()} - delivered.update(location) - view["content_view"] = location - context = {"ref": ref, "revision": view["revision"], "resources": [delivered], - "sources": view["sources"], "content_bytes": len(data), "omissions": []} - view.pop("resources") - view.pop("required_resources", None) - view.update(ref=ref, content=content, content_resource=path) - return view, context diff --git a/src/inferrsi/apps/workflows/session_knowledge.py b/src/inferrsi/apps/workflows/session_knowledge.py index 5205afa8f..6bd9fa5c0 100644 --- a/src/inferrsi/apps/workflows/session_knowledge.py +++ b/src/inferrsi/apps/workflows/session_knowledge.py @@ -1,382 +1,54 @@ -"""Find and read knowledge as separate, attributable operations in a campaign.""" +"""Adapt CLI options to a shared Harness knowledge operation.""" -from __future__ import annotations - -import json -import shutil -from contextlib import contextmanager -from pathlib import Path -from uuid import uuid4 - -from inferrsi import __version__ -from inferrsi.harness import optimization, project_service -from inferrsi.harness.atomic_json import atomic_write_json -from inferrsi.harness.optimization_session import _runtime_identity -from inferrsi.harness.records.evidence import bounded_record_bytes, sanitized_text -from inferrsi.harness.records.knowledge_capture import ( - MAX_CONTEXT_CAPTURE_BYTES, - capture_campaign, - scoped_response, - store_capture, -) -from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, skill_procedure -from inferrsi.knowledge.catalog import ( - SCENARIO_ALIASES, - _catalog_corpus, - knowledge_records, -) -from inferrsi.knowledge.channels import no_match_across_sources +from inferrsi.harness.optimization import knowledge_operation +from inferrsi.harness.records.knowledge_capture import scoped_response from inferrsi.knowledge.context_projection import assemble_context_text -from inferrsi.knowledge.knowledge_find import rank -from inferrsi.knowledge.knowledge_operations import service_body, service_resources from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, managed_ranking_policy from ..integrations.external_channels import round_provider -from .knowledge import read_continuation, read_page - -# Only portable Find data goes in an immutable capture. The installed launcher and -# session directory belong to this invocation, not the material's identity. -_HIT = ( - "material_ref", "revision", "body_resource", "material_read_args", "id", "authority", "kind", - "path", "title", "summary", "state", "score", "source", "source_location", "applicability", - "limitations", "limitations_withheld", "findings", "findings_withheld", - "next_read_content_bytes", "matched", "unreadable", - "repo", "backend", "scenario", "tier", "sources", "locally_verified", -) - - -@contextmanager -def _campaign(root): - manifest = capture_campaign(root, "find") - with optimization._locked(root): - if not manifest.get("managed_optimization"): - yield manifest, {}, None, None, DEFAULT_RANKING_POLICY - return - plan, state = optimization._load(root) - service = plan.get("evaluation_mode") == "service_reuse" - active = state if not service else { - **state, "deadline": optimization._service_deadline(state), - "state": "active" if state["state"] == "needs_baseline" else state["state"], - } - number = optimization._knowledge_round(plan, active) - binding = optimization._context_diagnosis(plan, state) - if not service and plan["runtime_identity"] != _runtime_identity(): - raise ValueError("Optimization runtime changed, use its frozen runtime to resume") - policy = optimization.resolve_frozen_ranking(plan, managed_ranking_policy) - yield manifest, plan, state, (number, binding), policy - - -def _save(root, campaign, state, step, *, context_id, action, request, items, display, contexts=()): - number, binding = step or (None, None) - service = campaign.get("evaluation_mode") == "service_reuse" - captured_by = f"inferrsi {action} {__version__}" - selection = {"method": FIND_RELEVANCE, "ranking_applied": action == "find", - "state": "applied" if action == "find" else "explicit_ids", - "ranking_policy": request["ranking_policy"]} - observation = {"schema_version": 1, "entrypoint": action, "calls": [action], - "request": request, "selection": selection, "display": display, - "counts": {"matched": display.get("matched"), "returned": len(items)}, - "items": [{k: row[k] for k in ("ref", "revision") if k in row} for row in items]} - facts = { - "request": request, "selection": selection, "items": items, "omissions": [], - "context_omissions": [], "context_budget": None, - "context_bytes_used": sum(c["content_bytes"] for c in contexts), - "contexts": list(contexts), "retrieval": observation, - } - kind = "knowledge_search" if action == "find" else "delivered_context" - path = f"knowledge/{context_id}.json" - reference = {"path": path, "kind": kind} - if service: - document = {**facts, "kind": "service_knowledge_context", "context_id": context_id, - "captured_by": captured_by, "prepared_not_consumed": True} - if action == "find": - document["source_snapshot"] = f"knowledge/sources/{context_id}" - if binding: - document["diagnosis_binding"] = binding - project_service.no_fingerprints(document) - (root / "knowledge").mkdir(exist_ok=True) - atomic_write_json(project_service.safe_path(root, path), document) - else: - target, digest = store_capture( - root, campaign_id=campaign["campaign_id"], context_id=context_id, - captured_by=captured_by, diagnosis_binding=binding, - assembled_text=assemble_context_text(list(contexts)), - **facts, - ) - reference["sha256"] = digest - document = json.loads(target.read_bytes()) - if state is not None: - retained = {**reference, "round": number} - if binding: - retained["diagnosis_id"] = binding["diagnosis_id"] - if action == "read": - retained["search_ref"] = request["search_ref"] - state["contexts"].append(retained) - return reference, document -def _retain_service_sources(root, context_id, selections): - """Publish only complete, byte-consistent source sets before their search receipt.""" - relative = f"knowledge/sources/{context_id}" - destination = project_service.safe_path(root, relative) - temporary = destination.with_name("." + context_id) - temporary.mkdir(parents=True) - try: - for record, document in selections: - resources = service_resources(record) - primary = record.get("skill_documents", {}).get("original") or "record.json" - if document.kind == "skill": - if (primary != "data/skill_library/" + document.path - or record["skill_metadata"]["name"] != document.identity - or record["backend"] != document.backend): - raise ValueError( - "Knowledge ownership changed while finding material; run Find again" - ) - raw = resources[primary].decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") - body, _ = skill_procedure(primary, raw.encode("utf-8")) - if body.decode("utf-8") != document.fields["body"]: - raise ValueError("Knowledge changed while finding material; run Find again") - directory = temporary / record["id"] - for path, content in resources.items(): - target = project_service.safe_path(directory, path) - target.parent.mkdir(parents=True, exist_ok=True) - target.write_bytes(content) - target.chmod(target.stat().st_mode & ~0o222) - temporary.rename(destination) - finally: - if temporary.exists(): - shutil.rmtree(temporary) +def _operate(args, reader, action, options): + return knowledge_operation( + args.session, reader, action, options, default_policy=DEFAULT_RANKING_POLICY, + ranking_policy_for=managed_ranking_policy, + assemble_context=assemble_context_text, external_provider_for=round_provider, + ) -def _service_find(args, policy, backend, root, context_id): - if not args.query: - raise ValueError("Service-reuse Find requires a question") - kinds = {item.strip() for item in args.kinds.split(",") if item.strip()} - if not kinds or kinds - {"case", "skill", "record"}: - raise ValueError("--kinds takes a subset of case,skill,record") - records = knowledge_records(file_fingerprints=False) - scenario = SCENARIO_ALIASES.get(args.scenario, args.scenario) +def _response(args, saved): + view = scoped_response( + saved["document"], saved["reference"], str(args.session), + skill_root=args.skill_root, store=args.store, + ) + if "external" in saved: + external = saved["external"] + prefix = ["benchmarks", "session"] if saved["task_source"] == "benchmark" else ["campaign"] + read = [*prefix, "knowledge-read", "--session", str(args.session), + "--search-ref", external["reference"]["path"], "--locator"] + view["external"] = {**external, "items": [ + {**hit, "read_args": [*read, hit["locator"]]} for hit in external["items"] + ]} + return view - def matches(record): - skill = record.get("index_type") == "packaged-skill" - declared = record.get("scenario", "") - applicable = (not scenario or declared == scenario - or (skill and declared == "skills.discovery") - or (declared.endswith(".*") and scenario.startswith(declared[:-1]))) - return (("skill" if skill else "record") in kinds - and (not backend or record["backend"] in ("common", backend)) - and (not args.tier or record.get("tier", "contribution") == args.tier) - and (not args.repo_type or record["repo"] == args.repo_type) - and applicable) - records = [record for record in records if matches(record)] - corpus, records = _catalog_corpus(records, file_fingerprints=False) - _, _, ranked = rank(args.query, corpus, policy) - items = [] - selections = [] - for score, _, index, components in ranked[:args.limit]: - record = records[index] - selections.append((record, corpus.documents[index])) - ref = "package:" + record["id"] - revision = record["sources"][0]["commit"] - path = record.get("skill_documents", {}).get("original") or "record.json" - items.append({ - "id": record["id"], "authority": "package", "title": record["title"], - "kind": "skill" if record.get("index_type") == "packaged-skill" else "record", - "repo": record["repo"], "tier": record.get("tier", "contribution"), - "backend": record["backend"], "scenario": record["scenario"], - "score": round(score, 2), "material_ref": ref, "revision": revision, - "body_resource": path, "material_read_args": ["read", ref, "--revision", revision], - **({"matched": components} if args.explain else {}), - }) - _retain_service_sources(root, context_id, selections) - return {"query": args.query, "matched": len(ranked), "no_match": not ranked, "items": items, - "ranking_policy": policy.configuration(), "sources": ["package"]} +def find_in_session(args, reader, options): + return _response(args, _operate(args, reader, "find", options)) -def _service_read(root, search, hit, resource): - snapshot = f"knowledge/sources/{search['context_id']}" - if search.get("source_snapshot") != snapshot: - raise ValueError("This Find has no retained source bytes; run Find again before reading") - source_root = project_service.safe_path(root, snapshot + "/" + hit["id"]) - record = project_service.read(project_service.safe_path(source_root, "record.json")) - if record.get("id") != hit["id"] or record["sources"][0]["commit"] != hit["revision"]: - raise ValueError("The retained source does not match this Find") - primary = hit["body_resource"] - path, data, locator = service_body(record, resource, source_root=source_root) - ref, revision = hit["material_ref"], hit["revision"] - selected = {"path": path, "role": "core" if path == primary else "reference", - "content": data.decode("utf-8"), **locator} - context = {"ref": ref, "revision": revision, "resources": [selected], - "content_bytes": len(data), "omissions": [], "sources": record["sources"]} - view = {"ref": ref, "id": hit["id"], "revision": revision, "entrypoint": primary, - "content_resource": path, "content": selected["content"], "sources": record["sources"]} - if resource is not None and path != resource: - view["body_resource"] = primary - if locator: - view["content_view"] = locator - return view, context - - -def find_in_session(args, find_local): - root = args.session.resolve() - if args.limit < 1: - raise ValueError("--limit must be positive") - if (args.decision_cards or args.input or args.external_source is not None - or args.platform - or args.searchspace_coordinate or args.show_searchspace_coordinates - or args.external_limit is not None or args.external_timeout != 8.0): - raise ValueError("Session Find provides body reads and uses its frozen external source") - with _campaign(root) as (campaign, plan, state, step, policy): - if state is not None and (args.skill_root or args.store or args.revisions): - raise ValueError("Managed Find uses the session's installed corpus") - query = args.query - backend = args.backend or campaign.get("backend") - settings = plan.get("external_knowledge") - external_enabled = (settings and not args.no_external - and (backend is None or backend == settings["backend"])) - if external_enabled: - if step[0] is None: - raise ValueError("Round budget consumed, run independent final evaluation") - query = sanitized_text(query, "", limit=None) - args.query = query - service = campaign.get("evaluation_mode") == "service_reuse" - context_id = "find-" + uuid4().hex - result = (_service_find(args, policy, backend, root, context_id) if service else - find_local(args, ranking_policy=policy, backend=backend, local_only=True)) - request = {"query": query, "relevance": query, "relevance_method": FIND_RELEVANCE, - "ranking_policy": result["ranking_policy"], - "backend": backend, "scenario": args.scenario, "limit": args.limit, - "kinds": args.kinds, "repo": args.repo_type, - "tier": args.tier, "sources": result["sources"]} - if args.no_external: - request["external_source"] = "none" - if args.revisions: - request["revisions"] = dict(pin.split("=", 1) for pin in args.revisions) - if plan: - optimization._check_context_ranking(plan, {"request": request}) - items = [{key: hit[key] for key in _HIT if key in hit} for hit in result["items"]] - # Some Find hits (for instance unavailable sources) have no material to open. - for item in items: - item["ref"] = item.get("material_ref") or f"{item['authority']}:{item['id']}" - argv = list(item.get("material_read_args", ())) - for flag in ("--skill-root", "--store"): - if flag in argv: - argv[argv.index(flag) + 1] = flag[2:].upper().replace("-", "_") - if argv: - item["material_read_args"] = argv - external = None - if external_enabled: - remaining = optimization._knowledge_time(plan, state) - external = (round_provider(plan).search(query, settings=settings, limit=args.limit, - timeout=remaining) if remaining > 0 else - {"state": "timeout", "items": [], "count": 0}) - result["no_match"] = no_match_across_sources(result["matched"], [external]) - display = {key: value for key, value in result.items() - if key not in ("items", "external", "searchspace_source")} - reference, document = _save( - root, campaign, state, step, context_id=context_id, - action="find", request=request, items=items, display=display, - ) - response = scoped_response(document, reference, str(args.session), - skill_root=args.skill_root, store=args.store) - if external is not None: - number = step[0] - search = {**external, **settings, "context_ref": reference["path"]} - extra = optimization._store_knowledge(root, "external_search", number, search) - state["contexts"].append(extra) - prefix = (["benchmarks", "session"] if plan["task_source"] == "benchmark" - else ["campaign"]) - read = [*prefix, "knowledge-read", "--session", str(args.session), - "--search-ref", extra["path"], "--locator"] - response["external"] = {**search, "reference": extra, "items": [ - {**hit, "read_args": [*read, hit["locator"]]} for hit in search["items"] - ]} - if state is not None: - atomic_write_json(root / "state.json", state) - return response - - -def _open_search(root, campaign, state, step, location): - path = Path(location) - if path.parent.as_posix() != "knowledge" or path.suffix != ".json": - raise ValueError("Supply a search reference from this campaign") - if state is not None: - number, binding = step - ref = next((entry for entry in state["contexts"] if entry["path"] == location - and entry["kind"] == "knowledge_search" and entry.get("round") == number - and entry.get("diagnosis_id") == (binding or {}).get("diagnosis_id")), None) - if ref is None: - raise ValueError("Supply a Find reference from the current round and diagnosis") - search = (project_service.read(project_service.safe_path(root, location)) - if campaign.get("evaluation_mode") == "service_reuse" else - optimization._read_context(root, ref)) - else: - from .campaign import verify_capture - - raw, _ = bounded_record_bytes(root, location, MAX_CONTEXT_CAPTURE_BYTES) - search = verify_capture(raw)[0] if raw else None - if not search or search["campaign_id"] != campaign["campaign_id"]: - raise ValueError("Supply a verified Find reference from this campaign") - if search.get("retrieval", {}).get("entrypoint") != "find": - raise ValueError("The reference must identify a Find result") - return search - - -def read_in_session(args, read_hit): +def read_in_session(args, reader): if not args.search_ref: raise ValueError("A session read requires the --search-ref returned by Find") - if (args.layer or args.finding or args.compact or args.max_bytes is not None): + if args.layer or args.finding or args.compact or args.max_bytes is not None: raise ValueError("Session Find supports a pinned body or --resource read") - root = args.session.resolve() - with _campaign(root) as (campaign, _, state, step, _): - search = _open_search(root, campaign, state, step, args.search_ref) - hit = next((item for item in search["items"] if item.get("material_ref") == args.id), None) - if not hit or not hit.get("revision") or hit["revision"] != args.revision: - raise ValueError("Read requires a hit and revision returned by this Find") - argv = list(hit["material_read_args"]) - for flag, value in (("--skill-root", args.skill_root), ("--store", args.store)): - if (flag in argv) != (value is not None): - raise ValueError("Use the source arguments returned by the original Find") - if value is not None: - argv[argv.index(flag) + 1] = str(value) - if args.installed_library != ("--installed-library" in argv): - raise ValueError("Use the source arguments returned by the original Find") - resource = args.resource - service = campaign.get("evaluation_mode") == "service_reuse" - view, context = (_service_read(root, search, hit, resource) if service else - read_hit({**hit, "material_read_args": argv}, resource=resource)) - delivered, = context["resources"] - read_page(view, args.byte_range, - source_hash=delivered.get("source_sha256", delivered.get("sha256")), - source_ranges=delivered.get("source_byte_ranges")) - if "content_range" in view: - delivered.update(content=view["content"], content_range=view["content_range"]) - delivered.update(view.get("content_view", {})) - context["content_bytes"] = len(view["content"].encode("utf-8")) - path = view["content_resource"] - request = {**search["request"], "search_ref": args.search_ref, "resource": path} - if args.byte_range is not None: - request["byte_range"] = args.byte_range - request.pop("context_bytes", None) # A manual campaign may reopen an earlier Find. - display = {key: view[key] for key in ( - "id", "ref", "revision", "kind", "title", "entrypoint", "content_resource", - "body_resource", "content_view", "content_range", "next_byte_range", - "sources", "limitations", "applicability", - ) if key in view} - if continuation := read_continuation(args, view): - for flag, replacement in (("--session", "."), ("--skill-root", "SKILL_ROOT"), - ("--store", "STORE")): - if flag in continuation: - continuation[continuation.index(flag) + 1] = replacement - display["next_read_args"] = continuation - material = {key: hit[key] for key in ("ref", "revision", "title", "kind") if key in hit} - prefix = "read-" + search["context_id"][:64] + "-" - reference, doc = _save( - root, campaign, state, step, context_id=prefix + uuid4().hex, action="read", - request=request, items=[material], display=display, contexts=[context], - ) - if state is not None: - atomic_write_json(root / "state.json", state) - return scoped_response(doc, reference, str(args.session), - skill_root=args.skill_root, store=args.store) + source_flags = [ + flag for flag, value in ( + ("--skill-root", args.skill_root), ("--store", args.store), + ("--installed-library", args.installed_library), + ) if value + ] + options = { + "search_ref": args.search_ref, "ref": args.id, "revision": args.revision, + "resource": args.resource, "byte_range": args.byte_range, "source_flags": source_flags, + } + return _response(args, _operate(args, reader, "read", options)) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 556710c8a..f66cd77f9 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -8,11 +8,19 @@ from functools import cache from pathlib import Path +from inferrsi import __version__ + from . import attempt_recovery, candidates from .artifact_primitives import digest, file_lock, sha256 from .atomic_json import atomic_write_json, durable_write_json -from .records.evidence import bounded_record_bytes -from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES, delivered_contexts +from .records.evidence import bounded_record_bytes, sanitized_text +from .records.knowledge_capture import ( + MAX_CONTEXT_CAPTURE_BYTES, + capture_campaign, + delivered_contexts, + store_capture, + verify_capture, +) from .task_protocol import TaskProtocolError from .usage import normalize_usage, usage_totals @@ -431,6 +439,275 @@ def _knowledge_time(plan, state): return state["deadline"] - time.time() - plan["final_reserve_seconds"] +# Only portable Find data goes in an immutable capture. The installed launcher and +# session directory belong to this invocation, not the material's identity. +_HIT = ( + "material_ref", "revision", "body_resource", "material_read_args", "id", "authority", "kind", + "path", "title", "summary", "state", "score", "source", "source_location", "applicability", + "limitations", "limitations_withheld", "findings", "findings_withheld", + "next_read_content_bytes", "matched", "unreadable", + "repo", "backend", "scenario", "tier", "sources", "locally_verified", +) + + +def _save_scoped_knowledge( + root, campaign, state, step, *, context_id, action, request, items, display, + assemble_context, contexts=(), +): + number, binding = step or (None, None) + service = campaign.get("evaluation_mode") == "service_reuse" + captured_by = f"inferrsi {action} {__version__}" + selection = {"method": request["relevance_method"], "ranking_applied": action == "find", + "state": "applied" if action == "find" else "explicit_ids", + "ranking_policy": request["ranking_policy"]} + observation = {"schema_version": 1, "entrypoint": action, "calls": [action], + "request": request, "selection": selection, "display": display, + "counts": {"matched": display.get("matched"), "returned": len(items)}, + "items": [{k: row[k] for k in ("ref", "revision") if k in row} for row in items]} + facts = { + "request": request, "selection": selection, "items": items, "omissions": [], + "context_omissions": [], "context_budget": None, + "context_bytes_used": sum(c["content_bytes"] for c in contexts), + "contexts": list(contexts), "retrieval": observation, + } + kind = "knowledge_search" if action == "find" else ( + "delivered_context" if facts["context_bytes_used"] else "empty_context" + ) + if kind == "empty_context": + observation["receipt_kind"] = kind + facts["context_omissions"] = [{"ref": items[0]["ref"], "reason": "empty_resource"}] + path = f"knowledge/{context_id}.json" + reference = {"path": path, "kind": kind} + if service: + from . import project_service + + document = {**facts, "kind": "service_knowledge_context", "context_id": context_id, + "captured_by": captured_by, "prepared_not_consumed": True} + if action == "find": + document["source_snapshot"] = f"knowledge/sources/{context_id}" + if binding: + document["diagnosis_binding"] = binding + project_service.no_fingerprints(document) + (root / "knowledge").mkdir(exist_ok=True) + atomic_write_json(project_service.safe_path(root, path), document) + else: + target, digest = store_capture( + root, campaign_id=campaign["campaign_id"], context_id=context_id, + captured_by=captured_by, diagnosis_binding=binding, + assembled_text=assemble_context(list(contexts)), + **facts, + ) + reference["sha256"] = digest + document = json.loads(target.read_bytes()) + if state is not None: + retained = {**reference, "round": number} + if binding: + retained["diagnosis_id"] = binding["diagnosis_id"] + if action == "read": + retained["search_ref"] = request["search_ref"] + state["contexts"].append(retained) + return reference, document + + +def _open_knowledge_search(root, campaign, state, step, location): + from . import project_service + + path = Path(location) + if path.parent.as_posix() != "knowledge" or path.suffix != ".json": + raise ValueError("Supply a search reference from this campaign") + if state is not None: + number, binding = step + ref = next((entry for entry in state["contexts"] if entry["path"] == location + and entry["kind"] == "knowledge_search" and entry.get("round") == number + and entry.get("diagnosis_id") == (binding or {}).get("diagnosis_id")), None) + if ref is None: + raise ValueError("Supply a Find reference from the current round and diagnosis") + search = (project_service.read(project_service.safe_path(root, location)) + if campaign.get("evaluation_mode") == "service_reuse" else + _read_context(root, ref)) + else: + raw, _ = bounded_record_bytes(root, location, MAX_CONTEXT_CAPTURE_BYTES) + search = verify_capture(raw)[0] if raw else None + if not search or search["campaign_id"] != campaign["campaign_id"]: + raise ValueError("Supply a verified Find reference from this campaign") + if search.get("retrieval", {}).get("entrypoint") != "find": + raise ValueError("The reference must identify a Find result") + return search + + +def _find_scoped(root, reader, campaign, plan, state, step, policy, options, *, + assemble_context, external_provider_for, context_id): + from . import project_service + + query = options["query"] + backend = options["backend"] or campaign.get("backend") + settings = plan.get("external_knowledge") + external_enabled = ( + settings and not options["no_external"] + and (backend is None or backend == settings["backend"]) + ) + if external_enabled: + if step[0] is None: + raise ValueError("Round budget consumed, run independent final evaluation") + query = sanitized_text(query, "", limit=None) + service = campaign.get("evaluation_mode") == "service_reuse" + retained_source = (project_service.safe_path(root, f"knowledge/sources/{context_id}") + if service else None) + result = reader.find( + query, kinds=tuple(k.strip() for k in options["kinds"].split(",") if k.strip()), + backend=backend, repo=options["repo"], tier=options["tier"], scenario=options["scenario"], + revisions=options["revisions"], + limit=options["limit"], explain=options["explain"], ranking_policy=policy, + retained_source=retained_source, pin_material=True, + ) + request = { + "query": query, "relevance": query, "relevance_method": "find-lexical-v1", + "ranking_policy": result["ranking_policy"], "backend": backend, + "scenario": options["scenario"], "limit": options["limit"], "kinds": options["kinds"], + "repo": options["repo"], "tier": options["tier"], "sources": result["sources"], + } + if options["no_external"]: + request["external_source"] = "none" + if options["revisions"]: + request["revisions"] = options["revisions"] + _check_context_ranking(plan, {"request": request}) + items = [{key: hit[key] for key in _HIT if key in hit} for hit in result["items"]] + for item in items: + item["ref"] = item.get("material_ref") or f"{item['authority']}:{item['id']}" + argv = list(item.get("material_read_args", ())) + for flag in ("--skill-root", "--store"): + if flag in argv: + argv[argv.index(flag) + 1] = flag[2:].upper().replace("-", "_") + if argv: + item["material_read_args"] = argv + external = None + if external_enabled: + remaining = _knowledge_time(plan, state) + external = (external_provider_for(plan).search( + query, settings=settings, limit=options["limit"], timeout=remaining, + ) if remaining > 0 else {"state": "timeout", "items": [], "count": 0}) + result["no_match"] = ( + False if result["matched"] or external["items"] + else (True if external["state"] == "ok" else None) + ) + display = {key: value for key, value in result.items() + if key not in ("items", "external", "searchspace_source")} + display["context_bytes_used"] = 0 + reference, document = _save_scoped_knowledge( + root, campaign, state, step, context_id=context_id, action="find", request=request, + items=items, display=display, assemble_context=assemble_context, + ) + response = {"reference": reference, "document": document} + if external is not None: + search = {**external, **settings, "context_ref": reference["path"]} + extra = _store_knowledge(root, "external_search", step[0], search) + state["contexts"].append(extra) + response.update(external={**search, "reference": extra}, task_source=plan["task_source"]) + return response + + +def _read_scoped(root, reader, campaign, plan, state, step, options, *, + assemble_context): + from . import project_service + + location = options["search_ref"] + search = _open_knowledge_search(root, campaign, state, step, location) + hit = next((row for row in search["items"] if row.get("material_ref") == options["ref"]), None) + if not hit or not hit.get("revision") or hit["revision"] != options["revision"]: + raise ValueError("Read requires a hit and revision returned by this Find") + material_args = hit["material_read_args"] + for flag in ("--skill-root", "--store", "--installed-library"): + if (flag in material_args) != (flag in options["source_flags"]): + raise ValueError("Use the source arguments returned by the original Find") + retained_source = None + if campaign.get("evaluation_mode") == "service_reuse": + snapshot = f"knowledge/sources/{search['context_id']}" + if search.get("source_snapshot") != snapshot: + raise ValueError("This Find has no retained source bytes; run Find again " + "before reading") + retained_source = project_service.safe_path(root, snapshot + "/" + hit["id"]) + resource = options.get("resource") + byte_range = options.get("byte_range") + view, context = reader.read_hit( + hit, resource=resource, byte_range=byte_range, retained_source=retained_source, + ) + delivered, = context["resources"] + if (context["ref"] != hit["ref"] or context["revision"] != hit["revision"] + or delivered["path"] != view["content_resource"] + or delivered["content"] != view["content"] + or context["content_bytes"] != len(delivered["content"].encode("utf-8"))): + raise ValueError("Read did not deliver the pinned resource bytes") + request = {**search["request"], "search_ref": location, "resource": view["content_resource"]} + if byte_range is not None: + request["byte_range"] = byte_range + request.pop("context_bytes", None) # An earlier manual Find may carry a packing budget. + _check_context_ranking(plan, {"request": request}) + display = {key: value for key, value in view.items() if key in ( + "id", "ref", "revision", "kind", "title", "entrypoint", "content_resource", + "body_resource", "content_view", "content_range", "next_byte_range", + "sources", "limitations", "applicability", + )} + if "next_byte_range" in view: + argv = list(material_args) + if resource is not None: + argv.extend(("--resource", resource)) + display["next_read_args"] = [ + *argv, "--session", ".", "--search-ref", location, + "--byte-range", *map(str, view["next_byte_range"]), + ] + item = {key: hit[key] for key in ("ref", "revision", "title", "kind") if key in hit} + context_id = f"read-{search['context_id'][:64]}-{uuid.uuid4().hex}" + reference, document = _save_scoped_knowledge( + root, campaign, state, step, context_id=context_id, + action="read", request=request, items=[item], display=display, + contexts=[context], assemble_context=assemble_context, + ) + return {"reference": reference, "document": document} + + +def knowledge_operation(root: Path, reader, action: str, options: dict, *, + default_policy, ranking_policy_for, assemble_context, + external_provider_for) -> dict: + """Run a Find or pinned Read and register its actual receipts under the session lock.""" + from .optimization_session import _runtime_identity + + root = root.resolve() + context_id = "find-" + uuid.uuid4().hex + campaign = capture_campaign(root, context_id) + with _locked(root): + plan, state, step, policy = {}, None, None, default_policy + if campaign.get("managed_optimization"): + plan, state = _load(root) + service = plan.get("evaluation_mode") == "service_reuse" + active = state if not service else { + **state, "deadline": _service_deadline(state), + "state": "active" if state["state"] == "needs_baseline" else state["state"], + } + step = _knowledge_round(plan, active), _context_diagnosis(plan, state) + if not service and plan["runtime_identity"] != _runtime_identity(): + raise ValueError("Optimization runtime changed, use its frozen runtime to resume") + policy = resolve_frozen_ranking(plan, ranking_policy_for) + if action == "find" and ( + reader.skill_root is not None or reader.store is not None + or options.get("revisions") + ): + raise ValueError("Managed Find uses the session's installed corpus") + if action == "find": + result = _find_scoped( + root, reader, campaign, plan, state, step, policy, options, context_id=context_id, + assemble_context=assemble_context, external_provider_for=external_provider_for, + ) + else: + result = _read_scoped( + root, reader, campaign, plan, state, step, options, + assemble_context=assemble_context, + ) + if state is not None: + _active(active, reserve=plan["final_reserve_seconds"]) + atomic_write_json(root / "state.json", state) + return result + + def _store_knowledge(root, kind, number, record): directory = root / "knowledge" if directory.is_symlink(): @@ -495,6 +772,12 @@ def _validate_knowledge_refs(root, contexts, refs): if not any(not separator or entry["ref"] == item for entry in delivered_contexts(capture)): raise ValueError("Cite an item with delivered resources from this context") + if ( + capture.get("retrieval", {}).get("entrypoint") != "read" + or not reference.get("search_ref") + or capture["request"].get("search_ref") != reference["search_ref"] + ): + raise ValueError("Cite a scoped Read receipt; legacy captures are audit-only") def _usage_record(source, *, fingerprint=True): @@ -524,13 +807,20 @@ def _token_totals(records): def _knowledge_summary(contexts, read_capture): - """Project empty legacy receipts without changing their archived references.""" - return [ - {**ref, "kind": "empty_context"} - if (ref["kind"] == "delivered_context" and ref.get("search_ref") is None - and not any(delivered_contexts(read_capture(ref)))) else ref - for ref in contexts - ] + """Summarize search and read receipts without altering historical records.""" + summary = [] + for ref in contexts: + if ref["kind"] == "knowledge_search": + capture = read_capture(ref) + summary.append({**ref, "hits": len(capture["items"]), "context_bytes_used": 0}) + elif ref["kind"] == "empty_context": + summary.append({**ref, "context_bytes_used": 0}) + elif (ref["kind"] == "delivered_context" and ref.get("search_ref") is None + and not any(delivered_contexts(read_capture(ref)))): + summary.append({**ref, "kind": "empty_context"}) + else: + summary.append(ref) + return summary def _summary(root, plan, state): diff --git a/src/inferrsi/harness/optimization_session.py b/src/inferrsi/harness/optimization_session.py index 18742c750..15767bcbd 100644 --- a/src/inferrsi/harness/optimization_session.py +++ b/src/inferrsi/harness/optimization_session.py @@ -328,6 +328,8 @@ def session_command(args, *, ranking_policy_for, task_source: Path | None = None if getattr(args, "alternative", None) is not None or getattr( args, "selection_reason", None) is not None: raise ValueError("Round decision declarations require a benchmark or AB/BA campaign") + if getattr(args, "knowledge_ref", None) is not None: + raise ValueError("Round knowledge references require a benchmark or AB/BA campaign") return optimization.service_command(root, args, ranking_policy_for=ranking_policy_for) if ( args.session_action in ("baseline", "refresh-references", "resume", "profile") diff --git a/src/inferrsi/harness/records/knowledge_capture.py b/src/inferrsi/harness/records/knowledge_capture.py index 3ae97f01b..c2723b36d 100644 --- a/src/inferrsi/harness/records/knowledge_capture.py +++ b/src/inferrsi/harness/records/knowledge_capture.py @@ -69,7 +69,10 @@ def scoped_response(document: dict, reference: dict, session: str, *, skill_root argv[argv.index(flag) + 1] = str(value) hit["read_args"] = [*argv, "--session", session, "--search-ref", reference["path"]] hits.append(hit) - return {"reference": reference, **display, "items": hits} + summary = {} + if "context_bytes_used" in display: + summary = {"hits": len(hits), "context_bytes_used": display["context_bytes_used"]} + return {**summary, "reference": reference, **display, "items": hits} response = {"reference": reference} if "next_read_args" in display: continuation = list(display["next_read_args"]) diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index d8e7b82d1..1c23481af 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -4,6 +4,7 @@ import json import posixpath import re +import shutil import sqlite3 from collections.abc import Container from dataclasses import dataclass @@ -15,15 +16,23 @@ from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import ( FIND_RELEVANCE, + INLINE_PAGE_BYTES, candidate_contexts, context_view, declared_skill_references, indexed_skill, record_context, skill_procedure, + text_page, validate_relevance_method, ) -from .catalog import KNOWLEDGE_SCOPES, SCENARIO_ALIASES, knowledge_records, lookup_record +from .catalog import ( + KNOWLEDGE_SCOPES, + SCENARIO_ALIASES, + _catalog_corpus, + knowledge_records, + lookup_record, +) from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy if TYPE_CHECKING: @@ -393,6 +402,190 @@ def service_body(record, resource=None, *, source_root=None): raise ValueError(f"Unknown resource: {requested}") +def _character_bytes(raw, start): + end = start + 1 + while end < len(raw) and raw[end] & 0xc0 == 0x80: + end += 1 + return end - start + + +def read_page(view, requested, *, source_hash=None, source_ranges=None): + """Slice the UTF-8 material view; offsets always refer to the same pinned view.""" + if "content" not in view: + if requested is not None: + raise ValueError("--byte-range requires --material or --resource") + return + content = view["content"] + raw = content.encode("utf-8") + if requested is None: + if len(raw) <= INLINE_PAGE_BYTES: + serialized = json.dumps(content, ensure_ascii=False).encode("utf-8") + if len(serialized) <= INLINE_PAGE_BYTES: + return + requested = (0, INLINE_PAGE_BYTES) + start, length = requested + if start < 0 or length < 1 or start > len(raw) or (start == len(raw) and start != 0): + raise ValueError("--byte-range requires a valid start byte and a positive length") + if start < len(raw) and raw[start] & 0xc0 == 0x80: + raise ValueError("--byte-range must start at a UTF-8 character boundary") + text, stop = text_page(raw, start, length) + if stop == start and start < len(raw): + raise ValueError(f"--byte-range needs at least {_character_bytes(raw, start)} bytes " + "for the next UTF-8 character") + # Put the continuation coordinates before a potentially long stdout body. + del view["content"] + view["content_range"] = { + "start": start, "end": stop, "total_bytes": len(raw), + "first_line": raw.count(b"\n", 0, start) + 1, + } + if stop < len(raw): + view["next_byte_range"] = [stop, max(length, _character_bytes(raw, stop))] + if source_hash is not None or source_ranges is not None: + # A Skill procedure omits frontmatter. Map the selected view bytes back + # onto the already pinned source ranges, including pages crossing a gap. + original = view.get("content_view", {}) + ranges, offset = [], 0 + for lo, hi in original.get("source_byte_ranges", source_ranges or [(0, len(raw))]): + begin, end = max(start - offset, 0), min(stop - offset, hi - lo) + if begin < end: + ranges.append([lo + begin, lo + end]) + offset += hi - lo + view["content_view"] = {"locator": "byte-range", "source_byte_ranges": ranges} + if source_hash is not None: + view["content_view"].update(source_sha256=source_hash, + sha256=_hash(raw[start:stop])) + view["content"] = text + + +def _retain_service_sources(destination, selections): + """Publish only complete, byte-consistent source sets before their search receipt.""" + temporary = destination.with_name("." + destination.name) + temporary.mkdir(parents=True) + try: + for record, document in selections: + resources = service_resources(record) + primary = record.get("skill_documents", {}).get("original") or "record.json" + if document.kind == "skill": + if (primary != "data/skill_library/" + document.path + or record["skill_metadata"]["name"] != document.identity + or record["backend"] != document.backend): + raise ValueError( + "Knowledge ownership changed while finding material; run Find again" + ) + raw = resources[primary].decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") + body, _ = skill_procedure(primary, raw.encode("utf-8")) + if body.decode("utf-8") != document.fields["body"]: + raise ValueError("Knowledge changed while finding material; run Find again") + directory = temporary / record["id"] + for path, content in resources.items(): + target = directory / safe_path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + target.chmod(target.stat().st_mode & ~0o222) + temporary.rename(destination) + finally: + if temporary.exists(): + shutil.rmtree(temporary) + + +def _find_service(query, destination, *, kinds, backend, repo, tier, scenario, + limit, explain, policy): + from .knowledge_find import rank + + if not query: + raise ValueError("Service-reuse Find requires a question") + if type(limit) is not int or limit < 1: + raise ValueError("limit must be a positive integer") + records = knowledge_records(file_fingerprints=False) + scenario = SCENARIO_ALIASES.get(scenario, scenario) + + def matches(record): + skill = record.get("index_type") == "packaged-skill" + declared = record.get("scenario", "") + applicable = (not scenario or declared == scenario + or (skill and declared == "skills.discovery") + or (declared.endswith(".*") and scenario.startswith(declared[:-1]))) + return (("skill" if skill else "record") in kinds + and (not backend or record["backend"] in ("common", backend)) + and (not tier or record.get("tier", "contribution") == tier) + and (not repo or record["repo"] == repo) + and applicable) + + records = [record for record in records if matches(record)] + corpus, records = _catalog_corpus(records, file_fingerprints=False) + _, _, ranked = rank(query, corpus, policy) + items = [] + selections = [] + for score, _, index, components in ranked[:limit]: + record = records[index] + selections.append((record, corpus.documents[index])) + ref = "package:" + record["id"] + revision = record["sources"][0]["commit"] + path = record.get("skill_documents", {}).get("original") or "record.json" + items.append({ + "id": record["id"], "authority": "package", "title": record["title"], + "kind": "skill" if record.get("index_type") == "packaged-skill" else "record", + "repo": record["repo"], "tier": record.get("tier", "contribution"), + "backend": record["backend"], "scenario": record["scenario"], + "score": round(score, 2), "material_ref": ref, "revision": revision, + "body_resource": path, "material_read_args": ["read", ref, "--revision", revision], + **({"matched": components} if explain else {}), + }) + _retain_service_sources(destination, selections) + return {"query": query, "matched": len(ranked), "no_match": not ranked, "items": items, + "ranking_policy": policy.configuration(), "sources": ["package"]} + + +def _read_service_hit(source_root, hit, resource): + metadata = source_root / "record.json" + if metadata.is_symlink(): + raise ValueError("Symbolic retained knowledge record") + record = json.loads(metadata.read_bytes()) + if record.get("id") != hit["id"] or record["sources"][0]["commit"] != hit["revision"]: + raise ValueError("The retained source does not match this Find") + primary = hit["body_resource"] + path, data, locator = service_body(record, resource, source_root=source_root) + ref, revision = hit["material_ref"], hit["revision"] + selected = {"path": path, "role": "core" if path == primary else "reference", + "content": data.decode("utf-8"), **locator} + context = {"ref": ref, "revision": revision, "resources": [selected], + "content_bytes": len(data), "omissions": [], "sources": record["sources"]} + view = {"ref": ref, "id": hit["id"], "revision": revision, "entrypoint": primary, + "content_resource": path, "content": selected["content"], "sources": record["sources"]} + if resource is not None and path != resource: + view["body_resource"] = primary + if locator: + view["content_view"] = locator + return view, context + + +def _read_local_hit(source, hit, resource): + ref, bundle = source.read_resolved(hit["material_ref"], revision=hit["revision"]) + view = bundle.view() + body = hit["body_resource"] + path = resolve_resource_key(body if resource is None else resource, body, bundle.content) + if resource is not None and path != resource: + view["body_resource"] = body + raw = bundle.content[path] + data, locator = skill_procedure(path, raw) if resource is None else (raw, {}) + content = data.decode("utf-8") + digest = view["resources"][path] + role = "reference" if path != hit["body_resource"] else ( + "record" if path == "record.json" else "core" + ) + delivered = {"path": path, "role": role, "sha256": digest, "content": content} + if locator: + location = {**locator, "source_sha256": digest, "sha256": _hash(data)} + delivered.update(location) + view["content_view"] = location + context = {"ref": ref, "revision": view["revision"], "resources": [delivered], + "sources": view["sources"], "content_bytes": len(data), "omissions": []} + view.pop("resources") + view.pop("required_resources", None) + view.update(ref=ref, content=content, content_resource=path) + return view, context + + class KnowledgeReader: def __init__(self, *, skill_root: Path | None = None, store=None): self.skill_root = skill_root.resolve() if skill_root is not None else None @@ -403,6 +596,53 @@ def __init__(self, *, skill_root: Path | None = None, store=None): self._opened_records: dict[str, dict | None] = {} self._library: tuple[dict[str, bytes], str] | None = None + def find( + self, query: str, *, kinds=("case", "skill", "record"), backend=None, repo=None, + tier=None, scenario=None, revisions=None, + retained_source=None, + limit=5, explain=False, ranking_policy=DEFAULT_RANKING_POLICY, searchspace_index=None, + **options, + ) -> dict: + """Find within a scoped catalog or retain the pinned service source bytes.""" + from .knowledge_find import find, load_corpus + + if not kinds or set(kinds) - {"case", "skill", "record"}: + raise ValueError("--kinds takes a subset of case,skill,record") + if retained_source is not None: + return _find_service( + query, retained_source, kinds=kinds, backend=backend, repo=repo, tier=tier, + scenario=scenario, limit=limit, explain=explain, policy=ranking_policy, + ) + corpus = load_corpus( + self.skill_root, kinds=kinds, backend=backend, repo=repo, tier=tier, scenario=scenario, + searchspace_index=searchspace_index, store=self.store, revisions=revisions, + ) + return find(query, corpus, limit=limit, explain=explain, backend=backend, + ranking_policy=ranking_policy, **options) + + def read_hit(self, hit: dict, *, resource=None, byte_range=None, + retained_source=None) -> tuple[dict, dict]: + """Read one selected body or linked resource and report the exact returned page.""" + if retained_source is not None: + view, context = _read_service_hit(retained_source, hit, resource) + else: + from .knowledge_find import installed_skill_root + + source = (KnowledgeReader(skill_root=installed_skill_root()) + if "--installed-library" in hit["material_read_args"] + and self.skill_root is None else self) + view, context = _read_local_hit(source, hit, resource) + delivered, = context["resources"] + read_page( + view, byte_range, source_hash=delivered.get("source_sha256", delivered.get("sha256")), + source_ranges=delivered.get("source_byte_ranges"), + ) + if "content_range" in view: + delivered.update(content=view["content"], content_range=view["content_range"]) + delivered.update(view.get("content_view", {})) + context["content_bytes"] = len(view["content"].encode("utf-8")) + return view, context + def records(self) -> dict[str, dict]: """Installed catalog records, read once per reader (one package snapshot).""" if self._records is None: diff --git a/tests/apps/test_knowledge_read_ranges.py b/tests/apps/test_knowledge_read_ranges.py index 7dbe87937..98628aee3 100644 --- a/tests/apps/test_knowledge_read_ranges.py +++ b/tests/apps/test_knowledge_read_ranges.py @@ -108,6 +108,40 @@ def test_default_pages_and_explicit_large_ranges_return_bounded_executable_conti assert received == body +def test_scoped_empty_checkout_link_is_audit_only(tmp_path, capsys): + from tests.knowledge.test_knowledge_find import _plant_case + + library, campaign = tmp_path / "library", tmp_path / "campaign" + _plant_case(library, "casebook") + owner = library / "casebook" + body = owner / "SKILL.md" + with body.open("a", encoding="utf-8") as stream: + stream.write("\n[Empty reference](references/empty.md).\n") + (owner / "references").mkdir() + (owner / "references/empty.md").touch() + call(capsys, "campaign", "init", "--id", "empty", "--directory", str(campaign)) + found, _ = call( + capsys, "find", "casebook optimization benchmark", "--session", str(campaign), + "--skill-root", str(library), "--kinds", "skill", "--limit", "5", + ) + hit = next(item for item in found["items"] if item["id"] == "casebook") + argv = [*hit["read_args"], "--resource", "references/empty.md"] + view, output = call(capsys, *argv) + reference = view["reference"] + assert view["content"] == "" and reference["kind"] == "empty_context" + receipt, status = verify_capture((campaign / reference["path"]).read_bytes()) + assert status == "verified" and receipt["context_bytes_used"] == 0 + from inferrsi.harness import optimization + + with pytest.raises(ValueError, match="delivered context"): + optimization._validate_knowledge_refs(campaign, [reference], [reference["path"]]) + rows = _operation(tmp_path, [sys.executable, "-m", "inferrsi", *argv], output, "read") + _, archive = _import(tmp_path, rows, campaign=campaign, context_ids=[receipt["context_id"]]) + assert archive["coverage"] == "complete" and archive["observed"]["used"] == 0 + event, = archive["events"] + assert event["delivery"]["visible_resources"] == [] + + def test_content_read_does_not_expand_the_package_inventory(tmp_path, capsys): ref = "package:inferrsi.common.skills.inference_benchmark_design" revision = KnowledgeReader().read(ref).revision diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index f6ed3fc35..aaa705407 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1032,6 +1032,7 @@ def test_round_cites_the_cuda_skill_read_and_rejects_the_search(session, capsys) assert hit["material_ref"] == "package:inferrsi.common.skills.inference_benchmark_design" search = found["reference"] assert search["kind"] == "knowledge_search" + assert (found["hits"], found["context_bytes_used"]) == (2, 0) args = round_arguments(session, 2) with pytest.raises(SystemExit) as error: @@ -1110,17 +1111,33 @@ def test_legacy_retrieval_is_linked_only_by_matching_submission_snapshots(sessio assert path.read_bytes() == raw -def test_nonempty_legacy_capture_allows_both_reference_forms(session): - from inferrsi.harness import optimization +def test_nonempty_legacy_capture_is_audit_only_in_both_reference_forms(session, capsys): + from inferrsi.apps.workflows.campaign import verify_capture from tests.fixtures.knowledge_retrieval import install_legacy_capture - path, digest = install_legacy_capture(session, "managed-query", "legacy-delivered") - relative = path.relative_to(session).as_posix() - context, = json.loads(path.read_bytes())["contexts"] - reference = {"path": relative, "sha256": digest, "kind": "delivered_context"} - optimization._validate_knowledge_refs( - session, [reference], [relative, relative + "#" + context["ref"]], + plan, state = optimization.read_records(session)[:2] + binding = optimization._context_diagnosis(plan, state) + path, digest = install_legacy_capture( + session, "managed-query", "legacy-delivered", diagnosis=binding, + ranking_policy=plan["ranking_policy"], ) + state_file = session / "state.json" + relative = path.relative_to(session).as_posix() + raw = path.read_bytes() + capture, status = verify_capture(raw) + assert status == "verified" + context, = capture["contexts"] + state["contexts"].append({"path": relative, "sha256": digest, "kind": "delivered_context", + "diagnosis_id": binding["diagnosis_id"]}) + state_file.write_text(json.dumps(state), encoding="utf-8") + before = state_file.read_bytes() + args = round_arguments(session, 2) + for ref in (relative, f"{relative}#{context['ref']}"): + with pytest.raises(SystemExit) as error: + main([*args, "--knowledge-ref", ref]) + assert error.value.code == 2 + assert "legacy captures are audit-only" in capsys.readouterr().err + assert path.read_bytes() == raw and state_file.read_bytes() == before def test_round_declarations_follow_the_candidate_through_assessment(session, capsys, monkeypatch): diff --git a/tests/apps/test_service_knowledge_snapshot.py b/tests/apps/test_service_knowledge_snapshot.py index fc3b4cef0..f5fce8fde 100644 --- a/tests/apps/test_service_knowledge_snapshot.py +++ b/tests/apps/test_service_knowledge_snapshot.py @@ -6,9 +6,8 @@ import pytest from inferrsi.apps.cli import main -from inferrsi.apps.workflows import session_knowledge from inferrsi.harness import optimization, project_service -from inferrsi.knowledge import knowledge_operations +from inferrsi.knowledge import knowledge_find, knowledge_operations from inferrsi.knowledge.catalog import lookup_record from tests.apps.test_campaign_task_selection import BASELINE_CUE from tests.fixtures.service_reuse import call, diagnose, rejected @@ -103,7 +102,7 @@ def test_service_reads_and_continuations_keep_the_find_source(campaign, installe def test_service_search_does_not_publish_a_changed_ranked_body(campaign, installed_source, monkeypatch): - original_rank = session_knowledge.rank + original_rank = knowledge_find.rank def change_after_ranking(*args, **kwargs): result = original_rank(*args, **kwargs) @@ -111,7 +110,7 @@ def change_after_ranking(*args, **kwargs): primary.write_bytes(primary.read_bytes() + b"\nChanged before retention.\n") return result - monkeypatch.setattr(session_knowledge, "rank", change_after_ranking) + monkeypatch.setattr(knowledge_find, "rank", change_after_ranking) call(campaign, "start") diagnose(campaign) assert rejected(["find", BASELINE_CUE, "--backend", "cuda", "--session", diff --git a/tests/fixtures/knowledge_retrieval.py b/tests/fixtures/knowledge_retrieval.py index ba1aae1ed..5189ea49c 100644 --- a/tests/fixtures/knowledge_retrieval.py +++ b/tests/fixtures/knowledge_retrieval.py @@ -78,13 +78,16 @@ def legacy_records(): return json.load(source) -def install_legacy_capture(root, sample, context_id, *, collection="samples", diagnosis=None): +def install_legacy_capture(root, sample, context_id, *, collection="samples", diagnosis=None, + ranking_policy=None): """Place a recorded response into the synthetic campaign used by an importer test.""" doc = legacy_records()[collection][sample] doc["campaign_id"] = json.loads((root / "campaign.json").read_bytes())["campaign_id"] doc["context_id"] = context_id if diagnosis is not None: doc["diagnosis_binding"] = diagnosis + if ranking_policy is not None: + doc["request"]["ranking_policy"] = ranking_policy raw = (json.dumps(doc, ensure_ascii=False, indent=2) + "\n").encode("utf-8") path = root / "knowledge" / (context_id + ".json") path.parent.mkdir(exist_ok=True) From 5e6c6e11220a434a16966b9e0122851bcbe6d857 Mon Sep 17 00:00:00 2001 From: Zhou ziheng Date: Thu, 26 Nov 2026 22:07:57 +0800 Subject: [PATCH 7/7] Use the public Knowledge Reader in retrieval checks Keep service ranking assertions and the indexer pinned-read measurement working after the Apps helpers moved. Agent-assisted-by: Codex (author) Signed-off-by: Zhou ziheng --- tests/knowledge/test_ranking_policy.py | 22 ++++++++++++---------- tools/evaluate_indexer.py | 3 +-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/tests/knowledge/test_ranking_policy.py b/tests/knowledge/test_ranking_policy.py index 48e6e0026..ec36e90a0 100644 --- a/tests/knowledge/test_ranking_policy.py +++ b/tests/knowledge/test_ranking_policy.py @@ -4,6 +4,7 @@ import pytest from inferrsi.knowledge.knowledge_find import Corpus, Document, rank +from inferrsi.knowledge.knowledge_operations import KnowledgeReader from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy @@ -55,28 +56,29 @@ def test_default_preserves_body_length_idf_backend_and_all_tie_breaks(): def test_packaged_service_uses_same_weights_without_content_fingerprints(tmp_path): - from inferrsi.apps.cli.arguments import parser - from inferrsi.apps.workflows.session_knowledge import _service_find from inferrsi.harness.project_service import no_fingerprints - args = parser().parse_args(["find", "cgroupv2", "--limit", "1"]) - selected = _service_find(args, DEFAULT_RANKING_POLICY, None, tmp_path, "find-default") + reader = KnowledgeReader() + selected = reader.find( + "cgroupv2", limit=1, retained_source=tmp_path / "find-default", + ranking_policy=DEFAULT_RANKING_POLICY, + ) no_fingerprints(selected) hit, = selected["items"] assert hit["material_ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" assert selected["ranking_policy"] == DEFAULT_RANKING_POLICY.configuration() zero = RankingPolicy("zero", dict.fromkeys(DEFAULT_RANKING_POLICY.weights, 0)) - other = _service_find(args, zero, None, tmp_path, "find-zero") + other = reader.find( + "cgroupv2", limit=1, retained_source=tmp_path / "find-zero", ranking_policy=zero, + ) assert other["ranking_policy"] == zero.configuration() assert other["items"] == [] def test_service_rejects_finite_weights_that_overflow_a_score(tmp_path): - from inferrsi.apps.cli.arguments import parser - from inferrsi.apps.workflows.session_knowledge import _service_find - - args = parser().parse_args(["find", "cgroupv2", "--limit", "1"]) weights = dict.fromkeys(DEFAULT_RANKING_POLICY.weights, sys.float_info.max) policy = RankingPolicy("large", weights) with pytest.raises(ValueError, match="Ranking score overflow for policy 'large'"): - _service_find(args, policy, None, tmp_path, "find-overflow") + KnowledgeReader().find( + "cgroupv2", limit=1, retained_source=tmp_path / "find-overflow", ranking_policy=policy, + ) diff --git a/tools/evaluate_indexer.py b/tools/evaluate_indexer.py index b634b6656..0eec7d7eb 100644 --- a/tools/evaluate_indexer.py +++ b/tools/evaluate_indexer.py @@ -108,7 +108,6 @@ def measure(call): def worker(root, action, payload): sys.path.insert(0, str(root / "src")) - from inferrsi.apps.workflows.knowledge import read_selected_hit from inferrsi.knowledge.knowledge_find import find, installed_skill_root, load_corpus from inferrsi.knowledge.knowledge_operations import KnowledgeReader @@ -127,7 +126,7 @@ def worker(root, action, payload): hits = find(query, load_corpus(**scope), limit=limit, pin_material=True) if hits["items"]: hit = hits["items"][0] - rows["pinned_read"] = measure(lambda: read_selected_hit(hit)[0]) + rows["pinned_read"] = measure(lambda: KnowledgeReader().read_hit(hit)[0]) for name, probe in (("cli_find_relevance", case), ("cli_find_search", {"query": "cgroupv2", "limit": 5})): query, limit, scope = find_options(probe)