okstra 0.230.0 → 0.231.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.
Files changed (57) hide show
  1. package/docs/architecture/storage-model.md +67 -6
  2. package/docs/architecture.md +2 -0
  3. package/docs/coding-rules.md +15 -0
  4. package/docs/project-structure-overview.md +2 -1
  5. package/package.json +2 -2
  6. package/runtime/BUILD.json +2 -2
  7. package/runtime/prompts/coding-preflight/clean-code.md +8 -0
  8. package/runtime/prompts/coding-preflight/overview.md +1 -0
  9. package/runtime/prompts/launch.template.md +2 -0
  10. package/runtime/prompts/lead/okstra-lead-contract.md +5 -5
  11. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -0
  12. package/runtime/python/okstra_ctl/agent/invocation.py +48 -4
  13. package/runtime/python/okstra_ctl/blocking_checks.py +10 -0
  14. package/runtime/python/okstra_ctl/conformance_evidence.py +148 -67
  15. package/runtime/python/okstra_ctl/execution_mutation_audit.py +13 -1
  16. package/runtime/python/okstra_ctl/incremental_carry.py +7 -4
  17. package/runtime/python/okstra_ctl/paths.py +19 -4
  18. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +1 -0
  19. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +8 -0
  20. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +1 -0
  21. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +53 -0
  22. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +5 -1
  23. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +2 -0
  24. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +19 -3
  25. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +1 -1
  26. package/runtime/python/okstra_ctl/phases/implementation/spec.md +2 -0
  27. package/runtime/python/okstra_ctl/phases/implementation/validation.py +152 -30
  28. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -22
  29. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +2 -2
  30. package/runtime/python/okstra_ctl/phases/implementation_planning/wizard.py +11 -4
  31. package/runtime/python/okstra_ctl/phases/release_handoff/operations.py +4 -5
  32. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +1 -1
  33. package/runtime/python/okstra_ctl/plan_items.py +28 -0
  34. package/runtime/python/okstra_ctl/render.py +15 -0
  35. package/runtime/python/okstra_ctl/report_assembly.py +102 -1
  36. package/runtime/python/okstra_ctl/report_execution_evidence.py +220 -0
  37. package/runtime/python/okstra_ctl/report_inputs.py +28 -0
  38. package/runtime/python/okstra_ctl/report_narrative.py +12 -3
  39. package/runtime/python/okstra_ctl/run.py +16 -0
  40. package/runtime/python/okstra_ctl/stage_close.py +52 -6
  41. package/runtime/python/okstra_ctl/stage_fix_carry.py +21 -1
  42. package/runtime/python/okstra_ctl/stage_integrate.py +90 -25
  43. package/runtime/python/okstra_ctl/verification_dispatch.py +8 -2
  44. package/runtime/python/okstra_ctl/verification_evidence.py +26 -7
  45. package/runtime/python/okstra_ctl/verification_generation.py +12 -4
  46. package/runtime/python/okstra_ctl/verification_inputs.py +10 -0
  47. package/runtime/python/okstra_ctl/verification_invocation.py +2 -1
  48. package/runtime/python/okstra_ctl/wizard/engine.py +23 -0
  49. package/runtime/python/okstra_ctl/wizard/steps_plan.py +6 -2
  50. package/runtime/python/okstra_ctl/worktree/git_ops.py +8 -1
  51. package/runtime/python/okstra_ctl/worktree/rebase.py +5 -2
  52. package/runtime/schemas/final-report-v3.0.schema.json +184 -1
  53. package/runtime/skills/okstra-run/SKILL.md +5 -1
  54. package/runtime/templates/reports/html/i18n/en.json +7 -0
  55. package/runtime/templates/reports/html/i18n/ko.json +7 -0
  56. package/runtime/validators/validate-run.py +24 -5
  57. package/runtime/validators/validate-workflow.sh +1 -1
@@ -142,8 +142,12 @@ legacy inputs, repeated reads and per-operation cache lifetime.
142
142
  verification-generation seals. Its in-memory `VerificationSourceSnapshot` retains
143
143
  the source root, tracked path set, generated roots, explicit input paths, and
144
144
  read-only protected/generated fingerprint maps. Tracked files and explicit inputs
145
- take precedence over generated roots. Unclassified existing files, including
146
- Git-ignored files, remain protected. The existing collector excludes installed
145
+ take precedence over generated roots. Git-ignored paths count as generated
146
+ output, so a check may rewrite a build directory or test cache; a tracked or
147
+ explicit-input file stays protected even when ignored. A generation records
148
+ the ignored roots that held output at the seal as `source.ignoredRoots`, and
149
+ its validator classifies against them; unlike `generatedRoots`, they need not
150
+ match between captures. Other unclassified existing files remain protected. The existing collector excludes installed
147
151
  dependency trees, the runtime artifact tree, and other registered worktrees;
148
152
  explicit inputs and tracked files are recovered from excluded artifact and
149
153
  dependency trees. Explicit inputs use the shared QA regular-file validator and reject
@@ -169,6 +173,19 @@ The reader bounds path expansion and checks schema, classification and byte dige
169
173
  without rereading live inputs. the retired Python suite covers
170
174
  correction generations, tampering, lock waits and target changes.
171
175
 
176
+ Prepare marks a new implementation or final-verification run with
177
+ `verificationEvidenceVersion: "1.0"` when it freezes the run's verification
178
+ inputs and those inputs hold an approved plan and an `id` on every `qaCommands`
179
+ entry, and the plan's conformance baseline was captured
180
+ (`verification_inputs.evidence_contract_applies`). Without a plan a generation seals no
181
+ conformance stage, and an entry without an `id` cannot be run as a `qa:` check,
182
+ so such a run stays unmarked and keeps the sidecar and narrative paths. A
183
+ recorded run manifest keeps the field it was prepared with
184
+ (`render._evidence_contract_fields`), so a run prepared before this change
185
+ resumes unmarked. Declared generated roots stay empty; a check may rewrite
186
+ Git-ignored output, and a file it writes that the repository does not ignore
187
+ makes that check and every later one of the generation end `target-changed`.
188
+
172
189
  Invocation materialization can bind a verifier to one sealed generation through
173
190
  `AgentInvocationRequest.verification_generation`. A run marked with
174
191
  `verificationEvidenceVersion: "1.0"` requires that reference for implementation
@@ -198,8 +215,9 @@ no baseline refuses the seal and quotes the recorded capture error, if any.
198
215
  source the executor deleted is not required. Generated roots and extra artifact
199
216
  inputs stay empty: no declared QA output location lies inside a source root (the
200
217
  verifier's task `qa/` grant lies under `.okstra/`, which the seal already
201
- excludes), and Git-ignored files remain protected. Every untracked file outside
202
- `.okstra/` is therefore a protected input. A seal is immutable:
218
+ excludes); Git-ignored paths are generated output (above). Every other
219
+ untracked file outside `.okstra/` is therefore a protected input, so a command
220
+ that writes a file the repository does not ignore ends `target-changed`. A seal is immutable:
203
221
  re-materializing over an unchanged source reuses it, and a source change outside
204
222
  a new correction round is refused. Only a prompt being published is sealed; reuse
205
223
  of a published prompt checks the generation its metadata already binds. Seal
@@ -260,13 +278,56 @@ whose script changed, with the existing `decide_conformance_gate` policy; the
260
278
  diff-surface check keeps the run's own stage scope. A blocked stage whose latest
261
279
  records are no usable evidence names each record and its defect, such as
262
280
  `status is target-changed`, instead of reporting that its script never ran. Unmarked runs keep reading
263
- the sidecar. `okstra stage-close` still reads the sidecar, because it receives a
264
- task and stage rather than the run whose records decide that stage. These rules
281
+ the sidecar. `okstra stage-close` reads the stage's latest implementation run
282
+ manifest (the highest sequence under `runs/implementation/stage-<N>/manifests`):
283
+ when that run is marked, the stage result comes from its records through the
284
+ same collection, and a record that is no usable evidence refuses the close;
285
+ otherwise it reads the sidecar. These rules
265
286
  are covered by `tests/run/test_conformance_evidence.py`,
266
287
  `tests/contract/test_okstra_ctl_conformance.py`,
267
288
  `tests/contract/test_validate_run_conformance.py` and
268
289
  `tests/worktree/test_worktree_exec_lock.py`.
269
290
 
291
+ Every verifier invocation is bound to the generation its reserved invocation
292
+ metadata names (`agent.invocation.reserved_generation_reference`, through the
293
+ reservation under `agentContract.invocationReservationRootPath`). The bound path
294
+ must be the generation the invocation's dispatch kind seals, and the generation
295
+ file must still have the digest the metadata recorded; otherwise evidence
296
+ collection fails instead of trusting the file at the computed path. An invocation
297
+ the run reserved no metadata for is bound to no generation.
298
+
299
+ Report contract 3.0 registers the run's verification directory as the
300
+ `execution-evidence` input, owned by `verification-execution`, for a marked
301
+ implementation or final-verification run (`report_inputs.py`).
302
+ `report_execution_evidence.collect_report_evidence` takes, for each verifier, the
303
+ invocation bound to the run's newest generation, its latest attempt, and the
304
+ latest `run-<k>` of every check that attempt ran. An earlier stage that the
305
+ newest generation does not seal is gated by an older generation's record
306
+ (`conformance_evidence`), which the report does not show. Report assembly writes one
307
+ `ExecutionEvidenceRef` per record: record path and byte digest, invocation,
308
+ attempt, check, check run, generation path and digest, `collection`, the
309
+ record's command, exit code or signal, and the last 20 lines (at most 2000
310
+ characters) of the saved `stdout.log`. A record that is unreadable, not
311
+ `completed`, bound elsewhere, or whose saved output differs from it is
312
+ `collection: incomplete` with its `defect`. An implementation report attaches
313
+ the references to `verifierResults[].executionEvidence` by roster verifier
314
+ worker id and skips `not-run` rows; a final-verification report appends one
315
+ `readonlyCommandLog` row per record, `executed` or `evidence-incomplete`, with
316
+ the reference in `executionEvidence`. The report writer cannot author either
317
+ field, and the narrative of a marked run cannot write an executed Tier 2 or
318
+ Tier 3 command row. `validate-run` derives the evidence again and blocks
319
+ (`execution-evidence BLOCKING:`) a reference to another invocation, attempt,
320
+ check, check run or generation, a changed record, a derived field that differs,
321
+ an omitted record, and an executed Tier 2 or Tier 3 row without a record. A
322
+ marked implementation run cannot settle a FAIL through `leadFixes`, and a stage
323
+ settled after correction round N needs each verifier's generation N + 1
324
+ records. Unmarked runs and historical reports, including 2.0 reports and
325
+ `verdict: not-run` rows, assemble and validate as before; nothing converts them
326
+ or builds records from their strings. Execution records carry no server-target
327
+ observation and no applicability or skip disposition per frozen check, so the
328
+ report neither distinguishes an unconfirmed server target nor checks that every
329
+ applicable check ran. No automated test covers these rules.
330
+
270
331
  `okstra model-io run-input --run-manifest <path>` projects the recorded
271
332
  `verificationInputsPath` and `verificationInputsDigest` as fixed scalar lines.
272
333
  Absent or non-scalar values display `-`, including older manifests without a
@@ -518,6 +518,8 @@ The PR base follows the stage's `depends-on`, after dropping predecessors alread
518
518
  | one | that stage's branch — a stacked PR | no |
519
519
  | several | a branch merging their recorded `done.head_commit`s, named `<work-category-namespace>/<task-id-segment>-g<n1>-<n2>` | yes, by `pr-plan` |
520
520
 
521
+ okstra builds a merge-base branch from the implementation anchor by merging each predecessor's completion commit with `--no-ff` in stage order. Its merges, the whole-task integration merges and dependency-order rebases run with `core.hooksPath` set to the null device, so repository hooks never run on okstra's own commits. An existing merge-base branch is reused only when it contains the anchor and every predecessor commit, and carries no other non-merge commit. When two predecessors conflict, okstra deletes the half-built branch and the error lists the manual rebuild that a retry accepts.
522
+
521
523
  This derivation covers stacking inside one task. The release base must contain the task's implementation anchor base: a task built on another task's unmerged stage branch takes that branch as its release base. Prepare names it as the recommended Q2 option in `release-handoff-input.md`, and `pr-plan` refuses a release base that lacks the anchor, because the PR would also carry the other task's commits. A merge-base branch combines independent predecessors and is a base only, never a PR head. When a predecessor advances, `okstra_ctl.stage_rebase` rebases downstream stage branches in dependency order instead of merging the moving base into them. Implementation entry, verification target acquisition, and PR planning share this operation. Old heads are preserved under `refs/okstra/rebase-backups/`; registry bases and completion commits are updated, invalidating previous verification. PR planning stops after a stack change for fresh final-verification. Conflicts abort the current rebase, and dirty or active stages stop synchronization. A published branch that diverges from origin needs explicit delivery instructions; merging old origin history back into it is not recovery. Merge PRs in dependency order with a merge commit or rebase-merge; squashing replaces the commits the next PR's base points at.
522
524
 
523
525
  Entry is based on **task ID**, without a brief. Briefs are inputs to entry phases; for release-handoff, prepare determines eligibility from the approved plan's Stage Map + Stage Lifecycle Snapshot, then automatically creates an input document (`<task_root>/release-handoff-input.md`) that cites the verification reports. Stage selection comes from the okstra-run wizard's `handoff_stage_pick` multiselect or CLI `--stages <csv>`; an empty selection takes every eligible stage, and the result is exposed to the lead as `HANDOFF_STAGES` in run-context.
@@ -12,12 +12,27 @@ enforcement point is a wish, not a rule.
12
12
  | R2 — No exception swallowed without a signal | `tests-js/coding-rules.test.mjs` |
13
13
  | R3 — No untracked `TODO` / `FIXME` / `HACK` / `XXX` | `tests-js/coding-rules.test.mjs` |
14
14
  | G1–G4 — Comment honesty | Code review. Not mechanical |
15
+ | T1 — Reuse existing tests | Change review and code review; no automatic test-count rule |
15
16
 
16
17
  Scanner: [`tools/coding-rules.mjs`](../tools/coding-rules.mjs). Allowance ledger:
17
18
  [`config/coding-rules-baseline.json`](../config/coding-rules-baseline.json).
18
19
 
19
20
  ---
20
21
 
22
+ ## T1: Reuse existing tests
23
+
24
+ Before changing a function, search by its name, observable behavior, callers, and assertions, then read the candidate test bodies.
25
+
26
+ - When a behavior test exists, strengthen that test in place. If it already verifies the changed contract, run and retain it; do not add a parallel test.
27
+ - Add a test only when no existing test covers that behavior. Prefer the nearest existing test file; a new file needs a distinct ownership or boundary reason.
28
+ - Keep only cases that distinguish changed outcomes or meaningful failures. Do not create a test per function, extracted helper, or syntactic branch, or generate every model, provider, or task-type combination.
29
+ - Give each behavior one primary test owner. Add an integration case only for a separate wiring failure that the existing behavior test cannot observe.
30
+ - Record the changed function and the retained or extended test location. A new test records the uncovered behavior and why an existing test could not be strengthened.
31
+
32
+ Enforcement is a review criterion: change descriptions and code review check this mapping. Test-count targets and new tests that only check these prose rules are not required.
33
+
34
+ ---
35
+
21
36
  ## How the enforcement works: a ratchet, not a wall
22
37
 
23
38
  At the time these rules landed the repository already violated R1 in 138 places and R2 in 21. R3 stood at zero.
@@ -298,7 +298,8 @@ Important modules:
298
298
  | `conformance.py` | validates task-level Tier 3 manifests, parses `QA-RESULT`, detects diff capability surfaces, and reduces results to PASS/ADVISORY/BLOCKING; DB/HTTP/external non-PASS is user-owned advisory while local IO and contract defects remain blocking, enforced by `scripts/okstra_ctl/conformance.py::decide_conformance_gate` and `validators/validate-run.py::_validate_conformance`. Also the single definition of the plan's `Conformance tests:` declaration format (`parse_conformance_tests`, `malformed_conformance_stages`), read both at the approval boundary (`run.py::_validate_approved_plan`) and at the end of an implementation run (`validators/validate-run.py`) so the two cannot disagree |
299
299
  | `pr_template.py` | PR body template resolution for release-handoff |
300
300
  | `report_views.py`, `render_final_report.py`, `final_report_schema.py` | Final-report render layer: from the assembled `data.json` (schema v2 or v3) it independently produces the full reading copy Markdown and human HTML; both schema versions render the reading copy from `final-report-v2.template.md` (schema v3 reuses the v2 template for read/render compatibility) |
301
- | `report_inputs.py` | Report contract 3.0 role-input path + single-owner registry — resolves each owning role's input artifact from the manifest (`narrative` → report-writer, `approval-decisions` → lead, `agent-activity` → activity ledger, `execution-status` → team-state, `convergence`) |
301
+ | `report_inputs.py` | Report contract 3.0 role-input path + single-owner registry — resolves each owning role's input artifact from the manifest (`narrative` → report-writer, `approval-decisions` → lead, `agent-activity` → activity ledger, `execution-status` → team-state, `convergence`; for an implementation or final-verification run marked `verificationEvidenceVersion`, `execution-evidence` → verification-execution, the run's verification directory) |
302
+ | `report_execution_evidence.py` | Derives each verifier's execution evidence references and final-verification command rows from the verification execution records, and compares a report's references with them for the phase validators |
302
303
  | `report_assembly.py` | Validates the role-owned report inputs and publishes the contract 3.0 record once (assembled in a temp file, then atomically promoted); a bad input aborts with owner / artifact path / field path / reason and preserves the existing `data.json` |
303
304
  | `report_projections.py` | Pure projections turning role-owned execution inputs (agent activity, execution status, convergence, design, token usage) into canonical final-report fragments |
304
305
  | `report_narrative.py` | Lossless read/write contract for the report-writer-owned narrative Markdown (`report-narrative-<task-type>-<seq>.md`) — the only artifact the report-writer authors under contract 3.0 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okstra",
3
- "version": "0.230.0",
3
+ "version": "0.231.0",
4
4
  "description": "Host-aware multi-provider cross-verification orchestrator runtime and agent skills.",
5
5
  "license": "MIT",
6
6
  "author": "devonshin",
@@ -39,7 +39,7 @@
39
39
  "test:py": "python3 tools/run-pytest-shards.py",
40
40
  "test:workflow": "bash validators/validate-workflow.sh",
41
41
  "test:e2e": "bash tests-e2e/run-all.sh",
42
- "check": "npm run build && npm run test:js && npm run test:py && npm run test:workflow && npm run test:e2e"
42
+ "check": "npm run build && npm run test:py && npm run test:workflow"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@types/node": "^26.2.0",
@@ -1,5 +1,5 @@
1
1
  {
2
- "package": "0.230.0",
3
- "builtAt": "2026-11-02T16:29:00.133Z",
2
+ "package": "0.231.0",
3
+ "builtAt": "2026-11-03T06:50:19.435Z",
4
4
  "repoRoot": "/home/runner/work/okstra/okstra"
5
5
  }
@@ -232,6 +232,14 @@ These principles apply to every test file regardless of language or framework. T
232
232
 
233
233
  Follow the testing-waiver policy in `overview.md` "Tests planned". An explicit waiver applies only to the named behavior or check, including its branch-test, branch-deletion, or resource-bound requirement. Record that scope as unverified. All checks outside the waiver and the quality rules for tests that are written or edited still apply.
234
234
 
235
+ ### Reuse tests before adding coverage
236
+
237
+ Before changing a function, search by its name, behavior, callers, and assertions and read the matching test bodies. Strengthen an existing behavior test in place. If it already verifies the changed contract, run and retain it. Add a test only when no existing test covers that behavior; prefer the nearest existing test file and justify a new file by a distinct ownership or boundary.
238
+
239
+ Keep cases that separate changed outcomes or meaningful failures. A function extraction, renamed helper, or additional syntactic branch does not by itself justify another test. Do not create parallel tests for the same input and outcome or generate every model, provider, and task-type combination. One behavior has one primary test owner; an integration case needs a separate wiring risk.
240
+
241
+ The review evidence names the changed function, the existing test that was retained or strengthened, or the uncovered behavior that required a new test. Branch-deletion checks below apply to this coverage; they do not require a separate test function for every branch. Completion self-check and code review assess this evidence.
242
+
235
243
  ### No self-mocking
236
244
 
237
245
  A unit test for class `Foo` must **not** stub, spy on, or replace methods on the instance of `Foo` being tested. Mocking injected collaborators (other services, repositories, adapters, ports, the clock) is fine and expected.
@@ -52,6 +52,7 @@ If no Stage 1 language rule matches (an unlisted language), stop and ask the use
52
52
  - [ ] **Mutation and state boundaries** (`clean-code.md`): decide on the direct identifier, not a status/flag proxy; capture before-state in one snapshot ahead of the mutating boundary; update only this work's owned fields on an existing row; re-read state before calling a zero-affected-rows write success or failure; put priority-between-inputs in a named domain function; keep error messages to what was observed.
53
53
  - [ ] **Untrusted input and security** (`clean-code.md`), for every file that reads input from outside the process or acts on its behalf: a size/count bound rejects oversized input before any check or step that grows faster than the input; input reaches SQL, shell, paths, server-side fetches, templates and regexes only through parameters, allowlists or escaping; new entry points enforce the project's operation-specific access policy, including shared, administrative, and explicitly public access where applicable; protect secrets and limit personal-data disclosure as specified in `clean-code.md`, including authorized data responses and credential issuance; no eval or unsafe deserialization of input.
54
54
  - [ ] Tests planned: which test(s) cover this change. New behaviour without a test is **incomplete** unless the user has explicitly opted out for this change and project rules permit it. Record the exact waived behavior or check and its unverified coverage. That waiver applies to the corresponding branch-test, branch-deletion, and resource-bound checks in this pack; it does not waive unrelated checks, weaken existing tests, or establish verified coverage.
55
+ - [ ] **Function changes reuse tests first:** before changing a function, search its behavior and callers and read candidate tests. If a behavior test exists, strengthen it in place; if it already verifies the changed contract, run and retain it. Add a test only when that behavior has no existing test, preferring an existing file. Record the function, reused test location, or uncovered outcome that justifies a new test. Do not generate one test per function, helper, or branch, or expand model/provider/task-type combinations without distinct outcomes. This is checked in the completion self-check and code review, not by a test-count target.
55
56
  - [ ] **Existing tests surveyed (run this before planning any new test):** for every surface this change touches, `grep -rln` the candidate test files, list their test names, then READ the bodies of the ones that could overlap. A list of names does not tell you what a test asserts, and behavioural overlap does not collide on names — treat a clean name search as unfinished, not as a clear result. Record per surface: `extend <path:line>` / `new (nothing covers <behaviour>)` / `retire <path:line> (behaviour moved to <where>)`. A new test or test file with no survey line is unfinished work. The survey may change the design — moving the seam so existing tests keep passing beats adding parallel ones. Carry out a `retire` verdict in the same commit, on behavioural grounds only: the behaviour it asserted is gone, or a new test asserts it more strongly through the same seam. "Looks similar" / "touches the same file" is not grounds; without grounds the test stays, because a silent coverage loss costs more than one extra test.
56
57
  - [ ] **Testing discipline:** apply the recorded testing waiver only to its stated scope. For tests written or edited, the test does not stub/spy methods on the SUT itself (collaborators are fine), and assertions are on outcomes (return values, state, events, boundary calls) — not on which internal helper was called. Each unwaived branch this change adds (`catch`, guard, early return, `else`) has a test that fails when the branch body is deleted; assertions land on the last write to a record, not an intermediate one; each test title names its unit and the single condition it isolates; no effect is claimed under its own mock; shared fixtures keep their ordinary defaults; the scenarios' setup values actually differ; every new test helper/mock is used by a test in this same change; no positional mock-argument access (`rg 'mock\.calls'`).
57
58
  - [ ] **Third-party wrapper (when this change wraps a library call):** the wrapper adds behaviour the library does not already provide — read the installed library source before keeping a recovery branch — no comment names a condition the call site does not establish, and a rethrow keeps the original error as `cause`.
@@ -203,6 +203,8 @@ The **default is full re-verification**. Narrow this re-run to the impacted stag
203
203
  ```
204
204
  A non-zero exit means the writer changed or omitted a carried stage, the item set drifted, or the stage scopes conflict. Fall back to **full** and re-verify every stage. The command writes only the convergence-owned plan state. It never patches the writer narrative or final `data.json`. `verdictCard` / `finalVerdict` are never carried.
205
205
 
206
+ The carry stamps verified hashes onto the state rows and rewrites the state's `dispatchQueue`. It also copies that queue into the prepared envelope without narrowing it by reusable verdicts, so that envelope is provisional. Before dispatch, run in this order: `okstra plan-items prepare --narrative ... --run-manifest ... --state <this run's plan-body-verification state>`, `okstra plan-items prompt --run-manifest ...` (it takes no `--state`), then `okstra plan-items validate-prepared --narrative ... --run-manifest ... --state <the same state>`. Without `--state`, validate-prepared re-derives the queue and evidence from no prior rows and refuses the envelope a `--state` prepare wrote. Re-run `plan-items seed` only after a narrative correction adds or renames plan items. `team await` refuses a round whose prepared items name an item outside the state's `dispatchQueue`. **Enforced:** `plan_items.queue_candidate_ids`, which both `incremental_carry._recompute_dispatch_queue` and `implementation_planning.authoring._queue_for` use, and `authoring._narrow_dispatch_queue`.
207
+
206
208
  **Carry completeness (BLOCKING).** In incremental mode, this run's `planItems` MUST contain every plan-item id from the re-verified stages, each carried forward with its updated verdict. If re-verification concludes a plan item should be REMOVED, that is a signal the answer's blast radius is NOT local — abandon incremental and re-route to a FULL re-verification. The carry merge only ever ADDS prior items whose id is absent from this run; it cannot distinguish a legitimate deletion from an untouched carry, so it would resurrect a stale verdict.
207
209
 
208
210
  **Enforced:** `scripts/okstra_ctl/incremental_carry.py` `_merge_stage_aware` performs the carry and exits non-zero when a re-verified stage's item set drifted from the prior run's `planItems`.
@@ -57,7 +57,7 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
57
57
  | `okstra model-io run-input --run-manifest <path>` | Read run identity, worker roster, model assignments, and artifact paths instead of opening the run manifest | `context-loader` "Step 3" |
58
58
  | `okstra model-io active-context-input --project-root <dir> --run-manifest <path>` | Read the prior executor base ref for an incremental re-run | launch prompt "Incremental re-verification" |
59
59
  | `okstra incremental-scope --prev-data <path>` | Decide re-verify vs carry-forward stages on a clarification re-run | launch prompt "Incremental re-verification" |
60
- | `okstra incremental-carry --prev-data <path> --prev-seq <seq> --cur-narrative <path>` | Merge carried-forward plan-item verdicts after `plan-items seed` | launch prompt "Incremental re-verification" |
60
+ | `okstra incremental-carry --prev-data <path> --prev-seq <seq> --cur-narrative <path>` | Merge carried-forward plan-item verdicts after `plan-items seed`; then repeat `plan-items prepare --state`, `prompt` and `validate-prepared --state` | launch prompt "Incremental re-verification" |
61
61
  | `okstra stage-map <task-key>` | Read the prior Stage Map and done stages before re-planning | host orchestration rules (implementation-planning) |
62
62
  | `okstra stage-close <task-key> --stage <N> --from-commit <sha> [--supersede-failed <reason>]` | Close a stage whose work already landed outside okstra, or a `failed` stage whose failure no longer applies |
63
63
  | `okstra stage-reopen <task-key> --stage <N> --reason <why> [--evidence <report>]` | Reopen a `done` stage for a fix run, e.g. after a `blocked` final-verification of that stage | host orchestration rules (implementation-planning) |
@@ -161,9 +161,9 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
161
161
  | `okstra agent-prompt check-corrections --project-root <dir> --run-manifest <path> --corrections <path>` | Check a report-writer corrections ledger before a corrective dispatch | `report-writer` "Corrective report-writer dispatch" |
162
162
  | `okstra agent-prompt apply-corrections --project-root <dir> --run-manifest <path> --corrections <path>` | Apply a ledger that `check-corrections` reported `mechanical: true`, without a writer round | `report-writer` "Corrective report-writer dispatch" |
163
163
  | `okstra design-snapshot --narrative <path> --output <path>` | Complete the design-surface detector snapshot; both paths come from the run manifest | `report-writer` "Implementation-planning sequence" |
164
- | `okstra plan-items prepare --run-manifest <path> --narrative <path>` | Extract this round's plan items (add `--state <path>` after a self-fix, `--tie-vote` for a critic tie round) | `plan-body-verification` "Round protocol" |
164
+ | `okstra plan-items prepare --run-manifest <path> --narrative <path>` | Extract this round's plan items (add `--state <path>` after a self-fix or `incremental-carry`, `--tie-vote` for a critic tie round) | `plan-body-verification` "Round protocol" |
165
165
  | `okstra plan-items prompt --run-manifest <path>` | Print the plan-items block placed verbatim in every verifier prompt | `plan-body-verification` "Round protocol" |
166
- | `okstra plan-items validate-prepared --run-manifest <path> --narrative <path>` | Validate the prepared envelope before dispatch | `plan-body-verification` "Round protocol" |
166
+ | `okstra plan-items validate-prepared --run-manifest <path> --narrative <path>` | Validate the prepared envelope before dispatch; pass the same `--state` the last `prepare` used | `plan-body-verification` "Round protocol" |
167
167
  | `okstra plan-items seed --narrative <path>` | Create the `planItems[]` rows a round lands in | `plan-body-verification` "Round protocol" |
168
168
  | `okstra plan-items extract --narrative <path> --output <path>` | Re-extract plan items after a round and re-verify any item whose subject shifted | `plan-body-verification` "Round protocol" |
169
169
  | `okstra plan-items correction-prompt --run-manifest <path> --state <path> --worker <id>` | Put its output first in a `worker-correction` re-dispatch prompt | `plan-body-verification` "Round protocol" |
@@ -173,7 +173,7 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
173
173
  | `okstra plan-items next-dispatch --state <path>` | Decide whether the round opens another worker batch | `plan-body-verification` "Round protocol" |
174
174
  | `okstra plan-items resolve-dissent --state <path> --item <P-id> --decision-file <path>` | Record an evidence-based lead decision after the single self-fix | `plan-body-verification` "Round protocol" |
175
175
  | `okstra plan-verify --report <path>` | Score the plan-body gate; never tally votes in a script | `plan-body-verification` "Round protocol" |
176
- | `okstra worktree-lock --worktree <dir> --command <text>` | Lead minor fix (implementation only): re-run each Tier 1 command and failing verifier check that covers a fixed finding, in the stage worktree, under its lock | `_implementation-deliverable.md` "Lead minor fix" |
176
+ | `okstra worktree-lock --worktree <dir> --command <text>` | Lead minor fix (implementation only, never in a run marked `verificationEvidenceVersion`): re-run each Tier 1 command and failing verifier check that covers a fixed finding, in the stage worktree, under its lock | `_implementation-deliverable.md` "Lead minor fix" |
177
177
 
178
178
  ### Phase 7 — persist
179
179
 
@@ -394,7 +394,7 @@ For `--task-type implementation` runs, the task bundle additionally pins one of
394
394
 
395
395
  Lead MUST dispatch Edit/Write-bearing work only through that executor binding: use the host primitive with `hostModelValue` for `runner=native-session`. For `runner=cli-wrapper`, use `okstra team dispatch` when `terminalBackend` is `cmux-pane`, or `okstra worker-dispatch` with `modelExecutionValue` otherwise. The other providers in the roster still run as read-only verifiers in the same run; the executor's own provider does not, because its worker ID materializes as the executor on every dispatch — so the diff is reviewed context-isolated by the remaining verifiers. Session isolation is the primary self-review safeguard — a verifier reusing the executor's model variant is acceptable in a distinct session. A different model variant (e.g. executor=opus / Claude verifier=sonnet) is recommended but not mandatory.
396
396
 
397
- The one exception is the **lead minor fix**: after the verifier round and Phase 5.5 convergence, and before the report-writer dispatch, the lead edits and commits in the stage worktree itself to fix verifier FAIL findings that meet every eligibility rule in `scripts/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md` "Lead minor fix" — a local fix at the cited location, at most 30 changed lines in total, no change to a test's expected values, dependencies, schemas, migrations or config of record, only files inside the stage's planned paths or already changed by the executor, one pass per run. It then re-runs the covering checks through `okstra worktree-lock --worktree <dir> --command <text>` and records them in `implementation.leadFixes`. No worker dispatch is open at that point, so no read-only worker's mutation audit window covers the edit. Any finding outside those rules goes through the executor — first in a correction round inside this run (`_implementation-deliverable.md` "Correction round", at most 2), and in a fix run only when the finding needs a plan change or the rounds are spent. **Enforced:** `validators/validate-run.py` `_validate_lead_fixes` fails a fix recorded as passing with a failing check, a fix over 30 lines, and a stage settled over a FAIL that no passing fix answers; the remaining eligibility rules are instructions only.
397
+ The one exception is the **lead minor fix**, which a run marked `verificationEvidenceVersion` does not have (every fix there goes through a correction round; `_validate_lead_fixes` blocks a recorded lead fix): after the verifier round and Phase 5.5 convergence, and before the report-writer dispatch, the lead edits and commits in the stage worktree itself to fix verifier FAIL findings that meet every eligibility rule in `scripts/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md` "Lead minor fix" — a local fix at the cited location, at most 30 changed lines in total, no change to a test's expected values, dependencies, schemas, migrations or config of record, only files inside the stage's planned paths or already changed by the executor, one pass per run. It then re-runs the covering checks through `okstra worktree-lock --worktree <dir> --command <text>` and records them in `implementation.leadFixes`. No worker dispatch is open at that point, so no read-only worker's mutation audit window covers the edit. Any finding outside those rules goes through the executor — first in a correction round inside this run (`_implementation-deliverable.md` "Correction round", at most 2), and in a fix run only when the finding needs a plan change or the rounds are spent. **Enforced:** `validators/validate-run.py` `_validate_lead_fixes` fails a fix recorded as passing with a failing check, a fix over 30 lines, and a stage settled over a FAIL that no passing fix answers; the remaining eligibility rules are instructions only.
398
398
 
399
399
  Executor is chosen at run-prep time via `--executor <claude|codex|antigravity>` (or `OKSTRA_DEFAULT_EXECUTOR`, fallback `claude`); the model used by the executor is taken from the corresponding worker model flag (`--claude-model` / `--codex-model` / `--antigravity-model`). For CLI-backed executors, the underlying file mutation happens inside the executor CLI's own auto-edit mode (e.g. `codex exec --sandbox danger-full-access`), not through the lead runtime's `write_artifact` operation.
400
400
 
@@ -15,6 +15,8 @@ prompt through `prepare_agent_invocation()` before `worker-dispatch`.
15
15
 
16
16
  Load the applicable coding conventions for every language the diff will touch, then state in ONE line which conventions apply (e.g. `Applying TS + hexagonal overlay; domain at src/domains/*/domain/`). Lint/test green is necessary but NOT sufficient — self-mocked tests, interaction-only assertions, and untruthful names all pass a green pipeline; this gate is what keeps them out of the diff.
17
17
 
18
+ - **Reuse tests for function changes:** search by function behavior and callers, then read candidate test bodies before editing. Strengthen an existing behavior test; if it already verifies the changed contract, run and retain it. Add a test only when no existing test covers that behavior, preferably in an existing file. Record the function and reused test location or the uncovered outcome. Do not create tests per helper or branch, repeat the same input/outcome, or generate model/provider/task-type combinations without distinct behavior. This rule also applies when routed resources are unavailable. Completion self-check and code review assess the evidence; there is no test-count target.
19
+
18
20
  - **Resource selection — read the routed pack, never inline it here.** Use this worker prompt's `**Coding preflight pack:**` anchor header as the absolute path to the installed routed pack. Detect each touched file's language and framework from its extension or project manifest (`package.json`, `Cargo.toml`, `pyproject.toml`, `pom.xml`, `build.gradle*`, `prisma/schema.prisma`), then read that pack's resources via the Read tool by absolute path. Always read `overview.md` (the router) + `clean-code.md`, then select per the router's three ordered stages — Stage 1 language → `languages/<lang>.md`, Stage 2 framework → `frameworks/<fw>.md` (e.g. `frameworks/node-server.md` for server-side Node), Stage 3 architecture → `architectures/<arch>.md` (e.g. `architectures/hexagonal.md` for ports-and-adapters / NestJS-hex). Each stage is a list of rules; include EVERY matching resource (a change set can touch multiple languages/frameworks/architectures) — do not stop at the first match. These files are runtime resources, not Skill-tool skills, so always read them by path.
19
21
  - **Project policy projection:** before selecting resources, run `okstra model-io project-context --project-root <PROJECT_ROOT> --task-ref <TASK_KEY>` (the full `Task key` your dispatch prompt names). Consume its `Architecture style` and `Project Review Rule Packs` sections. Follow the `**Verification inputs:**` declaration-source rule when that header is present; use the named `okstra model-io verification-input --run-manifest <run-manifest>` projection for frozen declarations. The legacy lookup uses the projection's `Project QA Commands` only for an unfrozen baseline. Consume fixed text projections; do not open Okstra-owned JSON storage.
20
22
  - **Declared architecture style — an authoritative Stage 3 input, and it binds.** A projected `hexagonal` selects `architectures/hexagonal.md` even when none of Stage 3's layout signals matched, so the declaration — not the directory shape — decides. A projected `layered` has no pack resource; its invariant applies from this line: dependencies run one direction only — an upper layer may import a lower one, never the reverse — and a variation point is extracted onto a layer boundary. A declared style makes this overlay binding rather than advisory, and which rule binds follows the style: under `hexagonal` the overlay's otherwise-advisory concrete-adapter item is blocking, so a service dependency you add or modify goes through a port instead of a concrete implementation and that placement violation is fixed before the write rather than recorded as a note; under `layered` what binds is the direction invariant just stated — your own judgement over the import list of every file the diff touches, plus extracting a variation point onto a layer boundary — while the concrete-adapter item stays advisory, since `layered` has no ports to route it through. An absent or `none` projected style leaves Stage 3 detection-driven and its overlay advisory. The verifier re-grades the same diff under the same declaration (`_implementation-verifier.md` → Static design & test-quality review), so a placement violation missed here returns as a verdict `FAIL`.
@@ -713,7 +713,7 @@ def materialize_retry_invocation(
713
713
  retry_metadata_path = retry_prompt_path.with_name(
714
714
  retry_prompt_path.name + ".meta.json"
715
715
  )
716
- retry_invocation_id = f"{metadata['invocationId']}-attempt-{attempt}"
716
+ retry_invocation_id = _attempt_invocation_id(identity.invocation_ref, attempt)
717
717
  retry_metadata = dict(metadata)
718
718
  retry_metadata["invocationId"] = retry_invocation_id
719
719
  retry_metadata["attempt"] = attempt
@@ -754,7 +754,7 @@ def materialize_retry_invocation(
754
754
  }
755
755
  with _exclusive_lock(reservation_root / "publish.lock"):
756
756
  _publish_or_reuse_exact(
757
- reservation_root / f"{retry_invocation_id}.json",
757
+ _reservation_path(reservation_root, retry_invocation_id),
758
758
  _pretty_json(reservation),
759
759
  )
760
760
  with _exclusive_lock(_prompt_lock_path(retry_prompt_path)):
@@ -1695,7 +1695,7 @@ def _publish_or_reuse_reservation(materialized: _MaterializedInvocation) -> None
1695
1695
  reservation = materialized.reservation
1696
1696
  if root is None or reservation is None:
1697
1697
  return
1698
- path = root / f"{materialized.prepared.invocation_id}.json"
1698
+ path = _reservation_path(root, materialized.prepared.invocation_id)
1699
1699
  if path.exists():
1700
1700
  if _read_json_if_object(path) != reservation:
1701
1701
  raise AgentInvocationError(
@@ -2000,6 +2000,50 @@ def metadata_generation_reference(
2000
2000
  )
2001
2001
 
2002
2002
 
2003
+ def reserved_generation_reference(
2004
+ project_root: Path, manifest: Mapping[str, object], invocation_ref: str,
2005
+ attempt: int,
2006
+ ) -> VerificationGenerationReference | None:
2007
+ """The generation the metadata of one reserved v2 attempt is bound to; None
2008
+ when the run reserved no such attempt or bound it to no generation.
2009
+
2010
+ The reservation names the metadata, so a reader does not take a generation
2011
+ file on the strength of the path its dispatch kind computes.
2012
+ """
2013
+ contract = manifest.get("agentContract")
2014
+ if not isinstance(contract, Mapping):
2015
+ return None
2016
+ root = _project_path(
2017
+ project_root, contract.get("invocationReservationRootPath"), must_exist=False,
2018
+ )
2019
+ path = _reservation_path(root, _attempt_invocation_id(invocation_ref, attempt))
2020
+ if not path.is_file():
2021
+ return None
2022
+ reservation = _load_json_object(path, "invocation reservation")
2023
+ metadata = _load_json_object(
2024
+ _project_path(project_root, reservation.get("metadataPath"), must_exist=True),
2025
+ "agent invocation metadata",
2026
+ )
2027
+ for payload in (reservation, metadata):
2028
+ if (payload.get("invocationRef"), payload.get("attempt")) != (
2029
+ invocation_ref, attempt):
2030
+ raise AgentInvocationError(
2031
+ f"invocation reservation {path} names another invocation attempt"
2032
+ )
2033
+ return metadata_generation_reference(metadata)
2034
+
2035
+
2036
+ def _attempt_invocation_id(invocation_ref: str, attempt: int) -> str:
2037
+ """A v2 attempt's invocation id. The first attempt's id is the invocation
2038
+ reference (`_validate_v2_run_identity`), and every retry derives from it so
2039
+ a reader holding only the reference finds the attempt's reservation."""
2040
+ return invocation_ref if attempt == 1 else f"{invocation_ref}-attempt-{attempt}"
2041
+
2042
+
2043
+ def _reservation_path(root: Path, invocation_id: str) -> Path:
2044
+ return root / f"{invocation_id}.json"
2045
+
2046
+
2003
2047
  def _metadata_run_manifest(
2004
2048
  metadata: Mapping[str, object], project_root: Path,
2005
2049
  ) -> tuple[Path | None, dict[str, object]]:
@@ -2415,7 +2459,7 @@ def _verify_reservation(
2415
2459
  contract["invocationReservationRootPath"],
2416
2460
  must_exist=True,
2417
2461
  )
2418
- path = root / f"{metadata['invocationId']}.json"
2462
+ path = _reservation_path(root, metadata["invocationId"])
2419
2463
  actual = _load_json_object(path, "invocation reservation")
2420
2464
  except (AgentInvocationError, KeyError):
2421
2465
  return ["invocation reservation is missing or invalid"]
@@ -235,6 +235,16 @@ _BLOCKING: tuple[tuple[str, str], ...] = (
235
235
  "verifierResults 가 마지막 라운드의 verdict 가 아니면 release_gate.py 와 "
236
236
  "stage_fix_carry.py 가 다른 라운드의 판정으로 stage 를 정착시키거나 fix run 을 연다.",
237
237
  ),
238
+ # An evidence-contract run's checks are the execution records the runner
239
+ # observed (`report_execution_evidence.py`).
240
+ (
241
+ "execution-evidence BLOCKING:",
242
+ "The report shows a check result that is not the verifier's current "
243
+ "execution record (another invocation, attempt, check, check run or "
244
+ "generation, changed bytes, or an incomplete record shown as executed), "
245
+ "so the stage and release gates read a verification this run did not "
246
+ "observe.",
247
+ ),
238
248
  (
239
249
  "implementation run declares stage-",
240
250
  "stage 캐리 사이드카가 디스크에 없다 — consumers.py 의 "