okstra 0.231.1 → 0.233.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 (265) hide show
  1. package/README.md +19 -271
  2. package/dist/cli-registry.mjs +14 -1
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.d.mts +6 -1
  5. package/dist/commands/execute/render-bundle.mjs +139 -32
  6. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  7. package/dist/commands/lifecycle/config.mjs +6 -74
  8. package/dist/commands/lifecycle/config.mjs.map +1 -1
  9. package/dist/commands/memory/memory.mjs +9 -55
  10. package/dist/commands/memory/memory.mjs.map +1 -1
  11. package/dist/commands/trace/capacity.d.mts +12 -0
  12. package/dist/commands/trace/capacity.mjs +21 -0
  13. package/dist/commands/trace/capacity.mjs.map +1 -0
  14. package/dist/commands/trace/model.d.mts +89 -0
  15. package/dist/commands/trace/model.mjs +251 -0
  16. package/dist/commands/trace/model.mjs.map +1 -0
  17. package/dist/commands/trace/progression.d.mts +11 -0
  18. package/dist/commands/trace/progression.mjs +194 -0
  19. package/dist/commands/trace/progression.mjs.map +1 -0
  20. package/dist/commands/trace/review.d.mts +7 -0
  21. package/dist/commands/trace/review.mjs +51 -0
  22. package/dist/commands/trace/review.mjs.map +1 -0
  23. package/dist/commands/trace/task-link.d.mts +18 -0
  24. package/dist/commands/trace/task-link.mjs +72 -0
  25. package/dist/commands/trace/task-link.mjs.map +1 -0
  26. package/dist/commands/trace/trace.d.mts +1 -0
  27. package/dist/commands/trace/trace.mjs +293 -0
  28. package/dist/commands/trace/trace.mjs.map +1 -0
  29. package/dist/lib/bounded-file.d.mts +1 -0
  30. package/dist/lib/bounded-file.mjs +36 -0
  31. package/dist/lib/bounded-file.mjs.map +1 -0
  32. package/dist/lib/config-store.d.mts +34 -0
  33. package/dist/lib/config-store.mjs +70 -0
  34. package/dist/lib/config-store.mjs.map +1 -0
  35. package/dist/lib/file-lock.mjs +4 -5
  36. package/dist/lib/file-lock.mjs.map +1 -1
  37. package/dist/lib/input-limit.d.mts +4 -0
  38. package/dist/lib/input-limit.mjs +8 -0
  39. package/dist/lib/input-limit.mjs.map +1 -0
  40. package/dist/lib/memory-auto-register.d.mts +1 -0
  41. package/dist/lib/memory-auto-register.mjs +98 -0
  42. package/dist/lib/memory-auto-register.mjs.map +1 -0
  43. package/dist/lib/memory-entry-contract.d.mts +12 -0
  44. package/dist/lib/memory-entry-contract.mjs +46 -0
  45. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  46. package/dist/lib/python-helper.d.mts +1 -1
  47. package/dist/lib/python-helper.mjs +3 -2
  48. package/dist/lib/python-helper.mjs.map +1 -1
  49. package/dist/lib/record-secrets.d.mts +1 -0
  50. package/dist/lib/record-secrets.mjs +28 -0
  51. package/dist/lib/record-secrets.mjs.map +1 -0
  52. package/dist/lib/report-language-tag.d.mts +1 -0
  53. package/dist/lib/report-language-tag.mjs +4 -0
  54. package/dist/lib/report-language-tag.mjs.map +1 -0
  55. package/dist/lib/report-language.d.mts +1 -0
  56. package/dist/lib/report-language.mjs +50 -0
  57. package/dist/lib/report-language.mjs.map +1 -0
  58. package/dist/lib/skill-catalog.mjs +3 -0
  59. package/dist/lib/skill-catalog.mjs.map +1 -1
  60. package/dist/lib/types.d.mts +2 -1
  61. package/docs/architecture/storage-model.md +163 -5
  62. package/docs/architecture.md +17 -4
  63. package/docs/cli.md +511 -0
  64. package/docs/contributor-change-matrix.md +1 -2
  65. package/docs/project-structure-overview.md +33 -42
  66. package/package.json +1 -1
  67. package/runtime/BUILD.json +2 -2
  68. package/runtime/agents/common.json +8 -8
  69. package/runtime/agents/operations/trace-interface-review.json +6 -0
  70. package/runtime/agents/operations/trace-scope-review.json +6 -0
  71. package/runtime/agents/roles/verifier.json +2 -4
  72. package/runtime/bin/okstra-provider-exec.py +10 -4
  73. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  74. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  75. package/runtime/prompts/coding-preflight/clean-code.md +88 -286
  76. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  77. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  78. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  79. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  80. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  81. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  82. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  83. package/runtime/prompts/coding-preflight/overview.md +25 -38
  84. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  85. package/runtime/prompts/duties/code-reviewer.json +15 -18
  86. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  87. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  88. package/runtime/prompts/host-orchestration/README.md +18 -9
  89. package/runtime/prompts/launch.template.md +3 -2
  90. package/runtime/prompts/lead/context-loader.md +2 -0
  91. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  92. package/runtime/prompts/lead/report-writer.md +6 -6
  93. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  94. package/runtime/prompts/profiles/_common-contract.md +1 -1
  95. package/runtime/python/okstra_ctl/agent/invocation.py +122 -36
  96. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +72 -26
  97. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  98. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +58 -14
  99. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  100. package/runtime/python/okstra_ctl/agent/standalone.py +15 -0
  101. package/runtime/python/okstra_ctl/analysis_packet.py +24 -30
  102. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  103. package/runtime/python/okstra_ctl/code_review_census.py +162 -7
  104. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  105. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  106. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  107. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  108. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  109. package/runtime/python/okstra_ctl/code_review_scope.py +49 -9
  110. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  111. package/runtime/python/okstra_ctl/code_review_target.py +212 -13
  112. package/runtime/python/okstra_ctl/consumers.py +12 -9
  113. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  114. package/runtime/python/okstra_ctl/design_review.py +207 -0
  115. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  116. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  117. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  118. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  119. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  120. package/runtime/python/okstra_ctl/doctor.py +8 -25
  121. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  122. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  123. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  124. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  125. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  126. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  127. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  128. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  129. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  130. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  131. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  132. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  133. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +300 -0
  134. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  135. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  136. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  137. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  138. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  139. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  140. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  141. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  142. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  143. package/runtime/python/okstra_ctl/json_boundary.py +51 -5
  144. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  145. package/runtime/python/okstra_ctl/manager_cli.py +148 -1
  146. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  147. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  148. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  149. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  150. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  151. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  152. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  153. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  154. package/runtime/python/okstra_ctl/manager_sync.py +45 -25
  155. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  156. package/runtime/python/okstra_ctl/material.py +2 -0
  157. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  158. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  159. package/runtime/python/okstra_ctl/model_io/renderers.py +16 -2
  160. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  161. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  162. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  163. package/runtime/python/okstra_ctl/paths.py +6 -1
  164. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  165. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  166. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  167. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
  168. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +23 -8
  169. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +6 -4
  170. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
  171. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  172. package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
  173. package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
  174. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  175. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  176. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +16 -9
  177. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  178. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  179. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +6 -6
  180. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  181. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  182. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  183. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  184. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  185. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  186. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  187. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  188. package/runtime/python/okstra_ctl/render.py +28 -2
  189. package/runtime/python/okstra_ctl/report_assembly.py +53 -11
  190. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  191. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  192. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  193. package/runtime/python/okstra_ctl/report_language.py +4 -1
  194. package/runtime/python/okstra_ctl/report_narrative.py +182 -7
  195. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  196. package/runtime/python/okstra_ctl/report_synthesis_packet.py +97 -38
  197. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  198. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  199. package/runtime/python/okstra_ctl/run.py +67 -36
  200. package/runtime/python/okstra_ctl/run_context.py +10 -1
  201. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  202. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  203. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  204. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  205. package/runtime/python/okstra_ctl/task_query.py +239 -0
  206. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  207. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  208. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  209. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  210. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  211. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  212. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  213. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  214. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  215. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  216. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  217. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  218. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  219. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  220. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  221. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  222. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  223. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  224. package/runtime/python/okstra_project/__init__.py +2 -0
  225. package/runtime/python/okstra_project/dirs.py +18 -0
  226. package/runtime/python/okstra_project/state.py +45 -20
  227. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  228. package/runtime/python/okstra_token_usage/cli.py +23 -10
  229. package/runtime/python/okstra_token_usage/collect.py +25 -22
  230. package/runtime/python/okstra_token_usage/policy.py +193 -0
  231. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  232. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  233. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  234. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  235. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  236. package/runtime/schemas/record-secret-patterns.json +41 -0
  237. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  238. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  239. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  240. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  241. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  242. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  243. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  244. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  245. package/runtime/skills/okstra-code-review/SKILL.md +92 -136
  246. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  247. package/runtime/skills/okstra-code-review/references/review-calibration.md +37 -61
  248. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  249. package/runtime/skills/okstra-explain-flow/SKILL.md +6 -2
  250. package/runtime/skills/okstra-manager/SKILL.md +31 -0
  251. package/runtime/skills/okstra-memory/SKILL.md +8 -1
  252. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  253. package/runtime/skills/okstra-run/SKILL.md +55 -183
  254. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  255. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  256. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  257. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  258. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  259. package/runtime/templates/implementation-worker-preamble.md +4 -9
  260. package/runtime/templates/manager/view.template.html +4 -0
  261. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  262. package/runtime/templates/trace/trace.template.md +42 -0
  263. package/runtime/templates/worker-prompt-preamble.md +4 -12
  264. package/runtime/validators/checks/fixtures-02.py +25 -33
  265. package/runtime/validators/validate-run.py +107 -38
@@ -4,7 +4,7 @@
4
4
 
5
5
  Phase 6 gives the report writer all settled analysis, convergence, task, and planning context required for synthesis. Read access supplies context; it does not grant write authority over another owner's file.
6
6
 
7
- The report writer writes only the report narrative Markdown, its pointer record, and its audit sidecar. It must not write or patch `final-report-*.data.json`, the approval decision ledger, activity ledger, team state, convergence state, or design-preparation input.
7
+ The report writer writes only the report authoring input, its pointer record, and its audit sidecar. The run manifest's `reportAuthoringFormat` selects standard JSON for `json-v1`; an absent field selects the existing `markdown-v1` line grammar. `reportNarrativePath` retains its name and identifies that exact input path. Never infer the format from its suffix or change an existing run's format. It must not write or patch `final-report-*.data.json`, the approval decision ledger, activity ledger, team state, convergence state, or design-preparation input.
8
8
 
9
9
  The narrative owns judgments, plan body, summaries, user explanation, recommended steps, and follow-up descriptions. It never owns `designPreparation`, `designSurfaceCoverage`, `executionStatus`, `executionRoles`, `tokenUsage`, `crossVerification`, `approvalContext`, `clarificationItems`, `agentActivity`, or `planBodyVerification`. It must not pre-fill a future round, future gate result, activity identifier, usage value, or resolution.
10
10
 
@@ -14,7 +14,7 @@ Report assembly reads the role-owned inputs, validates them, derives links and s
14
14
 
15
15
  | Input | Owner | Write boundary |
16
16
  |---|---|---|
17
- | report narrative Markdown | report-writer | `reportNarrativePath` |
17
+ | report authoring input in the declared format | report-writer | `reportNarrativePath` |
18
18
  | approval decision ledger | lead | `approvalDecisionsPath` through `okstra approval-decision` |
19
19
  | activity ledger | activity recorder | `leadEventsPath` through `okstra agent-activity append` |
20
20
  | team state and usage | runtime/accounting adapter | `teamStatePath` |
@@ -48,7 +48,7 @@ project-relative path and value. The report writer receives the
48
48
  packet's Markdown reading projection as the only task input instead of an
49
49
  independently assembled list of raw paths.
50
50
 
51
- The packet's authoring contract names the result path, narrative format, writing
51
+ The packet's authoring contract names the result path, selected authoring format, writing
52
52
  instructions, runtime-owned content, and validation rules. Missing configured
53
53
  paths and missing files are collected across the full source set before dispatch
54
54
  and reported together with their owners. Report assembly checks source availability
@@ -89,13 +89,13 @@ For `rewrite`, the materialized correction-only prompt supplies target values, c
89
89
 
90
90
  This section adds report-specific checks to [okstra-lead-contract](./okstra-lead-contract.md) "Worker instruction quality gate"; it does not limit that common gate to report-writer calls. A follow-up dispatch that revises a narrative which already exists and whose structure parses is a corrective dispatch, and its instruction is a corrections ledger, not prose:
91
91
 
92
- 1. Preserve the attempt: copy the current narrative to `worker-results/report-writer-narrative-a<N>-<task-type>-<seq>.md`. The ledger's `baseNarrativePath` names that copy, never the live `reportNarrativePath` — the correction overwrites the live file, and the copy is what the writer (or `apply-corrections`) reads.
92
+ 1. Preserve the attempt: copy the current input to a distinct attempt file in the same `worker-results/` directory, inserting `-a<N>` into its filename and retaining its actual `.json` or `.md` extension. Take the source path from `reportNarrativePath`. The ledger's `baseNarrativePath` names that copy, never the live `reportNarrativePath` — the correction overwrites the live file, and the copy is what the writer (or `apply-corrections`) reads. The preserved copy uses the run's declared format too.
93
93
  2. The ledger lives at `runs/<task-type>/state/report-writer-corrections-<task-type>-<seq>-a<N>.json` (schema `schemas/report-writer-corrections-v1.0.schema.json`) and holds one entry per defect: `replace` with the exact replacement value (add `current` when you want it checked), `remove` for an item or optional field, `rewrite` with a `rule` when the writer has to re-author prose. Paths use the validator's grammar (`implementationOptionSelection.rankedOptions[1].coverageSummary.coveragePercent`), so a report-assembly refusal can be copied into the ledger verbatim. Never write an indirect instruction such as `use the schema value`, `use the valid status`, or `fix the enum`: a `replacement` is the literal, and a `rule` names the required outcome. You do not copy allowed enum literals by hand — okstra attaches each `rewrite`'s schema constraint from the frozen schema.
94
94
  3. Run `okstra agent-prompt check-corrections --project-root <root> --run-manifest <path> --corrections <ledger>` until it reports no defect. It applies the ledger to a scratch copy of the base narrative and validates the complete proposed narrative against the writer-owned value schema and the task's semantic validator, listing every defect at once. Validating only the edited field is insufficient because one replacement can select a different schema branch, which is why the check covers the whole narrative.
95
95
  4. When the check reports `mechanical: true` and has corrections, run `okstra agent-prompt apply-corrections` with the same arguments: okstra writes the corrected narrative to `reportNarrativePath` and records a `lead-correction-applied` activity row naming the ledger and its correction ids. This includes validated `replace`, `remove`, `add`, `move`, and derived step counts. No writer dispatch, `record-dispatch`, or `link-result` follows; the roster row's result already exists.
96
96
  5. Otherwise materialize the writer prompt with the same `--corrections <ledger>` under a new invocation id and prompt path (when the first attempt's result is linked, retire that link with `reject-result` as `plan-body-verification` (the absolute path in **Okstra Runtime Resources**) describes; a dispatch that ended in `error` has no link, so skip that step). okstra renders the correction-only field values, evidence, schema constraints, replacement-file contract, application command, and output paths. Put context in the ledger; the initial instruction body is not sent to the correction writer.
97
97
 
98
- A report-writer materialization without `--corrections` whose narrative already exists and parses is refused before any prompt is written — free-form corrections cannot be checked before the writer runs, and four of six re-runs in the 2026-09-03 measurement were lead instructions that contradicted the authoring contract. Only a narrative whose structure does not parse (line grammar, an unknown top-level field) is re-authored, not corrected: that dispatch needs no ledger, and its body quotes the parser's message. Because re-authoring overwrites the live file in place, okstra copies the existing narrative to `worker-results/<narrative-name>.pre-<invocation-id>.md` at materialization and renders a `## Previous Attempt` section naming that copy (**Enforced:** `_preserve_reauthored_narrative` in `scripts/okstra_ctl/agent/prompt_cli/materialize.py`); the 2026-09-09 dev-10642 run lost a 579-line attempt to a failed in-place re-indent command with no copy to fall back on. A narrative that breaks the line grammar is not a produced artifact: the dispatcher settles that attempt as `required worker artifact is unusable: narrative does not parse: …` and retries it inside the same batch, so you see the parser's message at collection, not at Phase 7 assembly (**Enforced:** `okstra_ctl.dispatch_state.unusable_result_defect`, read by `missing_completion_paths` and the `team await` record path). The synthesis packet's Authoring Contract carries the line grammar itself (`report_narrative.NARRATIVE_GRAMMAR_INSTRUCTIONS`), so a writer that reads only the packet still sees it. Value defects — an id outside its pattern, a value outside its enum, a missing required field — leave the structure readable and are exactly what the ledger fixes; the a3 attempt of the 2026-09-03 run carried twenty `SC-` ids that assembly refused and was still a corrective base.
98
+ A report-writer materialization without `--corrections` whose narrative already exists and parses is refused before any prompt is written — free-form corrections cannot be checked before the writer runs. Only an input whose structure does not parse under the run's declared format is re-authored: that dispatch needs no ledger, and its body quotes the parser's message. Before overwriting the live input, okstra preserves a `worker-results/<narrative-stem>.pre-<invocation-id><original-extension>` copy and renders a `## Previous Attempt` section naming it. Retain the actual `.json` or `.md` extension and the run's declared format (**Enforced:** `_preserve_reauthored_narrative` in `scripts/okstra_ctl/agent/prompt_cli/materialize.py`). An input that breaks its declared syntax is not a produced artifact: the dispatcher settles that attempt as `required worker artifact is unusable: narrative does not parse: …` and retries it inside the same batch, so the parser's message appears at collection (**Enforced:** `okstra_ctl.dispatch_state.unusable_result_defect`, read by `missing_completion_paths` and the `team await` record path). The synthesis packet carries `JSON_NARRATIVE_INSTRUCTIONS` for `json-v1` or `NARRATIVE_GRAMMAR_INSTRUCTIONS` for `markdown-v1`. Value defects — an id outside its pattern, a value outside its enum, a missing required field — leave the structure readable and are handled by the correction ledger.
99
99
 
100
100
  **Enforced:** `_with_report_writer_sections` / `_refuse_free_form_correction` in `scripts/okstra_ctl/agent/prompt_cli/materialize.py`, `report_corrections.check_corrections`, `agent/prompt_cli/corrections.run_corrections_apply`; the retired Python suite and the retired Python suite keep this procedure in the lead contract.
101
101
 
@@ -107,7 +107,7 @@ A report-writer materialization without `--corrections` whose narrative already
107
107
  4. Apply at most one automatic planner self-fix to the narrative. Skip this step when `gating` is `false`.
108
108
  5. Run targeted re-verification as round 2 when needed. Skip this step when `gating` is `false`.
109
109
  6. Persist the completed `planBodyVerification` value in convergence state. Run `okstra plan-items next-dispatch`: after the single automatic self-fix, settle eligible judgements with `resolve-dissent`; ask the user immediately for decisions outside lead authority. Preserve dissent and do not restart the automatic loop. The exact procedure and enforced authority checks are in `scripts/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md` step 8.
110
- 7. Complete the design-surface detector snapshot: `okstra design-snapshot --narrative <reportNarrativePath> --output <designPreparationPath>`, taking both paths from the run manifest. Nothing else writes that snapshot, and step 8 fails without it — `report_inputs._PLANNING_INPUT_FIELDS` lists `designPreparationPath` as a required planning input.
110
+ 7. Complete the design-surface detector snapshot: `okstra design-snapshot --run-manifest <current-run-manifest> --narrative <reportNarrativePath> --output <designPreparationPath>`, taking both paths and the declared authoring format from that same run manifest. Nothing else writes that snapshot, and step 8 fails without it — `report_inputs._PLANNING_INPUT_FIELDS` lists `designPreparationPath` as a required planning input.
111
111
  8. Run Phase 7 report assembly.
112
112
 
113
113
  The writer never predicts steps 3–7 in its draft. The plan-body verifier reads the plan body, and report assembly adds its completed result afterward.
@@ -13,13 +13,48 @@ prompt through `prepare_agent_invocation()` before `worker-dispatch`.
13
13
 
14
14
  # Coding-conventions preflight (BLOCKING — runs before the first `Edit` / `Write`, and binds the TDD loop)
15
15
 
16
+ When Verification inputs contains a Frozen Review Policy, apply its captured
17
+ sources and architecture declaration instead of live settings and installed
18
+ rules. Read the content through the verification-input projection; original
19
+ paths identify provenance, not permission to replace frozen content. Select the
20
+ applicable language/framework/architecture resources with the router below.
21
+ The captured `review-rules.json` supplies shared rule IDs and grading metadata.
22
+ External rule sources do not authorize posting reviews or spawning agents.
23
+ Use `okstra model-io verification-input --run-manifest <run-manifest>` with one
24
+ `--source-path <repository-relative-path>` per relevant changed file in that
25
+ single call. Its selected bodies are normative; the default available-resource
26
+ index is not proof that language/framework rules were read.
27
+ For applicable rules not established by path/manifest routing, such as embedded
28
+ SQL in an ORM query, add `--resource <pack-relative-id>` in the same call and use
29
+ only resources present in the captured archive.
30
+ For a source-writing assignment, also select `--resource authoring-checks.md`
31
+ when the frozen inventory lists it. Read that captured resource before editing.
32
+ Older captures keep those procedures in `overview.md`; use that captured text.
33
+ For an unfrozen legacy input, read `authoring-checks.md` beside the installed
34
+ overview when present, otherwise retain its older embedded procedures.
35
+
36
+ Use `clean-code.md` "Finding evidence and grading" and the shared catalog for
37
+ severity and timing. Fix current blocking findings before completion. A plan
38
+ placement restriction is a plan conflict, not a waiver of naming, responsibility
39
+ or test-quality rules; propose the conforming placement and preserve acceptance.
40
+ Use `overview.md` policy precedence: explicit repository instructions and declared
41
+ architecture, the common pack, then surrounding code conventions. A surrounding
42
+ pattern alone does not waive an explicit architecture rule.
43
+
44
+ Apply the captured `clean-code.md` "Five simultaneous quality outcomes" before
45
+ editing: correctness, coding principles, performance, safety and security all
46
+ retain their applicable acceptance conditions. Use existing plan, validation and
47
+ result fields for the expected outcomes, bounds and evidence. Missing required
48
+ policy, performance bounds or execution evidence stays explicit and unverified.
49
+ Read complete selected rule sections; never clip normative lines to save context.
50
+
16
51
  Load the applicable coding conventions for every language the diff will touch, then state in ONE line which conventions apply (e.g. `Applying TS + hexagonal overlay; domain at src/domains/*/domain/`). Lint/test green is necessary but NOT sufficient — self-mocked tests, interaction-only assertions, and untruthful names all pass a green pipeline; this gate is what keeps them out of the diff.
17
52
 
18
53
  - **Reuse tests for function changes:** search by function behavior and callers, then read candidate test bodies before editing. Strengthen an existing behavior test; if it already verifies the changed contract, run and retain it. Add a test only when no existing test covers that behavior, preferably in an existing file. Record the function and reused test location or the uncovered outcome. Do not create tests per helper or branch, repeat the same input/outcome, or generate model/provider/task-type combinations without distinct behavior. This rule also applies when routed resources are unavailable. Completion self-check and code review assess the evidence; there is no test-count target.
19
54
 
20
- - **Resource selection — read the routed pack, never inline it here.** Use this worker prompt's `**Coding preflight pack:**` anchor header as the absolute path to the installed routed pack. Detect each touched file's language and framework from its extension or project manifest (`package.json`, `Cargo.toml`, `pyproject.toml`, `pom.xml`, `build.gradle*`, `prisma/schema.prisma`), then read that pack's resources via the Read tool by absolute path. Always read `overview.md` (the router) + `clean-code.md`, then select per the router's three ordered stages — Stage 1 language → `languages/<lang>.md`, Stage 2 framework → `frameworks/<fw>.md` (e.g. `frameworks/node-server.md` for server-side Node), Stage 3 architecture → `architectures/<arch>.md` (e.g. `architectures/hexagonal.md` for ports-and-adapters / NestJS-hex). Each stage is a list of rules; include EVERY matching resource (a change set can touch multiple languages/frameworks/architectures) — do not stop at the first match. These files are runtime resources, not Skill-tool skills, so always read them by path.
21
- - **Project policy projection:** before selecting resources, run `okstra model-io project-context --project-root <PROJECT_ROOT> --task-ref <TASK_KEY>` (the full `Task key` your dispatch prompt names). Consume its `Architecture style` and `Project Review Rule Packs` sections. Follow the `**Verification inputs:**` declaration-source rule when that header is present; use the named `okstra model-io verification-input --run-manifest <run-manifest>` projection for frozen declarations. The legacy lookup uses the projection's `Project QA Commands` only for an unfrozen baseline. Consume fixed text projections; do not open Okstra-owned JSON storage.
22
- - **Declared architecture style — an authoritative Stage 3 input, and it binds.** A projected `hexagonal` selects `architectures/hexagonal.md` even when none of Stage 3's layout signals matched, so the declaration — not the directory shape — decides. A projected `layered` has no pack resource; its invariant applies from this line: dependencies run one direction only — an upper layer may import a lower one, never the reverse — and a variation point is extracted onto a layer boundary. A declared style makes this overlay binding rather than advisory, and which rule binds follows the style: under `hexagonal` the overlay's otherwise-advisory concrete-adapter item is blocking, so a service dependency you add or modify goes through a port instead of a concrete implementation and that placement violation is fixed before the write rather than recorded as a note; under `layered` what binds is the direction invariant just stated — your own judgement over the import list of every file the diff touches, plus extracting a variation point onto a layer boundary — while the concrete-adapter item stays advisory, since `layered` has no ports to route it through. An absent or `none` projected style leaves Stage 3 detection-driven and its overlay advisory. The verifier re-grades the same diff under the same declaration (`_implementation-verifier.md` → Static design & test-quality review), so a placement violation missed here returns as a verdict `FAIL`.
23
- - **Project review rule packs:** a pack applies when either source names it — the task brief's `Source Material` / `Reporter Confirmations` cites its exact `SKILL.md` path, or the project-context projection lists it as a standing standard. The two sources are a union. Read only those files and the `references/*.md` files they directly name; a declared path that will not open is recorded as `project-review-rules: declared <path> unreadable`, never silently dropped. Do not search parent directories or host skill catalogs. Apply those rules during implementation as a prevention pass, not a PR-comment generation workflow: do not dispatch reviewer subagents from the executor. For Fonts Ninja-style PR review packs, the executor must avoid newly introduced duplicate helper stacks, tautological tests that merely re-call the delegated helper, self-mocking, domain rules in adapters/ports, domain objects outside `domain/`, dead APIs, weak public names, and functions that fail the plain-English read.
24
- - **Language-agnostic principles that ALWAYS bind (the TDD loop MUST satisfy them):** (1) no self-mocking of the SUT — stub/spy only injected collaborators, never the subject's own methods; (2) behavioral assertions on outcomes (return value, state, persisted rows, events, boundary calls) — never `toHaveBeenCalled*` on an internal helper as the only/primary assertion; (3) truthful names — a `get*` / `find*` that writes/inserts, or a name encoding the caller's use-case (`*ForInit`) or hiding a domain rule (`findValid*`), is a defect; (4) single-purpose functions ≤50 effective lines, plain-English readability. Self-mocking (1) — Enforced by `validators/detect_self_mock.py` (static), which the implementation **verifier** runs; it is never delegated to the executor (`_implementation-verifier.md` §"Self-mock detection"). Naming the enforcement here says who will check your diff, not that you should run the check: the executor's half is satisfying principle (1) in the code it writes, and it MUST NOT invoke the detector or write `<task_root>/qa/self-mock-*.json`. **Enforced:** that sidecar is not among the paths an executor attempt's `writePolicy.artifactPolicy.allowedPaths` carries, so writing it closes an otherwise-passing stage as `error` with `artifact-root change exceeds batch policy union` (`scripts/okstra_ctl/execution_mutation_audit.py`). The sidecar's absence BLOCKS at `validate-run.py` on the verifier's report.
25
- - **Graceful degradation (codex / antigravity executor runtimes, or any runtime where the resolved coding-preflight pack files are absent or unreadable):** do NOT skip the gate — apply the agnostic principles above plus the project's own `CLAUDE.md` / `CONTRIBUTING` / formatter+lint config, and record `coding-conventions: resource-unavailable → applied <project rules + agnostic principles>` in the final report. Never claim a resource read that did not happen.
55
+ - **Resource selection:** use the selected frozen policy above when present. Only legacy inputs without a frozen policy use the `**Coding preflight pack:**` installed path. Read `overview.md` and `clean-code.md`, then select every matching language, framework and architecture resource for the changed files and relevant manifests. Server-side Node includes both JavaScript/TypeScript and Node-server rules. A frozen resource's absence is a blocked input, not permission to substitute live content.
56
+ - **Project policy projection:** a `**Verification inputs:**` declaration supplies the policy and QA baseline through its named projection. Only an unfrozen legacy baseline uses `okstra model-io project-context --project-root <PROJECT_ROOT> --task-ref <TASK_KEY>` and its `Architecture style`, `Project Review Rule Packs` and `Project QA Commands` sections. Consume fixed text projections; do not open Okstra-owned JSON storage.
57
+ - **Declared architecture style — an authoritative Stage 3 input.** A projected `hexagonal` selects `architectures/hexagonal.md` even without layout signals. Apply H1–H6 and the policy precedence above; declaration also makes H5's otherwise-advisory concrete-adapter item binding. A projected `layered` selects no pack resource: dependencies run from upper to lower layers, never in reverse, and variation points sit on layer boundaries; ports are not required. An explicit `none` selects no architecture overlay. Only an absent or `undeclared` style uses layout detection; an inferred hexagonal overlay retains each rule's criteria and severity, including H5's undeclared-style advisory exception. The verifier applies the same policy; an established current blocking placement violation returns `FAIL`.
58
+ - **Project review rule packs:** union the policy's standing standards with exact `SKILL.md` paths cited by the task brief's `Source Material` / `Reporter Confirmations`. With a frozen policy, read their captured bodies and directly named captured `references/*.md` bodies through the verification-input projection, not live originals. A cited pack or reference missing from that capture is blocked input to report for recapture; do not omit it or substitute live content. Only unfrozen legacy inputs obtain standing standards from project-context and read those declared files and their directly named references; record an unreadable declaration as `project-review-rules: declared <path> unreadable`. Do not search parent directories or host skill catalogs. Apply those rules during implementation as a prevention pass, not a PR-comment generation workflow: do not dispatch reviewer subagents from the executor. For Fonts Ninja-style PR review packs, inspect newly introduced duplicate helper stacks, tautological tests that merely re-call the delegated helper, self-mocking, domain rules in adapters/ports, domain objects outside `domain/`, dead APIs, misleading public names and mixed responsibilities under their applicable criteria. Establish the explicit project rule breach or concrete maintenance or design impact before treating a preferred alternative as a finding.
59
+ - **Language-agnostic principles (apply under the policy precedence above):** (1) no self-mocking of the SUT — stub/spy only injected collaborators, never the subject's own methods; (2) behavioral assertions on outcomes (return value, state, persisted rows, events, boundary calls) — never `toHaveBeenCalled*` on an internal helper as the only/primary assertion; (3) truthful names that disclose caller-visible mutations and define business terms; domain-oriented query names alone are not defects when their port contract identifies the domain-owned policy; (4) cohesive responsibility, manageable complexity, consistent abstraction levels and comprehensible control flow. More than 50 effective lines, deep nesting or inline phases prompt inspection, not an automatic split or failure; record the concrete impact or the reason for retaining a cohesive longer function. Use focused regression and failure tests, with selective mutation checks under `clean-code.md` "Testing discipline" and explicit project requirements. Self-mocking (1) — Enforced by `validators/detect_self_mock.py` (static), which the implementation **verifier** runs; it is never delegated to the executor (`_implementation-verifier.md` §"Self-mock detection"). Naming the enforcement here says who will check your diff, not that you should run the check: the executor's half is satisfying principle (1) in the code it writes, and it MUST NOT invoke the detector or write `<task_root>/qa/self-mock-*.json`. **Enforced:** that sidecar is not among the paths an executor attempt's `writePolicy.artifactPolicy.allowedPaths` carries, so writing it closes an otherwise-passing stage as `error` with `artifact-root change exceeds batch policy union` (`scripts/okstra_ctl/execution_mutation_audit.py`). The sidecar's absence BLOCKS at `validate-run.py` on the verifier's report.
60
+ - **Legacy graceful degradation:** if no frozen policy exists and installed resources are unreadable, apply the agnostic principles above and the project's local rules, record `coding-conventions: resource-unavailable → applied <project rules + agnostic principles>`, and keep unavailable verification explicit. Do not degrade a readable captured policy merely because its original installation is absent. Never claim an unperformed read.
@@ -14,7 +14,7 @@ profile document.
14
14
  - For a new `implementation-planning` run, the plan-body sequence is initial verification → one planner self-fix → targeted re-verification → user gate. The initial verification is round 1, the targeted re-verification is round 2, and a second automatic self-fix is a contract violation. A user-directed correction does not consume the automatic self-fix limit, and a verification failure after that correction does not restart the automatic loop.
15
15
  - **provider-unavailable fallback (tolerance).** A worker dispatch can fail to produce a result for two distinct reasons, and both take the same recovery path. (1) **Pane budget:** the dispatch is rejected because a teammate pane could not be created — this is the harness running out of room for its own teammate panes, not okstra placing a worker. The wording is the host's, so match the condition rather than a fixed string. (2) **Sandbox CLI-start failure:** an external CLI worker wrapper exits non-zero within seconds with empty stdout and its live-log shows `operation not permitted`. In either case the lead spends the one shared retry budget through the assignment's recorded runner. If the provider is still unavailable, record that terminal status and continue only under the convergence quorum rules; never replace it silently with a fixed provider or count a substitute as the original provider's vote. Completed external-CLI workers hold no pane of their own. A pane the harness opened for its own teammate carries no id okstra recorded, so no okstra command closes it — the host and the user own that surface. (This is a prompt instruction, not a code-enforced gate.)
16
16
  - Dual-audience final-report contract (shared):
17
- - The report writer authors the report narrative Markdown. Report assembly combines it with role-owned machine inputs and publishes data.json once; the reading copy and human HTML are derived from that record.
17
+ - The report writer authors the input at the run manifest's `reportNarrativePath` using its declared `reportAuthoringFormat`: standard JSON for `json-v1`, or the existing narrative line grammar for `markdown-v1` when the field is absent. Description strings in JSON may contain ordinary Markdown. Report assembly combines it with role-owned machine inputs and publishes data.json once; the reading copy and human HTML are derived from that record.
18
18
  - User-facing information belongs in `humanSummary` and the selected task block's `userNarrative`; it must not exist only in Markdown. The HTML human main body explains the result with those fields plus task facts.
19
19
  - Agent coordination and audit details belong in `crossVerification`, `executionStatus`, and `tokenUsage`. HTML may expose them only inside collapsed audit details, never as the primary result.
20
20
  - Clarification and approval controls are rendered from the lead-owned approval decision ledger after report assembly. A question that could have been resolved before dispatch through the profile or Reporter Confirmations is an intake failure, not a final-report question.
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
  from pathlib import PurePosixPath
13
13
  import re
14
14
  import tempfile
15
- from typing import Any, Iterator, Literal, Mapping, get_args
15
+ from typing import TYPE_CHECKING, Any, Iterator, Literal, Mapping, get_args
16
16
 
17
17
  from ..domain.role import RoleCatalogError, role_for_duty
18
18
  from ..verification_invocation import (
@@ -26,6 +26,9 @@ from ..json_boundary import (
26
26
  load_owned_object,
27
27
  )
28
28
 
29
+ if TYPE_CHECKING:
30
+ from ..code_review_invocation import CodeReviewInputs
31
+
29
32
 
30
33
  AgentAudience = Literal[
31
34
  "lead",
@@ -45,6 +48,7 @@ AgentAudience = Literal[
45
48
  "report-writer",
46
49
  "code-reviewer",
47
50
  "schedule-verifier",
51
+ "interface-reviewer",
48
52
  "business-flow-investigator",
49
53
  ]
50
54
 
@@ -190,6 +194,7 @@ class AgentInvocationRequest:
190
194
  # dispatch has used it. See `_publish_or_reuse`.
191
195
  replace_undispatched: bool = False
192
196
  verification_generation: VerificationGenerationReference | None = None
197
+ review_inputs: CodeReviewInputs | None = None
193
198
 
194
199
 
195
200
  @dataclass(frozen=True)
@@ -648,6 +653,9 @@ def prepare_agent_invocation(
648
653
  """Materialize one immutable prompt and its adjacent completion metadata."""
649
654
  request = _bind_generation_request(request)
650
655
  _validate_request(request)
656
+ from ..code_review_invocation import bind_review_invocation
657
+
658
+ request = bind_review_invocation(request)
651
659
  materialized = _materialize(request)
652
660
  if materialized.reservation_root is None:
653
661
  with _exclusive_lock(_prompt_lock_path(request.prompt_path)):
@@ -944,8 +952,9 @@ def publish_standalone_completion(
944
952
  invocation_id=invocation_id,
945
953
  metadata_path=canonical_metadata,
946
954
  )
955
+ review_audit = _complete_standalone_review_audit(project_root, canonical_metadata)
947
956
  completion = {
948
- "schemaVersion": 1,
957
+ "schemaVersion": 2 if review_audit is not None else 1,
949
958
  "purpose": purpose,
950
959
  "invocationId": invocation_id,
951
960
  "status": "completed",
@@ -962,10 +971,34 @@ def publish_standalone_completion(
962
971
  "resultEnvelopeDigest": _sha256(envelope_bytes),
963
972
  "completedAt": completed,
964
973
  }
974
+ if review_audit is not None:
975
+ completion["reviewAuditDigest"] = review_audit
965
976
  _publish_exclusive(completion_path, _canonical_json(completion))
966
977
  return completion_path
967
978
 
968
979
 
980
+ def _complete_standalone_review_audit(project_root: Path, metadata_path: Path) -> str | None:
981
+ from ..code_review_invocation import complete_review_audit
982
+
983
+ try:
984
+ return complete_review_audit(
985
+ project_root, metadata_path,
986
+ _load_json_object(metadata_path, "agent invocation metadata"),
987
+ )
988
+ except (OSError, ValueError, KeyError) as exc:
989
+ raise AgentInvocationError(f"standalone review integrity failed: {exc}") from exc
990
+
991
+
992
+ @dataclass(frozen=True)
993
+ class _StandaloneCompletion:
994
+ payload: Mapping[str, Any]
995
+ invocation_id: str
996
+ root: Path
997
+ metadata_path: Path
998
+ result_path: Path
999
+ completion_path: Path
1000
+
1001
+
969
1002
  def verify_standalone_completion(
970
1003
  completion_path: Path,
971
1004
  *,
@@ -973,6 +1006,49 @@ def verify_standalone_completion(
973
1006
  expected_purpose: str,
974
1007
  ) -> VerifiedStandaloneResult:
975
1008
  """Verify a completion marker and return its already-read immutable body."""
1009
+ context = _read_standalone_completion(completion_path, project_root, expected_purpose)
1010
+ with _exclusive_lock(context.root / f"{context.invocation_id}.result.publish.lock"):
1011
+ authority_id, _authority_root, canonical_metadata = _standalone_authority(
1012
+ project_root=project_root,
1013
+ purpose=expected_purpose,
1014
+ metadata_path=context.metadata_path,
1015
+ )
1016
+ if authority_id != context.invocation_id:
1017
+ raise AgentInvocationError("standalone completion identity does not match")
1018
+ envelope_bytes, returned_body = _verified_result_envelope(
1019
+ context.result_path,
1020
+ project_root=project_root,
1021
+ purpose=expected_purpose,
1022
+ invocation_id=context.invocation_id,
1023
+ metadata_path=canonical_metadata,
1024
+ )
1025
+ digest = _sha256(envelope_bytes)
1026
+ if context.payload.get("resultEnvelopeDigest") != digest:
1027
+ raise AgentInvocationError("result envelope digest does not match completion")
1028
+ from ..code_review_invocation import verify_review_completion
1029
+
1030
+ try:
1031
+ verify_review_completion(
1032
+ project_root, canonical_metadata,
1033
+ _load_json_object(canonical_metadata, "agent invocation metadata"),
1034
+ context.payload,
1035
+ )
1036
+ except (OSError, ValueError, KeyError) as exc:
1037
+ raise AgentInvocationError(f"standalone review integrity is invalid: {exc}") from exc
1038
+ return VerifiedStandaloneResult(
1039
+ purpose=expected_purpose,
1040
+ invocation_id=context.invocation_id,
1041
+ prompt_metadata_path=context.metadata_path,
1042
+ result_path=context.result_path,
1043
+ completion_path=context.completion_path,
1044
+ result_envelope_digest=digest,
1045
+ returned_body=returned_body,
1046
+ )
1047
+
1048
+
1049
+ def _read_standalone_completion(
1050
+ completion_path: Path, project_root: Path, expected_purpose: str,
1051
+ ) -> _StandaloneCompletion:
976
1052
  _validate_slug(expected_purpose, "standalone purpose")
977
1053
  completion = _load_json_object(completion_path, "standalone completion")
978
1054
  expected_keys = {
@@ -985,7 +1061,9 @@ def verify_standalone_completion(
985
1061
  "resultEnvelopeDigest",
986
1062
  "completedAt",
987
1063
  }
988
- if set(completion) != expected_keys or completion.get("schemaVersion") != 1:
1064
+ if completion.get("schemaVersion") == 2:
1065
+ expected_keys.add("reviewAuditDigest")
1066
+ if set(completion) != expected_keys or completion.get("schemaVersion") not in (1, 2):
989
1067
  raise AgentInvocationError("standalone completion schema is invalid")
990
1068
  if completion.get("purpose") != expected_purpose:
991
1069
  raise AgentInvocationError("standalone completion purpose does not match")
@@ -1013,32 +1091,8 @@ def verify_standalone_completion(
1013
1091
  must_exist=True,
1014
1092
  ):
1015
1093
  raise AgentInvocationError("standalone completion result path does not match")
1016
- with _exclusive_lock(root / f"{invocation_id}.result.publish.lock"):
1017
- authority_id, _authority_root, canonical_metadata = _standalone_authority(
1018
- project_root=project_root,
1019
- purpose=expected_purpose,
1020
- metadata_path=metadata_path,
1021
- )
1022
- if authority_id != invocation_id:
1023
- raise AgentInvocationError("standalone completion identity does not match")
1024
- envelope_bytes, returned_body = _verified_result_envelope(
1025
- result_path,
1026
- project_root=project_root,
1027
- purpose=expected_purpose,
1028
- invocation_id=invocation_id,
1029
- metadata_path=canonical_metadata,
1030
- )
1031
- digest = _sha256(envelope_bytes)
1032
- if completion.get("resultEnvelopeDigest") != digest:
1033
- raise AgentInvocationError("result envelope digest does not match completion")
1034
- return VerifiedStandaloneResult(
1035
- purpose=expected_purpose,
1036
- invocation_id=invocation_id,
1037
- prompt_metadata_path=metadata_path,
1038
- result_path=result_path,
1039
- completion_path=canonical_completion,
1040
- result_envelope_digest=digest,
1041
- returned_body=returned_body,
1094
+ return _StandaloneCompletion(
1095
+ completion, invocation_id, root, metadata_path, result_path, canonical_completion,
1042
1096
  )
1043
1097
 
1044
1098
 
@@ -1090,6 +1144,8 @@ def _verified_result_envelope(
1090
1144
  invocation_id: str,
1091
1145
  metadata_path: Path,
1092
1146
  ) -> tuple[bytes, str]:
1147
+ project_root = project_root.resolve(strict=True)
1148
+ result_path = result_path.parent.resolve(strict=True) / result_path.name
1093
1149
  try:
1094
1150
  body = result_path.read_bytes()
1095
1151
  envelope = load_external_json(
@@ -1184,11 +1240,30 @@ def _bind_generation_request(request: AgentInvocationRequest) -> AgentInvocation
1184
1240
  try:
1185
1241
  manifest = _load_request_manifest(request)
1186
1242
  reference = _typed_generation_reference(request)
1187
- _require_sealed_generation(
1243
+ generation = read_invocation_generation(
1188
1244
  request.project_root, request.run_manifest_path, manifest,
1189
1245
  reference, request.audience,
1190
1246
  )
1191
- return _with_generation_anchors(request, reference)
1247
+ bound = _with_generation_anchors(request, reference)
1248
+ if generation is not None and "designReview" in generation:
1249
+ from ..design_review import render_design_review
1250
+
1251
+ supplement = render_design_review(generation["designReview"])
1252
+ from ..design_review_evidence import prior_design_review_prompt
1253
+
1254
+ supplement += prior_design_review_prompt(
1255
+ request.project_root, request.run_manifest_path,
1256
+ request.role_execution_ref, generation["generation"],
1257
+ request.invocation_ref, request.attempt,
1258
+ )
1259
+ body = bound.instruction.body
1260
+ if not body.rstrip().endswith(supplement.rstrip()):
1261
+ if "\n## Frozen Design Review\n" in body:
1262
+ raise ValueError("design review body differs from sealed generation")
1263
+ bound = replace(bound, instruction=replace(
1264
+ bound.instruction, body=body.rstrip() + "\n" + supplement,
1265
+ ))
1266
+ return bound
1192
1267
  except (OSError, ValueError) as exc:
1193
1268
  raise AgentInvocationError(str(exc)) from exc
1194
1269
 
@@ -1973,6 +2048,9 @@ def _verify_prompt_file(
1973
2048
  errors.extend(_verify_model_header(metadata, body))
1974
2049
  errors.extend(_verify_execution_delivery(metadata, path, body))
1975
2050
  errors.extend(_verify_generation_reference(metadata, project_root, body))
2051
+ from ..code_review_invocation import review_policy_errors_for_prompt
2052
+
2053
+ errors.extend(review_policy_errors_for_prompt(project_root, metadata, body))
1976
2054
  return errors
1977
2055
 
1978
2056
 
@@ -2010,6 +2088,16 @@ def reserved_generation_reference(
2010
2088
  The reservation names the metadata, so a reader does not take a generation
2011
2089
  file on the strength of the path its dispatch kind computes.
2012
2090
  """
2091
+ metadata_path = reserved_invocation_metadata_path(project_root, manifest, invocation_ref, attempt)
2092
+ if metadata_path is None:
2093
+ return None
2094
+ metadata = _load_json_object(metadata_path, "agent invocation metadata")
2095
+ return metadata_generation_reference(metadata)
2096
+
2097
+
2098
+ def reserved_invocation_metadata_path(
2099
+ project_root: Path, manifest: Mapping[str, object], invocation_ref: str, attempt: int,
2100
+ ) -> Path | None:
2013
2101
  contract = manifest.get("agentContract")
2014
2102
  if not isinstance(contract, Mapping):
2015
2103
  return None
@@ -2020,17 +2108,15 @@ def reserved_generation_reference(
2020
2108
  if not path.is_file():
2021
2109
  return None
2022
2110
  reservation = _load_json_object(path, "invocation reservation")
2023
- metadata = _load_json_object(
2024
- _project_path(project_root, reservation.get("metadataPath"), must_exist=True),
2025
- "agent invocation metadata",
2026
- )
2111
+ metadata_path = _project_path(project_root, reservation.get("metadataPath"), must_exist=True)
2112
+ metadata = _load_json_object(metadata_path, "agent invocation metadata")
2027
2113
  for payload in (reservation, metadata):
2028
2114
  if (payload.get("invocationRef"), payload.get("attempt")) != (
2029
2115
  invocation_ref, attempt):
2030
2116
  raise AgentInvocationError(
2031
2117
  f"invocation reservation {path} names another invocation attempt"
2032
2118
  )
2033
- return metadata_generation_reference(metadata)
2119
+ return metadata_path
2034
2120
 
2035
2121
 
2036
2122
  def _attempt_invocation_id(invocation_ref: str, attempt: int) -> str:
@@ -7,8 +7,11 @@ TypeScript 포워더가 들고 있던 USAGE 문자열이 여기로 왔다.
7
7
  from __future__ import annotations
8
8
 
9
9
  import argparse
10
+ import json
11
+ from collections.abc import Sequence
10
12
  from pathlib import Path
11
13
  import sys
14
+ from typing import TYPE_CHECKING
12
15
 
13
16
  from ..invocation import AgentInvocationError
14
17
  from ...worker_prompt_headers import WorkerPromptHeaderError
@@ -32,6 +35,9 @@ from .results import (
32
35
  _verify_completion,
33
36
  )
34
37
 
38
+ if TYPE_CHECKING:
39
+ from ...operation_invocation import OperationSlot
40
+
35
41
 
36
42
  _CLI_EPILOG = r"""Usage:
37
43
  okstra agent-prompt materialize [options] [--jobs-out <path>]
@@ -39,6 +45,7 @@ _CLI_EPILOG = r"""Usage:
39
45
  okstra agent-prompt jobs --project-root <dir> --run-manifest <path> --dispatch-kind <kind> --metadata <path> [--metadata <path>] --out <path>
40
46
  okstra agent-prompt check-corrections --project-root <dir> --run-manifest <path> --corrections <file>
41
47
  okstra agent-prompt apply-corrections --project-root <dir> --run-manifest <path> --corrections <file>
48
+ okstra agent-prompt resolve-operation --operation <id> [--count <n>] [--model <provider/model> ...] [--host-runtime <host>] [--out <path>] [--json]
42
49
  okstra agent-prompt verify [options]
43
50
  okstra agent-prompt materialize-result [options]
44
51
  okstra agent-prompt complete [options]
@@ -71,6 +78,18 @@ def _parser() -> argparse.ArgumentParser:
71
78
  "--count", type=int, default=None,
72
79
  help="slots to open, from 1 to the operation contract's count (default: the contract's count)",
73
80
  )
81
+ operation.add_argument(
82
+ "--model", action="append", default=[],
83
+ help="provider/model for one team, in team order; repeat per team (overrides operationModels)",
84
+ )
85
+ operation.add_argument(
86
+ "--host-runtime", default="",
87
+ help="also check that every slot resolves a cli-wrapper binding on this host",
88
+ )
89
+ operation.add_argument(
90
+ "--out", default="",
91
+ help="also write the JSON result to this file (the --slots input of code-review prepare)",
92
+ )
74
93
  operation.add_argument("--json", action="store_true")
75
94
  jobs = commands.add_parser("jobs", help="generate a verified jobs file without dispatching")
76
95
  _common_paths(jobs)
@@ -129,6 +148,12 @@ def _add_materialize_parser(commands: argparse._SubParsersAction) -> None:
129
148
  materialize.add_argument("--model-role", help=standalone_only)
130
149
  materialize.add_argument("--model", default="", help=standalone_only)
131
150
  materialize.add_argument("--purpose", help=standalone_only)
151
+ materialize.add_argument("--review-policy", help=standalone_only + "; frozen shared code-review policy")
152
+ materialize.add_argument("--review-census", help=standalone_only + "; assigned code-review census")
153
+ materialize.add_argument("--review-base", help=standalone_only + "; fixed review base")
154
+ materialize.add_argument("--review-head", help=standalone_only + "; fixed review head")
155
+ materialize.add_argument("--review-resource", action="append", default=[],
156
+ help=standalone_only + "; additional frozen pack-relative resource")
132
157
  materialize.add_argument(
133
158
  "--replace-undispatched",
134
159
  action="store_true",
@@ -301,48 +326,66 @@ def _refreeze_contracts(args: argparse.Namespace) -> dict[str, object]:
301
326
  }
302
327
 
303
328
 
304
- def _resolve_operation(operation_id: str, count: int | None) -> dict[str, object]:
305
- """이 작업이 열 칸과 각 칸의 모델. 기술은 작업 이름만 알면 된다."""
329
+ def _resolve_operation(
330
+ operation_id: str, count: int | None, models: Sequence[str] = (), host_runtime: str = "",
331
+ cwd: Path | None = None,
332
+ ) -> dict[str, object]:
333
+ """The slots an operation opens and each slot's model; a skill passes only the operation name.
334
+
335
+ Model selection belongs to `resolve_operation_team()`; this function adds the
336
+ optional host binding check and the output shape.
337
+ """
306
338
  from ...model_pool import ModelPool
307
339
  from ...operation_invocation import (
308
340
  OperationPreparationError,
309
- resolve_operation_slots,
341
+ operation_contract_root,
342
+ resolve_operation_team,
343
+ slot_payload,
310
344
  )
311
- from ...paths import find_asset_root
312
345
  from ...registry.provider_registry import default_provider_registry
313
346
 
314
- root = find_asset_root(("agents", "operations"), is_present=Path.is_dir)
315
- if root is None:
316
- raise AgentPromptCliError(
317
- "operation contracts not found: no agents/operations under "
318
- "OKSTRA_HOME or this checkout"
319
- )
320
347
  try:
321
- slots = resolve_operation_slots(
322
- operation_id,
323
- contract_root=root,
324
- pool=ModelPool.from_registry(default_provider_registry()),
325
- count=count,
348
+ slots, source = resolve_operation_team(
349
+ operation_id, models, count, contract_root=operation_contract_root(),
350
+ pool=ModelPool.from_registry(default_provider_registry()), cwd=cwd or Path.cwd(),
326
351
  )
327
352
  except OperationPreparationError as exc:
328
353
  raise AgentPromptCliError(str(exc)) from exc
354
+ if host_runtime:
355
+ _check_runnable(slots, host_runtime)
329
356
  return {
330
357
  "operation": operation_id,
331
358
  "dutyId": slots[0].duty_id,
332
359
  "roleId": slots[0].role_id,
333
360
  "count": len(slots),
334
- "slots": [
335
- {
336
- "ordinal": slot.ordinal,
337
- "provider": slot.provider_id,
338
- "modelRef": slot.model_ref,
339
- "model": slot.display_name,
340
- }
341
- for slot in slots
342
- ],
361
+ "slots": [{**slot_payload(slot), "source": source} for slot in slots],
343
362
  }
344
363
 
345
364
 
365
+ def _check_runnable(slots: Sequence[OperationSlot], host_runtime: str) -> None:
366
+ """Resolve each slot's cli-wrapper binding on the host, as `code-review prepare` will."""
367
+ from ...assignment_environment import load_assignment_context
368
+ from ...assignment_resolver import AssignmentResolutionError
369
+ from ...dispatch_state import detect_terminal_backend
370
+ from ..invocation import AgentInvocationError
371
+ from ..standalone import standalone_assignment
372
+
373
+ try:
374
+ context = load_assignment_context(
375
+ host_runtime=host_runtime, terminal_backend=detect_terminal_backend(),
376
+ execution_provider_ids=tuple(slot.provider_id for slot in slots),
377
+ include_native_provider=False,
378
+ )
379
+ except ValueError as exc:
380
+ raise AgentPromptCliError(f"cannot check bindings on {host_runtime}: {exc}") from exc
381
+ for slot in slots:
382
+ try:
383
+ standalone_assignment(context=context, provider=slot.provider_id, model_role=slot.role_id,
384
+ model=slot.model_ref, requested_runner="cli-wrapper")
385
+ except (AgentInvocationError, AssignmentResolutionError, RuntimeError, ValueError) as exc:
386
+ raise AgentPromptCliError(f"{slot.model_ref} cannot run on {host_runtime}: {exc}") from exc
387
+
388
+
346
389
  def _materialize_batch_command(args: argparse.Namespace) -> int:
347
390
  payload = materialize_batch(args, _parser)
348
391
  if args.json:
@@ -374,7 +417,10 @@ def main(argv: list[str] | None = None) -> int:
374
417
  try:
375
418
  args = _parser().parse_args(argv)
376
419
  if args.command == "resolve-operation":
377
- payload = _resolve_operation(args.operation, args.count)
420
+ payload = _resolve_operation(args.operation, args.count, args.model, args.host_runtime)
421
+ if args.out:
422
+ Path(args.out).write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
423
+ encoding="utf-8")
378
424
  if args.json:
379
425
  _emit(payload, True)
380
426
  else:
@@ -387,7 +433,7 @@ def main(argv: list[str] | None = None) -> int:
387
433
  for slot in payload["slots"]:
388
434
  print(
389
435
  f" slot {slot['ordinal']}: "
390
- f"provider={slot['provider']} model={slot['modelRef']}"
436
+ f"provider={slot['provider']} model={slot['modelRef']} source={slot['source']}"
391
437
  )
392
438
  return 0
393
439
  if args.command == "jobs":