okstra 0.142.0 → 0.143.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.
@@ -243,6 +243,7 @@ Important modules:
243
243
  | `incremental_carry.py` | carry merge for an incremental re-run — merges the previous run's plan-item verdicts that this run does not re-verify into the current data.json with a `carriedForwardFromSeq` tag. On `schemaVersion` drift it exits non-zero with `CarryError` to force a full fallback. CLI: `okstra incremental-carry` |
244
244
  | `build_tools.py` | allowlist SSOT for deciding whether a plan's command cell invokes the project build toolchain (`npm`/`pytest`/`cargo`/`gradle`/… behind transparent leaders like `sudo`/`env`). The planning worktree has no dependencies installed, so `validators/validate-run.py` uses this to warn (advisory) when a toolchain stage declares no install precondition. Intentionally an allowlist, not a denylist, so unknown tokens go undetected rather than firing on `grep`/`sed` in every plan |
245
245
  | `stage_citations.py` | shared grammar SSOT for reading the Stage Map stage numbers a prose cell cites (`Stages 1, 2, and 3`, ranges, etc.). One definition serves two readers that must not drift — the coverage check in `validators/validate-run.py` proving every stage traces to a requirement, and `incremental_scope.py`'s back-trace resolving which stages an answered clarification touches |
246
+ | `self_mock_signals.py` | self-mock signal SSOT — language-keyed regexes (`SIGNALS`), the `EXT_TO_LANG` extension map, and `selfmock_path_key` (the one path-normalization the coverage check and the waiver matcher both share). The signals are each ported from a `prompts/coding-preflight/languages/<lang>.md` "Self-mock signals to refuse" bullet with the source `doc_keyword` retained so a drift guard fails when doc and module diverge. Patterns stay deliberately narrow (only the "stub the subject's own method, then assert the stub" shape and reaching into the subject's privates; subject identity is never inferred beyond the literal `sut` token). Both the static detector `validators/detect_self_mock.py` and the drift guard MUST import from here; four documented shapes needing subject identity no regex has are left to the mutation gate |
246
247
  | `run_context.py` | Per-task mutex, run context and run-input persistence; `consumers_mutex` helper for atomic `consumers.jsonl` writes |
247
248
  | `path_hints.py` | Compact path-hint persistence + legacy context hydration — stores `run-context` / `active-run-context` in the schemaVersion `2.0` `identity` + `pathHints` compact schema, and hydrates the legacy flat path keys (`RUN_MANIFEST_RELATIVE_PATH`, `TEAM_STATE_PATH`, etc.) in memory the moment the host-side reader reads them |
248
249
  | `consumers.py` | Append-only `consumers.jsonl` writer + reader — records which `implementation` runs consumed which `implementation-planning` stage |
@@ -378,6 +379,7 @@ Optional (v1.0 backward-compatible) top-level keys:
378
379
  | `validate-schedule.py` | Schedule section/order/code validation |
379
380
  | `validate-implementation-plan-stages.py` | enforces the Stage Map structure — checks the S1–S8 rules (`## 5.5 Stage Map` + `## 5.5.<i> Stage <i>` sections, ≤ 8 steps per stage, etc.) |
380
381
  | `validate_improvement_report.py` | enforces the 11-item contract of the improvement-discovery final-report. Automatically invoked by `validate-run.py` when `task_type == "improvement-discovery"` |
382
+ | `detect_self_mock.py` | static self-mock detector — scans the changed TEST files for SUT-stub signals (patterns imported from the SSOT `scripts/okstra_ctl/self_mock_signals.py`, never redefined here), matching each file as one whole-file string so multi-line signals are caught. Writes a `qa/self-mock[-stage-<N>].json` sidecar and prints `QA-RESULT: PASS|FAIL` as its last line (exit 0 = no hits, exit 1 = at least one hit). The sidecar records `scannedFiles`/`skippedFiles` so the gate can prove every changed test file was actually scanned (a run that skips them cannot pass on empty input). An optional `--waivers <path>` moves hits matching `(file,line,signal)` from `staticDetect.hits` to `staticDetect.waived` (each carrying the user's `reason`/`acknowledgedBy`) and records the file as `waiverSource`. Its verdict feeds the fail-closed `_validate_selfmock` gate in `validate-run.py` (implementation / final-verification): a diff that touches test files with no readable PASS sidecar blocks the run; a `waived` entry missing `reason`/`acknowledgedBy`, or a `waiverSource` that is not the task's own `qa/self-mock-waivers.json`, also blocks |
381
383
  | `validate-workflow.sh` | End-to-end fixture workflow validation |
382
384
  | `lib/*.sh` | Shared shell validator helpers and fixtures |
383
385
 
@@ -47,14 +47,17 @@ sequenceDiagram
47
47
  Skill->>Wizard: task-type error-analysis selected
48
48
  Wizard-->>Skill: workers/base-ref/model args
49
49
  Skill->>Run: render-bundle --render-only
50
+ Run->>Run: canonical brief preflight
50
51
  Run->>Run: validate brief/profile
51
52
  Run->>Run: resolve worker roster
52
53
  Run->>WT: provision/reuse worktree
53
54
  Run->>Art: analysis-profile.md includes common contract
54
- Run->>Art: task-manifest workflow next=implementation-planning
55
+ Run->>Art: task-manifest workflow next=validated report route
55
56
  ```
56
57
 
57
- The static next phase in `workflow.py` is `implementation-planning`. The actual final report may say more investigation is needed, but in the lifecycle the fix does not go straight ahead; it moves on to planning.
58
+ For canonical briefs, preflight runs before worker resolution, worktree provisioning, or report creation. A brief whose `reporter-confirmations` status is `pending` stops at this point; legacy briefs keep the compatibility path.
59
+
60
+ The final report records its next phase in `errorAnalysis.routing.nextTaskType`. After report validation passes, workflow metadata persists that route as `nextRecommendedPhase`. The static `error-analysis` → `implementation-planning` mapping is a fallback only when report data is missing, legacy, or not an error-analysis report.
58
61
 
59
62
  ## 4. lead execution flow
60
63
 
@@ -69,7 +72,7 @@ flowchart TD
69
72
  Report --> Persist[Phase 7 persist + validate]
70
73
  ```
71
74
 
72
- The workers analyze the symptom and evidence independently. The report-writer does not analyze during Phase 4/5 but writes the final report in Phase 6.
75
+ The workers analyze the symptom and evidence independently. In adversarial mode, even a finding reported by multiple workers enters the verification queue instead of receiving automatic consensus. Evidence-backed counter-evidence remains in the finding's round history, so later agreement cannot turn it into full consensus. The report-writer does not analyze during Phase 4/5 but writes the final report in Phase 6.
73
76
 
74
77
  ## 5. Deliverables and prohibitions
75
78
 
@@ -82,13 +85,15 @@ flowchart LR
82
85
  Hyp -. forbidden .-> Fix[Code fix in this run]
83
86
  ```
84
87
 
85
- The final report must contain the following.
88
+ The expected final-report content is:
86
89
 
87
90
  - evidence-backed cause analysis
88
91
  - uncertainty boundary
89
92
  - practical next diagnostic steps
90
93
  - if there is blocking uncertainty, `## 1. Clarification Items`, usually `Blocks=next-phase`
91
94
 
95
+ For `error-analysis`, the structured `errorAnalysis` object is the source of truth for the verbatim symptom, reproduction status, `EA-NNN` cause candidates and their counter-evidence, the next diagnostic, and routing. Its shape is enforced by `schemas/final-report-v1.0.schema.json` `$defs.ErrorAnalysis`; `validators/validate-run.py::_validate_error_analysis_consistency` enforces the cross-field semantics. A route to `implementation-planning` needs a credible referenced leading cause and `begin-planning`. A route back to `error-analysis` needs the sharp next diagnostic and `continue-investigation`.
96
+
92
97
  What is prohibited is source edit, refactor, fix attempt, implementation design artifact, and running build/migration/deploy. Deferring ambiguity that could be answered from code or logs to a user question is also a defect per the profile.
93
98
 
94
99
  ## 6. Code reviewed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okstra",
3
- "version": "0.142.0",
3
+ "version": "0.143.0",
4
4
  "description": "Multi-agent cross-verification orchestrator runtime + Claude Code skills.",
5
5
  "license": "MIT",
6
6
  "author": "devonshin",
@@ -1,5 +1,5 @@
1
1
  {
2
- "package": "0.142.0",
3
- "builtAt": "2026-07-31T06:10:23.526Z",
2
+ "package": "0.143.0",
3
+ "builtAt": "2026-08-02T11:16:25.811Z",
4
4
  "repoRoot": "/home/runner/work/okstra/okstra"
5
5
  }
@@ -95,6 +95,7 @@ Rules (the schema enforces most of these — they are listed here so you know *w
95
95
  - `header.reportAuthor` is `"Report writer worker"`; `header.reportOwner` is `"Claude lead"`. Set author to `"Claude lead"` only for `release-handoff` runs (single-lead by design) or a recorded report-writer dispatch failure fallback.
96
96
  - **Source items (worker:item) preservation.** Every `consensus[].sourceItems`, `differences[].workersPosition[].itemId`, and `evidence.primary[].sourceItems` entry MUST carry the worker:item-id pair (e.g. `claude:F-001`, `codex:1.1`, `antigravity:F-3`, or `lead:mcp-1` for lead-only evidence). The schema enforces this via the `SourceItem` regex; bare worker-name lists no longer parse.
97
97
  - **Verdict Card consistency.** `verdictCard.verdictToken` and `verdictCard.direction` MUST byte-match `finalVerdict.verdictToken` / `.direction`; `validators/validate-run.py` diffs both and fails the run on divergence. `verdictCard.nextStep` names the same action as `finalVerdict.nextStep` and `recommendedNextSteps[0].text` but is written as the actionable command the reader runs (e.g. `/okstra-run task-key=… task-type=release-handoff`) where the other two are prose — it is deliberately not a byte copy. Duplicating the compared values across `verdictCard` and `finalVerdict` is intentional so the validator can diff them.
98
+ - **Error-analysis diagnosis and routing.** When `header.taskType` is `error-analysis`, populate the required `errorAnalysis` object. Copy `errorAnalysis.symptomVerbatim` byte-for-byte from the symptom stated in the brief's `Source Material`; do not paraphrase it. Every `causeCandidates[]` row includes the full `supportingEvidence`, `falsifyingEvidenceChecked`, `confidence`, and `disproveWith` fields. Route `errorAnalysis.routing.nextTaskType=implementation-planning` with `direction=begin-planning`, or route `errorAnalysis.routing.nextTaskType=error-analysis` with `direction=continue-investigation`; no other pairing is valid. `verdictCard.nextStep`, `finalVerdict.nextStep`, the first `recommendedNextSteps` action and command, and the unique `followUpTasks` row whose `origin` is `phase-continuation` MUST all point to the same `errorAnalysis.routing.nextTaskType` target. The schema enforces only the presence of a `phase-continuation` row. Phase validation MUST enforce exact target agreement and uniqueness through `validators/validate-run.py::_validate_error_analysis_consistency`; until that check is implemented and executed, those semantics are contract requirements rather than enforced guarantees.
98
99
  - **Reader Summary.** Populate `readerSummary` when the schema excerpt exposes it. It is the human-first entrypoint for both Markdown and HTML: one sentence for the decision, one for the human action required, one for blockers, one for audit sections safe to skip on first read, and one runnable recommended command. Do not duplicate raw evidence tables here.
99
100
  - **External QA advisory.** A Tier 3 entry requiring `db`, `http`, or
100
101
  `external` may be non-PASS without changing approval or final verdict. Render
@@ -103,7 +104,7 @@ Rules (the schema enforces most of these — they are listed here so you know *w
103
104
  and add the exact rerun command to `recommendedNextSteps`. Never turn this
104
105
  advisory alone into a clarification, Acceptance Blocker, conditional
105
106
  acceptance condition, or blocked routing.
106
- - **§7 phase-continuation row (mandatory for non-terminal task-types).** When `header.taskType` is one of `requirements-discovery` / `implementation-planning` / `error-analysis` / `implementation` / `final-verification`, `followUpTasks` MUST contain at least one row whose `origin` is `phase-continuation`, `suggestedTaskType` equals the next phase (byte-identical to `finalVerdict.nextStep`'s referenced phase), `newTaskId` reuses the current task-id, `autoSpawn` is `"no"`, and `priority` is `"P0"`. For `release-handoff` runs, omit the phase-continuation row. Schema `allOf` clause enforces this via `contains`.
107
+ - **§7 phase-continuation row (mandatory for non-terminal task-types).** When `header.taskType` is one of `requirements-discovery` / `implementation-planning` / `error-analysis` / `implementation` / `final-verification`, `followUpTasks` MUST contain at least one row whose `origin` is `phase-continuation`, `newTaskId` reuses the current task-id, `autoSpawn` is `"no"`, and `priority` is `"P0"`. For `release-handoff` runs, omit the phase-continuation row. The schema `allOf` / `contains` clause enforces row presence, not exact route-target agreement or uniqueness; phase validation must enforce those error-analysis semantics as specified above.
107
108
  - **No deprecated sections.** The schema has no `4.5.8 User Approval Request` body field, no `4.5.9 Open Questions`, no `5.1 Additional Material Request`, no `5.2 User Confirmation Questions` — clarifications go under the unified `clarificationItems[]` array.
108
109
  - **Optional Section 0.** Include `clarificationCarryIn` ONLY when the lead's prompt provides a non-empty carry-in path. Omit the key entirely otherwise (do NOT set it to `null` or an empty object).
109
110
  - **Reading Confirmation** goes at `**Audit sidecar path:**` per the selected report-writer preamble's `Required reading` section — never in the data.json or the main worker-results file.
@@ -126,9 +126,9 @@ Read source files lazily:
126
126
 
127
127
  ### Brief Reporter-Confirmation Precondition (BLOCKING)
128
128
 
129
- After reading `task-brief.md`, extract the frontmatter `reporter-confirmations` field (`complete | partial | pending | skipped`) and apply the shared handling matrix in `prompts/profiles/_common-contract.md` "Brief handoff contract" → "Reporter confirmation precondition" — that block is the single authority on per-value semantics; do not re-derive them here.
129
+ After reading `task-brief.md`, extract the frontmatter `reporter-confirmations` field (`complete | partial | pending | skipped`) when present and apply the shared handling matrix in `prompts/profiles/_common-contract.md` "Brief handoff contract" → "Reporter confirmation precondition" — that block is the single authority on per-value semantics; do not re-derive them here.
130
130
 
131
- Loader-level flow control only: on `pending` (or field missing), emit `REPORTER_CONFIRMATION_PENDING` and STOP — do not invoke `team-contract` or any analyser; the operator must rerun `okstra-brief-gen` Step 6.5 before Phase 2 can start. Every other value proceeds to Step 5 (with the matrix's flags carried forward for the phase profile).
131
+ Loader-level defensive flow control only: on `pending`, emit `REPORTER_CONFIRMATION_PENDING` and STOP — do not invoke `team-contract` or any analyser, and do not write a final report. Regenerate the brief with `okstra-brief-gen` Step 6.5 and prepare a fresh run. A missing field is a legacy brief, not `pending`, and proceeds to Step 5. Current-format missing or invalid values are rejected during preparation, before a fresh run can reach this loader. Every other value proceeds to Step 5 with the matrix's flags carried forward for the phase profile.
132
132
 
133
133
  ## Step 5: Read Run Manifest and Team State
134
134
 
@@ -85,7 +85,10 @@ Read the worker result files generated in Phase 4/5 and extract individual findi
85
85
  - Only one worker confirms a finding → one single-source group.
86
86
  4. When grouping is ambiguous, prefer splitting over merging (avoid over-merging). Semantic matching, ticket-set equality, and evidence interpretation remain lead judgments; the engine does not perform fuzzy matching or decide whether evidence is credible.
87
87
  5. Write `runs/<task-type>/state/convergence-groups-<task-type>-<seq>.json`. Each group carries its `ticketIds`, `originWorker`, `originEvidence`, `discoveredBy`, and every `<worker>:<item-id>` source in `sourceItems`. When a live command or external read produced reproducible evidence, also include `evidenceArtifacts[]` with its `.okstra/` path, SHA-256 digest, command, and environment. The field is optional because historical or inaccessible evidence may not have a captured artifact. The lead and verifier MUST NOT infer live or external evidence from wording or keyword matching; they use the finding's explicit claim, provenance, and supplied artifacts. Include the resolved worker roster in order with functional `audience` values; do not derive scope from provider or model identity. The `audience` enum is a convergence role, not a phase label: every finding-producing worker uses `analysis` — an `implementation` run's verifiers included — and only the report author uses `report-writer`. There is no `implementation-verifier` audience here; map the verifier roster to `analysis`.
88
- 6. Do not write a queue or classification in this grouped-input artifact. `okstra convergence seed` deterministically marks multi-source groups `full-consensus` and puts only single-source groups in the working queue. Section 6 never enters the grouped input.
88
+ 6. Do not write a queue or classification in this grouped-input artifact. `okstra convergence seed` classifies Round 0 by mode:
89
+ - Collaborative mode: multi-source groups become `full-consensus` immediately; only single-source groups enter the working queue.
90
+ - Adversarial mode: every finding enters the working queue regardless of source count. Semantic grouping merges provenance only; it does not decide a finding is reliable.
91
+ Section 6 never enters the grouped input.
89
92
 
90
93
  ### Round 1-N: Re-verification Loop (queue-pruned)
91
94
 
@@ -208,7 +211,7 @@ ELSE:
208
211
 
209
212
  `contested` remains a **final classification only** (per §"Scope and Terminology"): a disputed finding is carried forward through intermediate rounds and labelled `contested` only at the last executed round. For `requirements-discovery` (`effectiveMaxRounds = 1`) the single round IS the last round, so a split-with-hard-refute finding is labelled `contested` in that one round. The final-classifier block of §"Convergence Algorithm" honours this: its first branch classifies an adversarially carried-forward finding `contested` regardless of the AGREE tally, so the two sections cannot assign the same finding different labels.
210
213
 
211
- Design intent: one `counter-evidence` refute denies a claim consensus (it cannot rise above `contested` however many others AGREE); a lone `burden-not-met` doubt does not sink an otherwise-surviving claim — only a majority of them does. When every non-discoverer refutes (all_others_disagree) the finding is worker-unique regardless of refute basis — only the discoverer still holds it. A SUPPLEMENT/caveat with zero disagrees lands partial-consensus, not full-consensus, because a caveat means the claim does not pass cleanly (unlike the collaborative classifier, where SUPPLEMENT counts as full agreement).
214
+ Design intent: one `counter-evidence` refute denies a claim consensus (it cannot rise above `contested` however many others AGREE); later-round agreement does not erase that refutation history. The only resolution that overrides prior `counter-evidence` is a later round where every non-discoverer non-error worker disagrees, producing `worker-unique`. A lone `burden-not-met` doubt does not sink an otherwise-surviving claim — only a majority of them does. When every non-discoverer refutes (all_others_disagree) the finding is worker-unique regardless of refute basis — only the discoverer still holds it. A SUPPLEMENT/caveat with zero disagrees lands partial-consensus, not full-consensus, because a caveat means the claim does not pass cleanly (unlike the collaborative classifier, where SUPPLEMENT counts as full agreement).
212
215
 
213
216
  ## Re-verification Dispatch
214
217
 
@@ -291,7 +291,7 @@ Skipping this file because "the real report is in `reports/`" is wrong. Both fil
291
291
 
292
292
  Section numbering follows `templates/reports/final-report.template.md` exactly — that file is the documentation SSOT for section names and ordering. For full body structure at authoring time, consult your run's **phase-stripped** `final-report-template.md` (the per-task-type instruction-set copy defined in Phase 6 dispatch item 10); the "copy that block verbatim" references below mean the §-block as it appears in that stripped copy, not a re-read of the full source.
293
293
 
294
- **Verdict Card (top-of-report, mandatory).** Render `## Verdict Card` between the report header and the (conditional) Approval block. Its `Verdict Token` / `Direction` / `Next Step` cells MUST byte-match the corresponding cells in `## 7. Final Verdict` and the first item of `## 3. Recommended Next Steps`. Divergence is `contract-violated`.
294
+ **Verdict Card (top-of-report, mandatory).** Render `## Verdict Card` between the report header and the (conditional) Approval block. Its `Verdict Token` and `Direction` cells MUST byte-match the corresponding cells in `## 7. Final Verdict`. Its `Next Step`, the final-verdict next step, and the first item of `## 3. Recommended Next Steps` MUST name the same route target, though the actionable command and prose need not be byte-identical. Divergence is `contract-violated`.
295
295
 
296
296
  **Background and Rationale (top-of-report, mandatory — every task-type).** Fill the data.json `rationale` object (rendered as `## Background and Rationale`, right after the Verdict Card). It is the reviewer-facing narrative that answers four questions, in order — write each as **prose**, not a table:
297
297
  - `motivation` — why we are doing this work (goal / context).
@@ -306,18 +306,19 @@ Every field MUST anchor its claim with at least one evidence reference — a `pa
306
306
  0. **Clarification Response Carried In** — render this `## 0.` heading ONLY when `{{CLARIFICATION_RESPONSE_RELATIVE_PATH}}` is non-empty. Walk every `C-*` row of the prior report's `## 1. Clarification Items` table, reconcile against new evidence, and record the outcome (`resolved` / `obsolete`) with citation before drafting the verdict. When no carry-in path was provided, OMIT the `## 0.` heading entirely — the validator fails an empty Section 0 stub. The lead calls `okstra incremental-scope` exactly once, combining answered-clarification stage impacts (`--impacted`) and changed PREP IDs (`--prep-items`); selected-option, Stage Map, or recommended-approach changes pass both CSVs empty to force full mode. Record that single decision JSON verbatim into `implementationPlanning.incrementalDecision` (`mode`, `reverifyStages`, `carryStages`, `reason`); the renderer emits the `### 0.1 Incremental Re-Verification Scope` audit block from it, and the validator fails an `incremental`-mode run whose Section 0 omits that block. In `incremental` mode this run's `planItems` MUST carry every plan-item id from the re-verified stages 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 — do not drop it here, tell the lead to abandon incremental and re-route to a FULL re-verification, because the carry merge only adds prior items and would resurrect the removed item's stale verdict. After authoring the current data.json, call `okstra incremental-carry`, passing the decision's `carryStages` CSV to `--carry-stages` and its `reverifyStages` CSV to `--reverify-stages`. A `CarryError` means the stage/PREP ownership contract is unsafe: discard the partial merged output and route the run through full re-verification; never publish a partially merged report.
307
307
  1. **Clarification Items** — single unified `C-*` table; column schema (4 columns with the short fields stacked in one record-meta cell), ID convention, and rerun behaviour are owned by `_common-contract.md §Clarification request policy` (SSOT). The deprecated `5.5.9 Open Questions` / `1.1 Additional Material Request` / `1.2 User Confirmation Questions` sub-sections are removed; the validator fails reports that reintroduce them.
308
308
  2. **Evidence and Detailed Analysis** — primary evidence rows (file path, line, snippet); secondary evidence / alternate interpretations. If `reference-expectations.md` lists explicit expected values, record match/gap per row.
309
+ - **Error-analysis diagnosis and routing.** When `header.taskType` is `error-analysis`, populate the required `errorAnalysis` object. Copy `errorAnalysis.symptomVerbatim` byte-for-byte from the symptom stated in the brief's `Source Material`; do not paraphrase it. Every `causeCandidates[]` row includes the full `supportingEvidence`, `falsifyingEvidenceChecked`, `confidence`, and `disproveWith` fields. Route `errorAnalysis.routing.nextTaskType=implementation-planning` with `direction=begin-planning`, or route `errorAnalysis.routing.nextTaskType=error-analysis` with `direction=continue-investigation`; no other pairing is valid. `verdictCard.nextStep`, `finalVerdict.nextStep`, the first `recommendedNextSteps` action and command, and the unique `followUpTasks` row whose `origin` is `phase-continuation` MUST all point to the same `errorAnalysis.routing.nextTaskType` target. The schema enforces only the presence of a `phase-continuation` row. Phase validation MUST enforce exact target agreement and uniqueness through `validators/validate-run.py::_validate_error_analysis_consistency`; until that check is implemented and executed, those semantics are contract requirements rather than enforced guarantees.
309
310
  3. **Recommended Next Steps** — prioritized actions. After Phase 7's follow-up spawner runs, append a row per newly created task-key (see "Phase 6 → Phase 7 execution sequence" above). **Approval-gate consistency:** when §1 carries any `Blocks: approval` row with `Status` ∈ {open, answered}, the Verdict Card `Next Step` and the first recommended step MUST point to the clarification rerun (`resume-clarification` of the SAME task-type) — never to "flip frontmatter `approved: true` → jump straight to `implementation`". Run-prep enforces this gate (`run.py _validate_approved_plan` fail-closes on those rows and on a blocking data.json `gateResult`), so a direct-implementation next-step is an instruction the reader cannot actually follow. **Cross-project pointer rule:** for cross-project dependencies (another repo / a different top-level deployment module / a published package), `crossProjectDependencies` (§5.4 Cross-Project Dependencies) is authoritative — do NOT duplicate that substance (prerequisite work / verification signals / handoff) into `recommendedNextSteps`; put only a one-line pointer to that section (no double-recording).
310
311
  4. **Follow-up Tasks** — auto-spawn-eligible table. Each row drives `okstra-spawn-followups.py`; see template §4 for the row schema.
311
312
  5. **Missing Information and Risks** — uncertain / "I don't know" items. `implementation-planning` adds §5.5 (see heading contract below); `release-handoff` adds §5.6.
312
313
  6. **Cross Verification Results** — 4 categories (Full / Partial / Contested / Worker-Unique) when convergence is enabled, per `convergence`. Prepend the Round History sub-table (columns: `Round | inputQueueSize | resolvedCount | carriedForwardCount | dispatches | skippedWorkers`) plus a `round2SkippedReason: <value>` note, pulled verbatim from `convergence-<task-type>-<seq>.json`. Empty contested list renders as `- No items lacking consensus.`. Convergence-disabled runs use the legacy Consensus/Differences format and omit the round table.
313
- 7. **Final Verdict** — `Direction` ∈ `continue-investigation` / `begin-implementation` / `approve` / `reject` / `hold`. **Verdict Token** is `not-applicable` for every task-type except `final-verification` — see "Final-verification verdict token contract" below for that case.
314
+ 7. **Final Verdict** — `Direction` ∈ `continue-investigation` / `begin-planning` / `begin-implementation` / `approve` / `reject` / `hold`. **Verdict Token** is `not-applicable` for every task-type except `final-verification` — see "Final-verification verdict token contract" below for that case.
314
315
 
315
316
  **§5.10 Fix History (data-presence gated).** When the run-manifest carries a `fixCycleId`, fill the data.json `fixCycle` block (`cycle` / `targetReport` / `symptom` / `runs`). Read the values from the task root's `history/fix-cycles.jsonl`: `cycle` MUST equal `fixCycleId`, `targetReport` / `symptom` come from that cycle's `opened` row, and `runs` lists its attached `run` rows (`taskType` / `runSeq` / `runManifest`). The validator (`validators/validate-run.py` → `_validate_fix_cycle`) fails the run when the block is missing or `fixCycle.cycle` does not match `fixCycleId`. When the run-manifest has no `fixCycleId`, OMIT the `fixCycle` block entirely — the renderer omits §5.10.
316
317
 
317
318
  ### Writing Guidelines
318
319
 
319
320
  - Write in Markdown. **Prefer tables over prose bullet lists** for any section that enumerates multiple items with the same shape (evidence rows, risks, options, dependencies, rollback steps, follow-ups, open questions). Bullets are reserved for short, single-line standalone statements (e.g., "- No additional information requested."). When the template provides a table form, do NOT degrade it back to bullets in the rendered report. **Exception — `## Background and Rationale` (`rationale`) is deliberately prose**: it is connected narrative explaining the *why*, not a same-shape enumeration, so write full sentences there rather than forcing it into a table.
320
- - **Do not restate the same conclusion verbatim across sections.** The Verdict Card and Reader Summary are *digests*: give the outcome in one or two sentences and point to `## 7. Final Verdict` / `## 5.8.8 Routing Recommendation` for the full reasoning, rather than copying their multi-clause conclusion word-for-word. Only the `Verdict Token` / `Direction` / `Next Step` cells must byte-match §7 (per the Verdict Card contract above); the prose conclusion must not be a duplicate.
321
+ - **Do not restate the same conclusion verbatim across sections.** The Verdict Card and Reader Summary are *digests*: give the outcome in one or two sentences and point to `## 7. Final Verdict` / `## 5.8.8 Routing Recommendation` for the full reasoning, rather than copying their multi-clause conclusion word-for-word. Only the `Verdict Token` and `Direction` cells must byte-match §7 (per the Verdict Card contract above). `Next Step` must point to the same routing target as §7, but its actionable command and prose need not be byte-identical. The prose conclusion must not be a duplicate.
321
322
  - **Keep each sentence to one main idea.** A single sentence that stacks four or five clauses with em-dashes and nested parentheticals (300+ characters) is hard to read, and the renderer can only line-break at sentence ends — so break such reasoning into separate sentences. Facts, evidence, and IDs still live in the tables; prose carries only the connective *why*.
322
323
  - Write the final report body in the language passed in **Report Language**
323
324
  above (`en` or `ko`). The template's fixed labels (section asides,
@@ -32,7 +32,9 @@ profile document.
32
32
  - `complete` → proceed normally.
33
33
  - `partial` → proceed; treat still-unmarked `intent-check:` / `conversion-block:` rows as the `skipped` branch.
34
34
  - `skipped` → do NOT silently infer the missing answers. Promote each unmarked `intent-check:` / `conversion-block:` row into this run's `## 1. Clarification Items` as `Kind=decision`. Use `Blocks=approval` in `implementation-planning`, where the row gates the `approved:` frontmatter flip; otherwise use `Blocks=next-phase`. The recommended answer is drawn from the brief's matching content and clearly labelled `reporter direct-confirmation recommended`.
35
- - `pending` (or field missing) ABORT analysis; render the Verdict Card with `Verdict Token = blocked` + `Direction = hold` and write a single `## Reporter Confirmation Required` block (no leading number) summarising which rows are pending. The `## 1. Clarification Items` table carries one row per pending item with `Blocks=approval` in `implementation-planning`, otherwise `Blocks=next-phase`. The operator must rerun `okstra-brief-gen` Step 6.5. Do NOT emit `## 0.` for this case — Section 0 is reserved for clarification-response carry-in only.
35
+ - Current-format `pending`, missing, or invalid values are rejected during task-bundle preparation, so they never reach a new run. A brief is current-format only when its frontmatter contains the `reporter-confirmations` key; its value, `type`, and `generator` are then validated together.
36
+ - Defensive upgrade path: if an already-prepared bundle contains `pending`, the context loader emits `REPORTER_CONFIRMATION_PENDING` and stops before worker or report-writer dispatch. It writes no final report. Regenerate the brief with `okstra-brief-gen` Step 6.5 and prepare a fresh run.
37
+ - A legacy brief with no `reporter-confirmations` field is not reinterpreted as `pending`; it keeps the compatibility path and proceeds without this reporter-confirmation gate.
36
38
  `[CONFIRMED <YYYY-MM-DD> → RC-N]` markers on `Open Questions` rows are the per-row signal that the reporter has answered; their answers live verbatim under `## Reporter Confirmations` in the brief.
37
39
  - `Source Material` is reporter-verbatim. Do NOT paraphrase, summarize, reorder, or restructure it. Quote it directly when needed.
38
40
  - `Related Task Graph` is the structured task-topology handoff. If the section is present and not `_(none)_`, read it before classification, diagnosis, candidate discovery, fan-out, or next-step routing. Preserve the edge direction exactly as written: `From` → `To` is load-bearing for `depends-on`, `blocks`, parent/child, follow-up, and split relations.
@@ -22,6 +22,10 @@
22
22
  - **Graph-aware scope:** a graph edge can explain ordering or duplication, but it is not proof of cause by itself. Cite code/log evidence before claiming an upstream related task caused the current symptom.
23
23
  - **Sharp next diagnostic:** end with the single highest-value diagnostic command, log capture, or file inspection that should happen next, plus the expected signal that would confirm or reject the leading cause.
24
24
  - **Fix-design boundary:** do not design the implementation fix beyond what is necessary to validate the cause. If the cause is credible, route to `implementation-planning` with the verified evidence; if the cause is still unclear, route to another `error-analysis` run with the next diagnostic.
25
+ - Structured diagnosis and routing contract:
26
+ - `errorAnalysis` is the source of truth for reproduction status, `EA-NNN` cause candidates, the sharp next diagnostic, and the next route.
27
+ - A route to `implementation-planning` requires a credible leading cause referenced by `routing.leadingCauseId` and `begin-planning` as the direction. A route back to `error-analysis` requires the sharp next diagnostic and `continue-investigation` as the direction.
28
+ - Structure is enforced by `schemas/final-report-v1.0.schema.json` `$defs.ErrorAnalysis`. Cross-field diagnosis and route semantics are enforced by `validators/validate-run.py::_validate_error_analysis_consistency`.
25
29
  - Primary focus areas:
26
30
  - symptom and trigger clarification
27
31
  - root-cause candidates
@@ -40,7 +44,7 @@
40
44
  - **Codebase-first ambiguity resolution (defect rule)**: any ambiguity about repro, file behavior, or symbol semantics that can be answered by `Read` / `Grep` / log inspection MUST be resolved that way and recorded with file:line (or log-line) evidence. Writing a clarification row for something the codebase or shipped logs already answer is a defect of this phase.
41
45
  - **Evidence note required inside `Statement`**: every clarification row includes `Evidence checked: <path:line>` or `Evidence checked: none — <reporter-only reason>` in the `Statement` cell. `none` is allowed ONLY when the row's nature is "only the reporter can answer this" (reporter-side data, business priority, environment they observed). A row with `none` that *could* have been answered by code or logs is a defect.
42
46
  - Cross-verification mode:
43
- - Phase 5.5 convergence runs in **adversarial mode** for this phase (`convergence.adversarial=true`). Verifiers actively try to refute each root-cause / reproduction claim by directly re-inspecting the cited code, logs, or config; the burden of proof sits on the claim. See `prompts/lead/convergence.md` §"Adversarial Verification Mode". A single evidence-backed refutation prevents a finding from reaching consensus.
47
+ - Phase 5.5 convergence runs in **adversarial mode** for this phase (`convergence.adversarial=true`). Verifiers actively try to refute each root-cause / reproduction claim by directly re-inspecting the cited code, logs, or config; the burden of proof sits on the claim. See `prompts/lead/convergence.md` §"Adversarial Verification Mode". Multi-source findings enter the adversarial queue rather than becoming automatic consensus. A single evidence-backed refutation prevents a finding from reaching consensus, remains in the round history, and cannot be erased into full consensus by later agreement.
44
48
  {{INCLUDE:_coverage-critic.md}}
45
49
  - Non-goals:
46
50
  - implementation details unless they are necessary to validate the cause
@@ -20,6 +20,27 @@ BRIEF_SECTIONS = (
20
20
  "Task Continuity Notes",
21
21
  "Available MCP Servers",
22
22
  )
23
+ ERROR_ANALYSIS_BRIEF_SECTIONS = (
24
+ "Source Material",
25
+ "Context",
26
+ "Problem / Symptom",
27
+ "Desired Outcome",
28
+ "Expected Behavior",
29
+ "Preserved Behavior",
30
+ "Expected Outcome",
31
+ "External Gates",
32
+ "Constraints",
33
+ "Scan Scope",
34
+ "Priority Lenses",
35
+ "Related Artifacts",
36
+ "Related Task Graph",
37
+ "Open Questions",
38
+ "Reporter Confirmations",
39
+ "Augmentation",
40
+ ) + BRIEF_SECTIONS
41
+ BRIEF_SECTIONS_BY_TASK_TYPE = {
42
+ "error-analysis": ERROR_ANALYSIS_BRIEF_SECTIONS,
43
+ }
23
44
  PROFILE_SECTIONS = (
24
45
  "Primary focus areas",
25
46
  "Expected output emphasis",
@@ -30,6 +51,7 @@ WORKER_PROFILE_SECTIONS_BY_TASK_TYPE = {
30
51
  "Worker discovery procedure",
31
52
  ),
32
53
  "error-analysis": (
54
+ "Brief consumption",
33
55
  "Worker diagnosis procedure",
34
56
  ),
35
57
  "implementation-planning": (
@@ -79,7 +101,7 @@ def build_analysis_packet(
79
101
  bool(clarification_response_path),
80
102
  )
81
103
  )
82
- parts.extend(_brief_block(brief_text))
104
+ parts.extend(_brief_block(task_type, brief_text))
83
105
  parts.extend(_profile_block(task_type, profile_text))
84
106
  parts.extend(_reference_block(reference_text))
85
107
  parts.extend(_fix_history_block(fix_history_text))
@@ -138,12 +160,15 @@ def _intro_block(
138
160
  return lines
139
161
 
140
162
 
141
- def _brief_block(brief_text: str) -> list[str]:
163
+ def _brief_block(task_type: str, brief_text: str) -> list[str]:
142
164
  return [
143
165
  "",
144
166
  "## Task-Specific Brief Extract",
145
167
  "",
146
- _extract_sections(brief_text, BRIEF_SECTIONS),
168
+ _extract_sections(
169
+ brief_text,
170
+ BRIEF_SECTIONS_BY_TASK_TYPE.get(task_type, BRIEF_SECTIONS),
171
+ ),
147
172
  ]
148
173
 
149
174
 
@@ -0,0 +1,56 @@
1
+ """Shared lightweight parser for brief markdown frontmatter."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from pathlib import Path
6
+ from typing import Mapping
7
+
8
+
9
+ _BRIEF_FRONTMATTER_LINE_RE = re.compile(r"^([a-zA-Z0-9_\-]+)\s*:\s*(.*)$")
10
+
11
+
12
+ def read_brief_frontmatter(path: Path) -> dict[str, str]:
13
+ """Read a brief's YAML-style frontmatter into a flat key-value map.
14
+
15
+ Returns ``{}`` if the file is unreadable, has no frontmatter, or the
16
+ frontmatter is malformed. Comments and quoted values are stripped.
17
+ """
18
+ try:
19
+ text = path.read_text(encoding="utf-8")
20
+ except OSError:
21
+ return {}
22
+ if not text.startswith("---"):
23
+ return {}
24
+ lines = text.splitlines()
25
+ if not lines or lines[0].strip() != "---":
26
+ return {}
27
+ out: dict[str, str] = {}
28
+ for line in lines[1:]:
29
+ if line.strip() == "---":
30
+ break
31
+ comment_idx = line.find("#")
32
+ if comment_idx >= 0:
33
+ line = line[:comment_idx]
34
+ match = _BRIEF_FRONTMATTER_LINE_RE.match(line.strip())
35
+ if not match:
36
+ continue
37
+ key, value = match.group(1), match.group(2).strip()
38
+ if (
39
+ len(value) >= 2
40
+ and value[0] == value[-1]
41
+ and value[0] in ("'", '"')
42
+ ):
43
+ value = value[1:-1]
44
+ out[key] = value
45
+ return out
46
+
47
+
48
+ def is_canonical_generated_brief(frontmatter: Mapping[str, str]) -> bool:
49
+ return (
50
+ frontmatter.get("type") == "brief"
51
+ and frontmatter.get("generator") == "okstra-brief-gen"
52
+ )
53
+
54
+
55
+ def has_reporter_confirmation_contract(frontmatter: Mapping[str, str]) -> bool:
56
+ return "reporter-confirmations" in frontmatter
@@ -78,7 +78,9 @@ def seed_working_state(grouped_input: Mapping[str, Any]) -> dict[str, Any]:
78
78
  state["stopReason"] = "auto-disabled"
79
79
  return state
80
80
 
81
- findings, queue = _parse_groups(source.get("groups"), analysis_workers)
81
+ findings, queue = _parse_groups(
82
+ source.get("groups"), analysis_workers, adversarial=config["adversarial"]
83
+ )
82
84
  state["findings"] = findings
83
85
  state["queueFindingIds"] = queue
84
86
  return state
@@ -206,6 +208,37 @@ def classify_adversarial_round(
206
208
  return "partial-consensus"
207
209
 
208
210
 
211
+ def _round_has_counter_evidence(
212
+ votes: Mapping[str, Mapping[str, Any]],
213
+ ) -> bool:
214
+ return any(
215
+ vote.get("verdict") == "disagree"
216
+ and vote.get("disagreeBasis") == "counter-evidence"
217
+ for vote in votes.values()
218
+ if isinstance(vote, Mapping)
219
+ )
220
+
221
+
222
+ def _classify_adversarial_history(
223
+ rounds: list[Mapping[str, Any]],
224
+ ) -> str | None:
225
+ """Classify adversarial rounds without erasing earlier counter-evidence."""
226
+ counter_evidence_seen = False
227
+ for row in rounds:
228
+ votes = row.get("votes") if isinstance(row, Mapping) else None
229
+ if not isinstance(votes, Mapping):
230
+ continue
231
+ counter_evidence_seen = (
232
+ counter_evidence_seen or _round_has_counter_evidence(votes)
233
+ )
234
+ classification = classify_adversarial_round(votes)
235
+ if classification == "worker-unique":
236
+ return classification
237
+ if classification is not None and not counter_evidence_seen:
238
+ return classification
239
+ return None
240
+
241
+
209
242
  def apply_round_results(
210
243
  state: Mapping[str, Any],
211
244
  plan: Mapping[str, Any],
@@ -251,7 +284,7 @@ def apply_round_results(
251
284
  {"round": expected_plan["round"], "votes": round_votes}
252
285
  )
253
286
  classification = (
254
- classify_adversarial_round(round_votes)
287
+ _classify_adversarial_history(finding["rounds"])
255
288
  if adversarial
256
289
  else classify_collaborative_round(round_votes)
257
290
  )
@@ -1321,20 +1354,21 @@ def _expected_final_classification(
1321
1354
  rounds = finding.get("rounds")
1322
1355
  if not isinstance(rounds, list) or not rounds:
1323
1356
  return None
1357
+ if adversarial:
1358
+ try:
1359
+ return _classify_adversarial_history(rounds) or "contested"
1360
+ except ConvergenceContractError:
1361
+ return "contested"
1324
1362
  for row in rounds:
1325
1363
  if not isinstance(row, Mapping) or not isinstance(row.get("votes"), Mapping):
1326
1364
  continue
1327
1365
  try:
1328
- resolved = (
1329
- classify_adversarial_round(row["votes"])
1330
- if adversarial
1331
- else classify_collaborative_round(row["votes"])
1332
- )
1366
+ resolved = classify_collaborative_round(row["votes"])
1333
1367
  except ConvergenceContractError:
1334
1368
  continue
1335
1369
  if resolved is not None:
1336
1370
  return resolved
1337
- return "contested" if adversarial else _final_collaborative_classification(finding)
1371
+ return _final_collaborative_classification(finding)
1338
1372
 
1339
1373
 
1340
1374
  def _validate_round_ledger_counts(
@@ -1347,7 +1381,7 @@ def _validate_round_ledger_counts(
1347
1381
  if not isinstance(history_row, Mapping):
1348
1382
  continue
1349
1383
  ledgers = _round_ledgers(findings, round_number)
1350
- resolved = _resolved_ledger_count(ledgers, adversarial)
1384
+ resolved = _resolved_ledger_count(findings, round_number, adversarial)
1351
1385
  expected = (len(ledgers), resolved, len(ledgers) - resolved)
1352
1386
  actual = (
1353
1387
  history_row.get("inputQueueSize"),
@@ -1381,17 +1415,32 @@ def _round_ledgers(
1381
1415
 
1382
1416
 
1383
1417
  def _resolved_ledger_count(
1384
- ledgers: list[Mapping[str, Any]],
1418
+ findings: list[Any],
1419
+ round_number: int,
1385
1420
  adversarial: bool,
1386
1421
  ) -> int:
1387
1422
  resolved = 0
1388
- for row in ledgers:
1389
- votes = row.get("votes")
1423
+ for finding in findings:
1424
+ rounds = finding.get("rounds") if isinstance(finding, Mapping) else None
1425
+ if not isinstance(rounds, list):
1426
+ continue
1427
+ current_rounds = [
1428
+ row
1429
+ for row in rounds
1430
+ if isinstance(row, Mapping)
1431
+ and isinstance(row.get("round"), int)
1432
+ and row["round"] <= round_number
1433
+ ]
1434
+ current = next(
1435
+ (row for row in current_rounds if row.get("round") == round_number),
1436
+ None,
1437
+ )
1438
+ votes = current.get("votes") if isinstance(current, Mapping) else None
1390
1439
  if not isinstance(votes, Mapping):
1391
1440
  continue
1392
1441
  try:
1393
1442
  classification = (
1394
- classify_adversarial_round(votes)
1443
+ _classify_adversarial_history(current_rounds)
1395
1444
  if adversarial
1396
1445
  else classify_collaborative_round(votes)
1397
1446
  )
@@ -1486,7 +1535,7 @@ def _validate_no_reappearance_after_resolution(
1486
1535
  continue
1487
1536
  try:
1488
1537
  classification = (
1489
- classify_adversarial_round(votes)
1538
+ _classify_adversarial_history(rounds[: index + 1])
1490
1539
  if adversarial
1491
1540
  else classify_collaborative_round(votes)
1492
1541
  )
@@ -1842,6 +1891,8 @@ def _parse_workers(value: Any) -> list[dict[str, str]]:
1842
1891
  def _parse_groups(
1843
1892
  value: Any,
1844
1893
  analysis_workers: list[str],
1894
+ *,
1895
+ adversarial: bool,
1845
1896
  ) -> tuple[list[dict[str, Any]], list[str]]:
1846
1897
  if not isinstance(value, list):
1847
1898
  raise ConvergenceContractError("groups must be an array")
@@ -1855,7 +1906,7 @@ def _parse_groups(
1855
1906
  raise ConvergenceContractError(f"duplicate findingId: {finding_id}")
1856
1907
  seen_ids.add(finding_id)
1857
1908
  finding, source_workers = _parse_group(group, index, analysis_workers)
1858
- if len(source_workers) >= 2:
1909
+ if len(source_workers) >= 2 and not adversarial:
1859
1910
  finding["classification"] = "full-consensus"
1860
1911
  else:
1861
1912
  queue.append(finding_id)