okstra 0.225.1 → 0.227.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 (99) hide show
  1. package/README.md +1 -0
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.mjs +5 -0
  5. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  6. package/dist/commands/execute/wizard.mjs +12 -15
  7. package/dist/commands/execute/wizard.mjs.map +1 -1
  8. package/docs/cli.md +46 -6
  9. package/docs/project-structure-overview.md +3 -1
  10. package/package.json +1 -1
  11. package/runtime/BUILD.json +2 -2
  12. package/runtime/agents/operations/code-review.json +1 -1
  13. package/runtime/bin/lib/okstra/cli.sh +5 -1
  14. package/runtime/bin/lib/okstra/globals.sh +1 -0
  15. package/runtime/bin/lib/okstra/usage.sh +3 -0
  16. package/runtime/bin/okstra.sh +2 -0
  17. package/runtime/prompts/duties/technical-verification-worker.json +2 -1
  18. package/runtime/prompts/lead/convergence.md +4 -1
  19. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  20. package/runtime/prompts/lead/phase-routing.md +7 -3
  21. package/runtime/prompts/lead/team-contract.md +1 -1
  22. package/runtime/prompts/wizard/prompts.ko.json +59 -0
  23. package/runtime/python/okstra_ctl/adapters/providers/codex/adapter.py +5 -0
  24. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +63 -0
  25. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +3 -0
  26. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +5 -0
  27. package/runtime/python/okstra_ctl/analysis_packet.py +108 -2
  28. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +206 -0
  29. package/runtime/python/okstra_ctl/brief_sources.py +200 -0
  30. package/runtime/python/okstra_ctl/business_flow/store.py +15 -2
  31. package/runtime/python/okstra_ctl/cmux.py +18 -3
  32. package/runtime/python/okstra_ctl/code_review_coverage.py +70 -18
  33. package/runtime/python/okstra_ctl/code_review_target.py +77 -53
  34. package/runtime/python/okstra_ctl/convergence_critic_prompt.py +4 -1
  35. package/runtime/python/okstra_ctl/correction_cli.py +6 -5
  36. package/runtime/python/okstra_ctl/correction_round.py +1 -1
  37. package/runtime/python/okstra_ctl/design_surfaces.py +19 -7
  38. package/runtime/python/okstra_ctl/domain/worker_defaults.py +106 -0
  39. package/runtime/python/okstra_ctl/execution_mutation_audit.py +20 -18
  40. package/runtime/python/okstra_ctl/file_size_cap.py +56 -6
  41. package/runtime/python/okstra_ctl/implementation_direction.py +10 -0
  42. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +41 -0
  43. package/runtime/python/okstra_ctl/manager_split.py +185 -27
  44. package/runtime/python/okstra_ctl/next_phase.py +3 -1
  45. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +128 -0
  46. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +8 -5
  47. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +1 -1
  48. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +84 -0
  49. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +2 -2
  50. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +2 -2
  51. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +2 -2
  53. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +13 -5
  54. package/runtime/python/okstra_ctl/phases/implementation_option_selection/boundary.json +1 -1
  55. package/runtime/python/okstra_ctl/phases/implementation_option_selection/entry.py +67 -0
  56. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +4 -2
  57. package/runtime/python/okstra_ctl/phases/implementation_option_selection/report_assets/implementation-option-selection.template.html +2 -1
  58. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +127 -18
  59. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +22 -0
  60. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  61. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +2 -1
  62. package/runtime/python/okstra_ctl/phases/technical_verification/profile.md +2 -2
  63. package/runtime/python/okstra_ctl/ports/worker_defaults.py +25 -0
  64. package/runtime/python/okstra_ctl/registry/worker_defaults_store.py +8 -0
  65. package/runtime/python/okstra_ctl/report_assembly.py +23 -2
  66. package/runtime/python/okstra_ctl/report_views.py +2 -1
  67. package/runtime/python/okstra_ctl/run.py +61 -2
  68. package/runtime/python/okstra_ctl/run_context.py +13 -8
  69. package/runtime/python/okstra_ctl/stage_done.py +5 -4
  70. package/runtime/python/okstra_ctl/wizard/cli.py +16 -4
  71. package/runtime/python/okstra_ctl/wizard/confirmation.py +27 -0
  72. package/runtime/python/okstra_ctl/wizard/engine.py +25 -3
  73. package/runtime/python/okstra_ctl/wizard/ids.py +29 -0
  74. package/runtime/python/okstra_ctl/wizard/registry.py +21 -0
  75. package/runtime/python/okstra_ctl/wizard/render.py +6 -2
  76. package/runtime/python/okstra_ctl/wizard/roles.py +73 -23
  77. package/runtime/python/okstra_ctl/wizard/sources.py +33 -11
  78. package/runtime/python/okstra_ctl/wizard/state.py +59 -14
  79. package/runtime/python/okstra_ctl/wizard/steps_options.py +74 -9
  80. package/runtime/python/okstra_ctl/wizard/steps_roles.py +5 -3
  81. package/runtime/python/okstra_ctl/wizard/worker_settings.py +334 -0
  82. package/runtime/python/okstra_ctl/worker_defaults.py +135 -0
  83. package/runtime/python/okstra_ctl/worker_prompt_body.py +21 -1
  84. package/runtime/python/okstra_ctl/worker_prompt_headers.py +11 -4
  85. package/runtime/python/okstra_ctl/worker_prompt_policy.py +3 -0
  86. package/runtime/python/okstra_ctl/write_policy.py +33 -18
  87. package/runtime/schemas/final-report-v2.0.schema.json +74 -0
  88. package/runtime/schemas/final-report-v3.0.schema.json +99 -2
  89. package/runtime/skills/okstra-brief-gen/SKILL.md +26 -0
  90. package/runtime/skills/okstra-code-review/SKILL.md +25 -23
  91. package/runtime/skills/okstra-code-review/references/review-calibration.md +2 -2
  92. package/runtime/skills/okstra-manager/SKILL.md +15 -2
  93. package/runtime/skills/okstra-run/SKILL.md +21 -1
  94. package/runtime/templates/reports/brief.template.md +10 -1
  95. package/runtime/templates/reports/html/i18n/en.json +8 -0
  96. package/runtime/templates/reports/html/i18n/ko.json +8 -0
  97. package/runtime/templates/worker-prompt-preamble.md +1 -1
  98. package/runtime/validators/validate-brief.py +39 -1
  99. package/runtime/validators/validate-run.py +5 -0
@@ -52,7 +52,7 @@ template's check; that template is gone.
52
52
  - **External-source adapters — structure AND fixture both derive from a captured real sample; a self-authored fixture is NOT reality evidence:** when this run's diff builds or changes an `external-interface` or `transformation-mapping` surface (an HTTP / network client, or a parser / mapper of a third-party payload — HTML / JSON / XML / CSV originating outside this repo), the adapter's structural assumptions (selectors, field paths, expected response shape) AND the static fixture / golden that tests them MUST BOTH derive from a **captured real sample** of that payload — the capture cited in the stage's `external-interface` / `transformation-mapping` design-prep item, or one captured this run and recorded with its `source` + capture time. The captured sample is a static fixture (no live socket), so a parser test against it stays in source like any unit test — the Real-IO isolation rule below governs *live* calls, not the captured bytes. Do NOT hand-invent the shape and then hand-write a fixture that agrees with it: the passing test then only proves the code matches your assumption, never that the assumption matches reality (self-confirming oracle — the observed failure was a parser whose selectors existed in its synthetic fixture and in zero real pages: hundreds of green units over a fiction, and the whole structure built on the wrong shape). When no real sample is reachable (no network this run, or the brief supplied none), do NOT synthesize a stand-in and present its green tests as correctness: mark the adapter's shape `reality-unverified (no captured sample)` in `Validation evidence`, keep any placeholder fixture explicitly labelled an assumption (never validation evidence), and surface an explicit **user-owned** item in the routing recommendation to confirm against real data. Unlike the DB gate above this does NOT itself block acceptance — live external verification stays a user-owned item per `final-verification`'s External QA advisory policy — but a synthetic external fixture presented as reality-verified is exactly the mock-only external evidence the `final-verification` test-correctness pass is meant to reject.
53
53
  - **Real-IO test isolation (BLOCKING).** A test that exercises a **real** datastore, HTTP endpoint, external service, message queue, or filesystem — a live DB connection / DSN, a real `fetch` / `axios` / `http` request, an actual S3 / queue client, anything the project's normal CI test suite cannot run because that backend is absent — MUST be written under the task's qa scripts directory `<task_root>/qa/scripts/` (`<TASK_QA_PATH>/scripts`; the `qa/` root itself holds only data sidecars — the Tier 3 conformance manifest and `result-*.json`). It MUST NOT be written into the project source test tree — `src/**`, `test/**`, `tests/**`, `**/__test__/**`, `**/__tests__/**`, `*.spec.*`, `*.test.*`, or anywhere the project's lint/test globs collect. Two reasons: (a) the project's CI / normal suite has no real DB or network, so a real-IO test placed in source silently breaks the pipeline; (b) it is an okstra verification artifact, and the artifact-home rule confines okstra outputs to `.okstra/`. **The dividing line is the IO, not the intent:** a unit test that stubs/spies only *injected collaborators* (mock — no real socket, no real DB handle) is a TDD red-green artifact and stays in source; the moment a test opens a real connection or makes a real network call it belongs in qa. A stage's real-IO requirement check is a Tier 3 conformance script under `<task_root>/qa/scripts/` (declared via the implementation-planning conformance entry) — never smuggle real IO into a `*.spec.*` in source to make it run "as a unit test". The `db-test` real-execution gate above is satisfied by the conformance/db-test path against the replica, NOT by adding a live-DB `*.spec.*` to the project suite. **Author qa specs with the project's own test framework — never hand-roll `describe`/`it`/`expect`.** When the project ships a test runner as a devDependency (jest / vitest / pytest …), the qa spec uses it, invoked with the project config plus a discovery override pointing at the qa scripts dir (jest: `npx jest --config <project jest config> --roots <task_root>/qa/scripts --runInBand <spec-name>`) — the project config keeps module aliases resolving while the default sweep never collects the file; never widen the project's own test config to include qa paths. For TypeScript qa specs also write `<task_root>/qa/scripts/tsconfig.json` (`extends` the project tsconfig, adds the runner's `types` entry, `"include": ["**/*.ts"]`) so editors resolve path aliases and test globals — it is a qa artifact like the rest (untracked). **These qa artifacts stay untracked — never commit them.** `.okstra/**` is gitignored (the artifact-home rule); conformance scripts and their results are *executed* and recorded in the carry sidecar / verifier result, never written into git history. A committed `.okstra/qa` file is a stage-branch defect that leaks okstra internals into the eventual PR (see the `git add` rules below).
54
54
  - **Stage conformance script (BLOCKING when the approved plan declared `Conformance tests:`).** Planning only declared the path and `requires`. This run MUST write the script to that path under `<task_root>/qa/scripts/` and add the matching `<task_root>/qa/conformance-manifest.json` entry: `stageKey` (= `<task-id>-stage-<N>`), `script`, `runCommand`, `requirementIds`, `requires` (the set the plan declared, widened by any db/io/http/external surface this stage's diff touches that the plan left out — never narrowed; `validate-run.py` `_declared_conformance_errors` accepts a superset and rejects a subset), `passContract`, `exemption: null`, `waiver: null`. Do not skip this when the plan declared tests. If the plan declared `Conformance exemption:`, do not invent a script — with one exception: when this stage's diff touches a db/io/http/external surface the exemption promised it would not (the verifier's diff-surface cross-check names the surface), write the script and the manifest entry for this stage exactly as for a declared stage, with `requires` covering those surfaces. The approved plan is not rewritten; `validate-run.py` `_declared_conformance_errors` accepts an entry for a stage the plan exempted and still rejects one for a stage the plan does not have. The script's standard interface: a `main` that exits `0`=PASS / non-zero=FAIL, and whose stdout ends with `QA-RESULT: PASS|FAIL` followed by one `REQ <id>: PASS|FAIL: <reason>` line per requirement. The verifier runs `runCommand` from the **worktree cwd**, and that cwd is the tree under test. `runCommand` MUST NOT repoint it: a leading `cd <checkout> &&` sends the script at a tree without this stage's changes. Absolute paths are fine and usually necessary — the script and its `tsconfig` live under `<task_root>/qa/scripts/`, i.e. under `.okstra/`, and a worktree does not carry `.okstra/`. Point at those by absolute path; leave the cwd alone. **Enforced:** `scripts/okstra_ctl/conformance.py` `_check_entry` rejects a `runCommand` whose first word in any `&&` / `;` segment changes directory; `validators/validate-run.py` `_validate_conformance` fails the run if the inherited declaration has no script file.
55
- - read the approved plan at this prompt's `**Approved plan:**` anchor end-to-end and parse the `## 5.5 Stage Map`. Read this prompt's `**Stage for this implementation run:**` anchor: the single stage number this run owns. The runtime already selected and reserved this stage (one run = one stage) — do NOT recompute the start stage from `consumers.jsonl`. Both anchors are generated headers; when either is missing, stop and report `contract-violated` rather than inferring the value.
55
+ - read the stage extract at this prompt's `**Approved plan stage extract:**` anchor end-to-end. It is the approved plan projected onto this run's stage: the whole Stage Map (`stageMap`), this stage's entry, the requirement-coverage, validation, rollback and risk rows that name this stage or name no stage, each with the `planItemId` (`P-Val-4`, `P-Rb-2`) directives cite it by, and the clarification items. Its `omitted` object names everything left out and why. The plan at the `**Approved plan:**` anchor stays the source of record: open it only for a targeted lookup of a key the extract omits, never end-to-end. When the prompt has no extract anchor (a Markdown plan, or a prompt published before the extract existed), read the approved plan end-to-end and parse its Stage Map instead. Read this prompt's `**Stage for this implementation run:**` anchor: the single stage number this run owns. The runtime already selected and reserved this stage (one run = one stage) — do NOT recompute the start stage from `consumers.jsonl`. Both anchors are generated headers; when either is missing, stop and report `contract-violated` rather than inferring the value.
56
56
  - load every `runs/<plan-key>/carry/stage-<i>.json` for `i ∈ depends-on(this stage)` and inject them into the executor's working context as "runtime carry-in". For a `depends-on (none)` stage, no sidecar load — task-brief only.
57
57
  - this stage's `depends-on` are all already `status:done`. Its file list, step order, Stage Validation commands, Stage Exit Contract, and rollback path are the authoritative scope.
58
58
  - **Clarification answers carried in (read before the first edit):** when the user answered the approved plan's `## 1. Clarification Items` rows, those answers arrive with this prompt under the heading `# Clarification answers carried in (authoritative)`, or as the `Clarification response` path under `## Inputs`. Treat each answer as an authoritative refinement of the plan's scope for the matching row; an answer that contradicts or expands the approved scope beyond the plan is a re-plan trigger (route to a new `implementation-planning` run), not a silent in-run change.
@@ -92,7 +92,7 @@ template's check; that template is gone.
92
92
  The file MUST NOT exist before the run starts (overwrite is refused — see `--force-stage` non-goal). **Enforced:** `validators/validate-run.py` `_validate_stage_carry_sidecar_exists` fails a run that declares `stageSidecarEvidence` without the file on disk. Transcribing the JSON into the report is not the same as writing it: `consumers` treats the carry file as the source of truth for marking the stage `done`, so a missing file leaves the stage permanently incomplete and blocks every dependent stage with a `PrepareError` — while this run reports success.
93
93
  - **Verifier gates are not yours to run (BLOCKING).** The self-mock detector (`validators/detect_self_mock.py`) belongs to the implementation verifier and is never delegated to you (`_implementation-verifier.md` §"Self-mock detection"). The coding-conventions preflight names it as the enforcement behind the no-self-mocking principle — that names who will check your diff, not a command for you to run. You MUST NOT invoke it and MUST NOT write `<task_root>/qa/self-mock-*.json`; running it early does not pre-satisfy the gate, because the verifier runs it again under its own duty. **Enforced:** that sidecar is not among the paths your attempt's `writePolicy.artifactPolicy.allowedPaths` carries, so the write audit closes the attempt as `error` with `artifact-root change exceeds batch policy union` (`scripts/okstra_ctl/execution_mutation_audit.py`) — a stage whose every gate passed still lands as a failed run. The same holds for the conformance results `<task_root>/qa/result-*.json`: you may run a conformance script to check your work — a baseline capture or `--compare` target goes under `<task_root>/qa/baseline/` and anything else it writes (build logs, measurements) under `<task_root>/qa/output/`, the only qa directories besides `qa/scripts/` your attempt may write — but the verifier records every result, including an earlier stage's result that your rewrite of its script made stale. When the approved plan tells you to write one, leave it and name it in your result as a plan step the verifier owns.
94
94
  - **An external Tier 3 non-PASS does NOT withhold the carry evidence.** A Tier 3 entry whose `requires` include `http`, `external`, or `db` is advisory. Its FAIL, MISSING, no result, startup failure, or credential / network / service absence gets recorded honestly — exact command, exit code, output tail, marked `ADVISORY` in `Validation evidence` — and you emit the carry evidence anyway. Only Tier 1 and Tier 2 failures withhold it. Withholding on an external result is what actually blocks the stage: the carry file is the only thing that can mark a stage `done`, the verifier re-runs that same command from the host (where a call your sandbox could not complete often passes), and a stage the verifier then PASSes can never be closed because its evidence was never written.
95
- - **File size: aim for 300 lines, never exceed 400 (BLOCKING at 400).** Each threshold is broken the same three ways — a new file over it, an existing file taken past it, a file already over it that grows by any net line — counted in physical lines. Breaking 400 is a blocking finding; breaking only 300 is an advisory recommendation the verifiers record. Put a new responsibility — a group of functions, a class, a `describe` block — in a new module or test file beside the existing one instead of appending, and when a file would pass 400, split it by responsibility; never compress code or drop comments to meet the number. Lockfiles, data (JSON / YAML), Markdown, fixtures, snapshots, generated and vendored files are exempt, as are languages okstra has no coding preflight for. Check with `okstra correction file-size --base <stage-base>` before you emit the carry evidence; it writes nothing, so you may run it. **Enforced:** every verifier runs the same command and reports each `FILE-SIZE:` line (400) as a blocking finding and each `FILE-SIZE-ADVISORY:` line (300) as a recommendation, and `okstra stage-done` (`scripts/okstra_ctl/stage_done.py` `_check_file_size`) refuses to settle a stage whose carry range still breaks 400, so the stage goes to a correction round.
95
+ - **File size: aim for 300 lines, never take a file past 500 (BLOCKING at 500).** The 500 limit is broken by a new file over it or an existing file taken from 500 or fewer past it; the 300 target is broken those two ways and by a file already over it that grows by any net line, including a file already over 500 at the stage base. Lines are physical lines. Breaking 500 is a blocking finding; breaking only 300 is an advisory recommendation the verifiers record. Put a new responsibility — a group of functions, a class, a `describe` block — in a new module or test file beside the existing one instead of appending, and when a file would pass 500, split it by responsibility; never compress code or drop comments to meet the number. Lockfiles, data (JSON / YAML), Markdown, fixtures, snapshots, generated and vendored files are exempt, as are languages okstra has no coding preflight for. Check with `okstra correction file-size --base <stage-base>` before you emit the carry evidence; it writes nothing, so you may run it. **Enforced:** every verifier runs the same command and reports each `FILE-SIZE:` line (500) as a blocking finding and each `FILE-SIZE-ADVISORY:` line (300) as a recommendation, and `okstra stage-done` (`scripts/okstra_ctl/stage_done.py` `_check_file_size`) refuses to settle a stage whose carry range still breaks 500, so the stage goes to a correction round.
96
96
  - **Reverse link (BLOCKING).** The runtime already appended a `status:"started"` row for this stage before the run began. The terminal row belongs to the lead's post-stage persistence and is verdict-gated — `status:"done"` with `carry_path` on a non-`FAIL` verdict, `status:"failed"` on `FAIL` (`_implementation-deliverable.md` §"Lead post-stage persistence").
97
97
  - **No PR / push in this phase.** This run produces local commits, carry sidecar evidence, verifier results, and the implementation final report only. Push and PR creation belong exclusively to the later `release-handoff` phase after `final-verification` returns `accepted`.
98
98
 
@@ -17,7 +17,7 @@ fails, fix it or surface the violation — do not claim done on a failing item.
17
17
 
18
18
  - diff-review done: the `Pre-commit diff review sweep` ran over the full diff and its `Coverage:` footer is in your audit sidecar — every changed file named, with each applied rule set carrying its outcome (`clean` or `fixed <n>`). No footer, or entries with no outcome → the sweep is unfinished; do not claim done.
19
19
  - functions: every new/edited function ≤50 effective lines, single purpose — cite the longest function's actual line count, not "all under 50"
20
- - file size: no source or test file this diff adds or grows ends over 400 physical lines, and no file already over 400 grew — paste the output of `okstra correction file-size --base <stage-base>`; it must end `QA-RESULT: PASS`. Aim for 300: for each `FILE-SIZE-ADVISORY:` line it prints, split the file or say why not. A responsibility that would push a file over goes into its own new module or test file
20
+ - file size: no source or test file this diff adds ends over 500 physical lines, and no file at 500 or fewer at the stage base ends over 500 (a file already over 500 may grow; that is advisory) — paste the output of `okstra correction file-size --base <stage-base>`; it must end `QA-RESULT: PASS`. Aim for 300: for each `FILE-SIZE-ADVISORY:` line it prints, split the file or say why not. A responsibility that would push a file over goes into its own new module or test file
21
21
  - conventions: applied the routed pack + project patterns (name which ones)
22
22
  - names & comments: names say what, comments say why; no obvious-restatement comments; no truthful-name violations
23
23
  - verification: ran the actual build/test — paste the exact command line and its real exit code / output tail, never a paraphrased "tests pass"
@@ -214,9 +214,9 @@ Re-running commands proves the diff *builds and passes*; it does NOT prove the d
214
214
  - **Non-separating test data:** two scenarios whose setup values and assertions are identical, so a wrong implementation passes both; or new test tooling added in this diff (mock, state setter, repository branch) that no test calls.
215
215
  - **Effect claimed under its own mock:** a test presented as covering an effect whose producing path is replaced by a mock inside that same test. The mock's presence in the harness is not evidence the branch behind it works.
216
216
  - **Single-caller abstraction (KISS):** an abstraction layer this diff introduces — a helper module, a strategy / factory / builder, an indirection or wrapper layer, an interface or abstract base — that has exactly one caller after the change, where inlining it at that call site would be simpler. The rule is `overview.md` core principle 2: name the second caller now, or inline. Four exits are legitimate and each must **cite its evidence**: the approved plan declares it (a `testSeams[]` boundary or a variation-point extraction — cite the plan step); the project declares `architecture.style = hexagonal` and this is a port at the domain boundary (a port with one adapter is the normal shape, not a violation); it breaks a real import cycle (name both modules); or its single caller is the public API of a published package. Absent one of those, cite `path:line` and recommend the inlined shape. Do NOT raise this on a function extracted purely to bring a body under the 50-line cap — that is principle 5 doing its job — nor on a pre-existing abstraction this diff merely edits.
217
- - **File-size limit (every verifier, not only the stage QA owner):** run `okstra correction file-size --base <base>` from the worktree cwd and log it in the `Read-only command log`. Each `FILE-SIZE:<path>:401 <before>-><after>` line it prints is a blocking finding cited exactly as printed — a new file over 400 lines, a file the diff took past 400, or a file already over 400 the diff grew. Recommended fix: move whole responsibilities into new modules or test files beside it. The command writes nothing and its result is the same for every verifier, so the finding converges and the lead sends it to a correction round. Each `FILE-SIZE-ADVISORY:<path>:301` line (the 300-line target, same three conditions) goes under the advisory findings below, not here. Do not judge size yourself: a file it does not print is not a finding (lockfiles, data, Markdown, fixtures, snapshots, generated files and languages without a coding preflight are exempt by `scripts/okstra_ctl/file_size_cap.py` `capped_path`).
217
+ - **File-size limit (every verifier, not only the stage QA owner):** run `okstra correction file-size --base <base>` from the worktree cwd and log it in the `Read-only command log`. Each `FILE-SIZE:<path>:501 <before>-><after>` line it prints is a blocking finding cited exactly as printed — a new file over 500 lines, or a file the diff took from 500 or fewer past 500. A file already over 500 at the stage base that the diff grows is not blocking; the command prints it as an advisory line. Recommended fix: move whole responsibilities into new modules or test files beside it. The command writes nothing and its result is the same for every verifier, so the finding converges and the lead sends it to a correction round. Each `FILE-SIZE-ADVISORY:<path>:301` line (the 300-line target: a new file over 300, a file the diff took past 300, or a file already over 300 the diff grew, including one already over 500) goes under the advisory findings below, not here. Do not judge size yourself: a file it does not print is not a finding (lockfiles, data, Markdown, fixtures, snapshots, generated files and languages without a coding preflight are exempt by `scripts/okstra_ctl/file_size_cap.py` `capped_path`).
218
218
  - **Caller-less identifier (YAGNI / orphan):** an identifier this diff leaves with zero callers — either newly added and never called (a speculative parameter, an optional config object, a "future-proof" hook, an exported helper whose only caller is hypothetical), or pre-existing code orphaned because this diff removed its last caller. Grep the identifier across the whole repository rather than the diff alone; a hit inside its own declaration, its own test, or a commented-out line is not a caller. Two exits are legitimate and must be **stated with their evidence**, never assumed: an identifier the approved plan reserves for a named later stage (cite the plan step), and a contract point something other than project code calls (a framework entrypoint, an implemented interface method, a migration hook, the public API of a published package — cite the caller or the registration). Anything else is work no requirement asked for: recommend deleting it, or folding an added parameter back into its single call site. A caller-less identifier is the one YAGNI violation that survives a green pipeline unchanged, which is why it grades here rather than as a recommendation.
219
- - **Advisory findings (recorded as recommendations; verdict MAY still PASS):** each `FILE-SIZE-ADVISORY:` line from the file-size command (a file over the 300-line target but within 400), function >50 effective lines, a single body mixing read+write stages, weak readability, a missing-but-non-critical outcome assertion, weak-but-not-misleading names, priority-between-inputs policy inlined in a service condition instead of a named domain function, an error message asserting a cause the code never observed, a memory / concurrency / batching change with no test pinning the bound it claims, or (hexagonal overlay only) a service dependency this diff adds or modifies that injects a concrete adapter instead of a port — record it with the port sketch; advisory only while the project has not declared `architecture.style = hexagonal`, since that declaration — and only that one — promotes exactly this item to blocking per the declared-style bullet above, while a declared `layered` binds dependency direction instead and leaves this item advisory; an existing convention of concrete injections does not convert this one to `clean`, it is the debt the rule pays down. These land in the verifier result as `should-fix` / `nit` recommendations, not as a `FAIL`.
219
+ - **Advisory findings (recorded as recommendations; verdict MAY still PASS):** each `FILE-SIZE-ADVISORY:` line from the file-size command (a file over the 300-line target but within 500), function >50 effective lines, a single body mixing read+write stages, weak readability, a missing-but-non-critical outcome assertion, weak-but-not-misleading names, priority-between-inputs policy inlined in a service condition instead of a named domain function, an error message asserting a cause the code never observed, a memory / concurrency / batching change with no test pinning the bound it claims, or (hexagonal overlay only) a service dependency this diff adds or modifies that injects a concrete adapter instead of a port — record it with the port sketch; advisory only while the project has not declared `architecture.style = hexagonal`, since that declaration — and only that one — promotes exactly this item to blocking per the declared-style bullet above, while a declared `layered` binds dependency direction instead and leaves this item advisory; an existing convention of concrete injections does not convert this one to `clean`, it is the debt the rule pays down. These land in the verifier result as `should-fix` / `nit` recommendations, not as a `FAIL`.
220
220
  - **Output.** Every finding — blocking or advisory — is a structured item in the verifier's worker result (`path:line`, rule, severity, suggested fix) so it carries into Phase 5.5 convergence and the final report. A blocking hit sets the verifier verdict to `FAIL` with the rule cited, using the same verdict machinery as the Discrepancy rule above. The Okstra lead MUST NOT silently downgrade a cited blocking finding to advisory during synthesis; an override requires a concrete cited reason, exactly as for the Discrepancy rule.
221
221
 
222
222
  ### Fix-run incremental scope (applies when the profile carries a "Fix-Run Carry" block)
@@ -52,12 +52,18 @@ def requirement_instructions(original_requirement_ids: Sequence[str], participat
52
52
  "A ranked option is valid only when every participating analyser "
53
53
  "supplied one feasibility vote, at least "
54
54
  f"{required_feasible_votes(participating_analysers)} of them are "
55
- "`feasible`, and both `safetyBlockers` and `unresolvedFeasibilityFacts` "
56
- "are empty.",
55
+ "`feasible`, `safetyBlockers` is empty, and every "
56
+ "`unresolvedFeasibilityFacts` entry is a `deferred-gate` fact that names "
57
+ "its `gate`. A candidate whose `splitAcceptance.clarificationRef` names "
58
+ "the user's `accept-risk` answer to the split needs one `feasible` vote, "
59
+ "and its remaining facts stay on the row as the accepted risk; never set "
60
+ "`splitAcceptance` before that answer is recorded.",
57
61
  ("Classify each `unresolvedFeasibilityFacts` entry with `resolutionKind`: "
58
62
  "`user-decision` requires nonempty `clarificationRefs` linking that fact "
59
63
  "to actual C-NNN records, including answered records; `technical-verification` "
60
- "requires no user question. Preserve the fact, whyItMatters, and evidence. "
64
+ "requires no user question; `deferred-gate` is for a fact only a later gate "
65
+ "can close (a deployed-environment measurement technical-verification may not "
66
+ "run) and requires `gate` naming that gate. Preserve the fact, whyItMatters, and evidence. "
61
67
  "Historical unclassified facts remain readable but require classification "
62
68
  "before blocked report reassembly. Saving does not lift blocked routing."),
63
69
  ("After a linked decision is answered, preserve its disposition and selected "
@@ -73,8 +79,10 @@ def requirement_instructions(original_requirement_ids: Sequence[str], participat
73
79
  "`requirement-fit`, `correctness-risk`, `architecture-fit`, "
74
80
  "`weightedScore`, then id.",
75
81
  "In `candidate-comparison`, keep `preselectedDirection` null. In "
76
- "`preselected-validation`, emit exactly one validated option, an empty "
77
- "`candidateAudit`, and a cited `preselectedDirection`.",
82
+ "`preselected-validation`, keep a cited `preselectedDirection`; a "
83
+ "validated direction is the only ranked option with an empty "
84
+ "`candidateAudit`, and a direction that did not validate is the only "
85
+ "`candidateAudit` row with no ranked option.",
78
86
  "Record candidate validity and selection mode; the lead chooses the next "
79
87
  "phase under `## implementation-option-selection` in "
80
88
  "`prompts/lead/phase-routing.md`.",
@@ -1,5 +1,5 @@
1
1
  {
2
- "allowed": " - candidate-comparison evidence for up to three options per worker\n - preselected-validation of exactly ONE candidate: every analyser returns its own feasibility verdict on that one direction, `candidateAudit` stays empty, and no analyser generates an alternative. It is not a re-evaluation of the merged set — `okstra_ctl.phases.implementation_option_selection.validation._validate_mode` rejects a preselected-validation report carrying more than one option or a non-empty audit\n - a ranked display of at most three options with requirement mappings\n - an audit record for every rejected candidate\n - one endStateCoverage row per brief end-state id (this phase authors no goal of its own)",
2
+ "allowed": " - candidate-comparison evidence for up to three options per worker\n - preselected-validation of exactly ONE candidate: every analyser returns its own feasibility verdict on that one direction and no analyser generates an alternative. A validated direction is the only ranked option with an empty `candidateAudit`; a direction that did not validate is the only `candidateAudit` row and the run routes `blocked` or `technical-verification`. It is not a re-evaluation of the merged set — `okstra_ctl.phases.implementation_option_selection.validation._validate_mode` rejects any other shape\n - a ranked display of at most three options with requirement mappings\n - an audit record for every rejected candidate\n - one endStateCoverage row per brief end-state id (this phase authors no goal of its own)",
3
3
  "forbidden": [
4
4
  "source or configuration edits, refactors, or fix attempts",
5
5
  "tests, builds, migrations, deployments, or any state-mutating command",
@@ -2,9 +2,15 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  from pathlib import Path
5
+ from okstra_ctl.final_report_paths import final_report_data_path
6
+ from okstra_ctl.json_boundary import JsonBoundaryError, load_owned_object
7
+ from okstra_ctl.path_resolve import relative_to_project_root
5
8
  from okstra_ctl.prepare_error import PrepareError
6
9
  from okstra_ctl.scope_provenance import brief_end_state_id_sequence
7
10
 
11
+ CANDIDATE_COMPARISON = "candidate-comparison"
12
+ PRESELECTED_VALIDATION = "preselected-validation"
13
+
8
14
 
9
15
  def validate_brief_requirements(brief_path: Path) -> None:
10
16
  if not brief_end_state_id_sequence(brief_path):
@@ -12,3 +18,64 @@ def validate_brief_requirements(brief_path: Path) -> None:
12
18
  "regenerate the brief with stable end-state IDs before starting "
13
19
  "implementation-option-selection"
14
20
  )
21
+
22
+
23
+ def selection_mode(preselected_direction: str) -> str:
24
+ return PRESELECTED_VALIDATION if preselected_direction.strip() else CANDIDATE_COMPARISON
25
+
26
+
27
+ def upstream_next_steps(carry_in: Path) -> tuple[str, ...]:
28
+ """The next-phase instruction a carried-in report gave this phase.
29
+
30
+ The clarification carry-in projects only the report's C-NNN rows, so a
31
+ routing rationale such as "confirm one already-chosen direction" never
32
+ reached the designers.
33
+ """
34
+ data_path = final_report_data_path(carry_in)
35
+ if not data_path.is_file():
36
+ return ()
37
+ try:
38
+ data = load_owned_object(data_path, artifact="carried-in final report")
39
+ except JsonBoundaryError as exc:
40
+ raise PrepareError(str(exc)) from exc
41
+ card = data.get("verdictCard")
42
+ steps = [card.get("nextStep")] if isinstance(card, dict) else []
43
+ for row in data.get("recommendedNextSteps") or []:
44
+ if isinstance(row, dict):
45
+ steps.append(row.get("text"))
46
+ return tuple(step.strip() for step in steps if isinstance(step, str) and step.strip())
47
+
48
+
49
+ def selection_mode_packet_block(
50
+ preselected_direction: str, carry_in: Path | None, project_root: Path,
51
+ ) -> str:
52
+ mode = selection_mode(preselected_direction)
53
+ lines = ["## Direction Selection Mode", "", f"This run's mode: `{mode}`.", ""]
54
+ if mode == PRESELECTED_VALIDATION:
55
+ lines += [
56
+ "The lead preselected the direction below. Validate only this direction",
57
+ "as `Worker direction-selection procedure` describes for",
58
+ "`preselected-validation`: do not generate, rank or compare alternatives.",
59
+ "Record open choices inside the direction as uncertainties with evidence.",
60
+ "",
61
+ "### Preselected Direction and Citation",
62
+ "",
63
+ preselected_direction.strip(),
64
+ ]
65
+ else:
66
+ lines += [
67
+ "No direction was preselected for this run. Propose and compare",
68
+ "candidates as `Worker direction-selection procedure` describes for",
69
+ "`candidate-comparison`.",
70
+ ]
71
+ steps = upstream_next_steps(carry_in) if carry_in is not None else ()
72
+ if steps:
73
+ lines += [
74
+ "",
75
+ "### Upstream Next-Phase Instruction",
76
+ "",
77
+ f"From `{relative_to_project_root(final_report_data_path(carry_in), project_root)}`:",
78
+ "",
79
+ *(f"- {step}" for step in steps),
80
+ ]
81
+ return "\n".join(lines)
@@ -8,7 +8,8 @@
8
8
  - Worker direction-selection procedure:
9
9
  - In `candidate-comparison` mode, produce candidate, supporting and contradicting evidence, criterion scores, and requirement mappings. For every candidate, state one feasibility verdict — `feasible`, `not-feasible`, or `uncertain` — with a rationale and the strongest counterevidence, each citing inspected evidence. Write the rationale as long as the argument needs: say why each cited finding supports the verdict, not only which findings do. The report's `feasibilityVotes` row for this worker is built from that statement, so a candidate without one leaves the writer nothing but another worker's words.
10
10
  - In `candidate-comparison` mode only, submit at most three candidates. A candidate must be feasible from inspected evidence, not from an assumed future change.
11
- - In `preselected-validation` mode, receive one preselected direction from the lead and validate its evidence, counterevidence, criterion scores, and requirement mappings, and state the same feasibility verdict with its rationale and counterevidence. The worker must not generate new candidates.
11
+ - Read the run's mode, and in `preselected-validation` the one preselected direction with its citation, from the packet's `## Direction Selection Mode` section (`--preselected-direction`).
12
+ - In `preselected-validation` mode, validate the one preselected direction: its evidence, counterevidence, criterion scores, and requirement mappings, and state the same feasibility verdict with its rationale and counterevidence. The worker must not generate new candidates.
12
13
  - Do not produce detailed file lists, stage maps, execution commands, or a plan approval request.
13
14
  - Census aspects:
14
15
  - requirement mapping: Which candidate or preselected direction satisfies this requirement, and how?
@@ -26,7 +27,8 @@
26
27
  - Map every displayed candidate or preselected direction to the stable brief end-state IDs it satisfies, preserves, or leaves unresolved.
27
28
  - **Close the vote gaps before you conclude `blocked`.** Round 1 runs the designers in parallel, so each one votes only on the candidates it proposed and the merged set ends up with a different hole per analyser. A candidate that is otherwise sound then fails the every-analyser clause and drops out of the ranking — three such candidates blocked a run whose comparison had in fact converged (2026-09-10, dev-10629-4: IO-001, IO-002 and IO-003 each held two `feasible` votes and each was missing a different designer). Run `okstra option-votes gaps --task-manifest <taskManifestPath> --narrative <report writer narrative>` before assembly. For each analyser it names, dispatch one vote-completion assignment asking for that analyser's own feasibility verdict, rationale, and counterevidence on the named candidate — no new candidate, so the run stays in `candidate-comparison` mode. The command reports no gap when a vote cannot settle the block (safety blockers, unresolved feasibility facts, too few feasible verdicts); that is the honest `blocked`.
28
29
  - Clarification request policy (phase-specific addenda — shared policy is in `_common-contract.md`):
29
- - Classify every `unresolvedFeasibilityFacts` entry with `resolutionKind`: `user-decision` requires nonempty `clarificationRefs` naming the actual C-NNN records for that fact; `technical-verification` requires source review, design evidence, or experiments and does not require a user question. Preserve `fact`, `whyItMatters`, and `evidence`. Reuse answered questions and their recorded dispositions; never reopen one merely to save the report. An unrelated open question does not satisfy a missing reference. Historical unclassified entries remain readable, but blocked report reassembly requires the writer to classify them explicitly. Enforced by `validate_blocked_answer_channel` in `scripts/okstra_ctl/phases/implementation_option_selection/validation.py`, called by report assembly and `validate-run.py`. Saving preserves `routing: blocked` and does not make a candidate valid. In `humanSummary.actions`, `verdictCard.nextStep`, and selection guidance, distinguish pending user decisions from remaining technical verification; after the pilot route is answered, carry the selected route and remove the old answer-waiting instruction.
30
+ - Classify every `unresolvedFeasibilityFacts` entry with `resolutionKind`: `user-decision` requires nonempty `clarificationRefs` naming the actual C-NNN records for that fact; `technical-verification` requires source review, design evidence, or experiments and does not require a user question. `deferred-gate` marks a fact that no technical-verification run can close because closing it needs something that phase forbids, such as a deployed environment (for example, a cold-start measurement of a deployed Lambda); it requires `gate`, naming where the fact closes (a brief `External Gates` entry, or final-verification user-owned external QA), and it does not make the candidate invalid. A fact that a probe, a source read, or a disposable local service can close is `technical-verification`, not `deferred-gate`. The selected direction snapshot carries every remaining fact of the chosen option as `deferredFeasibilityFacts`, so planning schedules its gate. Enforced by `blocking_feasibility_facts` in `scripts/okstra_ctl/phases/implementation_option_selection/validation.py`. Preserve `fact`, `whyItMatters`, and `evidence`. Reuse answered questions and their recorded dispositions; never reopen one merely to save the report. An unrelated open question does not satisfy a missing reference. Historical unclassified entries remain readable, but blocked report reassembly requires the writer to classify them explicitly. Enforced by `validate_blocked_answer_channel` in `scripts/okstra_ctl/phases/implementation_option_selection/validation.py`, called by report assembly and `validate-run.py`. Saving preserves `routing: blocked` and does not make a candidate valid. In `humanSummary.actions`, `verdictCard.nextStep`, and selection guidance, distinguish pending user decisions from remaining technical verification; after the pilot route is answered, carry the selected route and remove the old answer-waiting instruction.
31
+ - **A split vote ends in a user decision, not another run.** When no candidate is valid only because its votes split (at least one `feasible`, the others `uncertain` or `not-feasible`, no `safetyBlockers`), another option-selection or technical-verification run asks the same designers the same question and returns the same split (fontradar dev-11562: three runs, `feasible` against `uncertain` each time). Before you route `blocked` or `technical-verification` on such a candidate, open one approval decision for it with `okstra approval-decision open --ledger <approvalDecisionsPath>` (classification `noncritical-dissent`): the recommended option is `accept-risk` (proceed with this direction and carry the dissent and the remaining facts into planning), the alternative is `request-revision` (keep the run blocked). Ask the user in-session; record the answer with `okstra approval-decision resolve`. On `accept-risk`, the writer sets `splitAcceptance.clarificationRef` on that candidate, which makes it valid with one `feasible` vote; it then follows the ordinary routing (`implementation-planning` for a validated preselected direction, `pending-direction-selection` in `candidate-comparison`). Leave the votes and facts on the row. When the user is not present, publish the report `blocked` with that approval row open; the next run carries the answer. Enforced by `validate_split_acceptance` in `scripts/okstra_ctl/phases/implementation_option_selection/validation.py`, called by report assembly and `validate-run.py`.
30
32
  {{INCLUDE:_clarification-recommendation.md}}
31
33
  - Cross-verification mode:
32
34
  - Phase 5.5 convergence runs in adversarial mode (`convergence.adversarial=true`).
@@ -33,6 +33,7 @@
33
33
  <table data-report-field="implementationOptionSelection.rankedOptions.feasibilityVotes"><thead><tr><th>{{ t('tasks.implementation-option-selection.worker') }}</th><th>{{ t('tasks.implementation-option-selection.reason') }}</th><th>{{ t('tasks.implementation-option-selection.counterevidence') }}</th></tr></thead><tbody>{% for vote in row.feasibilityVotes %}<tr>{{ row_key(pairs=[(t('tasks.implementation-option-selection.worker'), vote.worker)], status_name=t('tasks.implementation-option-selection.verdict'), status_raw=vote.verdict, status_text=vote.verdict | enum_label('feasibilityVerdict')) }}<td>{{ vote.rationale | inline_code(extra) }}</td><td>{{ vote.counterevidence | inline_code(extra) }}</td></tr>{% endfor %}</tbody></table>
34
34
  {% if row.safetyBlockers %}<p><strong>{{ t('tasks.implementation-option-selection.safety-blockers') }}</strong></p>
35
35
  <ul>{% for blocker in row.safetyBlockers %}<li><span class="status status-risk">{{ blocker.category | enum_label('safetyCategory') }}</span> {{ blocker.statement | inline_code(extra) }} <span class="evidence-refs">{{ t('macros.layout.evidence') }} {{ blocker.evidence | evidence_refs(extra) }}</span></li>{% endfor %}</ul>{% endif %}
36
+ {% if row.get('splitAcceptance') %}<p><strong>{{ t('tasks.implementation-option-selection.split-acceptance') }}</strong> {{ row.splitAcceptance.clarificationRef | inline_code(extra) }}</p>{% endif %}
36
37
  {{ unresolved_facts(row, extra) }}
37
38
  </div>
38
39
  <div class="option-detail">
@@ -49,7 +50,7 @@
49
50
 
50
51
  {% macro unresolved_facts(row, extra) -%}
51
52
  {% if row.unresolvedFeasibilityFacts %}<p><strong>{{ t('tasks.implementation-option-selection.unresolved-facts') }}</strong></p>
52
- <ul>{% for fact in row.unresolvedFeasibilityFacts %}<li>{% if fact.get('resolutionKind') == 'technical-verification' %}{{ t('tasks.implementation-option-selection.technical-verification') }}: {% elif fact.get('resolutionKind') == 'user-decision' %}{{ t('tasks.implementation-option-selection.user-decision') }} ({{ fact.get('clarificationRefs', []) | join(', ') | inline_code(extra) }}): {% else %}{{ t('tasks.implementation-option-selection.classification-required') }}: {% endif %}{{ fact.fact | inline_code(extra) }} — {{ t('tasks.implementation-option-selection.why-it-matters') }} {{ fact.whyItMatters | inline_code(extra) }} <span class="evidence-refs">{{ t('macros.layout.evidence') }} {{ fact.evidence | evidence_refs(extra) }}</span></li>{% endfor %}</ul>{% endif %}
53
+ <ul>{% for fact in row.unresolvedFeasibilityFacts %}<li>{% if fact.get('resolutionKind') == 'technical-verification' %}{{ t('tasks.implementation-option-selection.technical-verification') }}: {% elif fact.get('resolutionKind') == 'deferred-gate' %}{{ t('tasks.implementation-option-selection.deferred-gate') }} ({{ fact.get('gate', '') | inline_code(extra) }}): {% elif fact.get('resolutionKind') == 'user-decision' %}{{ t('tasks.implementation-option-selection.user-decision') }} ({{ fact.get('clarificationRefs', []) | join(', ') | inline_code(extra) }}): {% else %}{{ t('tasks.implementation-option-selection.classification-required') }}: {% endif %}{{ fact.fact | inline_code(extra) }} — {{ t('tasks.implementation-option-selection.why-it-matters') }} {{ fact.whyItMatters | inline_code(extra) }} <span class="evidence-refs">{{ t('macros.layout.evidence') }} {{ fact.evidence | evidence_refs(extra) }}</span></li>{% endfor %}</ul>{% endif %}
53
54
  {%- endmacro %}
54
55
 
55
56
  {% block human_content %}
@@ -41,6 +41,11 @@ MAX_RANKED_OPTIONS = 3
41
41
  MAX_RAW_CANDIDATES_PER_ANALYSER = 3
42
42
  CANDIDATE_COMPARISON_ROUTING = "pending-direction-selection"
43
43
  NO_VALID_OPTIONS_ROUTING = "blocked"
44
+ # 배포된 환경이 있어야 닫히는 사실(예: 배포된 Lambda 의 실행 시간)은
45
+ # technical-verification 이 배포를 금하므로 그 phase 의 재실행으로 닫히지 않는다.
46
+ # 그런 사실은 닫히는 게이트를 적고 후보를 무효로 만들지 않는다.
47
+ DEFERRED_GATE_KIND = "deferred-gate"
48
+ SPLIT_ACCEPTANCE_DISPOSITION = "accept-risk"
44
49
 
45
50
  _FINGERPRINT_FIELDS = (
46
51
  "goal",
@@ -233,6 +238,37 @@ def required_feasible_votes(participating_analysers: Sequence[str]) -> int:
233
238
  return min(MIN_FEASIBLE_VOTES, max(1, len(set(participating_analysers))))
234
239
 
235
240
 
241
+ def split_acceptance_ref(option: Mapping[str, object]) -> str:
242
+ """후보가 인용한 사용자 위험 감수 결정의 C-id. 없으면 빈 문자열."""
243
+ acceptance = option.get("splitAcceptance")
244
+ if not isinstance(acceptance, Mapping):
245
+ return ""
246
+ return str(acceptance.get("clarificationRef") or "").strip()
247
+
248
+
249
+ def _is_deferred_gate_fact(fact: object) -> bool:
250
+ return (
251
+ isinstance(fact, Mapping)
252
+ and fact.get("resolutionKind") == DEFERRED_GATE_KIND
253
+ and bool(str(fact.get("gate") or "").strip())
254
+ )
255
+
256
+
257
+ def blocking_feasibility_facts(option: Mapping[str, object]) -> list[object]:
258
+ """후보를 무효로 두는 미확정 사실.
259
+
260
+ 게이트를 적은 `deferred-gate` 사실은 막지 않는다. 사용자가 위험 감수로
261
+ 받아들인 후보(`splitAcceptance`)는 남은 사실을 기록으로만 들고 간다 —
262
+ 계획 phase 의 `accept-risk` 와 같은 뜻이다.
263
+ """
264
+ if split_acceptance_ref(option):
265
+ return []
266
+ return [
267
+ fact for fact in option.get("unresolvedFeasibilityFacts") or ()
268
+ if not _is_deferred_gate_fact(fact)
269
+ ]
270
+
271
+
236
272
  def _validate_option_feasibility(
237
273
  option: Mapping[str, object],
238
274
  participating_analysers: Sequence[str],
@@ -255,13 +291,36 @@ def _validate_option_feasibility(
255
291
  isinstance(vote, Mapping) and vote.get("verdict") == "feasible"
256
292
  for vote in votes
257
293
  )
258
- required = required_feasible_votes(participating_analysers)
294
+ # 갈린 표는 같은 분석자들에게 다시 물어도 갈린다. 사용자가 위험 감수로
295
+ # 받아들인 후보는 `feasible` 한 표로 충분하다 — 방향을 낸 근거가 있어야
296
+ # 받아들일 대상이 있다.
297
+ accepted = bool(split_acceptance_ref(option))
298
+ required = 1 if accepted else required_feasible_votes(participating_analysers)
259
299
  if require_valid and feasible < required:
260
- errors.append(f"{option_id} must have at least {required} feasible vote(s)")
300
+ errors.append(
301
+ f"{option_id} must have at least {required} feasible vote(s); a split "
302
+ "vote is settled by a user accept-risk decision cited in splitAcceptance, "
303
+ "not by another run with the same analysers"
304
+ )
261
305
  if require_valid and option.get("safetyBlockers"):
262
306
  errors.append(f"{option_id} safetyBlockers must be empty")
263
- if require_valid and option.get("unresolvedFeasibilityFacts"):
264
- errors.append(f"{option_id} unresolvedFeasibilityFacts must be empty")
307
+ blocking_facts = blocking_feasibility_facts(option)
308
+ if require_valid and blocking_facts:
309
+ errors.append(
310
+ f"{option_id} unresolvedFeasibilityFacts must be empty, "
311
+ f"{DEFERRED_GATE_KIND} facts that name their gate, or accepted through "
312
+ "splitAcceptance"
313
+ )
314
+ for index, fact in enumerate(option.get("unresolvedFeasibilityFacts") or ()):
315
+ if (
316
+ isinstance(fact, Mapping)
317
+ and fact.get("resolutionKind") == DEFERRED_GATE_KIND
318
+ and not _is_deferred_gate_fact(fact)
319
+ ):
320
+ errors.append(
321
+ f"{option_id} unresolvedFeasibilityFacts[{index}]: a "
322
+ f"{DEFERRED_GATE_KIND} fact must name the gate that closes it"
323
+ )
265
324
  copied = _copied_votes(votes)
266
325
  for first, second in copied:
267
326
  errors.append(
@@ -272,7 +331,7 @@ def _validate_option_feasibility(
272
331
  all_participated
273
332
  and feasible >= required
274
333
  and not option.get("safetyBlockers")
275
- and not option.get("unresolvedFeasibilityFacts")
334
+ and not blocking_facts
276
335
  and not copied
277
336
  )
278
337
 
@@ -415,9 +474,7 @@ def vote_gaps(
415
474
  for row in (selection.get(key) or ())
416
475
  if isinstance(row, Mapping)
417
476
  ):
418
- if candidate.get("safetyBlockers") or candidate.get(
419
- "unresolvedFeasibilityFacts"
420
- ):
477
+ if candidate.get("safetyBlockers") or blocking_feasibility_facts(candidate):
421
478
  continue
422
479
  votes = candidate.get("feasibilityVotes") or ()
423
480
  if _copied_votes(votes):
@@ -489,12 +546,13 @@ def validate_blocked_answer_channel(
489
546
  continue
490
547
  label += f" ({fact.get('fact')})"
491
548
  kind = fact.get("resolutionKind")
492
- if kind == "technical-verification":
549
+ if kind in {"technical-verification", DEFERRED_GATE_KIND}:
493
550
  continue
494
551
  if kind != "user-decision":
495
552
  errors.append(f"{label}: classification required — set resolutionKind to "
496
- "user-decision or technical-verification; preserve the fact "
497
- "and evidence, then reassemble; do not infer a user question")
553
+ "user-decision, technical-verification or deferred-gate; "
554
+ "preserve the fact and evidence, then reassemble; do not "
555
+ "infer a user question")
498
556
  continue
499
557
  refs = fact.get("clarificationRefs")
500
558
  if not isinstance(refs, list) or not refs or any(
@@ -507,6 +565,46 @@ def validate_blocked_answer_channel(
507
565
  return errors
508
566
 
509
567
 
568
+ def validate_split_acceptance(report_data: Mapping[str, object]) -> list[str]:
569
+ """`splitAcceptance` 가 인용한 C-id 가 사용자의 위험 감수 기록인지 검사한다.
570
+
571
+ 서술 검증(`validate_implementation_option_selection`)은 clarification 행을
572
+ 보지 못한다. 리드 원장이 합쳐진 뒤에만 이 인용이 실제 `accept-risk` 답인지
573
+ 알 수 있으므로 조립과 `validate-run.py` 가 이 함수를 따로 부른다.
574
+ """
575
+ selection = report_data.get("implementationOptionSelection")
576
+ if not isinstance(selection, Mapping):
577
+ return []
578
+ rows = {
579
+ row.get("id"): row
580
+ for row in (report_data.get("clarificationItems") or ())
581
+ if isinstance(row, Mapping)
582
+ }
583
+ errors: list[str] = []
584
+ for candidate in (
585
+ row for key in ("rankedOptions", "candidateAudit")
586
+ for row in (selection.get(key) or ()) if isinstance(row, Mapping)
587
+ ):
588
+ ref = split_acceptance_ref(candidate)
589
+ if not ref and "splitAcceptance" not in candidate:
590
+ continue
591
+ row = rows.get(ref)
592
+ if (
593
+ row is None
594
+ or str(row.get("blocks") or "").strip().lower() != "approval"
595
+ or str(row.get("status") or "").strip().lower() == "obsolete"
596
+ or clarification_disposition(row) != SPLIT_ACCEPTANCE_DISPOSITION
597
+ ):
598
+ errors.append(
599
+ f"{candidate.get('id')} splitAcceptance {ref!r} must name a "
600
+ "`blocks: approval` clarification the user answered with "
601
+ f"`{SPLIT_ACCEPTANCE_DISPOSITION}`; open it with `okstra "
602
+ "approval-decision open --ledger <approvalDecisionsPath>`, record "
603
+ "the answer with `okstra approval-decision resolve`, then reassemble"
604
+ )
605
+ return errors
606
+
607
+
510
608
  def _validate_candidate_audit(
511
609
  data: Mapping[str, object],
512
610
  options: Sequence[Mapping[str, object]],
@@ -630,18 +728,29 @@ def _validate_mode(
630
728
  if options and data.get("routing") != CANDIDATE_COMPARISON_ROUTING:
631
729
  errors.append("candidate-comparison with options must await direction selection")
632
730
  return
633
- if len(options) != 1:
634
- errors.append("preselected-validation must contain exactly one validated option")
635
- if audit:
636
- errors.append("preselected-validation candidateAudit must be empty")
731
+ # A direction that failed validation cannot be displayed (displayed options must be
732
+ # valid), so it is the one audit row; `_validate_option_count_and_routing` then
733
+ # requires `blocked` or `technical-verification`.
734
+ validated = bool(options)
735
+ if validated:
736
+ if len(options) != 1:
737
+ errors.append("preselected-validation must contain exactly one validated option")
738
+ if audit:
739
+ errors.append("preselected-validation candidateAudit must be empty")
740
+ elif len(audit) != 1:
741
+ errors.append(
742
+ "preselected-validation must contain exactly one validated option, "
743
+ "or the one unvalidated direction as its only candidateAudit row"
744
+ )
637
745
  if not isinstance(direction, Mapping):
638
746
  errors.append("preselected-validation requires preselectedDirection")
639
747
  return
640
- if options and direction.get("optionId") != options[0].get("id"):
641
- errors.append("preselectedDirection optionId must name the validated option")
748
+ target = options[0] if validated else (audit[0] if len(audit) == 1 else None)
749
+ if target is not None and direction.get("optionId") != target.get("id"):
750
+ errors.append("preselectedDirection optionId must name the preselected direction")
642
751
  if not _CITATION_RE.search(str(direction.get("citation") or "")):
643
752
  errors.append("preselectedDirection citation must be citable")
644
- if data.get("routing") != "implementation-planning":
753
+ if validated and data.get("routing") != "implementation-planning":
645
754
  errors.append("validated preselected direction must route to implementation-planning")
646
755
 
647
756
 
@@ -67,6 +67,7 @@ from okstra_ctl.plan_item_evidence import (
67
67
  from okstra_ctl.plan_review_context import render_review_context
68
68
  from okstra_ctl.stage_ledger import build_stage_ledger
69
69
  from okstra_ctl.claim_reproduction import NOT_RUNNABLE, reproduce
70
+ from okstra_ctl.file_size_cap import headroom_text, planned_file_headroom
70
71
  from okstra_ctl.final_report_schema import load_schema_version
71
72
  from okstra_ctl.report_narrative import parse_narrative
72
73
  from okstra_ctl.report_assembly import validate_plan_draft
@@ -538,12 +539,16 @@ def _prepare(args: argparse.Namespace) -> dict[str, Any]:
538
539
  envelope.update(_reverify_carry(args, envelope["dispatchQueue"]))
539
540
  gating = not advisory_plan_body_gating(_planning(source), envelope["items"])
540
541
  _sync_task_manifest_gating(args.run_manifest, gating)
542
+ envelope["fileSizeHeadroom"] = planned_file_headroom(
543
+ _planning(source), authority.project_root,
544
+ )
541
545
  write_json_atomic(output, envelope)
542
546
  return {
543
547
  "ok": True,
544
548
  "operation": "prepare",
545
549
  "path": str(output),
546
550
  "gating": gating,
551
+ "fileSizeHeadroom": envelope["fileSizeHeadroom"],
547
552
  }
548
553
 
549
554
 
@@ -1045,6 +1050,20 @@ def _render_inputs(run_manifest: Path) -> str:
1045
1050
  return "\n## Inputs\n\n" + "".join(rows) if rows else ""
1046
1051
 
1047
1052
 
1053
+ def _render_file_size_headroom(rows: object) -> str:
1054
+ if not isinstance(rows, list) or not rows:
1055
+ return ""
1056
+ lines = [
1057
+ "\n## File-size headroom\n",
1058
+ "Existing files this plan writes, measured before any stage runs. Information "
1059
+ "only: it is not a verdict criterion.\n",
1060
+ ]
1061
+ lines.extend(
1062
+ line("File-size headroom", headroom_text(row)) for row in rows if isinstance(row, Mapping)
1063
+ )
1064
+ return "".join(lines)
1065
+
1066
+
1048
1067
  def _prompt(args: argparse.Namespace) -> str:
1049
1068
  inputs = _checked_review_inputs(args.run_manifest)
1050
1069
  envelope = _load_json_object(
@@ -1074,6 +1093,7 @@ def _prompt(args: argparse.Namespace) -> str:
1074
1093
  rows.append(render_review_context(
1075
1094
  [item["id"] for item in items], inputs, authority.payload, authority.project_root,
1076
1095
  ))
1096
+ rows.append(_render_file_size_headroom(envelope.get("fileSizeHeadroom")))
1077
1097
  _checked_review_inputs(args.run_manifest)
1078
1098
  for index, item in enumerate(items, 1):
1079
1099
  if not isinstance(item, Mapping):
@@ -2566,6 +2586,8 @@ def main(argv: list[str] | None = None) -> int:
2566
2586
  )
2567
2587
  if "gating" in result:
2568
2588
  rows += line("Gating", result["gating"])
2589
+ for row in result.get("fileSizeHeadroom", []):
2590
+ rows += line("File-size headroom", headroom_text(row))
2569
2591
  print(rows, end="")
2570
2592
  else:
2571
2593
  print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -413,7 +413,7 @@ round before any host or provider process starts.
413
413
 
414
414
  For contract 3.0, `prepare` checks the selected-direction draft with the same semantic validator as publication before writing the queue. Correct all reported references, coverage rows and planned commands through the writer correction procedure, then retry in this run. **Enforced:** `report_assembly.validate_plan_draft` and `plan_items_cli._prepare`; `tests/report/test_report_assembly.py` checks that invalid coverage creates no prepared queue.
415
415
 
416
- 1. Lead runs `okstra plan-items prepare --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`, places the fixed output of `okstra plan-items prompt --run-manifest <run-manifest>` verbatim in every verifier prompt, then runs `okstra plan-items validate-prepared --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`. After a self-fix rewrite, pass `--state <plan-body-verification.json>` on prepare and validate-prepared. The runtime reuses a verdict only when its body, complete declared evidence closure, shared analysis packet, plan metadata, reviewer assignments and review contract have the same fingerprint. A missing or uncertain dependency declaration, unresolved reference, non-result or executable fact probe stays in the re-verification queue. Detailed verdicts and their original rounds remain unchanged for reused items. File dependencies cover whole files; step items also include preceding steps; plan-wide and preparation items include all plan items. Python resolves the one convergence-owned state path from that run identity. Dispatch only after exact-match validation succeeds. `observed` / `deferred` stages remain omitted. An empty queue opens no worker dispatch and creates no verification round. **Enforced:** `implementation_planning.authoring._queue_for`, `plan_item_evidence.review_fingerprint`, `_validate_prepared` and `tests/run/test_plan_items.py`. An incremental carry without evidence snapshots keeps active items queued until prepare can validate their dependencies.
416
+ 1. Lead runs `okstra plan-items prepare --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`, places the fixed output of `okstra plan-items prompt --run-manifest <run-manifest>` verbatim in every verifier prompt, then runs `okstra plan-items validate-prepared --narrative <report-writer-narrative.md> --run-manifest <run-manifest>`. A `File-size headroom` line that prepare prints, and that `okstra plan-items prompt` carries under `## File-size headroom`, is a report only: it names an existing file the plan writes, its lines left before the 500-line implementation limit and the stages that write it. It does not block, open a correction or count as a verdict. After a self-fix rewrite, pass `--state <plan-body-verification.json>` on prepare and validate-prepared. The runtime reuses a verdict only when its body, complete declared evidence closure, shared analysis packet, plan metadata, reviewer assignments and review contract have the same fingerprint. A missing or uncertain dependency declaration, unresolved reference, non-result or executable fact probe stays in the re-verification queue. Detailed verdicts and their original rounds remain unchanged for reused items. File dependencies cover whole files; step items also include preceding steps; plan-wide and preparation items include all plan items. Python resolves the one convergence-owned state path from that run identity. Dispatch only after exact-match validation succeeds. `observed` / `deferred` stages remain omitted. An empty queue opens no worker dispatch and creates no verification round. **Enforced:** `implementation_planning.authoring._queue_for`, `plan_item_evidence.review_fingerprint`, `_validate_prepared` and `tests/run/test_plan_items.py`. An incremental carry without evidence snapshots keeps active items queued until prepare can validate their dependencies.
417
417
 
418
418
  **Then seed the landing table (BLOCKING):** `okstra plan-items seed --narrative <report-writer-narrative.md> --state <plan-body-verification.json> --run-manifest <run-manifest.json>`. `apply-verdicts` in step 8 refuses a verdict whose item has no `planBodyVerification.planItems[]` row. The report writer never owns that state, so the deterministic seed is the only creator of its rows. The seed is idempotent by id and never touches existing verdicts, so it is safe to re-run between rounds and after a self-fix re-extraction. It does refresh `contentHash` from the current extract. Skipping it makes step 8 fail with `plan-body state has no row for [...]`.
419
419
 
@@ -19,6 +19,7 @@ Plan for the actual worktree layout before approval. Shared documentation direct
19
19
  - **Selected-direction planning procedure** — perform these steps in order and no others:
20
20
  1. Read `selected-direction.json` and the original requirements ledger end-to-end. The ledger is not a separate file: it is the brief's `Expected Behavior` / `Preserved Behavior` / `Expected Outcome` sections (`EB-` / `PB-` / `EO-` ids), carried verbatim in the analysis packet's `## Task-Specific Brief Extract`.
21
21
  1a. Fill `selectedDirectionRef` from that snapshot: copy `sourceReport`, `sourceDataSha256`, and `optionId` verbatim from the file; write `snapshotPath` as the snapshot's path relative to the **task root** (`instruction-set/selected-direction.json`, never project-relative and never absolute) and `snapshotSha256` as the SHA-256 of its exact bytes. Those last two are the only ref fields the snapshot does not carry.
22
+ 1b. When the snapshot carries `deferredFeasibilityFacts`, the direction was validated with those facts still open. A `deferred-gate` fact names the `gate` that closes it; carry it into the plan as that gate (an `External Gates` dependency or final-verification user-owned external QA), not as a stage validation row, because a stage row the implementation run cannot execute blocks the stage. When the snapshot also carries `splitAcceptance`, the user accepted the direction over a split feasibility vote; the remaining facts are that accepted risk, so record each in `dependencyMigrationRisk` or the validation that would expose it, and do not reopen the direction choice.
22
23
  2. Concretize the selected direction into files, interfaces, stages, validation, and rollback without changing its mechanism or boundaries.
23
24
  3. Link every planned file and stage bidirectionally to the original requirements.
24
25
  4. If current evidence requires changing the selected direction, emit `direction-invalidated` and stop planning.
@@ -147,7 +148,7 @@ Plan for the actual worktree layout before approval. Shared documentation direct
147
148
  **Pick the cases by distinct outcome, not by line coverage.** When the stage writes or reconciles state, its meaningfully different outcomes are usually more than three — normal success, target already in the desired state (resume), existing data reused rather than created, a conflicting concurrent state, target absent, and mid-way failure with rollback. Enumerate the ones this stage actually implements and route them across the three lines (the `boundary` line is where resume / already-done / reuse belongs; `failure` carries conflict, absence, and rollback), naming each in the cell rather than collapsing them into "edge input". An implemented outcome with no declared case is a coverage gap the executor will not backfill.
148
149
  - **Per-stage subsections** (`## 5.5.<i> Stage <i>: <title>` for each `i`), each containing the four required subsections:
149
150
  - `### Carry-In` — for `depends-on (none)`: task-brief only. Otherwise: each depended-on stage's static exit contract + runtime sidecar path `runs/<impl-key>/carry/stage-<i>.json` placeholder.
150
- - `### Stepwise Execution Order` — bite-sized table with `step | action | files | command | outcome | expected`. `outcome` is one word — `PASS` or `FAIL` — and `expected` is the sentence saying what that looks like here; a verdict written inside the sentence is not read as one. The `files` cell lists each touched path in full and `<PROJECT_ROOT>`-relative — never ellipsis-abbreviated (`…` / `...`), which does not resolve and is rejected by plan-body verification as a kind-b path mismatch. **The narrative row additionally carries `plannedPaths`: the paths this step may write as an array, one repository-relative path per entry, with no globs, exclusions, counts or commentary. Read-only checks use `plannedPaths: []`; their working directory belongs in the command, not the write ledger. Never declare the repository or worktree root. Planning assembly and correction preflight enforce this through `write_policy.planned_path_declaration_errors`.** **File size:** the implementation run aims for 300 physical lines per source and test file and enforces 400 — a new file over 400, an existing file taken past 400, and a file already over 400 that grows are blocking findings the executor must split in a correction round; the same conditions at 300 are advisory. When a step would add code or tests to a file near or over 300 lines (`wc -l`), plan a new module or test file for that responsibility in `plannedPaths` instead of appending to the existing one. **Enforced at implementation, not here:** `okstra correction file-size` (`scripts/okstra_ctl/file_size_cap.py`), re-run by `okstra stage-done`. `files` is the sentence a reader sees; `plannedPaths` is the ledger report assembly preserves and the implementer write policy enforces. When a step legitimately covers a set too large to enumerate, split it or name the directory the set lives under. **Effective row count ≤ 8** (excluding header / divider / blank). Each step is one cohesive, self-contained change. **TDD ordering is MUST, not a preference:** the **first** effective step's `action` cell MUST start with the literal `RED:` and describe the failing test(s) that capture this stage's `Acceptance` **and the three declared `Test case (success|boundary|failure)` lines** (`outcome` = `FAIL`); at least one later `action` cell MUST start with the literal `GREEN:` and describe the minimal implementation that makes it pass (`outcome` = `PASS`); an optional refactor step starts with `REFACTOR:`. **Exemption:** doc-only / config-only / pure-rename stages with no observable runtime behaviour may omit RED/GREEN by declaring one line `TDD exemption: <reason>` in the stage section. A stage that is truthfully none of those three declares `TDD exemption: user-bypass — <the user's words>`, which holds only while the user has granted it for that stage with `okstra prepare --tdd-bypass "<stage>:<reason>"` — never file the nearest of the three instead. Validator S10c enforces RED-first + GREEN; the `outcome` cell agreeing with its prefix is a schema conditional. S10e rejects an unsupported exemption reason and a `user-bypass` with no user grant (`validators/validate-implementation-plan-stages.py`).
151
+ - `### Stepwise Execution Order` — bite-sized table with `step | action | files | command | outcome | expected`. `outcome` is one word — `PASS` or `FAIL` — and `expected` is the sentence saying what that looks like here; a verdict written inside the sentence is not read as one. The `files` cell lists each touched path in full and `<PROJECT_ROOT>`-relative — never ellipsis-abbreviated (`…` / `...`), which does not resolve and is rejected by plan-body verification as a kind-b path mismatch. **The narrative row additionally carries `plannedPaths`: the paths this step may write as an array, one repository-relative path per entry, with no globs, exclusions, counts or commentary. Read-only checks use `plannedPaths: []`; their working directory belongs in the command, not the write ledger. Never declare the repository or worktree root. Planning assembly and correction preflight enforce this through `write_policy.planned_path_declaration_errors`.** **File size:** the implementation run aims for 300 physical lines per source and test file and enforces 500 — a new file over 500 and an existing file taken from 500 or fewer past 500 are blocking findings the executor must split in a correction round; a file already over 500 that grows is advisory, as is a new, crossing or growing file over 300. When a step would add code or tests to a file near or over 300 lines (`wc -l`), plan a new module or test file for that responsibility in `plannedPaths` instead of appending to the existing one. **Enforced at implementation:** `okstra correction file-size` (`scripts/okstra_ctl/file_size_cap.py`), re-run by `okstra stage-done`. A plan does not say how many lines a step adds, so planning cannot apply the limit; instead `okstra plan-items prepare`, correction preflight (`check-corrections`) and the plan verifier prompt report one `File-size headroom` line per existing source or test file the plan's `plannedPaths` name that has more than 300 and at most 500 lines, with the lines left before 500 and every stage that writes it (`file_size_cap.planned_file_headroom`). The report is information for the plan's readers: it never blocks, and it is not a verdict criterion or a reason for a correction. Files the plan creates and files already over 500 are not listed. `files` is the sentence a reader sees; `plannedPaths` is the ledger report assembly preserves and the implementer write policy enforces. The design-surface detector maps every selected-option `fileStructure` path to the stage whose `files` or `plannedPaths` names it; a path neither names fails the draft check that correction preflight and `plan-items prepare` share (`scripts/okstra_ctl/report_assembly.py` `validate_plan_draft`). When a step legitimately covers a set too large to enumerate, split it or name the directory the set lives under. **Effective row count ≤ 8** (excluding header / divider / blank). Each step is one cohesive, self-contained change. **TDD ordering is MUST, not a preference:** the **first** effective step's `action` cell MUST start with the literal `RED:` and describe the failing test(s) that capture this stage's `Acceptance` **and the three declared `Test case (success|boundary|failure)` lines** (`outcome` = `FAIL`); at least one later `action` cell MUST start with the literal `GREEN:` and describe the minimal implementation that makes it pass (`outcome` = `PASS`); an optional refactor step starts with `REFACTOR:`. **Exemption:** doc-only / config-only / pure-rename stages with no observable runtime behaviour may omit RED/GREEN by declaring one line `TDD exemption: <reason>` in the stage section. A stage that is truthfully none of those three declares `TDD exemption: user-bypass — <the user's words>`, which holds only while the user has granted it for that stage with `okstra prepare --tdd-bypass "<stage>:<reason>"` — never file the nearest of the three instead. Validator S10c enforces RED-first + GREEN; the `outcome` cell agreeing with its prefix is a schema conditional. S10e rejects an unsupported exemption reason and a `user-bypass` with no user grant (`validators/validate-implementation-plan-stages.py`).
151
152
  - **Real-IO tests stay out of the plan's committed steps (BLOCKING).** A step never creates, edits, or runs a test that opens a real database connection, makes a real network call, or talks to a real external service inside the project source test tree (`src/**`, `test/**`, `tests/**`, `**/__tests__/**`, `*.spec.*`, `*.test.*`, `*.e2e-spec.*`), and no step's `PASS` depends on a reachable database or service. The implementation executor refuses such a step before its first edit (`_implementation-executor.md` "Real-IO test isolation"), so a plan that contains one stops the stage with zero changes (observed 2026-10-18, dev-11374: a live-MySQL `test/font-pairing.e2e-spec.ts` planned in steps 1, 4 and 5). The committed RED/GREEN steps test the adapter with its injected collaborator stubbed — the exact query text, its replacements, and the returned rows — and run without any backend. Real-backend verification is declared only as this stage's `Conformance tests:` line below (`requires=[db|http|external]`): the implementation run writes that script under `<task_root>/qa/scripts/`, runs it against a local or replica backend when one is reachable, never commits it, and records a non-PASS or unreachable backend as advisory. Read a brief line such as `verify: integration test against a test database` as that conformance declaration, not as a committed test. Do not plan a shared real-DB guard, a test DDL fixture, or an edit to an existing real-IO suite in source to support it. **Enforced:** every `P-Step-*` item of the §5.5.9 plan-body round carries this rule to its verifiers (`okstra_ctl.phases.implementation_planning.authoring._REAL_IO_STEP_NOTE`), which vote `DISAGREE(b)` on a step that breaks it; no path pattern tells a mocked test from a live one, so no validator checks it.
152
153
  - **The `command` cell runs inside an okstra task worktree, not a bare checkout (BLOCKING).** okstra provisions `.okstra`, the configured sync entries (`.project-docs`, `.claude`, …), and — for `implementation` — a nested `stage-<N>/` worktree into the tree the step executes in. Two consequences bind every command you write:
153
154
  - **Clean-tree assertions use `okstra worktree-status --check-clean`.** A bare `git status --porcelain` is never empty there, so an assertion built on one fails on okstra's scaffolding rather than on the stage's work. The okstra command asks the same question over source paths only and exits 1 when dirty, so it stands alone as a step's assertion: `okstra worktree-status --check-clean`. Validator S13 rejects the bare form. Do not add a `git tag stage-<N>-exit` to the step. Stage completion records the commit in the consumer ledger without creating or moving git tags.