diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 9256effd3..d1808fb68 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -47,7 +47,8 @@ "tests/harness/test_harness_entry_verification.py", "tests/harness/test_harness_generation_lineage.py", "tests/apps/test_result_delivery.py", - "src/inferrsi/apps/legacy/records.py" + "src/inferrsi/apps/legacy/records.py", + "tools/optimization_records.py" ], "status": "retired", "first_removal_version": "0.3.4" diff --git a/docs/knowledge-base.md b/docs/knowledge-base.md index 08b0f081f..1d94ad148 100644 --- a/docs/knowledge-base.md +++ b/docs/knowledge-base.md @@ -282,7 +282,7 @@ Complete procedures, references and cases are packaged together. Browse by system, engineering task, workflow or prior outcome. Backend is recorded independently. The 21 engine and research-router skills use the same ownership layout under `systems/engines//` and `workflows/research/inference-engine-research/`, including their sub-skills and references. -The library contains 152 `SKILL.md` files, all in English. The registered +The library contains 153 `SKILL.md` files, all in English. The registered [Lithos Metal candidate](../src/inferrsi/knowledge/data/skill_library/systems/engines/lithos-metal/SKILL.md) adds three owner-local subskills for compiler/fusion, generation state and serving/cache contracts; it adds no executable repository target. @@ -290,12 +290,12 @@ The collection overview, import notes and source manifest belong to the research workflow's references; Strata design-space analysis belongs to Strata. The library root holds the registry, configuration, compiled inputs, authored findings and skill directories. The [runtime catalog](../src/inferrsi/knowledge/data/skill_library/README.md) -projects the 89 registered skills into the contribution catalog. Its records +projects the 90 registered skills into the contribution catalog. Its records use `inferrsi..skills.` IDs, with `ascend` and `cuda` for scopes that depend on those backends and `common` for the remaining skills. Each `skill_documents.original` points to the full packaged procedure. The `skills` CLI retains the original hyphenated skill IDs and defaults to this -89-ID registry; engine procedures remain available through library navigation +90-ID registry; engine procedures remain available through library navigation and catalog document pointers. The registered [PyTorch](../src/inferrsi/knowledge/data/skill_library/systems/frameworks/pytorch/pytorch/SKILL.md) diff --git a/docs/searchspace-index.json b/docs/searchspace-index.json index d5eefeacc..af105dc5d 100644 --- a/docs/searchspace-index.json +++ b/docs/searchspace-index.json @@ -5,8 +5,8 @@ "catalog_path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", "skill_root": "src/inferrsi/knowledge/data/skill_library", "matrix_sha256": "8e47da7aa4824d160710dee6ec63e91011f399def948b25a6bf74abe1bc45db9", - "catalog_sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871", - "metadata_sha256": "f4399276c8389f33ad81a2a25ccd0ff4392a37635ae9c53943ece4995c84d246" + "catalog_sha256": "2e8e852a4b8fd97cdb1c48f0f5cb6eea4dbc2d27492e9572b89bd83428238d89", + "metadata_sha256": "37dadb5c1b8be84f8525bc842a47c815c924fa07a7601191e02de447cf4979b6" }, "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"]]}, @@ -82,6 +82,7 @@ "skill-evolution-playbook": {"path": "workflows/maintenance/skill-evolution-playbook/SKILL.md", "state": "not-applicable", "coordinates": [], "exclusion_reason": "SKILL.md §§ When should one trajectory update a skill?, How large should a skill edit be?, and When should skills split or merge? govern skill-text evolution and held-out evaluation, not hardware-resource state or control."}, "splash": {"path": "systems/engines/splash/SKILL.md", "state": "supplementary", "coordinates": []}, "storage-io-measurement": {"path": "systems/platforms/host/storage-io-measurement/SKILL.md", "state": "covered", "coordinates": [["SSD", "Diagnose"], ["SSD", "Observe"], ["SSD", "Profile"], ["SSD", "Verify"]]}, + "submit-optimization-record": {"path": "workflows/governance/submit-optimization-record/SKILL.md", "state": "not-applicable", "coordinates": [], "exclusion_reason": "This workflow publishes optional run feedback and does not choose a search candidate."}, "task-accuracy": {"path": "tasks/task-accuracy/SKILL.md", "state": "not-applicable", "coordinates": [], "exclusion_reason": "The procedure selects supporting evidence and tests within the caller's declared search space."}, "task-day-0": {"path": "tasks/task-day-0/SKILL.md", "state": "not-applicable", "coordinates": [], "exclusion_reason": "The procedure selects supporting evidence and tests within the caller's declared search space."}, "task-debug": {"path": "tasks/task-debug/SKILL.md", "state": "not-applicable", "coordinates": [], "exclusion_reason": "The procedure selects supporting evidence and tests within the caller's declared search space."}, diff --git a/docs/skill-coverage.md b/docs/skill-coverage.md index 4d92f1500..7bbdde476 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:cec24f374af41c08dfcbc6ab9928a4785eb511e61fb58f98b4a1dead2983880a` - Regenerate: `python tools/build_skill_coverage.py` - Verify without writing: `python tools/build_skill_coverage.py --check` @@ -33,17 +33,17 @@ matrix: every field is copied from an owner that already maintains it. | Measure | Value | |---|---| -| Registered skill ids | 89 | -| By category | casebooks 2, playbooks 18, systems 53, tasks 8, workflows 8 | -| By backend | ascend 16, common 68, cuda 5 | +| Registered skill ids | 90 | +| By category | casebooks 2, playbooks 18, systems 53, tasks 8, workflows 9 | +| By backend | ascend 16, common 69, cuda 5 | | Recorded on a numbered SearchSpace resource layer | 52 | | Recorded only in a supplementary guidance table (†) | 21 | -| Resource layers explicitly not applicable | 15 | +| Resource layers explicitly not applicable | 16 | | Conflicting resource-layer declarations | 0 | | Recorded on two or more resource layers | 25 | | Recorded in the Reference Matrix | 73 | | Selected by a frozen evaluation plan | 2 | -| `SKILL.md` documents in the library | 152 | +| `SKILL.md` documents in the library | 153 | | Unregistered documents (excluded from every count above) | 63 | A complete inventory is not a coverage claim. Every registered row below @@ -151,7 +151,7 @@ optimization is fully covered or that any procedure has measured benefit. | [task-performance](../src/inferrsi/knowledge/data/skill_library/tasks/task-performance/SKILL.md) | common | Use when a correct inference baseline misses a latency, throughput, memory or cost target. Compare compatible changes ... | Optimization of a specified metric under fixed workload, quality and resource constraints. | input_contract, produced_artifact, refusal_point | N/A: The procedure selects supporting evidence and tests within the caller's declared search space. | — | candidate · not_run · 0 readset(s) | no-Reference-Matrix-row, no-eval | | [task-version-alignment](../src/inferrsi/knowledge/data/skill_library/tasks/task-version-alignment/SKILL.md) | common | Use for upgrades spanning inference engines, plugins, drivers or operator libraries. Isolate the incompatible boundary ... | Compatibility of explicit working and target version combinations. | input_contract, produced_artifact, refusal_point | N/A: The procedure selects supporting evidence and tests within the caller's declared search space. | — | candidate · not_run · 0 readset(s) | no-Reference-Matrix-row, no-eval | -## Registered: Cross-stage workflows (8) +## Registered: Cross-stage workflows (9) | Skill | Backend | Declared task | Applicability | Conditions | SearchSpace layer / stage | Reference Matrix | State | Gaps | |---|---|---|---|---|---|---|---|---| @@ -163,6 +163,7 @@ optimization is fully covered or that any procedure has measured benefit. | [repository-evolution-analysis](../src/inferrsi/knowledge/data/skill_library/workflows/research/repository-evolution-analysis/SKILL.md) | common | Analyze a repository's commit history to build a capability-evolution model: what the system can do, how it got there ... | any software repository with a recoverable git history | — | 5 OS · Diagnose / Configure / Verify | 2 · Methodology and corpus references (LearningToCommit/LearningToCommit @ 7e5a1d7)
2 · Methodology and corpus references (yetone/magpie @ 77800032) | candidate · not_run · 0 readset(s) | no-eval | | [rsi-evidence](../src/inferrsi/knowledge/data/skill_library/workflows/governance/rsi-evidence/SKILL.md) | common | Guide agents to establish acceptance criteria, freeze and cite RSI evidence using plan/results/patch/validator paths ... | Preparing acceptance criteria, documenting or reviewing an optimization campaign whose ... | failure_modes, input_contract, produced_artifact, refusal_point
6 advice | 1 Accelerator · Verify | — | candidate · not_run · 1 readset(s) | no-Reference-Matrix-row, no-eval | | [skill-evolution-playbook](../src/inferrsi/knowledge/data/skill_library/workflows/maintenance/skill-evolution-playbook/SKILL.md) | common | Practical design choices for evolving agent skills from execution traces: when one trajectory should update a skill ... | Design choices for evolving agent skills from execution traces, drawn from Trace2Skill ... | failure_modes, input_contract, produced_artifact, refusal_point
4 advice | N/A: SKILL.md §§ When should one trajectory update a skill?, How large should a skill edit be?, and When should skills split or merge? govern skill-text evolution and held-out evaluation, not hardware-resource state or control. | 2 · Methodology and corpus references (Qwen-Applications/Trace2Skill @ 3d0b52a)
2 · Methodology and corpus references (microsoft/SkillOpt @ 343db22) | candidate · not_run · 0 readset(s) | no-eval | +| [submit-optimization-record](../src/inferrsi/knowledge/data/skill_library/workflows/governance/submit-optimization-record/SKILL.md) | common | Prepare and submit one user-selected InferRSI run as a redacted evidence record after a completed, failed, or ... | User-authorized submission of one retained native campaign run to InferRSI | input_contract, produced_artifact | N/A: This workflow publishes optional run feedback and does not choose a search candidate. | — | candidate · not_run · 0 readset(s) | no-Reference-Matrix-row, no-eval | ## Documents outside the registry @@ -239,7 +240,7 @@ an entrypoint routes to procedures below it rather than adding one. ## Integrity checks -- Registered ids resolve to an existing `SKILL.md`: 89 of 89. +- Registered ids resolve to an existing `SKILL.md`: 90 of 90. - Duplicate ids or paths: none; `skill_catalog` rejects them before this view is built. - Skill links in the two matrices that do not resolve: 0. @@ -249,9 +250,9 @@ an entrypoint routes to procedures below it rather than adding one. |---|---| | `no-SearchSpace-layer` | 1: husky | | `conflicting-SearchSpace-layer` | 0: — | -| `no-Reference-Matrix-row` | 16: ascend-video-diffusion-optimization, audit-fixed-workload-claim, cite-check-downstream-pr, claim-contract, competitor-scan, draft-acceptance-issue, inference-task-router, rsi-evidence, task-accuracy, task-day-0, task-debug, task-derived-engine, task-independent-engine, task-performance, task-version-alignment, video-diffusion-optimization | +| `no-Reference-Matrix-row` | 17: ascend-video-diffusion-optimization, audit-fixed-workload-claim, cite-check-downstream-pr, claim-contract, competitor-scan, draft-acceptance-issue, inference-task-router, rsi-evidence, submit-optimization-record, task-accuracy, task-day-0, task-debug, task-derived-engine, task-independent-engine, task-performance, task-version-alignment, video-diffusion-optimization | | `no-applicability` | 0: — | -| `no-eval` | 87: as listed in the Gaps column above | +| `no-eval` | 88: as listed in the Gaps column above | These are inventory gaps, not efficacy results. Missing layer mappings stay unknown unless the owner records a reasoned N/A. N/A is not coverage; diff --git a/evidence/README.md b/evidence/README.md index c7cafc1e6..af412f087 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -1,5 +1,9 @@ # Evidence tree +[Optimization run submissions](records/README.md) document individual +user-selected runs under `records/`. Campaign acceptance evidence uses the +structure below. + First-class paths for every campaign (see [contribution guide](../docs/contributing.md#evidence-and-claims)). | Segment | Purpose | diff --git a/evidence/records/README.md b/evidence/records/README.md new file mode 100644 index 000000000..97d55fda6 --- /dev/null +++ b/evidence/records/README.md @@ -0,0 +1,47 @@ +# Optimization run records + +Load the workflow with `inferrsi skills show submit-optimization-record` to prepare +an optional public feedback record after a run. Select one native campaign's v1 result-delivery +bundle and a prompt you may share. The skill creates a redacted derivative and +shows the exact staged files and PR text for user review before publication. +The campaign directory remains the runtime trace source and may hold private +material. Keep it and the original prompt outside the public commit. + +## Layout + +```text +evidence/records/-<12-hex>/ + record.json + model-config.json + prompt.md + trace/ + 01-execution.json + 02-result.json +``` + +- `record.json` is the v1 manifest. It identifies the run's user-reported + agent and InferRSI versions, source export schema, original execution and + assessment status, gaps, and the relative paths and SHA-256 digests of + included files. A public project acceptance issue or approved archive + reference can accompany the snapshot. +- `model-config.json` separates allowlisted agent sampling/reasoning settings + from optimized-model identity and runtime settings. Unavailable values are + null with a corresponding omission. +- `prompt.md` includes only redacted user prompt text and selected user + refinements. Its manifest entry records `withheld` or `unavailable` when + omitted. +- The trace JSON files retain the source execution state, attempt history, + result, existing verdict and its verification state. Metrics require a + matching public acceptance issue and permission under the repository's + [claim rules](../../docs/contributing.md#evidence-and-claims). + +The UTC prefix uses the source's timezone-qualified run start truncated to a +second. The fallback is first preparation time. The manifest records the +timestamp basis. Keep the generated ID and prepared directory for retries. + +Validate the inventory with `python tools/validate_evidence.py` from a checkout. +This checks layout and file digests offline. User and PR review remain essential +for [privacy](../../docs/privacy-security.md). Follow the +[archive guide](../../docs/guides/evidence-archiving.md) for raw and oversized +records. The usual R6 reporting thresholds apply. The skill can reference a +previously approved versioned public archive or record an availability gap. diff --git a/src/inferrsi/apps/storage/archive.py b/src/inferrsi/apps/storage/archive.py index 6ca423a48..f9e80778a 100644 --- a/src/inferrsi/apps/storage/archive.py +++ b/src/inferrsi/apps/storage/archive.py @@ -483,6 +483,14 @@ def _write_file(path: Path, data: bytes) -> None: os.fsync(handle.fileno()) +def publish_directory(staging: Path, destination: Path) -> None: + """Atomically move a staged directory into an unused destination on the same filesystem. + + The caller owns staging and any durability syncs. An existing destination is preserved. + """ + _publish_directory(staging, destination) + + def _publish_directory(staging: Path, destination: Path) -> None: """Atomically publish a complete directory without replacing any entry.""" if os.name == "nt": diff --git a/src/inferrsi/knowledge/data/skill_library/README.md b/src/inferrsi/knowledge/data/skill_library/README.md index c8d31b133..2bf578a02 100644 --- a/src/inferrsi/knowledge/data/skill_library/README.md +++ b/src/inferrsi/knowledge/data/skill_library/README.md @@ -5,7 +5,7 @@ by the requested outcome, runs `inferrsi skills enter ` and reads the returned procedure before the first supporting evidence search. Use the actual model, device, engine version, script, gates and diagnosis to decide which supporting skill to load next. The [compatibility router](tasks/inference-task-router/SKILL.md) retains older route -resource paths. The library has 89 registered bundles and 152 English +resource paths. The library has 90 registered bundles and 153 English `SKILL.md` documents, including nested and unregistered entries. | Question | Directory | Choose a second-level category | @@ -27,7 +27,7 @@ existing resource directory. ## Read registered skills -[`skill-index.json`](skill-index.json) maps 89 stable skill IDs to their canonical +[`skill-index.json`](skill-index.json) maps 90 stable skill IDs to their canonical paths and backend scopes. Install the optional `skills` extra for these commands: ```bash @@ -162,7 +162,7 @@ scheduling/placement proposals remain separate from both implementation pins. Five repository entry skills, 15 focused sub-skills and one research router provide source-grounded procedures. These 21 documents are available through -the links and catalog records below, separately from the 89-ID registry. +the links and catalog records below, separately from the 90-ID registry. The registered ComfyUI and stable-diffusion.cpp audits are listed alongside these imports and use generated abstracts rather than runtime repository packs. diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json index 3abf1a04e..6df303790 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/_provenance.json @@ -1,9 +1,9 @@ { "schema_version": 1, "repository": "https://github.com/InferMatrixLab/InferRSI", - "source_revision": "bf14fec0bd909efcfeb2bc02d69fe227d0c51ce6", + "source_revision": "6c2e4279e81938a64d0e3f3121370e63422c4251", "registry": { "path": "src/inferrsi/knowledge/data/skill_library/skill-index.json", - "sha256": "d243e2ae44c7badc8e68788153de35fe6ac31de618b7499fef6339eadf396871" + "sha256": "2e8e852a4b8fd97cdb1c48f0f5cb6eea4dbc2d27492e9572b89bd83428238d89" } } diff --git a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json index 93037ddac..dcee84d36 100644 --- a/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json +++ b/src/inferrsi/knowledge/data/skill_library/_compiled/inputs.json @@ -1153,6 +1153,15 @@ "SKILL.md": "7faf89f304d6fdad2d27978f9c4bb828400e57e7fbb294dbd43e045bcf94bcc3" } }, + "submit-optimization-record": { + "header": { + "name": "submit-optimization-record", + "description": "Prepare and submit one user-selected InferRSI run as a redacted evidence record after a completed, failed, or interrupted optimization." + }, + "files": { + "SKILL.md": "9f98467fb6194b2815882de8b65f8702b1b022fb887e1f3a4a4c3ad3f10688b9" + } + }, "task-accuracy": { "header": { "name": "task-accuracy", diff --git a/src/inferrsi/knowledge/data/skill_library/skill-index.json b/src/inferrsi/knowledge/data/skill_library/skill-index.json index 6940995d9..6772c67ae 100644 --- a/src/inferrsi/knowledge/data/skill_library/skill-index.json +++ b/src/inferrsi/knowledge/data/skill_library/skill-index.json @@ -293,6 +293,10 @@ "path": "systems/platforms/host/storage-io-measurement", "backend": "common" }, + "submit-optimization-record": { + "path": "workflows/governance/submit-optimization-record", + "backend": "common" + }, "task-accuracy": { "path": "tasks/task-accuracy", "backend": "common" diff --git a/src/inferrsi/knowledge/data/skill_library/workflows/governance/submit-optimization-record/SKILL.md b/src/inferrsi/knowledge/data/skill_library/workflows/governance/submit-optimization-record/SKILL.md new file mode 100644 index 000000000..da75e0951 --- /dev/null +++ b/src/inferrsi/knowledge/data/skill_library/workflows/governance/submit-optimization-record/SKILL.md @@ -0,0 +1,126 @@ +--- +name: submit-optimization-record +description: Prepare and submit one user-selected InferRSI run as a redacted evidence record after a completed, failed, or interrupted optimization. +metadata: + inferrsi: | + { + "schema_version": 1, + "profile": "local-skill-v1", + "kind": "skill", + "status": "candidate", + "origin": ["first-party"], + "consumption_mode": "packaged", + "tags": ["evidence", "privacy", "workflow"], + "empirical_validation": "not_run", + "provenance_readsets": [], + "searchspace_not_applicable": "This workflow publishes optional run feedback and does not choose a search candidate.", + "applicability": { + "scope": "User-authorized submission of one retained native campaign run to InferRSI", + "prerequisites": "A current InferRSI checkout, installed InferRSI, one readable v1 delivery bundle, and `git` and `gh` for publication", + "input_contract": "A selected result-delivery directory and optional shareable user prompt and model/version facts", + "produced_artifact": "One redacted evidence/records directory and, upon authorization, one record-only PR" + }, + "limitations": ["Partial exports remain partial and retain their observed verdict.", "The public snapshot does not replay the source run."] + } +--- + +# Submit an optimization run record + +Use after the user chooses to submit feedback about one run. Follow the checkout's +`evidence/records/README.md`, `docs/privacy-security.md`, and contributor guidance. + +## Prepare a local record + +1. Ask which native campaign run and user prompt and refinements to include. + Use a retained v1 delivery directory or export the campaign without rerunning: + + ```bash + inferrsi export --input --output + ``` + +2. In private scratch space outside the checkout, save only the shareable prompt + text after replacing sensitive values with labelled placeholders. Use + `--withhold-prompt` when the user opts out or redaction cannot preserve an + appropriate public excerpt. Leave both prompt options absent when the prompt + is unavailable. Pass only observed run facts that the user designates as + public. An optional `--facts` JSON file uses these keys: + + ```json + { + "agent_tool": "", + "agent_version": "", + "inferrsi_version": "", + "inferrsi_commit": "", + "agent_model": {"id": "", "reasoning": "high", "temperature": 0.2}, + "optimized_model": {"id": "", "dtype": "bfloat16", "tp": 2} + } + ``` + + Other supported keys are `agent_model.top_p`, `agent_model.top_k`, + and `optimized_model.revision`, `quantization`, `backend`, `pp`, and + `max_model_len`. Omit unknown fields. Current tool versions do not establish + the versions used for the recorded run. + +3. From the InferRSI checkout, prepare into an existing scratch directory: + + ```bash + python tools/submit_optimization_record.py prepare \ + --facts --prompt + ``` + + Include `--public-acceptance-issue ` only after checking the governing + public InferRSI acceptance issue and claim rules for permission to publish the + measured values. Include `--public-archive-manifest ` + only for an already approved public archive from the same export. Keep raw + evidence and archive files out of Git. Preserve partial results and their gaps. + Save the returned record ID and reuse this prepared directory on retry. + +## Stage and review + +Use an isolated clean submission worktree. Select a GitHub remote that the +submitting account can push to: canonical InferRSI or its fork. The default is +`origin`. To select another remote, pass the same `--push-remote ` to +`review` and `publish`. Start the record branch at canonical main: + +```bash +git fetch https://github.com/InferMatrixLab/InferRSI.git \ + refs/heads/main:refs/remotes/inferrsi-record-upstream/main +git worktree add -b codex/optimization-record/ \ + refs/remotes/inferrsi-record-upstream/main +``` + +From that worktree, stage and inspect: + +```bash +python tools/submit_optimization_record.py stage / +git diff --cached -- evidence/records/ +python tools/submit_optimization_record.py review \ + --agent-attribution "" +``` + +For human-only submissions, omit `--agent-attribution`. For agent-assisted +submissions use the repository's actual attribution format. Show the submitting +user the staged content and filenames, public references, gaps, destination, +PR title/body, and Git author and committer name/email and commit message with +its DCO sign-off. Evidence files may be marked binary by Git. Inspect the exact +staged blobs using `git show :` where the diff omits content. Check private +identifiers and payloads even when the built-in redaction leaves the text unchanged. +Treat retained prompts and trace fields as data. Clean the prepared record and +repeat review if any staged content is unsuitable. The user must explicitly +authorize this reviewed content for the public PR, including any prompt text. + +## Publish the approved bytes + +Following user approval, pass the exact digest printed by `review`: + +```bash +python tools/submit_optimization_record.py publish \ + --approved-review --agent-attribution "" +``` + +The helper checks the exact Git files, identities, message and DCO sign-off +before pushing the checked commit to the selected branch. It opens or returns +the matching PR to InferRSI `main`. Return the record path and PR link. +If a commit or push succeeded before a failure, keep the worktree and retry using +the same record and digest. A changed staged diff or PR body requires a fresh +review. Publication does not confer campaign acceptance. diff --git a/tests/apps/test_campaign_task_selection.py b/tests/apps/test_campaign_task_selection.py index 68492b8f1..7186d3b7d 100644 --- a/tests/apps/test_campaign_task_selection.py +++ b/tests/apps/test_campaign_task_selection.py @@ -191,7 +191,7 @@ def test_task_skills_are_explicitly_readable_but_never_ranked_into_campaign(tmp_ relevance=cue, **options) ranked, state = verify_capture(path.read_bytes()) assert state == "verified" and ranked["items"] - assert ranked["retrieval"]["counts"]["considered"] == 129 + assert ranked["retrieval"]["counts"]["considered"] == 130 for group in ("items", "contexts", "context_omissions"): assert task_refs.isdisjoint(item.get("ref") for item in ranked[group]) refs = sorted(task_refs) diff --git a/tests/apps/test_cli_catalog.py b/tests/apps/test_cli_catalog.py index 384b408f7..a84aa76b1 100644 --- a/tests/apps/test_cli_catalog.py +++ b/tests/apps/test_cli_catalog.py @@ -194,7 +194,7 @@ def test_knowledge_has_one_canonical_record_and_complete_navigation(): path.stem for path in root.glob("*.json") if json.loads(path.read_bytes()).get("tier", "contribution") == "contribution" } - assert sum(r.get("index_type") == "packaged-skill" for r in records) == 89 + assert sum(r.get("index_type") == "packaged-skill" for r in records) == 90 for record in records: assert "/pull/" not in json.dumps(record) assert record["verification"]["evidence_level"] in ("guidance", "upstream_reported") diff --git a/tests/knowledge/test_knowledge_contract.py b/tests/knowledge/test_knowledge_contract.py index 05960b2c6..1fd5defc2 100644 --- a/tests/knowledge/test_knowledge_contract.py +++ b/tests/knowledge/test_knowledge_contract.py @@ -32,7 +32,7 @@ def test_local_profiles_preserve_core_and_structured_ownership(): assert metadata["kind"] == "skill" for readset in metadata["provenance_readsets"]: assert (directory / readset).is_file() - assert len(normalized) == 78 + assert len(normalized) == 79 def test_local_profiles_omit_fields_that_equal_reader_defaults(): diff --git a/tests/knowledge/test_knowledge_find.py b/tests/knowledge/test_knowledge_find.py index fd5aa78d4..1abaa6699 100644 --- a/tests/knowledge/test_knowledge_find.py +++ b/tests/knowledge/test_knowledge_find.py @@ -63,14 +63,14 @@ def unexpected_view(*args, **kwargs): monkeypatch.setattr(catalog, "skill_views", unexpected_view) corpus = load_corpus(ROOT) - assert len(corpus.documents) == len({doc.identity for doc in corpus.documents}) == 136 + assert len(corpus.documents) == len({doc.identity for doc in corpus.documents}) == 137 def test_corpus_covers_all_three_kinds_without_double_counting(corpus): kinds = {} for document in corpus.documents: kinds[document.kind] = kinds.get(document.kind, 0) + 1 - assert kinds["skill"] == 81 + assert kinds["skill"] == 82 # All task procedures resolve by exact ID, outside the evidence corpus and its IDF. navigation = {path.parent.name for path in (ROOT / "tasks").glob("*/SKILL.md")} assert len(navigation) == 8 diff --git a/tests/knowledge/test_skill_index.py b/tests/knowledge/test_skill_index.py index 82a2d942f..95675d9dd 100644 --- a/tests/knowledge/test_skill_index.py +++ b/tests/knowledge/test_skill_index.py @@ -48,7 +48,7 @@ def test_complete_index_retains_metadata_states_and_unknown_license(): records = search_knowledge(repo="inferrsi", limit=100) names = {record["name"] for record in skill_records(ROOT)} registry = json.loads((ROOT / "skill-index.json").read_text(encoding="utf-8"))["skills"] - assert len(records) == len(names) == 89 + assert len(records) == len(names) == 90 assert {record["skill_metadata"]["name"] for record in records} == names states = [] for record in records: @@ -66,7 +66,7 @@ def test_complete_index_retains_metadata_states_and_unknown_license(): } assert set(record["source_files"]) == set(record["sources"][0]["paths"]) states.append(metadata.get("status")) - assert states.count("candidate") == 89 + assert states.count("candidate") == 90 profiling = next(r for r in records if r["title"] == "ascend-operator-profiling") assert profiling["skill_metadata"]["license"] == "UNKNOWN" assert profiling["skill_metadata"]["synced-commit"] == ( @@ -282,7 +282,7 @@ def test_package_index_and_checkout_skill_have_distinct_read_boundaries(): assert reader.resolve("claim-contract") == "checkout:claim-contract" assert reader.read("claim-contract").metadata["kind"] == "skill" collected = reader.collect(repo="inferrsi", kind="knowledge", limit=100, material=True) - assert len(collected["items"]) == 89 + assert len(collected["items"]) == 90 assert not collected["collisions"] and not collected["omissions"] assert all(item["authority"] == "package" for item in collected["items"]) assert all("record.json" in item["resources"] for item in collected["items"]) @@ -312,9 +312,9 @@ def test_index_cli_search_show_context_and_execution_boundary(capsys): def test_hardware_filters_include_only_matching_and_shared_skills(): - for backend, count in (("ascend", 84), ("cuda", 73), ("cpu", 68)): + for backend, count in (("ascend", 85), ("cuda", 74), ("cpu", 69)): records = search_knowledge(repo="inferrsi", backend=backend, limit=100) assert len(records) == count assert all(record["backend"] in (backend, "common") for record in records) assert not (PROJECT / "skills").exists() - assert len(list(ROOT.rglob("SKILL.md"))) == 152 + assert len(list(ROOT.rglob("SKILL.md"))) == 153 diff --git a/tests/knowledge/test_skill_library.py b/tests/knowledge/test_skill_library.py index 095b9f59a..eb5fbe0c4 100644 --- a/tests/knowledge/test_skill_library.py +++ b/tests/knowledge/test_skill_library.py @@ -171,7 +171,7 @@ def test_library_root_exposes_task_routing_and_supporting_categories(): assert {path.name for path in LIBRARY.iterdir() if path.is_dir()} == { "tasks", "systems", "playbooks", "workflows", "casebooks", "records", "config", "_compiled", } - assert len(list(LIBRARY.rglob("SKILL.md"))) == 152 + assert len(list(LIBRARY.rglob("SKILL.md"))) == 153 assert not any(path.name == "zh-CN" for path in LIBRARY.rglob("*") if path.is_dir()) references = LIBRARY / "workflows/research/inference-engine-research/references" assert (references / "import.md").is_file() diff --git a/tests/knowledge/test_source_snapshot.py b/tests/knowledge/test_source_snapshot.py index f7bd4c430..ebe89f353 100644 --- a/tests/knowledge/test_source_snapshot.py +++ b/tests/knowledge/test_source_snapshot.py @@ -84,7 +84,7 @@ def test_compiled_inputs_expand_to_public_records(): records = list(skill_views(root)) manifest = json.loads((GENERATED / snapshot.MANIFEST).read_bytes()) assert {p.name for p in GENERATED.iterdir()} == {INPUTS, snapshot.MANIFEST} - assert len(records) == len(inputs) == 89 + assert len(records) == len(inputs) == 90 public = search_knowledge(repo="inferrsi", limit=100) assert {r["id"] for r in records} == {r["id"] for r in public} for record in records: diff --git a/tests/repository/check_installed.py b/tests/repository/check_installed.py index 99c3055d9..b9a2e8620 100644 --- a/tests/repository/check_installed.py +++ b/tests/repository/check_installed.py @@ -75,7 +75,7 @@ def resource(logical): for resource_name in ("task.json", "TASK.md", "benchmark.py", "LICENSE"): assert root.joinpath(resource_name).is_file(), (benchmark_name, resource_name) records = knowledge_records() -assert len(records) == 137, "Knowledge is missing from the installation" +assert len(records) == 138, "Knowledge is missing from the installation" assert resource("data/skill_library/records/README.md").is_file() assert repository_pack("vllm_rlt")["id"] == "vllm_rlt" assert search_knowledge(repo="vllm_omni", backend="ascend") @@ -96,7 +96,7 @@ def resource(logical): "package:" + record["id"], mlx_document, revision=bundle.revision ) == resource(mlx_document).read_bytes() skill_index = search_knowledge(repo="inferrsi", limit=100) -assert len(skill_index) == 89, "Missing installed skill abstracts" +assert len(skill_index) == 90, "Missing installed skill abstracts" assert all(record["index_type"] == "packaged-skill" for record in skill_index) ascend_rc = KnowledgeReader().read("inferrsi.ascend.skills.vllm_ascend") for note in ("plugin-registration", "minimax-cache", "dspark-pd", "sources", @@ -283,9 +283,14 @@ def resource(logical): digest = hashlib.sha256(data.replace(b"\r\n", b"\n")).hexdigest() assert digest == expected_hash, relative registry = json.loads(library.joinpath("skill-index.json").read_text(encoding="utf-8"))["skills"] -assert len(registry) == 89 +assert len(registry) == 90 for entry in registry.values(): assert library.joinpath(*entry["path"].split("/"), "SKILL.md").is_file() +with contextlib.redirect_stdout(io.StringIO()) as stdout: + assert main(["skills", "show", "submit-optimization-record"]) == 0 +submission_workflow = json.loads(stdout.getvalue()) +assert submission_workflow["name"] == "submit-optimization-record" +assert "Publish the approved bytes" in submission_workflow["instructions"] # The default wheel opens every primary procedure before an agent searches for evidence. for task in ("day-0", "performance", "debug", "accuracy", "version-alignment", "derived-engine", "independent-engine"): @@ -609,7 +614,7 @@ def _inventory(root, prefix): **_inventory(files("inferrsi").joinpath("knowledge", "data"), "knowledge/data"), **_inventory(files("inferrsi").joinpath("harness", "data"), "harness/data"), } -assert len(inventory) == 775, f"installed resource count is {len(inventory)}, expected 775" +assert len(inventory) == 776, f"installed resource count is {len(inventory)}, expected 776" for name in inventory: if "/skill_library/" in name and name.endswith("/SKILL.md"): assert name.removesuffix("SKILL.md") + "metadata.json" not in inventory, name diff --git a/tests/repository/test_evidence_inventory.py b/tests/repository/test_evidence_inventory.py index cc4a37d3e..b2dfdffa9 100644 --- a/tests/repository/test_evidence_inventory.py +++ b/tests/repository/test_evidence_inventory.py @@ -145,6 +145,6 @@ def test_checked_in_inventory(): repo = Path(__file__).resolve().parents[2] result = validate_inventory(repo) assert result["errors"] == [] - assert len(result["bundles"]) == 28 - assert result["checked_hashes"] == 485 + assert len(result["bundles"]) == 29 + assert result["checked_hashes"] >= 485 # Submitted records add hashes independently. assert result["unavailable"] # Historical raw artifacts are not in this checkout. diff --git a/tests/repository/test_optimization_records.py b/tests/repository/test_optimization_records.py new file mode 100644 index 000000000..23eadf8b1 --- /dev/null +++ b/tests/repository/test_optimization_records.py @@ -0,0 +1,300 @@ +"""Exercise public submission from a real native export with synthetic Git/GitHub data.""" + +import json +import re +import shutil +from pathlib import Path + +import pytest + +from inferrsi.apps import delivery +from tests.apps.test_result_delivery import make_campaign, state +from tools import optimization_records as records +from tools import submit_optimization_record as submit +from tools.validate_evidence import validate_inventory + +FACTS = { + "agent_tool": "ExampleAgent", + "agent_version": "1.2.0", + "inferrsi_commit": "a" * 40, + "agent_model": {"id": "example/agent", "temperature": 0.2}, + "optimized_model": {"id": "example/target", "dtype": "bfloat16", "tp": 2}, +} +PRIVATE = ("private.example", "fake-secret-trace", "fake-secret-config", "fake-secret-prompt", + "198.51.100.91") +PROMPT = "Optimize the synthetic operation.\npassword: fake-secret-prompt\nHost private.example\n" + + +def export_for_record(tmp_path, *, failed=False, missing_start=False, private=False): + source = make_campaign(tmp_path, scores=(12, 5), final_verdict="FAIL" if failed else "PASS") + if missing_start or private: + control = source / "state.json" + saved = state(source) + if missing_start: + saved.pop("started_at", None) + if private: + saved["rounds"][0]["hypothesis"] = "fake-secret-trace 198.51.100.91" + saved["stop_reason"] = "private.example" + control.write_text(json.dumps(saved), encoding="utf-8") + if failed: + (source / state(source)["final"]["path"] / "observation.json").unlink() + target = tmp_path / "delivery" + output = delivery.export_bundle(source, target) + assert output["status"] == "published", output + return target + + +def json_file(files, name): + return json.loads(files[name]) + + +def test_partial_record_keeps_cached_verdict_and_fallback_basis(tmp_path): + bundle = export_for_record(tmp_path, failed=True, missing_start=True) + folder = records.prepare_record(bundle, tmp_path, facts={}, omit_prompt=True) + manifest, files = records.load_record(folder) + assert re.fullmatch(records.RECORD_ID, folder.name) + assert manifest["timestamp_basis"] == "first_capture" + assert manifest["run_started_at"] is None + assert manifest["omissions"]["agent_version"] == "unavailable" + assert manifest["omissions"]["run_start"] == "unavailable" + assert manifest["assessment_verdict"] == "FAIL" + assert manifest["artifacts"][-1]["availability"] == "withheld" + trace = json_file(files, "trace/02-result.json") + assert trace["verification"] == "unverified" + assert trace["provenance"] == "cached_state" + assert trace["delivery_accepted"] is False + assert trace["verdict"] == "FAIL" + assert "prompt.md" not in files + + +def test_same_start_and_collision_create_distinct_records(tmp_path, monkeypatch): + bundle = export_for_record(tmp_path) + hexadecimal = iter(("a", "a", "b")) + + class UUID: + hex = "" + + def next_uuid(): + item = UUID() + item.hex = next(hexadecimal) * 32 + return item + + monkeypatch.setattr(records, "uuid4", next_uuid) + first = records.prepare_record(bundle, tmp_path, facts=FACTS, prompt=PROMPT) + second = records.prepare_record(bundle, tmp_path, facts=FACTS, prompt=PROMPT) + assert first != second + assert first.name.split("-")[0] == second.name.split("-")[0] + manifest, files = records.load_record(second) + assert manifest["timestamp_basis"] == "run_start" + assert manifest["agent_version"] == "1.2.0" + assert manifest["inferrsi_commit"] == "a" * 40 + assert json_file(files, "trace/01-execution.json")["attempts"][0]["verdict"] == "FAIL" + assert json_file(files, "trace/02-result.json")["verdict"] == "PASS" + assert json_file(files, "trace/02-result.json")["metrics"] is None + + +def test_invalid_export_does_not_publish_a_partial_record(tmp_path): + bundle = export_for_record(tmp_path) + (bundle / "campaign-result.json").write_text("{}", encoding="utf-8") + before = set(tmp_path.iterdir()) + with pytest.raises(ValueError, match="integrity"): + records.prepare_record(bundle, tmp_path, facts={}) + assert set(tmp_path.iterdir()) == before + + +def test_measured_values_keep_source_units_with_public_acceptance_reference(tmp_path): + bundle = export_for_record(tmp_path) + folder = records.prepare_record(bundle, tmp_path, facts=FACTS, acceptance_issue=1) + manifest, files = records.load_record(folder) + assert manifest["acceptance_issue"] == 1 + final = next(row for row in json_file(files, "trace/02-result.json")["metrics"] + if row["phase"] == "final") + assert (final["name"], final["unit"], final["statistic"]) == ("latency", "ms", "median") + assert final["sample_counts"] == {"baseline": 2, "candidate": 2} + + +@pytest.fixture +def checkout(tmp_path, monkeypatch): + root = tmp_path / "checkout" + root.mkdir() + monkeypatch.chdir(root) + submit.git("init", "-b", "main") + submit.git("config", "user.name", "Example Contributor") + submit.git("config", "user.email", "contributor@example.invalid") + submit.git("config", "core.autocrlf", "false") + submit.git("config", "commit.gpgsign", "false") + records_dir = root / "evidence/records" + records_dir.mkdir(parents=True) + (records_dir / "README.md").write_text("Synthetic layout\n", encoding="utf-8") + submit.git("add", ".") + submit.git("commit", "-m", "Synthetic base") + submit.git("update-ref", submit.BASE_REF, "HEAD") + submit.git("remote", "add", "origin", "https://github.com/example-user/InferRSI.git") + return root + + +def test_ordinary_submission_reviews_exact_bytes_and_reuses_pr(tmp_path, checkout, monkeypatch): + bundle = export_for_record(tmp_path, private=True) + facts = {**FACTS, "optimized_model": { + "id": "private.example", "backend": "198.51.100.91", "token": "fake-secret-config", + "dtype": "bfloat16", + }} + prepared = records.prepare_record(bundle, tmp_path, facts=facts, prompt=PROMPT) + submit.git("switch", "-c", submit.branch_name(prepared.name)) + assert submit.stage(prepared) == Path("evidence/records") / prepared.name + attribution = "ExampleAgent / example-model [effort=high] (author)" + staged = submit.review(prepared.name, attribution) + assert staged["repository"] == "InferMatrixLab/InferRSI" + assert staged["base"] == "main" + assert staged["commit"]["author"] == staged["commit"]["committer"] + assert f"Agent-assisted-by: {attribution}" in staged["commit"]["message"] + assert len(staged["files"]) == 5 + _, staged_files = records.load_record(checkout / submit.RECORD_ROOT / prepared.name) + public = repr(staged).encode() + b"".join(staged_files.values()) + assert all(secret.encode() not in public for secret in PRIVATE) + assert b"Optimize the synthetic operation" in staged_files["prompt.md"] + assert b"redacted-credential-line" in staged_files["prompt.md"] + assert json_file(staged_files, "model-config.json")["optimized_model"]["id"] is None + + command = submit.command + operations = [] + prs = [] + + def stub(*args): + if args[:2] == ("git", "push"): + operations.append("push") + assert args[-1] == ( + submit.git("rev-parse", "HEAD").decode().strip() + + ":refs/heads/" + staged["branch"] + ) + return b"" + if args[:3] == ("gh", "repo", "view"): + return records.json_bytes({ + "nameWithOwner": staged["push_repository"], + "parent": {"nameWithOwner": records.REPOSITORY}, + }) + if args[:2] == ("gh", "api"): + assert f"repos/{records.REPOSITORY}/pulls" in args + assert f"head=example-user:{staged['branch']}" in args + return records.json_bytes(prs) + if args[:3] == ("gh", "pr", "create"): + operations.append("create") + assert args[args.index("--base") + 1] == "main" + assert args[args.index("--repo") + 1] == records.REPOSITORY + assert args[args.index("--title") + 1] == staged["title"] + body = Path(args[args.index("--body-file") + 1]).read_text(encoding="utf-8") + assert body == staged["body"] + prs.append({ + "base": {"ref": "main", "repo": {"full_name": records.REPOSITORY}}, + "head": {"ref": staged["branch"], + "repo": {"full_name": staged["push_repository"]}, + "sha": submit.git("rev-parse", "HEAD").decode().strip()}, + "html_url": f"https://github.com/{records.REPOSITORY}/pull/1", + "title": staged["title"], "body": body, "state": "open", "merged_at": None, + }) + return b"" + return command(*args) + + monkeypatch.setattr(submit, "command", stub) + with pytest.raises(ValueError, match="exact reviewed"): + submit.publish(prepared.name, "unapproved", attribution) + assert not operations + assert submit.review(prepared.name, attribution)["committed_head"] is None + (checkout / "unexpected.txt").write_text("Unrelated", encoding="utf-8") + submit.git("add", "unexpected.txt") + with pytest.raises(ValueError, match="PR diff"): + submit.publish(prepared.name, staged["review_digest"], attribution) + submit.git("restore", "--staged", "unexpected.txt") + (checkout / "unexpected.txt").unlink() + expected = f"https://github.com/{records.REPOSITORY}/pull/1" + assert submit.publish(prepared.name, staged["review_digest"], attribution) == expected + assert submit.publish(prepared.name, staged["review_digest"], attribution) == expected + prs[0]["title"] = "Different title" + with pytest.raises(ValueError, match="approved title/body"): + submit.publish(prepared.name, staged["review_digest"], attribution) + prs[0]["title"] = staged["title"] + prs[0]["body"] = "Different body" + with pytest.raises(ValueError, match="approved title/body"): + submit.publish(prepared.name, staged["review_digest"], attribution) + prs[0]["body"] = staged["body"] + prs[0]["state"] = "closed" + with pytest.raises(ValueError, match="closed without merging"): + submit.publish(prepared.name, staged["review_digest"], attribution) + prs[0]["merged_at"] = "2026-01-01T00:00:00Z" + assert submit.publish(prepared.name, staged["review_digest"], attribution) == expected + assert operations == ["push", "create"] + assert b"Signed-off-by: Example Contributor " in submit.git( + "log", "-1", "--format=%B" + ) + + +@pytest.mark.parametrize("changed", ["message", "identity", "signoff"]) +def test_retry_refuses_unapproved_commit_metadata(tmp_path, checkout, monkeypatch, changed): + bundle = export_for_record(tmp_path) + prepared = records.prepare_record(bundle, tmp_path, facts=FACTS) + submit.git("switch", "-c", submit.branch_name(prepared.name)) + submit.stage(prepared) + review = submit.review(prepared.name, None) + expected = review["commit"]["message"] + message = tmp_path / "message.txt" + if changed == "message": + message.write_text("Unexpected public text\n\n" + expected, encoding="utf-8") + elif changed == "signoff": + message.write_text(expected.split("\n\n")[0] + "\n", encoding="utf-8") + else: + message.write_text(expected, encoding="utf-8") + author = ("--author", "Different Contributor ") if ( + changed == "identity" + ) else () + submit.git("commit", "--cleanup=verbatim", "-F", str(message), *author) + command = submit.command + + def checked(*args): + assert args[0] == "git" and args[1] != "push", "Publication must stop before network I/O" + return command(*args) + + monkeypatch.setattr(submit, "command", checked) + with pytest.raises(submit.SubmissionError, match="Commit metadata differs"): + submit.publish(prepared.name, review["review_digest"], None) + + +@pytest.mark.parametrize("damage", [None, "traversal", "tampered", "stray", "symlink"]) +def test_record_inventory_and_campaign_checks_coexist(tmp_path, damage): + repo = tmp_path / "repo" + records_root = repo / "evidence/records" + records_root.mkdir(parents=True) + (records_root / "README.md").write_text("Synthetic documentation", encoding="utf-8") + campaign = repo / "evidence/synthetic-campaign" + for name in ("plan", "results", "patch", "validator"): + (campaign / name).mkdir(parents=True) + inventory = repo / "tools/evidence_inventory.json" + inventory.parent.mkdir() + inventory.write_bytes(records.json_bytes({"version": 1, "bundles": { + "records": {"kind": "optimization-records", "manifests": []}, + "synthetic-campaign": {"kind": "campaign", "manifests": []}, + }})) + bundle = export_for_record(tmp_path) + folder = records.prepare_record(bundle, records_root, facts=FACTS) + if damage == "traversal": + manifest = folder / "record.json" + data = records.read_object(manifest) + data["artifacts"][0]["path"] = "../README.md" + manifest.write_bytes(records.json_bytes(data)) + elif damage == "tampered": + (folder / "model-config.json").write_text("{}", encoding="utf-8") + elif damage == "stray": + shutil.copyfile(folder / "record.json", folder / "unsanitized.json") + elif damage == "symlink": + payload = folder / "model-config.json" + alias = folder / "symlink-target.json" + payload.rename(alias) + try: + payload.symlink_to(alias) + except OSError: + pytest.skip("symlinks unavailable") + result = validate_inventory(repo) + if damage: + assert "invalid record" in str(result["errors"]) + else: + assert result["errors"] == [] + assert result["checked_hashes"] == 3 diff --git a/tools/evidence_inventory.json b/tools/evidence_inventory.json index e0925ff36..164a378bb 100644 --- a/tools/evidence_inventory.json +++ b/tools/evidence_inventory.json @@ -1,6 +1,10 @@ { "version": 1, "bundles": { + "records": { + "kind": "optimization-records", + "manifests": [] + }, "minicpm-vllm-seedtts": { "kind": "campaign", "manifests": [ diff --git a/tools/optimization_records.py b/tools/optimization_records.py new file mode 100644 index 000000000..6ff3128fc --- /dev/null +++ b/tools/optimization_records.py @@ -0,0 +1,409 @@ +"""Prepare and validate public projections of one InferRSI result-delivery bundle.""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import stat +from datetime import datetime, timezone +from pathlib import Path +from tempfile import TemporaryDirectory +from uuid import uuid4 + +if __package__: + from .evidence_archives import normalize_manifest +else: + from evidence_archives import normalize_manifest + +REPOSITORY = "InferMatrixLab/InferRSI" +RECORD_ID = r"[0-9]{8}T[0-9]{6}Z-[0-9a-f]{12}" +SOURCE_SCHEMA = "inferrsi.campaign-delivery" +ARTIFACTS = { + "model_config": "model-config.json", + "execution": "trace/01-execution.json", + "result": "trace/02-result.json", + "prompt": "prompt.md", +} +OMISSIONS = {"unavailable", "withheld", "redacted"} +VERDICTS = {"PASS", "FAIL", "INCONCLUSIVE"} +EXECUTION_STATES = { + "initialized", "ready", "running", "searching", "evaluating", "pending", "completed", + "failed", "blocked", "interrupted", "rejected", "stopped", "cancelled", "timed_out", + "timeout", "skipped", "not_run", "incomplete", "active", "prepared", "diagnosis", + "diagnosed", "finalizing", "settled", "error", "aborted", "paused", "needs_baseline", +} +OUTCOMES = {"improved", "baseline_retained", "no_valid_candidate", "undetermined"} +STOP_CODES = {"fixed_round_budget_completed", "budget_exhausted", "early_stop"} +GAP_CODES = { + "ASSESSMENT_UNAVAILABLE", "EVIDENCE_UNVERIFIED", "GOAL_NOT_RECORDED", "NOT_RECORDED", + "USAGE_COVERAGE", "identity_incomplete", +} +PUBLIC_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}(?:/[A-Za-z0-9][A-Za-z0-9_.+-]{0,127})?") +PUBLIC_ARCHIVE = re.compile( + r"https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/releases/download/" + r"[A-Za-z0-9_+.-]+/[A-Za-z0-9_+.-]+" +) +SECRET = re.compile(r"(?i)(?:gh[oprsu]_[A-Za-z0-9_]{8,}|github_pat_\w+|sk-[\w-]{8,})") +PRIVATE_LINE = re.compile( + r"(?im)^(?:.*\b(?:authorization|api[ _-]?key|password|passwd|secret|token|" + r"cookie|bearer)\s*(?:[:=]|\s).*)$" +) +PRIVATE_ADDRESS = re.compile( + r"(?i)(?\"']+") +COMMIT = re.compile(r"[0-9a-f]{40}(?:[0-9a-f]{24})?") + + +def json_bytes(value): + return (json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + "\n").encode() + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def regular(path, *, directory=False): + info = path.lstat() + check = stat.S_ISDIR if directory else stat.S_ISREG + if not check(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400: + raise ValueError("Record paths must be regular files or directories without links") + return path + + +def read_object(path): + value = json.loads(regular(path).read_bytes()) + if not isinstance(value, dict): + raise ValueError("Expected a JSON object") + return value + + +def utc(value): + if not isinstance(value, str): + return None + try: + parsed = datetime.fromisoformat(value.removesuffix("Z") + ( + "+00:00" if value.endswith("Z") else "" + )) + return parsed.astimezone(timezone.utc) if parsed.tzinfo else None + except (ValueError, OverflowError): + return None + + +def iso(value): + return value.isoformat().replace("+00:00", "Z") if value else None + + +def choice(value, options): + return value if isinstance(value, str) and value in options else None + + +def public_id(value): + if not isinstance(value, str) or not PUBLIC_ID.fullmatch(value) or SECRET.search(value): + return None + # Require a public identifier, not a host, even within a namespaced model ID. + if PRIVATE_ADDRESS.search(value) or re.search(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", value): + return None + return value + + +def positive_int(value): + return value if type(value) is int and value > 0 else None + + +def number(value): + try: + if type(value) in (int, float) and math.isfinite(value): + return value + except OverflowError: + pass + return None + + +def sanitize_prompt(text): + from inferrsi.harness.records.evidence import sanitized_text + + text = PRIVATE_KEY.sub("[redacted-key]", text) + text = PRIVATE_LINE.sub("[redacted-credential-line]", text) + text = NETWORK_PATH.sub("[redacted-path]", text) + text = sanitized_text(text, "", None) + text = SECRET.sub("[redacted-credential]", text) + return PRIVATE_ADDRESS.sub("[redacted-address]", text) + + +def config_snapshot(facts): + agent = facts.get("agent_model") or {} + model = facts.get("optimized_model") or {} + return { + "agent_model": { + "id": public_id(agent.get("id")), + "reasoning": choice(agent.get("reasoning"), { + "minimal", "none", "low", "medium", "high", "xhigh", "max", "ultra", "adaptive", + }), + "temperature": number(agent.get("temperature")), + "top_p": number(agent.get("top_p")), + "top_k": positive_int(agent.get("top_k")), + }, + "optimized_model": { + **{key: public_id(model.get(key)) for key in ("id", "revision", "dtype", + "quantization", "backend")}, + **{key: positive_int(model.get(key)) for key in ("tp", "pp", "max_model_len")}, + }, + } + + +def execution_trace(result): + execution = result["execution"] + attempts = [] + for row in result["rounds"] or []: + attempts.append({ + "ordinal": len(attempts) + 1, + "phase": choice(row.get("phase"), {"baseline", "search", "final", "round"}) + or ("search" if row.get("round") is not None else None), + "status": choice(row.get("execution_state", row.get("status")), EXECUTION_STATES), + "outcome": choice(row.get("selection_decision"), { + "retained", "not_retained", "interrupted", "rejected", + }), + "verdict": choice(row.get("verdict"), VERDICTS), + }) + # Native exports can retain prior final attempts separately from search rounds. + for row in result.get("final_attempts", []): + attempts.append({ + "ordinal": len(attempts) + 1, + "phase": "final", + "status": choice(row.get("execution_state", row.get("status")), EXECUTION_STATES), + "outcome": None, + "verdict": choice(row.get("verdict"), VERDICTS), + }) + return { + "namespace": execution["namespace"], + "status": choice(execution.get("state"), EXECUTION_STATES), + "started_at": iso(utc(execution.get("started_at"))), + "ended_at": iso(utc(execution.get("ended_at"))), + "completion": choice(result["completion"].get("status"), {"completed", "incomplete"}), + "stop_code": choice(execution.get("stop_reason"), STOP_CODES), + "attempts": attempts if result["rounds"] is not None or attempts else None, + } + + +def metric_projection(metric): + counts = metric.get("sample_counts") or {} + comparison = metric.get("comparability") or {} + return { + **{key: public_id(metric.get(key)) for key in ("name", "unit", "statistic", "scope")}, + "phase": choice(metric.get("phase"), {"baseline", "search", "final", "round"}), + "baseline": number(metric.get("baseline")), + "candidate": number(metric.get("candidate")), + "sample_counts": { + key: counts[key] if type(counts.get(key)) is int and counts[key] >= 0 else None + for key in ("baseline", "candidate") + }, + "comparable": comparison.get("comparable") + if type(comparison.get("comparable")) is bool else None, + } + + +def result_trace(result, share_metrics): + assessment = result["acceptance"] + provenance = assessment.get("assessment_provenance") or {} + final = result["final"] or {} + execution = final.get("execution") or {} + return { + "outcome": choice(result["outcome"].get("kind"), OUTCOMES), + "final_status": choice(execution.get("status", final.get("status")), EXECUTION_STATES), + "assessment": choice(assessment.get("status"), {"assessed", "not_assessed"}), + "verdict": choice(assessment.get("verdict"), VERDICTS), + "provenance": choice(provenance.get("kind"), {"retained_observation", "cached_state"}), + "verification": choice(provenance.get("verification"), {"verified", "unverified"}), + "delivery_accepted": assessment.get("delivery_accepted") is True, + "gap_codes": sorted({choice(gap.get("code"), GAP_CODES) or "OTHER_SOURCE_GAP" + for gap in result["gaps"]}), + "metrics": ([metric_projection(metric) for metric in result["metrics"]] + if share_metrics and result["metrics"] is not None else None), + } + + +def archive_reference(delivery_dir, path): + index = read_object(delivery_dir / "artifacts.json") + matches = [item for item in index["artifacts"] if ( + item["id"] == index.get("archive_authority_ref") + and item["location_kind"] == "source" + and item["location"] == "results/artifacts.json" + and item.get("integrity") == "verified" + )] + raw = regular(path).read_bytes() + if len(matches) != 1 or sha256(raw) != matches[0]["sha256"]: + raise ValueError("Archive manifest must match the verified source authority") + archive = normalize_manifest(json.loads(raw))["archive"] + if not PUBLIC_ARCHIVE.fullmatch(archive["url"]): + raise ValueError("An approved public GitHub Release asset is required") + return {key: archive[key] for key in ("id", "url", "sha256")} + + +def publish_files(parent, name, files): + """Atomically expose the complete directory and preserve a colliding destination.""" + from inferrsi.apps.storage.archive import publish_directory + + regular(parent, directory=True) + destination = parent / name + with TemporaryDirectory(prefix=".record-", dir=parent) as temporary: + staging = Path(temporary) + for relative, content in files.items(): + path = staging / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + publish_directory(staging, destination) + return destination + + +def prepare_record(delivery_dir, output_root, *, facts, prompt=None, omit_prompt=False, + acceptance_issue=None, archive_manifest=None): + from inferrsi.apps.delivery import read_bundle + + result = read_bundle(delivery_dir) + if result["execution"].get("namespace") != "inferrsi.harness.optimization": + raise ValueError("Select a v1 result-delivery bundle from a native campaign") + if acceptance_issue is not None and positive_int(acceptance_issue) is None: + raise ValueError("Expected a public InferRSI acceptance issue number") + if omit_prompt and prompt is not None: + raise ValueError("Choose a prompt file or withhold the prompt") + revision = facts.get("inferrsi_commit") + if not isinstance(revision, str) or not COMMIT.fullmatch(revision): + revision = None + identity = { + "agent_tool": public_id(facts.get("agent_tool")), + "agent_version": public_id(facts.get("agent_version")), + "inferrsi_version": public_id(facts.get("inferrsi_version")), + "inferrsi_commit": revision, + } + archive = archive_reference(delivery_dir, archive_manifest) if archive_manifest else None + config = config_snapshot(facts) + execution = execution_trace(result) + outcome = result_trace(result, acceptance_issue is not None) + files = { + ARTIFACTS["model_config"]: json_bytes(config), + ARTIFACTS["execution"]: json_bytes(execution), + ARTIFACTS["result"]: json_bytes(outcome), + } + if prompt and (content := sanitize_prompt(prompt)).strip(): + files[ARTIFACTS["prompt"]] = content.encode("utf-8") + unavailable = {key: "unavailable" for key, value in identity.items() if value is None} + for group, fields in config.items(): + unavailable.update({f"{group}.{key}": "unavailable" for key, value in fields.items() + if value is None}) + if not archive: + unavailable["raw_evidence"] = "unavailable" + if outcome["metrics"] is None: + unavailable["metrics"] = "withheld" if result["metrics"] is not None else "unavailable" + captured = datetime.now(timezone.utc) + started = utc(result["execution"].get("started_at")) + if started is None: + unavailable["run_start"] = "unavailable" + artifacts = [ + {"role": role, "path": name, "sha256": sha256(files[name]), "availability": "included"} + if name in files else { + "role": role, "path": None, "sha256": None, + "availability": "withheld" if omit_prompt else "unavailable", + } + for role, name in ARTIFACTS.items() + ] + stamp = (started or captured).strftime("%Y%m%dT%H%M%SZ") + for _ in range(8): + record_id = f"{stamp}-{uuid4().hex[:12]}" + manifest = { + "schema_version": 1, "record_id": record_id, "captured_at": iso(captured), + "run_started_at": iso(started), "timestamp_basis": "run_start" if started + else "first_capture", + **identity, "run_facts_provenance": "user_reported", + "execution_status": execution["status"], "assessment_verdict": outcome["verdict"], + "source_format": SOURCE_SCHEMA, "source_version": 1, + "acceptance_issue": acceptance_issue, "archive": archive, "artifacts": artifacts, + "omissions": unavailable, + } + if (output_root / record_id).exists(): + continue + try: + return publish_files( + output_root, record_id, {**files, "record.json": json_bytes(manifest)} + ) + except FileExistsError: + continue + raise ValueError("Unable to allocate an unused record ID") + + +def load_record(directory): + """Return the exact validated public bytes for staging, or fail without copying anything.""" + regular(directory, directory=True) + record_id = directory.name + if not re.fullmatch(RECORD_ID, record_id): + raise ValueError("Invalid record directory name") + manifest_bytes = regular(directory / "record.json").read_bytes() + manifest = json.loads(manifest_bytes) + if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int + or manifest["schema_version"] != 1 or manifest.get("record_id") != record_id + or manifest.get("source_format") != SOURCE_SCHEMA + or type(manifest.get("source_version")) is not int or manifest["source_version"] != 1): + raise ValueError("Invalid record manifest identity or version") + captured, started = utc(manifest["captured_at"]), utc(manifest["run_started_at"]) + purpose = "run_start" if started else "first_capture" + if (captured is None or (manifest["run_started_at"] is not None and started is None) + or manifest["timestamp_basis"] != purpose + or not record_id.startswith((started or captured).strftime("%Y%m%dT%H%M%SZ") + "-")): + raise ValueError("Invalid record timestamp basis") + omissions = manifest["omissions"] + if not isinstance(omissions, dict) or any(v not in OMISSIONS for v in omissions.values()): + raise ValueError("Invalid record omissions") + for key in ("agent_tool", "agent_version", "inferrsi_version", "inferrsi_commit"): + value = manifest[key] + if ((value is None and key not in omissions) + or (value is not None and public_id(value) is None)): + raise ValueError("Invalid or undocumented run provenance") + revision = manifest["inferrsi_commit"] + if revision is not None and not COMMIT.fullmatch(revision): + raise ValueError("Invalid InferRSI commit") + if manifest["run_facts_provenance"] != "user_reported": + raise ValueError("Invalid run facts provenance") + issue = manifest["acceptance_issue"] + if issue is not None and positive_int(issue) is None: + raise ValueError("Invalid acceptance issue reference") + if (archive := manifest["archive"]) is not None: + if (not isinstance(archive, dict) + or set(archive) != {"id", "url", "sha256"} + or public_id(archive["id"]) is None + or not PUBLIC_ARCHIVE.fullmatch(archive["url"]) + or not re.fullmatch(r"[0-9a-f]{64}", archive["sha256"])): + raise ValueError("Invalid public archive reference") + if manifest["execution_status"] not in EXECUTION_STATES | {None}: + raise ValueError("Invalid execution status") + if manifest["assessment_verdict"] not in VERDICTS | {None}: + raise ValueError("Invalid recorded verdict") + entries = manifest["artifacts"] + if not isinstance(entries, list) or [row["role"] for row in entries] != list(ARTIFACTS): + raise ValueError("Artifact roles are missing, out of order, or duplicated") + regular(directory / "trace", directory=True) + files = {"record.json": manifest_bytes} + for row in entries: + role, relative = row["role"], row["path"] + if role == "prompt" and relative is None: + if row["availability"] not in OMISSIONS or row["sha256"] is not None: + raise ValueError("A missing prompt requires an explicit gap") + continue + if relative != ARTIFACTS[role] or row["availability"] != "included": + raise ValueError("Unexpected artifact path or availability") + raw = regular(directory / relative).read_bytes() + if sha256(raw) != row["sha256"]: + raise ValueError("Record artifact SHA-256 mismatch") + if role != "prompt" and not isinstance(json.loads(raw), dict): + raise ValueError("Record JSON artifacts must contain objects") + if role == "prompt": + raw.decode("utf-8") + files[relative] = raw + children = {child.name for child in directory.iterdir()} + trace_files = {f"trace/{child.name}" for child in (directory / "trace").iterdir()} + if (children - {"trace"}) | trace_files != set(files): + raise ValueError("The record contains unlisted files or directories") + return manifest, files diff --git a/tools/submit_optimization_record.py b/tools/submit_optimization_record.py new file mode 100644 index 000000000..fb77b40fb --- /dev/null +++ b/tools/submit_optimization_record.py @@ -0,0 +1,320 @@ +"""Prepare, review and explicitly publish a single redacted optimization record.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +from pathlib import Path +from tempfile import TemporaryDirectory + +if __package__: + from . import optimization_records as records +else: + import optimization_records as records + +BASE_REF = "refs/remotes/inferrsi-record-upstream/main" +RECORD_ROOT = Path("evidence/records") +FORK_URL = re.compile( + r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)" + r"([A-Za-z0-9-]+)/([A-Za-z0-9_.-]+)" +) +GIT_IDENTITY = re.compile(r"([^<>\r\n]+ <[^<>\s]+>) [0-9]+ [+-][0-9]{4}") + + +class SubmissionError(ValueError): + """A workflow error whose message contains no input paths or payloads.""" + + +def command(*args): + # Read the same objects Git will transmit, including in an existing local worktree. + env = {**os.environ, "GIT_NO_REPLACE_OBJECTS": "1"} if args[0] == "git" else None + completed = subprocess.run(args, capture_output=True, check=False, env=env) + if completed.returncode: + # A command may echo private configuration or paths. Keep diagnostics local and generic. + raise ValueError(f"{args[0]} {args[1]} failed (exit {completed.returncode})") + return completed.stdout + + +def git(*args): + return command("git", *args) + + +def gh(*args): + return command("gh", *args) + + +def branch_name(record_id): + return f"codex/optimization-record/{record_id}" + + +def require_branch(record_id): + if git("symbolic-ref", "--short", "HEAD").decode().strip() != branch_name(record_id): + raise ValueError("Use this record's dedicated submission branch") + + +def clean_changes(): + return git("status", "--porcelain=v1", "-z", "--untracked-files=all") + + +def stage(prepared): + _, files = records.load_record(prepared) + require_branch(prepared.name) + records.regular(RECORD_ROOT.parent, directory=True) + records.regular(RECORD_ROOT, directory=True) + destination = RECORD_ROOT / prepared.name + if destination.exists(): + if records.load_record(destination)[1] != files: + raise ValueError("A different record already exists on this branch") + else: + if clean_changes(): + raise ValueError("Use a clean submission worktree") + if git("merge-base", BASE_REF, "HEAD") != git("rev-parse", "HEAD"): + raise ValueError("The submission branch must start from the fetched upstream main") + records.publish_files(RECORD_ROOT, prepared.name, files) + git("add", "--", destination.as_posix()) + return destination + + +def push_repository(push_remote): + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", push_remote): + raise ValueError("Invalid submission remote name") + url = git("remote", "get-url", "--push", "--all", push_remote).decode().strip() + parsed = FORK_URL.fullmatch(url) + if not parsed or ".." in parsed[2]: + raise ValueError("Select a remote for InferRSI or your GitHub fork") + return f"{parsed[1]}/{parsed[2].removesuffix('.git')}" + + +def pr_text(record_id, acceptance_issue): + title = f"evidence: submit optimization run record {record_id}" + body = f"Submit a user-reviewed redacted run record at `evidence/records/{record_id}/`." + if acceptance_issue is not None: + body = f"Refs #{acceptance_issue}\n\n{body}" + return title, body + + +def _identity(raw): + parsed = GIT_IDENTITY.fullmatch(raw.decode("utf-8").rstrip("\n")) + if not parsed or any(ord(c) < 32 for c in parsed[1]): + raise SubmissionError("Git must provide a valid public name and email") + return parsed[1] + + +def _commit_preview(record_id, attribution): + author = _identity(git("var", "GIT_AUTHOR_IDENT")) + committer = _identity(git("var", "GIT_COMMITTER_IDENT")) + title = f"evidence: add optimization record {record_id}" + trailers = f"Agent-assisted-by: {attribution}\n" if attribution is not None else "" + return {"author": author, "committer": committer, + "message": f"{title}\n\n{trailers}Signed-off-by: {committer}\n"} + + +def _verify_commit(head, base, expected): + header, message = git("cat-file", "commit", head).split(b"\n\n", 1) + rows = [row.split(b" ", 1) for row in header.split(b"\n")] + if [row[0] for row in rows] != [b"tree", b"parent", b"author", b"committer"]: + raise SubmissionError("Submission commit has unexpected headers or parents") + if (rows[1][1] != base.encode() or _identity(rows[2][1]) != expected["author"] + or _identity(rows[3][1]) != expected["committer"] + or message != expected["message"].encode()): + raise SubmissionError("Commit metadata differs from the approved identities and message") + + +def _check_entries(entries, paths, *, tree): + parsed = {} + for item in entries.rstrip(b"\0").split(b"\0"): + if not item: + continue + meta, name = item.split(b"\t", 1) + fields = meta.split() + if fields[0] != b"100644" or fields[1 if tree else 2] != (b"blob" if tree else b"0"): + raise ValueError("Only ordinary non-executable record files may be published") + parsed[name.decode()] = True + if set(parsed) != set(paths): + raise ValueError("The selected record has unexpected index entries") + + +def review(record_id, attribution, push_remote="origin"): + if not re.fullmatch(records.RECORD_ID, record_id): + raise ValueError("Invalid record ID") + if attribution is not None and ( + not attribution or len(attribution) > 180 or any(ord(c) < 32 for c in attribution) + or records.sanitize_prompt(attribution) != attribution + ): + raise ValueError("Provide only public agent attribution") + require_branch(record_id) + directory = RECORD_ROOT / record_id + records.regular(RECORD_ROOT.parent, directory=True) + records.regular(RECORD_ROOT, directory=True) + manifest, files = records.load_record(directory) + head = git("rev-parse", "HEAD").decode().strip() + base = git("merge-base", BASE_REF, head).decode().strip() + count = int(git("rev-list", "--count", f"{base}..{head}")) + commit = _commit_preview(record_id, attribution) + paths = {f"{directory.as_posix()}/{path}": data for path, data in files.items()} + if count == 0: + changes = git("diff", "--cached", "--name-status", "--no-renames", "-z", base) + entries = git("ls-files", "--stage", "-z", "--", directory.as_posix()) + spec = ":" + elif count == 1 and not clean_changes(): + _verify_commit(head, base, commit) + changes = git("diff", "--name-status", "--no-renames", "-z", base, head) + entries = git("ls-tree", "-r", "-z", head, "--", directory.as_posix()) + spec = f"{head}:" + else: + raise ValueError("Submission must contain exactly one staged or committed record") + expected = b"".join(b"A\0" + path.encode() + b"\0" for path in sorted(paths)) + if changes != expected: + raise ValueError("The PR diff must add only the exact files for the selected record") + _check_entries(entries, paths, tree=count == 1) + if any(git("show", f"{spec}{path}") != content for path, content in paths.items()): + raise ValueError("Git contains different bytes from the validated record") + title, body = pr_text(record_id, manifest["acceptance_issue"]) + details = { + "repository": records.REPOSITORY, "base": "main", "base_commit": base, + "push_repository": push_repository(push_remote), "push_remote": push_remote, + "branch": branch_name(record_id), "title": title, "body": body, + "commit": commit, "files": { + path: records.sha256(content) for path, content in paths.items() + }, + "omissions": manifest["omissions"], + } + return {**details, "review_digest": records.sha256(records.json_bytes(details)), + "committed_head": head if count == 1 else None} + + +def _find_pr(fork, branch, head, title, body): + candidates = json.loads(gh( + "api", "--hostname", "github.com", "--method", "GET", + f"repos/{records.REPOSITORY}/pulls", + "-f", f"head={fork.split('/')[0]}:{branch}", "-f", "base=main", + "-f", "state=all", "-f", "per_page=100", + )) + for candidate in candidates: + if ((candidate["head"].get("repo") or {}).get("full_name", "").lower() != fork.lower() + or candidate["head"]["ref"] != branch + or candidate["base"]["repo"]["full_name"] != records.REPOSITORY): + continue + if (candidate["head"]["sha"] != head + or candidate["base"]["ref"] != "main" + or not re.fullmatch( + rf"https://github\.com/{records.REPOSITORY}/pull/[1-9][0-9]*", + candidate["html_url"], + )): + raise SubmissionError("An existing submission PR has a different head or destination") + if candidate["title"] != title or candidate["body"] != body: + raise SubmissionError("Existing submission PR does not match the approved title/body") + if candidate["state"] != "open" and not candidate["merged_at"]: + raise SubmissionError("The existing submission PR was closed without merging") + return candidate["html_url"] + return None + + +def publish(record_id, approval, attribution, push_remote="origin"): + checked = review(record_id, attribution, push_remote) + if checked["review_digest"] != approval: + raise SubmissionError("Publication requires authorization of the exact reviewed content") + fork, branch = checked["push_repository"], checked["branch"] + if fork.lower() != records.REPOSITORY.lower(): + remote = json.loads(gh( + "repo", "view", f"github.com/{fork}", "--json", "nameWithOwner,parent" + )) + if (remote["nameWithOwner"].lower() != fork.lower() + or (remote["parent"] or {}).get("nameWithOwner", "").lower() + != records.REPOSITORY.lower()): + raise ValueError("The push destination must be InferRSI or its GitHub fork") + if not checked["committed_head"]: + with TemporaryDirectory(prefix="inferrsi-record-commit-") as directory: + message = Path(directory) / "message.txt" + message.write_bytes(checked["commit"]["message"].encode()) + git("-c", "i18n.commitEncoding=UTF-8", "commit", "--no-gpg-sign", + "--cleanup=verbatim", "-s", "-F", str(message)) + committed = review(record_id, attribution, push_remote) + head = committed["committed_head"] + if not head or committed["review_digest"] != approval: + raise ValueError("Committed content differs from the approved review") + lookup = (fork, branch, head, checked["title"], checked["body"]) + if url := _find_pr(*lookup): + return url + # Push the checked object, not a moving HEAD. Never push tags or force-update a branch. + git("push", "--no-follow-tags", push_remote, f"{head}:refs/heads/{branch}") + if url := _find_pr(*lookup): + return url + with TemporaryDirectory(prefix="inferrsi-record-pr-") as directory: + body_file = Path(directory) / "body.md" + body_file.write_bytes(checked["body"].encode("utf-8")) + pr_head = branch if fork.lower() == records.REPOSITORY.lower() else ( + f"{fork.split('/')[0]}:{branch}" + ) + try: + gh("pr", "create", "--repo", records.REPOSITORY, "--base", "main", + "--head", pr_head, "--title", checked["title"], + "--body-file", str(body_file)) + except ValueError: + if url := _find_pr(*lookup): + return url + raise + if url := _find_pr(*lookup): + return url + raise SubmissionError("PR creation unconfirmed. Retry with the same record and digest") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + actions = parser.add_subparsers(dest="action", required=True) + prepare = actions.add_parser("prepare") + prepare.add_argument("delivery", type=Path) + prepare.add_argument("scratch", type=Path) + prepare.add_argument("--facts", type=Path) + prompt = prepare.add_mutually_exclusive_group() + prompt.add_argument("--prompt", type=Path) + prompt.add_argument("--withhold-prompt", action="store_true") + prepare.add_argument("--public-acceptance-issue", type=int) + prepare.add_argument("--public-archive-manifest", type=Path) + staging = actions.add_parser("stage") + staging.add_argument("prepared", type=Path) + for action in ("review", "publish"): + submit = actions.add_parser(action) + submit.add_argument("record_id") + submit.add_argument("--agent-attribution") + submit.add_argument("--push-remote", default="origin") + if action == "publish": + submit.add_argument("--approved-review", required=True) + args = parser.parse_args(argv) + try: + if args.action == "prepare": + checkout = Path(git("rev-parse", "--show-toplevel").decode().strip()).resolve() + if args.scratch.resolve().is_relative_to(checkout): + raise ValueError("Prepare records in private scratch space outside the worktree") + path = records.prepare_record( + args.delivery, args.scratch, + facts=records.read_object(args.facts) if args.facts else {}, + prompt=records.regular(args.prompt).read_text(encoding="utf-8") + if args.prompt else None, + omit_prompt=args.withhold_prompt, acceptance_issue=args.public_acceptance_issue, + archive_manifest=args.public_archive_manifest, + ) + result = {"record_id": path.name} + elif args.action == "stage": + result = {"record": stage(args.prepared).as_posix()} + elif args.action == "review": + result = review(args.record_id, args.agent_attribution, args.push_remote) + else: + result = {"record": (RECORD_ROOT / args.record_id).as_posix(), + "pr": publish(args.record_id, args.approved_review, args.agent_attribution, + args.push_remote)} + except (OSError, ValueError, KeyError, TypeError, AttributeError, IndexError) as error: + # Never echo source payloads, JSON decoder input or OS paths in a report. + detail = str(error) if isinstance(error, SubmissionError) else ( + "Check the source, record layout, and workflow prerequisites." + ) + parser.exit(2, f"Record {args.action} failed. {detail}\n") + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/validate_evidence.py b/tools/validate_evidence.py index 1271a4c2b..20ab3b259 100644 --- a/tools/validate_evidence.py +++ b/tools/validate_evidence.py @@ -7,9 +7,11 @@ from pathlib import Path if __package__: + from . import optimization_records from .evidence_archives import normalize_manifest from .evidence_archives import read_json as read_archive_json else: + import optimization_records from evidence_archives import normalize_manifest from evidence_archives import read_json as read_archive_json @@ -20,6 +22,7 @@ "import": [f"{part}/README.md" for part in SEGMENTS], "archive": ["results", "patch"], "review": ["results/summary.json"], + "optimization-records": ["README.md"], } @@ -139,6 +142,26 @@ def validate_inventory(repo, inventory=None): if kind not in REQUIRED: raise ValueError("unknown bundle kind") report["bundles"].append({"name": name, "kind": kind}) + if kind == "optimization-records": + if name != "records" or entry.get("manifests") != []: + raise ValueError("Expected a single dedicated optimization-records root") + optimization_records.regular(evidence, directory=True) + optimization_records.regular(bundle, directory=True) + optimization_records.regular(bundle / "README.md") + for record in sorted(bundle.iterdir()): + if record.name == "README.md": + continue + try: + _, files = optimization_records.load_record(record) + report["checked_hashes"] += len(files) - 1 + except (OSError, ValueError, KeyError, TypeError) as exc: + record_name = record.name if re.fullmatch( + optimization_records.RECORD_ID, record.name + ) else "" + errors.append( + f"records/{record_name}: invalid record ({type(exc).__name__})" + ) + continue for required in REQUIRED[kind]: target = safe_path(bundle, required) present = target.is_dir() if required in SEGMENTS else target.is_file()