cyc-stack 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cyc.mjs CHANGED
@@ -3,7 +3,7 @@ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { catalog, routeTask } from '../scripts/catalog.mjs';
6
- import { acceptFailure, activeRun, callerSession, inputPath, completeRun, controlRun, finishRun, nextRun, projectFile, proveRun, quickHandoff, readRun, recordHandoff, recoverRun, retryRun, reviewRun, startRun, verifyRun } from '../scripts/runtime.mjs';
6
+ import { acceptFailure, activeRun, callerSession, inputPath, completeRun, controlRun, finishRun, nextRun, projectFile, proveRun, quickHandoff, readRun, recordHandoff, recoverRun, retryRun, reviewRun, startRun, verifyRun, captureReview, recordReview } from '../scripts/runtime.mjs';
7
7
 
8
8
  const args = process.argv.slice(2);
9
9
  const positionals = [];
@@ -81,6 +81,8 @@ Execute through your existing AI host:
81
81
  cyc run status --run ID
82
82
  cyc run recover --run ID (read-only diagnosis and next action; preserves work and budgets)
83
83
  cyc run review --run ID (refresh the shared developer/PR review artifact)
84
+ cyc run review-capture --run ID --file CAPTURE.json (reviewer, optional scope)
85
+ cyc run review-record --run ID --file REVIEW.json (reviewId, evidence, identity or null, findings)
84
86
  cyc run pause|resume|stop --run ID
85
87
 
86
88
  Deliver the reply:
@@ -167,7 +169,7 @@ Hook activation/trust must be checked in your host; doctor does not certify it.`
167
169
  let input;
168
170
  if (options.file) {
169
171
  fileOnly(options, ['file', 'project', 'verbose']);
170
- input = inputObject(options.file, ['goal', 'playbook', 'criteria', 'allowedPaths', 'session', 'scout', 'plan']);
172
+ input = inputObject(options.file, ['goal', 'playbook', 'criteria', 'allowedPaths', 'session', 'scout', 'plan', 'evidenceVersion', 'requirements', 'reviewPolicy']);
171
173
  for (const key of ['goal', 'playbook', 'session', 'plan']) if (input[key] !== undefined && typeof input[key] !== 'string') throw new Error(`${key} must be a string.`);
172
174
  if (input.scout !== undefined && !object(input.scout)) throw new Error('scout must be the Scout assessment object (run start without it returns the template).');
173
175
  if (input.criteria !== undefined && (!Array.isArray(input.criteria) || !input.criteria.length || input.criteria.some(item => !object(item) || typeof item.id !== 'string' || typeof item.description !== 'string'))) throw new Error('criteria must be a nonempty array of {id, description} string records.');
@@ -221,6 +223,12 @@ Hook activation/trust must be checked in your host; doctor does not certify it.`
221
223
  case 'accept-failure': result = acceptFailure(root, options.run, { check: options.check, reason: options.reason }); break;
222
224
  case 'complete': result = completeRun(root, options.run); break;
223
225
  case 'review': result = reviewRun(root, options.run); break;
226
+ case 'review-capture':
227
+ if (!options.file) throw new Error('review-capture needs --file JSON with reviewer and optional scope.');
228
+ result = captureReview(root, options.run, inputObject(options.file, ['reviewer', 'scope'])); break;
229
+ case 'review-record':
230
+ if (!options.file) throw new Error('review-record needs --file JSON with reviewId, evidence, identity and findings.');
231
+ result = recordReview(root, options.run, inputObject(options.file, ['reviewId', 'evidence', 'identity', 'findings'])); break;
224
232
  case 'pause': case 'resume': case 'stop': result = controlRun(root, options.run, action); break;
225
233
  default: throw new Error('Unknown run action. Use cyc help.');
226
234
  }
@@ -264,6 +272,7 @@ function preexistingHint(ids) {
264
272
  function compact(action, result, root, options) {
265
273
  if (!result || typeof result !== 'object' || ['status', 'recover'].includes(action)) return result;
266
274
  const id = result.runId ?? result.id ?? options.run;
275
+ if (['review-capture', 'review-record'].includes(action)) { const { files, ...receipt } = result; return receipt; }
267
276
  if (action === 'prove-red') return result;
268
277
  if (action === 'finish') return result.failedAt === 'verify' && 'verificationStatus' in result ? { ...compact('verify', result, root, options), finished: false, failedAt: 'verify' } : result;
269
278
  if (action === 'verify') {
@@ -2,6 +2,12 @@
2
2
 
3
3
  Read this when an operation can reject input, fail during I/O, partially complete, or be retried. First inspect how callers already distinguish failures. Keep the project's existing result types, exception classes, and logging conventions; introduce a new taxonomy only when callers need a distinction they cannot currently express.
4
4
 
5
+ ## Preserve records when an operation recreates them
6
+
7
+ For delete, replace, undo or compensation that recreates stored records, define what must survive before choosing the payload: identity, business fields, references and relevant access metadata. Inspect the existing schema and affected writers/importers; a UI projection may omit valid stored data. Keep the allowlist for new client edits separate from trusted restoration data. Use a server-owned checkpoint, authenticated snapshot or another approach that preserves the contract without accepting client-forged ownership or permissions.
8
+
9
+ Check the semantic stored record after successful restore and after injected failure/retry, allowing only declared service-managed changes or intentional migrations. Include a valid field not rendered by the UI and nondefault permissions when they are part of the contract. The fixture must capture those fields and adapter arguments. Comparing two identically lossy projections or only an ID cannot establish complete restoration. Narrow tasks that do not recreate records need none of this extra procedure.
10
+
5
11
  ## Decide what a failure means
6
12
 
7
13
  | Trigger | Decision while building | Question during review |
@@ -2,11 +2,11 @@
2
2
 
3
3
  CYC's project installer adds skill copies and response-hook configuration to an existing project. It does not change global settings, install a marketplace, rewrite project instructions, edit the application's package.json, or execute the application's scripts. Node.js 20 or later is required on the machine running the AI tool; the target project can use any language.
4
4
 
5
- CYC offers npm, agent-guided and native plugin routes. The source checkout and npm archive also carry a top-level INSTALL.md entry guide. Registry commands require a published version on the selected channel; a reviewed checkout or archive also works. Downloading the npm package does not activate a project: `init` performs that explicit step, while a complete native plugin uses project activation through its Setup method.
5
+ CYC is [published on npm](https://www.npmjs.com/package/cyc-stack). The package and source checkout carry a top-level [INSTALL.md](../INSTALL.md) guide covering installation, AI-chat setup and a first task. A reviewed checkout or archive also works. Downloading the npm package does not activate a project: `init` performs that explicit step, while a complete native plugin uses project activation through its Setup method.
6
6
 
7
- After pilot publication, run `npx cyc-stack@next init` from the target project root. No flags are required. npm may ask before downloading the package. To save a development dependency in `package.json`, run `npm install --save-dev cyc-stack@next`, then `npx cyc-stack init`. Use unversioned registry installation after a release is promoted to `latest`. Downloading the package alone does not set up project integration.
7
+ Run `npx cyc-stack@latest init` from the target project root to install the latest published release. No flags are required. npm may ask before downloading the package. To save a development dependency in `package.json`, run `npm install --save-dev cyc-stack`, then `npx cyc-stack init`. Downloading the package alone does not set up project integration. After installation, reload your AI host and ask `/cyc` to set up the project's checks.
8
8
 
9
- While publication is pending, use `node bin/cyc.mjs init --project PATH` from a reviewed CYC checkout. Hosts are auto-detected from `CLAUDE.md`/`.claude/`, `AGENTS.md`/`.agents/`/`.codex/`, and `.cursor/`/`.cursorrules`; with no signal, all three are set up. Use `--hosts` to choose explicitly and `--dry-run` to inspect the plan:
9
+ For a source checkout, use `node bin/cyc.mjs init --project PATH` from the reviewed CYC checkout. Hosts are auto-detected from `CLAUDE.md`/`.claude/`, `AGENTS.md`/`.agents/`/`.codex/`, and `.cursor/`/`.cursorrules`; with no signal, all three are set up. Use `--hosts` to choose explicitly and `--dry-run` to inspect the plan:
10
10
 
11
11
  ```text
12
12
  node bin/cyc.mjs init --project "/absolute/path/to/project" --hosts claude,codex,cursor --dry-run
@@ -37,14 +37,14 @@ These options are for specific needs; the normal install requires none of them.
37
37
 
38
38
  | Need | Command |
39
39
  | --- | --- |
40
- | Preview local file changes | `npx cyc-stack@next init --dry-run` |
41
- | Install only one host | `npx cyc-stack@next init --hosts codex` |
42
- | Select a nested project instead of its CYC-enabled parent | `npx cyc-stack@next init --project .` |
40
+ | Preview local file changes | `npx cyc-stack@latest init --dry-run` |
41
+ | Install only one host | `npx cyc-stack@latest init --hosts codex` |
42
+ | Select a nested project instead of its CYC-enabled parent | `npx cyc-stack@latest init --project .` |
43
43
  | Select an approved published version | `npx cyc-stack@0.6.0 init` |
44
- | Use a published pilot channel | `npx cyc-stack@next init` |
45
- | Save as a development dependency | `npm install --save-dev cyc-stack@next`, then `npx cyc-stack init` |
44
+ | Follow the optional `next` channel | `npx cyc-stack@next init` |
45
+ | Save as a development dependency | `npm install --save-dev cyc-stack`, then `npx cyc-stack init` |
46
46
 
47
- `@latest` explicitly selects the current stable channel; an unversioned command can use a package already installed in the project. For exact dependency pinning, add `--save-exact` to `npm install`. In automation, npm's `--yes` option goes before the package name to suppress its download prompt. These controls do not replace host reload, trust or project check configuration.
47
+ `@latest` explicitly selects npm's `latest` tag; it is not a guarantee of production qualification. An unversioned command can use a package already installed in the project. For exact dependency pinning, add `--save-exact` to `npm install`. In automation, npm's `--yes` option goes before the package name to suppress its download prompt. These controls do not replace host reload, trust or project check configuration.
48
48
 
49
49
  ## Agent-guided installation
50
50
 
@@ -52,7 +52,7 @@ Ask your agent to install CYC in the target project from a reviewed checkout, ar
52
52
 
53
53
  For an agent performing this request:
54
54
 
55
- 1. Read the target project's instructions. Use the requested project and release; prefer a supplied reviewed checkout or archive while registry publication is pending. Do not treat a registry error as permission to alter credentials, visibility or global settings.
55
+ 1. Read the target project's instructions. Use the requested project and release, whether a published npm version or a supplied reviewed checkout/archive. Do not treat a registry error as permission to alter credentials, visibility or global settings.
56
56
  2. Preview with the selected CLI's `init --dry-run`, using `--project` for a different existing target directory. Explain the proposed changes and continue within the user's installation authorization. Resolve reported conflicts without deleting or taking ownership of existing files.
57
57
  3. Complete `init`, then follow [project setup](../methods/cyc-setup/SKILL.md). Find checks in the project's CI and configuration, explain which behavior they exercise, and use the project's authorization rules before running them. Do not invent always-passing checks.
58
58
  4. Keep installed files, configured checks, executed checks and real host activation distinct. Missing trust or prompt/Stop observations remain unverified. Use supported host controls; never simulate callbacks or edit trust/state to claim activation.
@@ -180,9 +180,11 @@ Use `/cyc` with an ordinary task, including setup. Plugin hosts may namespace it
180
180
  An update removes unchanged CYC-owned legacy supporting entries from `.claude/skills` and `.agents/skills`. Customized legacy entries cause an atomic conflict so their changes can be preserved and deliberately migrated; unrelated user skills are untouched. Reload the host after updating to remove previously loaded menu entries. Live menu rendering still requires host verification.
181
181
 
182
182
 
183
- ## npm publication preparation
183
+ <a id="npm-publication-preparation"></a>
184
184
 
185
- The source candidate includes public package metadata, an INSTALL.md entry guide, and an offline release preflight. In the CYC source checkout, run `npm run check:distribution`; add the desired tag to `node scripts/check-distribution.mjs` to check version agreement. This tooling is development-only and does not ship inside the local engine.
185
+ ## npm publication maintenance
186
+
187
+ CYC is published on npm. For future releases, the source includes public package metadata, an INSTALL.md entry guide, and an offline release preflight. In the CYC source checkout, run `npm run check:distribution`; add the desired tag to `node scripts/check-distribution.mjs` to check version agreement. This tooling is development-only and does not ship inside the local engine.
186
188
 
187
189
  The source workflow `.github/workflows/publish-npm.yml` is manually invoked for an existing release tag and defaults to the `next` channel. It uses Node 24, validates publishing-tool versions, runs tests, packs the candidate and uses npm OIDC. Package ownership, the exact npm trusted-publisher repository/workflow/environment binding and any required `npm-publish` environment reviewers must be configured by the maintainer. The repository is public; registry publication still requires an authorized npm account. This preparation does not publish anything. Registry install examples require an actual published release.
188
190
 
@@ -82,7 +82,7 @@ Standalone "Turn off the thousand character limit" and "Turn on the 1,000-charac
82
82
 
83
83
  The assistant confirms the setting after a toggle. Turning the limit OFF only lifts the length cap: visuals, acceptance checks, evidence, and honest limitations remain required. OFF permits useful depth without requiring verbosity. Expansion never silently turns an OFF setting back ON. Hook-generated repair continuations retain both the setting and retry budget.
84
84
 
85
- The standalone `check-response` utility is a stateless diagnostic: its default remains capped, and `--expanded` explicitly checks without the cap. The hook reads the conversation setting automatically.
85
+ `cyc check-reply` without `--session` is a stateless diagnostic: its default remains capped, and `--expanded` explicitly checks without the cap. With `--session`, and in the hook, the conversation setting applies automatically.
86
86
 
87
87
  ## Levels of done
88
88
 
package/docs/runtime.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # CYC execution controller
2
2
 
3
+ The updated workflow selects `evidenceVersion: 1` in structured start input, retaining original `requirements`, criteria and optional clauses. `reviewPolicy` selects `self-allowed` or `fresh-required`. Review capture/record commands bind an agent-reported review to the actual candidate before dispatch; versioned Verify retains scenario-to-command references and a reason review for decisive red-proof failures. See [versioned evidence examples](work-assessments.md#versioned-evidence-records) for the complete input shapes, conservative whole-source freshness and legacy limits. Unversioned callers remain compatible; a historical fresh-context string is labeled unlinked, never upgraded into a source-linked receipt.
4
+
3
5
  The controller tracks a task through the catalog's skill stages, validates recorded handoffs, runs configured project checks, and refuses unsupported completion. The existing AI host reads and performs the skills. CYC does not launch model calls, create paid agent fleets, or infer authorization to publish work.
4
6
 
5
7
  New implementation runs (routes containing Build) record work assessment contract v1. Scout must account for context freshness, existing functionality, alignment, and affected consumers. Verify must record semantic review and consumer checks. Deliver must account for retained learning and the selected error ledger. These are fields in existing handoffs, not new stages. See [assessment examples and the knowledge lifecycle](work-assessments.md). Advisory routes and legacy runs retain their prior handoffs and are explicitly labeled.
@@ -65,6 +65,84 @@ Run the applicable real journey/recipe checks, map acceptance criteria and affec
65
65
 
66
66
  Every Scout consumer must appear once; add newly discovered consumers with their own evidence. All listed checks must pass. Findings may be `resolved` or `dismissed` with evidence; an `open` finding prevents a passing Verify handoff. An empty findings array means the reviewer found no issues, not that review was skipped. Passing configured commands never substitutes for this assessment, and the controller cannot determine whether an agent's stated observations are true. Changes after the Verify handoff require returning to Verify, rerunning checks, and reviewing the current files before delivery.
67
67
 
68
+ ## Versioned evidence records
69
+
70
+ The updated implementation workflow starts with `evidenceVersion: 1`, `requirements` containing the original authorized outcomes, and explicit `criteria`. The existing implementation assessment contract remains v1; evidence version 1 adds structured provenance. Unversioned clients and saved runs remain supported with their original evidence limits. A bare fresh-context/peer label now renders **unlinked**, including on historical records. No review identity or missing evidence is invented during migration.
71
+
72
+ Keep original outcome IDs in `criteria`. Optional `clauses: [{"id":"permissions","description":"Original permissions survive restoration."}]` retain material obligations within an outcome. The controller stores the original requirements text and its SHA-256, and the criteria fingerprint. It can check missing IDs and links, but cannot decide that an agent captured every meaning of the user's request. Group headings belong in the short plan, not in a reduced acceptance list.
73
+
74
+ Set `reviewPolicy: "self-allowed"` (the default) or `"fresh-required"`. The latter requires current source-linked, agent-reported fresh-context coverage of every changed source path. Select it for the workflow's high-risk fresh-review route. If the host cannot provide a fresh reviewer, use the stated self-review fallback at start and disclose that limit; never invent a reviewer identity. No product approval step is added.
75
+
76
+ ### Capture the candidate before review
77
+
78
+ Run `cyc run review-capture --run ID --file CAPTURE.json` with `{"reviewer":"fresh-context","scope":["src/persistence"]}`. Reviewer is `self`, `fresh-context` or `peer`; omitted/empty scope means the whole covered source. Include affected contracts and producers in the review inputs. The controller stores canonical scope, the entire selected-source file manifest/fingerprint (including the implications of additions and deletions), criteria fingerprint and capture time in this run's receipt. This initial implementation uses conservative whole-source freshness, even for a scoped review: an unrelated selected-source change also stales it. It does not infer dependency coverage or combine old/new manifests as a current delta review.
79
+
80
+ After the actual review, run `cyc run review-record --run ID --file REVIEW.json`:
81
+
82
+ ```json
83
+ {
84
+ "reviewId": "ID_RETURNED_BY_CAPTURE",
85
+ "identity": null,
86
+ "evidence": "Actual review observations or reviewer output, with precise locations.",
87
+ "findings": []
88
+ }
89
+ ```
90
+
91
+ Findings use the existing unique `id`, `status` and `evidence` shape. Capture before dispatch; attaching today's source fingerprint to an earlier review is invalid. Recording refuses changed source/criteria, altered receipt bytes, foreign IDs and duplicate recording. `identity` is nullable and, when supplied, agent-reported. The record is inspectable provenance, not attestation of independence or correctness.
92
+
93
+ Put recorded IDs in `semanticReview.receipts`. A linked non-self reviewer label must match a receipt of that type. Referenced scopes must cover the changed files; full-source receipts satisfy this without manually listing them. Fresh and self receipts on the current candidate render **mixed**. Every receipt remains visible by type and scope. Final dispositions for receipt findings include `reviewId` alongside the original finding `id`, `status` and `evidence`. IDs are unique within each review: two reviewers may both use `f1`, but each needs its own `{reviewId, id}` disposition. A bare shared ID cannot resolve both findings. Later edits stale the capture, requiring a new review; this conservative first version does not support carrying fresh coverage forward across an edited candidate through a delta-only review. Missing or altered evidence renders unverified. Receipt hashes follow Verify into Deliver so later tampering cannot disappear from completion checks.
94
+
95
+ ### Record a scenario for every outcome and clause
96
+
97
+ Versioned Verify assessments also contain `criterionChecks`, generated by the template:
98
+
99
+ ```json
100
+ {
101
+ "criterionChecks": [
102
+ {
103
+ "id": "restore",
104
+ "clause": "permissions",
105
+ "scenario": "Delete then undo a record with nondefault permissions",
106
+ "check": "unit",
107
+ "receipt": "current-verification",
108
+ "result": "passed",
109
+ "origin": "agent-reported",
110
+ "evidence": "The actual recreation adapter receives the original permission arguments."
111
+ }
112
+ ]
113
+ }
114
+ ```
115
+
116
+ Omit `clause` for criteria without clauses. There must be exactly one entry for every criterion/clause pair, with a configured command ID and a meaningful scenario/observation. This is a coverage summary; one entry can cite several decisive cases. Entries may share a suite. `current-verification` is a controller-resolved reference to the current passing command receipt, not permission to fabricate a named passing runner result. For accepted pre-existing suite failures the scenario observation remains agent-reported and must identify its own actual result; the controller does not infer it from aggregate counts. A missing required result or an unavailable external check remains unverified; record a blocked handoff with the limitation rather than claim completion. The current parser retains failing case identities and aggregate passing counts, so named passing observations are deliberately not labeled machine-verified.
117
+
118
+ The controller binds and fingerprints the registered command receipt after checks run. Foreign, stale or altered receipts cannot satisfy a passing Verify. Both step-by-step recording and `run finish` retain the mappings, and Deliver/complete continue checking the evidence bytes.
119
+
120
+ ### Review the meaning of baseline failures
121
+
122
+ `prove-red` now retains each decisive diagnostic's ID, check, test name/file, error/details and a nonauthoritative hint. A module-load hint is not automatically an absent-new-interface defect, and a TypeError may be the original bug. In versioned runs the initial `proofClaim` explicitly states diagnostic red, with semantic interpretation unreviewed.
123
+
124
+ For non-exempt red proof, run `prove-red` before finalizing FINISH.json, then add:
125
+
126
+ ```json
127
+ {
128
+ "proofReview": {
129
+ "receipt": "current-proof",
130
+ "cases": [
131
+ {
132
+ "id": "FAILURE_ID_RETURNED_BY_PROVE_RED",
133
+ "category": "behavioral",
134
+ "reason": "Original duration is 90, while the existing public boundary must return 60.",
135
+ "boundary": "Existing duration() call exercised by the regression"
136
+ }
137
+ ]
138
+ }
139
+ }
140
+ ```
141
+
142
+ Categories are `behavioral`, `new-interface`, `setup`, and `unclassified`. Every selected case must match the current proof receipt and include a reason; behavioral cases also name the existing observable boundary. A bug fix needs a decisive behavioral case. A feature may establish an absent new interface, while final behavior still needs passing verification. Setup/unclassified cases alone cannot pass this reason review. Unselected diagnostics remain unclassified and visible. Refactors retain green-on-original proof without manufactured red. Truthful exemptions remain supported and never become demonstrated behavioral proof.
143
+
144
+ The controller links the reason review to the proof receipt and tests' existing freshness checks. Its generated claim separates behavioral and new-interface cases and identifies interpretation as agent-reported. It does not equate failing-test count with repaired-defect count. The normal fast route remains `prove-red` to obtain case IDs, then one `finish` to verify and deliver; unchanged proof is reused. If finish generated proof automatically, read its failures and supply the reason review before completion rather than relabeling diagnostics as behavior.
145
+
68
146
  ## Learning lifecycle and final file order
69
147
 
70
148
  1. Keep consequential decisions and provisional findings in run-local notes during work. Append failures to `run next`'s selected `ledgerPath` immediately, even for abandoned tasks. Preserve existing ledger formats. New runs use run-local history when shared documentation is outside permitted writes; retain shared-history lookup through `projectLedgerPath` and disclose pending promotion in `errorHistory.reason`. This does not waive explicit project policy or authorize more scope.
@@ -28,7 +28,7 @@ When the change introduces or reshapes state, ownership, or an interface, use th
28
28
  3. **Write the plan in about ten lines:**
29
29
 
30
30
  ```text
31
- Goal: one sentence. Done when: 2-4 checks.
31
+ Goal: one sentence. Done when: original user criteria, grouped for the short plan with a retained criterion-to-check mapping.
32
32
  Approach: reuse/extend/repair/create → existing capability and reason.
33
33
  Context: relevant history, freshness, known failed approaches (or no match).
34
34
  Change: file → what changes (one line each)
@@ -27,8 +27,11 @@ Apply the project's applicable `code-standards.md` and the relevant [code standa
27
27
  4. an HTTP request (`curl`) against the running app
28
28
  5. a headless browser such as Playwright for UI journeys (click, reload, check again)
29
29
  6. a human-in-the-loop step, as a last resort, with exact instructions and the expected observation
30
- 4. **Hit the edges the change created.** Old saved data, repeat actions (clicking twice), unknown IDs, empty state, and the error path. For a guard, show a rejected case, not only an allowed one.
30
+ 4. **Hit the edges the change created.** Old saved data, repeat actions (clicking twice), unknown IDs, empty state, and the error path. For a guard, show a rejected case, not only an allowed one. For operations that recreate records, apply the [preservation contract](../../docs/engineering/failure-handling.md#preserve-records-when-an-operation-recreates-them): inspect stored fields and relevant access metadata beyond the UI projection, through success and failure recovery. Check that the fixture would detect losing them.
31
+
32
+ Tie each original user criterion to a decisive check/scenario and the observed result, even when several share a suite command. In red proof, distinguish an assertion of the original defect from a missing newly introduced API or module-load failure. The latter may show a new dependency is absent; it does not establish the intended old-behavior failure. Keep useful genuine red assertions and state their limits.
31
33
  5. **Run configured checks on the final candidate.** For step-by-step execution use `run verify --run <ID>`; the fast implementation route's `run finish` executes these checks itself. Do not run both on an unchanged candidate merely to duplicate a receipt. Advisory routes without configured checks use clearly labeled inspected evidence. Focused checks give fast feedback; final checks cover the affected behavior.
34
+ With `evidenceVersion: 1`, fill `criterionChecks` for every original criterion/clause. Use a named scenario and actual observation, configured command ID, `receipt: "current-verification"`, `result: "passed"`, and `origin: "agent-reported"`. Missing or unavailable required checks stay unverified and cannot pass. For non-exempt red proof, run `prove-red` and fill `proofReview` against its failure IDs: `behavioral`, `new-interface`, `setup`, or `unclassified`, with a reason and an existing observable boundary for behavioral cases. A bug-fix proof needs a decisive behavioral case; a feature may demonstrate an absent new interface. Error type alone cannot decide the category. Review receipts must come from capture before the review and record afterward; later edits stale the whole-source capture. See the [evidence record examples](../../docs/work-assessments.md#versioned-evidence-records).
32
35
  6. **Fill the matrix with results.** Each row: passed (with the command and what you saw), failed (with output), or unverified (with why, such as no browser access). Model review of code goes in its own labeled row and never turns a row green.
33
36
  7. **Record semantic review separately.** Trace the important state, shared invariant, consumers and relevant failure paths in the actual diff; identify where a likely next change belongs. Review intent, conventions and the [engineering principles](../../docs/principles.md), using the [finding adjudication guidance](../../docs/code-quality.md#review-findings-before-turning-them-into-edits) for consequential diffs. For changed business rules/transitions, inspect the owner and callers using the [domain examples](../../docs/engineering/domain-design.md); for rejection, I/O or partial effects, inspect failure identity, committed/unknown state and retry safety using the [failure examples](../../docs/engineering/failure-handling.md). Apply their stated contracts and exceptions rather than requiring their exact code shape. Show the legitimate trigger or concrete maintenance consequence before requiring a repair; check whether a proposed simplification removes policy duplication or merely moves it. Resolve or dismiss findings with evidence, and keep unresolved required findings open and blocking. New implementation runs require the [Verify assessment](../../docs/work-assessments.md#verify-executable-evidence-plus-semantic-judgment), with a passing check for every Scout consumer and newly discovered consumer. Label self-review; extra reviewers depend on risk. If final context/ledger edits change source, rerun checks before recording the assessment.
34
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cyc-stack",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "type": "module",
@@ -25,7 +25,6 @@
25
25
  "bin",
26
26
  "scripts/baseline-worker.mjs",
27
27
  "scripts/catalog.mjs",
28
- "scripts/check-response.mjs",
29
28
  "scripts/claude-project-hook.mjs",
30
29
  "scripts/context-review.mjs",
31
30
  "scripts/host-activation.mjs",
@@ -83,8 +82,7 @@
83
82
  "pack:release": "node scripts/pack-release.mjs",
84
83
  "build:workflow": "node docs/assets/build-workflow-diagram.mjs",
85
84
  "test": "node --test",
86
- "cyc": "node bin/cyc.mjs",
87
- "check-response": "node scripts/check-response.mjs"
85
+ "cyc": "node bin/cyc.mjs"
88
86
  },
89
87
  "engines": {
90
88
  "node": ">=20"
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "cycstack",
4
- "version": "0.6.0",
4
+ "version": "0.7.0",
5
5
  "description": "Portable AI engineering workflows with shared project context and verifiable changes.",
6
6
  "author": {
7
7
  "name": "CYC Stack contributors"
@@ -7,9 +7,9 @@ import { hostname, tmpdir } from 'node:os';
7
7
  import { digest } from './response-gate.mjs';
8
8
  import { getPlaybook, routeTask } from './catalog.mjs';
9
9
  import { forgetDisproved, inspectSource as inspectSourceFiles, saveCache, sourcePolicy } from './source-snapshot.mjs';
10
- import { assessmentRequirements, assessmentTemplate, derivedAssessment, renderReview, reviewPath, validateAssessment } from './work-review.mjs';
10
+ import { assessmentRequirements, assessmentTemplate, derivedAssessment, renderReview, reviewPath, validateAssessment, reviewCoverage, validateProofReview } from './work-review.mjs';
11
11
  import { recoveryGuidance } from './recovery.mjs';
12
- import { cutOff, outputLimit, stable, summarizeTests, testsOf } from './test-output.mjs';
12
+ import { cutOff, outputLimit, stable, summarizeTests, testsOf, failureHint } from './test-output.mjs';
13
13
  import { runPacketDigest, writeRunPacket } from './packet.mjs';
14
14
  export { sourceSnapshot } from './source-snapshot.mjs';
15
15
 
@@ -947,13 +947,21 @@ export function proveRun(root, id, { tests } = {}) {
947
947
  : 'The tests fail on the run-start code, so they assert new behavior. A refactor must preserve behavior; fix the tests or reclassify the work.');
948
948
  // The sentence a reply may quote: what this check-level proof shows, and what it does not.
949
949
  const claim = !passed ? null : mode !== 'red' ? 'The new tests pass on the original code, so they pin its behavior.'
950
+ : state.evidenceVersion === 1 ? `Diagnostic red on original code (${caught.join(', ')}); behavioral meaning requires the case-specific proofReview. Failing test counts are not repaired-defect counts.`
950
951
  : listed ? `These new tests fail on the original code: ${listed} (check ${caught.join(', ')}).`
951
952
  : `At least one new test fails on the original code (check ${caught.join(', ')}); the cases were not run one by one.`;
952
953
  const receiptPath = `.cyc/runs/${id}/checks/proof-${randomUUID()}.json`;
953
- atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), checkedAt: new Date().toISOString() });
954
- state.testProof = { mode, passed, verdict, claim, testFiles: Object.fromEntries(testFiles.map(path => [path, before.files[path]])), sourceFiles, receiptPath, checkedAt: new Date().toISOString() };
954
+ const failures = treatment.flatMap(result => {
955
+ if (!caught.includes(result.id)) return [];
956
+ const parsed = testsOf(result);
957
+ const selected = [...(parsed?.failing.values() ?? [])].filter(entry => !named[result.id]?.length || named[result.id].includes(entry.path.join(' > ')));
958
+ if (!selected.length) return [{ id: digest(`${result.id}:check`).slice(0, 24), check: result.id, name: result.id, file: null, error: result.error ?? '', hint: 'unclassified' }];
959
+ return selected.map(entry => ({ id: digest(`${result.id}:${entry.file}:${entry.path.join(' > ')}`).slice(0, 24), check: result.id, name: entry.path.join(' > '), file: entry.file ?? null, error: entry.error ?? '', details: entry.details, hint: failureHint(entry) }));
960
+ });
961
+ atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, failures, base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), checkedAt: new Date().toISOString() });
962
+ state.testProof = { mode, passed, verdict, claim, failures, testFiles: Object.fromEntries(testFiles.map(path => [path, before.files[path]])), sourceFiles, receiptPath, receiptHash: digest(readFileSync(projectFile(root, receiptPath))), checkedAt: new Date().toISOString() };
955
963
  log(state, 'test-proof', { mode, passed, receipt: receiptPath });
956
- return { runId: id, mode, passed, verdict, ...(claim ? { proofClaim: claim } : {}), testFiles, sourceFiles, treatment: summary(treatment), control: summary(control), receiptPath };
964
+ return { runId: id, mode, passed, verdict, failures, ...(state.evidenceVersion === 1 && passed && mode === 'red' ? { proofReviewTemplate: { receipt: 'current-proof', cases: failures.map(f => ({ id: f.id, category: 'behavioral | new-interface | setup | unclassified', reason: '<why this failure establishes the selected category>', boundary: '' })) } } : {}), ...(claim ? { proofClaim: claim } : {}), testFiles, sourceFiles, treatment: summary(treatment), control: summary(control), receiptPath };
957
965
  });
958
966
  }
959
967
 
@@ -1026,7 +1034,7 @@ function declaredChecks(root) {
1026
1034
  return { source: commands.length > 1 ? `${found[0].source}, run as ${commands.map(command => command.id).join(', ')}` : found[0].source, commands };
1027
1035
  }
1028
1036
 
1029
- export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background' }) {
1037
+ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy }) {
1030
1038
  root = realpathSync(root);
1031
1039
  if (!text(goal)) throw new Error('A nonempty goal is required.');
1032
1040
  const selected = getPlaybook(playbook ?? routeTask(goal).playbook);
@@ -1039,6 +1047,10 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1039
1047
  const inferredCriteria = criteria === undefined;
1040
1048
  criteria ??= [{ id: 'goal', description: goal }];
1041
1049
  if (!Array.isArray(criteria) || !criteria.length || criteria.some(item => !item || !/^[a-zA-Z0-9_-]+$/.test(item.id ?? '') || !text(item.description)) || new Set(criteria.map(item => item.id)).size !== criteria.length) throw new Error('Criteria must be a nonempty array of unique {id, description} records.');
1050
+ if (evidenceVersion !== undefined && evidenceVersion !== 1) throw new Error('Unsupported evidenceVersion; use 1 or omit for legacy clients.');
1051
+ if (evidenceVersion === 1 && (!text(requirements) || inferredCriteria || !selected.stages.includes('build'))) throw new Error('evidenceVersion 1 needs original requirements text, explicit criteria and an implementation playbook.');
1052
+ if (reviewPolicy !== undefined && (evidenceVersion !== 1 || !['self-allowed', 'fresh-required'].includes(reviewPolicy))) throw new Error('reviewPolicy needs evidenceVersion 1 and self-allowed or fresh-required.');
1053
+ for (const c of criteria) if (c.clauses !== undefined && (!Array.isArray(c.clauses) || !c.clauses.length || new Set(c.clauses.map(x => x?.id)).size !== c.clauses.length || c.clauses.some(x => !/^[a-zA-Z0-9_-]+$/.test(x?.id ?? '') || !text(x.description)))) throw new Error(`Criterion ${c.id} clauses need unique {id, description} records.`);
1042
1054
  if (session !== undefined && !/^[A-Za-z0-9_-]{4,80}$/.test(session)) throw new Error('--session must be 4-80 letters, digits, dashes, or underscores.');
1043
1055
  session = gateSession(root, session);
1044
1056
  const id = randomUUID();
@@ -1072,7 +1084,7 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1072
1084
  : { status: 'pending', cacheKey, sourceHash: initialSource.hash, requestedAt: new Date().toISOString() };
1073
1085
  const state = {
1074
1086
  schemaVersion: 1, engineVersion, id, goal, playbook: selected.id, stages: selected.stages, requiresChecks: selected.requiresChecks,
1075
- workContractVersion, ...ledger,
1087
+ workContractVersion, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1076
1088
  criteria, inferredCriteria, session: session ?? null, status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1077
1089
  startedAt: new Date().toISOString(), limits: config.limits, commands, ...(declared ? { verificationSource: `declared by ${declared.source}` } : {}),
1078
1090
  protectedPaths: config.protectedPaths, protectedFiles: protectedSnapshot(root, config.protectedPaths), allowedPaths,
@@ -1172,6 +1184,7 @@ export function nextRun(root, id) {
1172
1184
  runId: state.id, engineVersion: state.engineVersion ?? 'unknown (legacy run)', status: state.status, goal: state.goal, playbook: state.playbook,
1173
1185
  stage: current(state), attempt: state.attempt, criteria: state.criteria,
1174
1186
  workContractVersion: state.workContractVersion ?? null, assessmentRequired: Object.keys(stageTemplate(root, state) ?? {}),
1187
+ ...(state.evidenceVersion === 1 ? { evidenceVersion: 1, reviewPolicy: state.reviewPolicy, requirements: state.requirements } : {}),
1175
1188
  assessmentTemplate: stageTemplate(root, state),
1176
1189
  ...(finishTemplate ? { finishTemplate, finishWith: `Copy ${finishTemplate} to FINISH.json, replace every <...> with what you found, list under acceptFailures only a check that already failed before this run and is unrelated, then: run finish --file FINISH.json` } : {}),
1177
1190
  ...(finishing(state) && !finishTemplate ? { finishWith: `run finish --run ${state.id} --summary "<result and limits>" --assessment <file with the template filled in> --criterion-evidence '${JSON.stringify(Object.fromEntries(state.criteria.map(item => [item.id, '<evidence>'])))}' (records Build if needed, proves new tests, verifies, and lists changed files itself)` } : {}),
@@ -1314,9 +1327,14 @@ export function recordHandoff(root, packet) {
1314
1327
  validatePacket(root, state, packet);
1315
1328
  if (packet.status === 'passed' && ['verify', 'deliver'].includes(current(state))) requireVerification(root, state);
1316
1329
  if (packet.status === 'passed' && current(state) === 'verify' && provable(state)) requireTestProof(root, state, packet.assessment?.testProof);
1330
+ bindEvidence(root, state, packet);
1317
1331
  if (packet.status === 'passed' && current(state) === 'deliver' && state.workContractVersion === 1) {
1318
1332
  const reviewed = state.handoffs.findLast(item => item.stage === 'verify' && item.status === 'passed');
1319
1333
  if (!reviewed?.assessment || reviewed.sourceHash !== cachedSnapshot(root).hash) throw new Error('Semantic review is missing or stale. Retry verify and review the current files before delivery.');
1334
+ if (state.evidenceVersion === 1) {
1335
+ assertArtifacts(root, reviewed.artifacts);
1336
+ for (const artifact of reviewed.artifacts) if (!packet.artifacts.some(a => a.path === artifact.path)) packet.artifacts.push(artifact);
1337
+ }
1320
1338
  }
1321
1339
  const entry = { ...packet, recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1322
1340
  state.handoffs.push(entry);
@@ -1408,6 +1426,8 @@ export function verifyRun(root, id) {
1408
1426
  state.verification = { ...receipt, results: results.map(({ tests, ...result }) => result) };
1409
1427
  const receiptPath = `.cyc/runs/${id}/checks/${randomUUID()}.json`;
1410
1428
  atomicJSON(projectFile(root, receiptPath), receipt);
1429
+ state.verification.receiptPath = receiptPath;
1430
+ state.verification.receiptHash = digest(readFileSync(projectFile(root, receiptPath)));
1411
1431
  log(state, 'verification', { passed, receipt: receiptPath, sourceHash: after.hash });
1412
1432
  if (!guard(root, state, after) || !budget(state)) return state;
1413
1433
  if (!passed) {
@@ -1591,7 +1611,7 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1591
1611
  fillDerived(root, state, 'deliver', assessment);
1592
1612
  const part = name => {
1593
1613
  const keys = assessmentRequirements(state, name);
1594
- const extra = name === 'verify' && 'testProof' in assessment ? ['testProof'] : [];
1614
+ const extra = name === 'verify' ? ['testProof', 'proofReview'].filter(key => key in assessment) : [];
1595
1615
  return keys.length ? Object.fromEntries([...keys, ...extra].filter(key => key in assessment).map(key => [key, assessment[key]])) : undefined;
1596
1616
  };
1597
1617
  assessmentPaths(root, assessment);
@@ -1713,6 +1733,12 @@ function writeReview(root, state) {
1713
1733
  try { assertArtifacts(root, [artifact]); }
1714
1734
  catch (error) { artifactIssues.push(`${artifact.path}: ${error.message}`); }
1715
1735
  }
1736
+ const assessment = state.handoffs.findLast(h => h.stage === 'verify' && h.status === 'passed')?.assessment;
1737
+ for (const id of assessment?.semanticReview?.receipts ?? []) {
1738
+ const receipt = state.reviewReceipts?.find(r => r.id === id);
1739
+ try { if (!receipt) throw new Error('Missing registered review receipt.'); assertArtifacts(root, [{ path: receipt.path, sha256: receipt.sha256 }]); }
1740
+ catch (error) { artifactIssues.push(`Review ${id}: ${error.message}`); }
1741
+ }
1716
1742
  writeFileSync(temporary, renderReview(state, cachedSnapshot(root).hash, artifactIssues), { mode: 0o600 });
1717
1743
  renameSync(temporary, path);
1718
1744
  return reviewPath(state);
@@ -1721,3 +1747,86 @@ function writeReview(root, state) {
1721
1747
  export function reviewRun(root, id) {
1722
1748
  return transact(root, id, state => ({ runId: id, status: state.status, reviewPath: reviewPath(state) }));
1723
1749
  }
1750
+
1751
+ export function captureReview(root, id, { reviewer, scope = [] } = {}) {
1752
+ return transact(root, id, state => {
1753
+ requireActive(state);
1754
+ if (!['self', 'fresh-context', 'peer'].includes(reviewer)) throw new Error('Review reviewer must be self, fresh-context or peer.');
1755
+ if (!budget(state) || !guard(root, state)) return state;
1756
+ const paths = normalizePaths(root, scope, 'review scope');
1757
+ const source = cachedSnapshot(root);
1758
+ if (source.skipped.length) throw new Error('Review capture cannot cover symlink source dependencies.');
1759
+ for (const path of paths) if (![...Object.keys(source.files), ...Object.keys(state.initialSource.files)].some(file => file === path || file.startsWith(`${path}/`))) throw new Error(`Review scope has no covered source: ${path}.`);
1760
+ const reviewId = randomUUID(), path = `.cyc/runs/${id}/reviews/${reviewId}.json`;
1761
+ const receipt = { version: 1, runId: id, id: reviewId, status: 'captured', reviewer, identity: null, provenance: 'agent-reported', scope: paths, sourceHash: source.hash, files: source.files, criteriaHash: state.criteriaHash ?? digest(JSON.stringify(state.criteria)), capturedAt: new Date().toISOString(), path };
1762
+ atomicJSON(projectFile(root, path), receipt);
1763
+ (state.reviewReceipts ??= []).push({ ...receipt, sha256: digest(readFileSync(projectFile(root, path))) });
1764
+ log(state, 'review-captured', { reviewId, sourceHash: source.hash });
1765
+ return receipt;
1766
+ });
1767
+ }
1768
+
1769
+ function checkedReview(root, state, id, sourceHash) {
1770
+ const record = state.reviewReceipts?.find(r => r.id === id);
1771
+ if (!record) throw new Error(`Unknown review ${id}.`);
1772
+ assertArtifacts(root, [{ path: record.path, sha256: record.sha256 }]);
1773
+ if (record.sourceHash !== sourceHash || record.criteriaHash !== (state.criteriaHash ?? digest(JSON.stringify(state.criteria)))) throw new Error(`Review ${id} is stale: source or criteria changed since capture.`);
1774
+ return record;
1775
+ }
1776
+
1777
+ export function recordReview(root, id, { reviewId, evidence, identity = null, findings = [] } = {}) {
1778
+ return transact(root, id, state => {
1779
+ requireActive(state);
1780
+ if (!budget(state) || !guard(root, state)) return state;
1781
+ const record = checkedReview(root, state, reviewId, cachedSnapshot(root).hash);
1782
+ if (!text(evidence) || (identity !== null && !text(identity))) throw new Error('Review needs actual evidence; identity is text or null when unknown.');
1783
+ if (!Array.isArray(findings) || new Set(findings.map(f => f?.id)).size !== findings.length || findings.some(f => !text(f?.id) || !text(f.evidence) || !['resolved', 'dismissed', 'open'].includes(f.status))) throw new Error('Review findings need unique ids, status and evidence.');
1784
+ if (record.status === 'recorded') throw new Error('Review already recorded; capture a new receipt for another review.');
1785
+ const { sha256, ...receipt } = { ...record, status: 'recorded', evidence, identity, findings, recordedAt: new Date().toISOString() };
1786
+ atomicJSON(projectFile(root, record.path), receipt);
1787
+ Object.assign(record, receipt, { sha256: digest(readFileSync(projectFile(root, record.path))) });
1788
+ log(state, 'review-recorded', { reviewId, reviewer: receipt.reviewer });
1789
+ return receipt;
1790
+ });
1791
+ }
1792
+
1793
+ // Called after machine verification; preflight only checks the assessment's structure.
1794
+ function bindEvidence(root, state, packet) {
1795
+ if (state.evidenceVersion !== 1 || packet.stage !== 'verify' || packet.status !== 'passed') return;
1796
+ const a = packet.assessment, snapshot = cachedSnapshot(root), sourceHash = snapshot.hash;
1797
+ const verification = state.verification;
1798
+ if (!verification?.passed || verification.sourceHash !== sourceHash) throw new Error('Scenario evidence needs current passing command verification.');
1799
+ assertArtifacts(root, [{ path: verification.receiptPath, sha256: verification.receiptHash }]);
1800
+ for (const row of a.criterionChecks) {
1801
+ if (!['current-verification', verification.receiptPath].includes(row.receipt)) throw new Error(`Scenario ${row.id} references a stale or foreign verification receipt.`);
1802
+ if (!verification.results.some(r => r.id === row.check && (r.passed || verification.acceptedPreexistingFailures?.includes(r.id)))) throw new Error(`Scenario ${row.id} check did not pass or retain an accepted baseline failure.`);
1803
+ row.receipt = verification.receiptPath;
1804
+ }
1805
+ packet.artifacts.push({ path: verification.receiptPath, sha256: verification.receiptHash });
1806
+ const refs = a.semanticReview.receipts ?? [];
1807
+ for (const ref of refs) {
1808
+ const receipt = checkedReview(root, state, ref, sourceHash);
1809
+ if (receipt.status !== 'recorded') throw new Error(`Review ${ref} has no recorded findings/evidence.`);
1810
+ for (const finding of receipt.findings) if (!a.semanticReview.findings.some(f => f.reviewId === receipt.id && f.id === finding.id && f.status !== 'open')) throw new Error(`Review finding ${receipt.id}/${finding.id} needs a receipt-scoped resolved or dismissed disposition.`);
1811
+ packet.artifacts.push({ path: receipt.path, sha256: receipt.sha256 });
1812
+ }
1813
+ for (const finding of a.semanticReview.findings) if (finding.reviewId !== undefined && !refs.includes(finding.reviewId)) throw new Error('Finding disposition references an unknown review receipt.');
1814
+ if (a.semanticReview.reviewer !== 'self' && !refs.some(ref => state.reviewReceipts.find(r => r.id === ref)?.reviewer === a.semanticReview.reviewer)) throw new Error('Claimed reviewer type does not match a recorded review receipt.');
1815
+ if (refs.length || state.reviewPolicy === 'fresh-required') {
1816
+ const changed = [...new Set([...Object.keys(state.initialSource.files), ...Object.keys(snapshot.files)])].filter(path => state.initialSource.files[path] !== snapshot.files[path]);
1817
+ const covered = path => refs.some(id => { const r = state.reviewReceipts.find(x => x.id === id); return !r.scope.length || r.scope.some(p => path === p || path.startsWith(`${p}/`)); });
1818
+ if (changed.some(path => !covered(path))) throw new Error('Review receipts do not cover all changed source; record the missing self/fresh review scope.');
1819
+ if (state.reviewPolicy === 'fresh-required' && (!refs.some(id => state.reviewReceipts.find(r => r.id === id)?.reviewer === 'fresh-context') || changed.some(path => !refs.some(id => { const r = state.reviewReceipts.find(x => x.id === id); return r.reviewer === 'fresh-context' && (!r.scope.length || r.scope.some(p => path === p || path.startsWith(`${p}/`))); })))) throw new Error('fresh-required policy needs current fresh-context receipts covering every changed source path.');
1820
+ if (reviewCoverage(state, a.semanticReview, sourceHash).status === 'stale') throw new Error('Review coverage is stale.');
1821
+ }
1822
+ if (state.testProof && a.testProof?.status !== 'exempt') {
1823
+ assertArtifacts(root, [{ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash }]);
1824
+ packet.artifacts.push({ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash });
1825
+ }
1826
+ if (a.proofReview && a.testProof?.status !== 'exempt') {
1827
+ validateProofReview(state, a.proofReview);
1828
+ a.proofReview.receipt = state.testProof.receiptPath;
1829
+ const names = category => a.proofReview.cases.filter(c => c.category === category).map(c => state.testProof.failures.find(f => f.id === c.id).name);
1830
+ state.testProof.claim = `Reason-reviewed baseline evidence (agent-reported interpretation): behavioral cases [${names('behavioral').join('; ')}]; new-interface cases [${names('new-interface').join('; ')}]. Setup and unclassified failures do not establish the intended behavior defect. This is not a repaired-defect count.`;
1831
+ }
1832
+ }
@@ -256,3 +256,13 @@ export function testsOf(result) {
256
256
 
257
257
  // Output whose earlier lines were dropped, with no complete summary to stand in for them.
258
258
  export const cutOff = result => result?.tests ? !result.tests.complete : [result?.stdout, result?.stderr].some(stream => (stream ?? '').length >= outputLimit);
259
+
260
+ // Diagnostic hints only. A TypeError or load failure can itself be the real old bug;
261
+ // only a case-specific reason review can establish the meaning of a failure.
262
+ export function failureHint(entry) {
263
+ const error = `${entry.error ?? ''}\n${(entry.details ?? []).join('\n')}`;
264
+ if (/ERR_MODULE_NOT_FOUND|Cannot find (?:module|package)|does not provide an export|ModuleNotFoundError/.test(error)) return 'module-load';
265
+ if (/AssertionError|ERR_ASSERTION|assertion failed|Expected:|expected .* to /i.test(error)) return 'assertion';
266
+ if (/timeout|timed out|ENOENT|ECONNREFUSED/.test(error)) return 'execution-or-setup';
267
+ return 'unclassified';
268
+ }