okstra 0.232.0 → 0.234.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 (205) hide show
  1. package/README.md +19 -283
  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/trace/capacity.d.mts +12 -0
  10. package/dist/commands/trace/capacity.mjs +21 -0
  11. package/dist/commands/trace/capacity.mjs.map +1 -0
  12. package/dist/commands/trace/model.d.mts +89 -0
  13. package/dist/commands/trace/model.mjs +251 -0
  14. package/dist/commands/trace/model.mjs.map +1 -0
  15. package/dist/commands/trace/progression.d.mts +11 -0
  16. package/dist/commands/trace/progression.mjs +194 -0
  17. package/dist/commands/trace/progression.mjs.map +1 -0
  18. package/dist/commands/trace/review.d.mts +7 -0
  19. package/dist/commands/trace/review.mjs +51 -0
  20. package/dist/commands/trace/review.mjs.map +1 -0
  21. package/dist/commands/trace/task-link.d.mts +18 -0
  22. package/dist/commands/trace/task-link.mjs +72 -0
  23. package/dist/commands/trace/task-link.mjs.map +1 -0
  24. package/dist/commands/trace/trace.d.mts +1 -0
  25. package/dist/commands/trace/trace.mjs +293 -0
  26. package/dist/commands/trace/trace.mjs.map +1 -0
  27. package/dist/lib/bounded-file.d.mts +1 -0
  28. package/dist/lib/bounded-file.mjs +36 -0
  29. package/dist/lib/bounded-file.mjs.map +1 -0
  30. package/dist/lib/config-store.d.mts +34 -0
  31. package/dist/lib/config-store.mjs +70 -0
  32. package/dist/lib/config-store.mjs.map +1 -0
  33. package/dist/lib/file-lock.mjs +4 -5
  34. package/dist/lib/file-lock.mjs.map +1 -1
  35. package/dist/lib/input-limit.d.mts +4 -0
  36. package/dist/lib/input-limit.mjs +8 -0
  37. package/dist/lib/input-limit.mjs.map +1 -0
  38. package/dist/lib/memory-auto-register.mjs +2 -17
  39. package/dist/lib/memory-auto-register.mjs.map +1 -1
  40. package/dist/lib/report-language-tag.d.mts +1 -0
  41. package/dist/lib/report-language-tag.mjs +4 -0
  42. package/dist/lib/report-language-tag.mjs.map +1 -0
  43. package/dist/lib/report-language.d.mts +1 -0
  44. package/dist/lib/report-language.mjs +50 -0
  45. package/dist/lib/report-language.mjs.map +1 -0
  46. package/dist/lib/skill-catalog.mjs +3 -0
  47. package/dist/lib/skill-catalog.mjs.map +1 -1
  48. package/docs/architecture/storage-model.md +55 -5
  49. package/docs/architecture.md +10 -4
  50. package/docs/cli.md +320 -3
  51. package/docs/contributor-change-matrix.md +1 -2
  52. package/docs/project-structure-overview.md +34 -43
  53. package/package.json +1 -1
  54. package/runtime/BUILD.json +2 -2
  55. package/runtime/agents/operations/trace-interface-review.json +6 -0
  56. package/runtime/agents/operations/trace-scope-review.json +6 -0
  57. package/runtime/prompts/coding-preflight/authoring-checks.md +1 -1
  58. package/runtime/prompts/coding-preflight/clean-code.md +18 -20
  59. package/runtime/prompts/coding-preflight/overview.md +1 -1
  60. package/runtime/prompts/duties/code-reviewer.json +1 -1
  61. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  62. package/runtime/prompts/host-orchestration/README.md +18 -9
  63. package/runtime/prompts/launch.template.md +3 -2
  64. package/runtime/prompts/lead/context-loader.md +2 -0
  65. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  66. package/runtime/prompts/lead/report-writer.md +6 -6
  67. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -2
  68. package/runtime/prompts/profiles/_common-contract.md +1 -1
  69. package/runtime/python/okstra_ctl/agent/invocation.py +1 -0
  70. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +66 -26
  71. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  72. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +28 -10
  73. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  74. package/runtime/python/okstra_ctl/agent/standalone.py +12 -0
  75. package/runtime/python/okstra_ctl/analysis_packet.py +22 -11
  76. package/runtime/python/okstra_ctl/business_flow/cli.py +60 -6
  77. package/runtime/python/okstra_ctl/business_flow/contracts.py +12 -1
  78. package/runtime/python/okstra_ctl/business_flow/engine.py +17 -5
  79. package/runtime/python/okstra_ctl/business_flow/history.py +60 -0
  80. package/runtime/python/okstra_ctl/business_flow/source.py +35 -2
  81. package/runtime/python/okstra_ctl/business_flow/store.py +51 -14
  82. package/runtime/python/okstra_ctl/business_flow/sweep.py +124 -0
  83. package/runtime/python/okstra_ctl/code_review_census.py +93 -2
  84. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  85. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  86. package/runtime/python/okstra_ctl/code_review_scope.py +13 -0
  87. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  88. package/runtime/python/okstra_ctl/code_review_target.py +140 -15
  89. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  90. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  91. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  92. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  93. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  94. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  95. package/runtime/python/okstra_ctl/doyouknow/cli.py +9 -9
  96. package/runtime/python/okstra_ctl/doyouknow/config.py +2 -2
  97. package/runtime/python/okstra_ctl/doyouknow/group_view.py +152 -0
  98. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +4 -3
  99. package/runtime/python/okstra_ctl/doyouknow/source_store.py +2 -2
  100. package/runtime/python/okstra_ctl/doyouknow/sources/business.py +116 -0
  101. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
  102. package/runtime/python/okstra_ctl/doyouknow/sync.py +34 -9
  103. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  104. package/runtime/python/okstra_ctl/fixed_text.py +10 -0
  105. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  106. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  107. package/runtime/python/okstra_ctl/json_boundary.py +33 -6
  108. package/runtime/python/okstra_ctl/manager_cli.py +122 -1
  109. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  110. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  111. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  112. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  113. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  114. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  115. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  116. package/runtime/python/okstra_ctl/manager_sync.py +42 -3
  117. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  118. package/runtime/python/okstra_ctl/material.py +2 -0
  119. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  120. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  121. package/runtime/python/okstra_ctl/model_io/renderers.py +3 -0
  122. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  123. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  124. package/runtime/python/okstra_ctl/paths.py +6 -1
  125. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  126. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  127. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
  128. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  129. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  130. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  131. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +12 -9
  132. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  133. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  134. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +5 -5
  135. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  136. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  137. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  138. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  139. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  140. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  141. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  142. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  143. package/runtime/python/okstra_ctl/project_group.py +175 -0
  144. package/runtime/python/okstra_ctl/project_group_cli.py +62 -0
  145. package/runtime/python/okstra_ctl/render.py +28 -2
  146. package/runtime/python/okstra_ctl/report_assembly.py +38 -11
  147. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  148. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  149. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  150. package/runtime/python/okstra_ctl/report_language.py +4 -1
  151. package/runtime/python/okstra_ctl/report_narrative.py +179 -7
  152. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  153. package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
  154. package/runtime/python/okstra_ctl/run.py +43 -35
  155. package/runtime/python/okstra_ctl/run_context.py +10 -1
  156. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  157. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  158. package/runtime/python/okstra_ctl/task_query.py +239 -0
  159. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  160. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  161. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  162. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  163. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  164. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  165. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  166. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  167. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  168. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  169. package/runtime/python/okstra_project/state.py +20 -0
  170. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  171. package/runtime/python/okstra_token_usage/cli.py +23 -10
  172. package/runtime/python/okstra_token_usage/collect.py +25 -22
  173. package/runtime/python/okstra_token_usage/policy.py +193 -0
  174. package/runtime/schemas/business-flow-v1.schema.json +3 -0
  175. package/runtime/schemas/doyouknow-config-v1.schema.json +1 -1
  176. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  177. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  178. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  179. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  180. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  181. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  182. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  183. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  184. package/runtime/skills/okstra-code-review/SKILL.md +58 -50
  185. package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
  186. package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
  187. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  188. package/runtime/skills/okstra-explain-flow/SKILL.md +33 -4
  189. package/runtime/skills/okstra-manager/SKILL.md +24 -0
  190. package/runtime/skills/okstra-memory/SKILL.md +1 -1
  191. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  192. package/runtime/skills/okstra-run/SKILL.md +55 -183
  193. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  194. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  195. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  196. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  197. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  198. package/runtime/templates/doyouknow/group-view.css +103 -0
  199. package/runtime/templates/doyouknow/group-view.js +317 -0
  200. package/runtime/templates/doyouknow/group-view.template.html +72 -0
  201. package/runtime/templates/manager/view.template.html +4 -0
  202. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  203. package/runtime/templates/trace/trace.template.md +42 -0
  204. package/runtime/validators/checks/fixtures-02.py +25 -33
  205. package/runtime/validators/validate-run.py +93 -36
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- The lead orchestrates the selected AI workers against a prepared task bundle, collects their independent outputs, supervises convergence, and ensures the final report is produced. When `Report writer worker` is in the selected roster, that worker authors the report narrative Markdown; report assembly publishes the final record from role-owned inputs. The lead never substitutes its own reasoning for a worker result and never bypasses a rostered report writer.
5
+ The lead orchestrates the selected AI workers against a prepared task bundle, collects their independent outputs, supervises convergence, and ensures the final report is produced. When `Report writer worker` is in the selected roster, that worker authors the report input in the run manifest's declared `reportAuthoringFormat`; report assembly publishes the final record from role-owned inputs. The lead never substitutes its own reasoning for a worker result and never bypasses a rostered report writer.
6
6
 
7
7
  The lead owns the approval decision ledger and writes it only through `okstra approval-decision`. The activity recorder owns the activity ledger. Runtime adapters own team state and usage. The convergence engine owns convergence state and the completed plan-body result. The design-surface detector owns the design-preparation snapshot. Report assembly validates these inputs and publishes `final-report-*.data.json` once; a failure is returned to the owner named in its diagnostic.
8
8
 
@@ -57,7 +57,7 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
57
57
  | `okstra model-io run-input --run-manifest <path>` | Read run identity, worker roster, model assignments, and artifact paths instead of opening the run manifest | `context-loader` "Step 3" |
58
58
  | `okstra model-io active-context-input --project-root <dir> --run-manifest <path>` | Read the prior executor base ref for an incremental re-run | launch prompt "Incremental re-verification" |
59
59
  | `okstra incremental-scope --prev-data <path>` | Decide re-verify vs carry-forward stages on a clarification re-run | launch prompt "Incremental re-verification" |
60
- | `okstra incremental-carry --prev-data <path> --prev-seq <seq> --cur-narrative <path>` | Merge carried-forward plan-item verdicts after `plan-items seed`; then repeat `plan-items prepare --state`, `prompt` and `validate-prepared --state` | launch prompt "Incremental re-verification" |
60
+ | `okstra incremental-carry --run-manifest <current-run-manifest> --prev-data <path> --prev-seq <seq> --cur-narrative <reportNarrativePath>` | Merge carried-forward plan-item verdicts after `plan-items seed`; then repeat `plan-items prepare --state`, `prompt` and `validate-prepared --state` using that same manifest | launch prompt "Incremental re-verification" |
61
61
  | `okstra stage-map <task-key>` | Read the prior Stage Map and done stages before re-planning | host orchestration rules (implementation-planning) |
62
62
  | `okstra stage-close <task-key> --stage <N> --from-commit <sha> [--supersede-failed <reason>]` | Close a stage whose work already landed outside okstra, or a `failed` stage whose failure no longer applies |
63
63
  | `okstra stage-reopen <task-key> --stage <N> --reason <why> [--evidence <report>]` | Reopen a `done` stage for a fix run, e.g. after a `blocked` final-verification of that stage | host orchestration rules (implementation-planning) |
@@ -160,19 +160,19 @@ Every `okstra` command the lead documents cite, grouped by phase, each spelled w
160
160
  |---|---|---|
161
161
  | `okstra agent-prompt check-corrections --project-root <dir> --run-manifest <path> --corrections <path>` | Check a report-writer corrections ledger before a corrective dispatch | `report-writer` "Corrective report-writer dispatch" |
162
162
  | `okstra agent-prompt apply-corrections --project-root <dir> --run-manifest <path> --corrections <path>` | Apply a ledger that `check-corrections` reported `mechanical: true`, without a writer round | `report-writer` "Corrective report-writer dispatch" |
163
- | `okstra design-snapshot --narrative <path> --output <path>` | Complete the design-surface detector snapshot; both paths come from the run manifest | `report-writer` "Implementation-planning sequence" |
163
+ | `okstra design-snapshot --run-manifest <path> --narrative <path> --output <path>` | Complete the design-surface detector snapshot; both paths and the authoring format come from that run manifest | `report-writer` "Implementation-planning sequence" |
164
164
  | `okstra plan-items prepare --run-manifest <path> --narrative <path>` | Extract this round's plan items (add `--state <path>` after a self-fix or `incremental-carry`, `--tie-vote` for a critic tie round) | `plan-body-verification` "Round protocol" |
165
165
  | `okstra plan-items prompt --run-manifest <path>` | Print the plan-items block placed verbatim in every verifier prompt | `plan-body-verification` "Round protocol" |
166
166
  | `okstra plan-items validate-prepared --run-manifest <path> --narrative <path>` | Validate the prepared envelope before dispatch; pass the same `--state` the last `prepare` used | `plan-body-verification` "Round protocol" |
167
- | `okstra plan-items seed --narrative <path>` | Create the `planItems[]` rows a round lands in | `plan-body-verification` "Round protocol" |
168
- | `okstra plan-items extract --narrative <path> --output <path>` | Re-extract plan items after a round and re-verify any item whose subject shifted | `plan-body-verification` "Round protocol" |
167
+ | `okstra plan-items seed --run-manifest <path> --narrative <path>` | Create the `planItems[]` rows a round lands in | `plan-body-verification` "Round protocol" |
168
+ | `okstra plan-items extract --run-manifest <path> --narrative <path> --output <path>` | Re-extract plan items after a round and re-verify any item whose subject shifted; use the input path declared by that run manifest | `plan-body-verification` "Round protocol" |
169
169
  | `okstra plan-items correction-prompt --run-manifest <path> --state <path> --worker <id>` | Put its output first in a `worker-correction` re-dispatch prompt | `plan-body-verification` "Round protocol" |
170
170
  | `okstra plan-items collect-verdicts --items <path> --result <worker>=<path> --output <path>` | Read a round's responses into a verdicts envelope; never parse them by hand | `plan-body-verification` "Round protocol" |
171
171
  | `okstra plan-items apply-verdicts --state <path> --round <N> --result <worker>=<path>` | Record the round's verdicts | `plan-body-verification` "Round protocol" |
172
172
  | `okstra plan-items complete-round --state <path> --run-manifest <path> --round <N>` | Record the completed round | `plan-body-verification` "Round protocol" |
173
173
  | `okstra plan-items next-dispatch --state <path>` | Decide whether the round opens another worker batch | `plan-body-verification` "Round protocol" |
174
174
  | `okstra plan-items resolve-dissent --state <path> --item <P-id> --decision-file <path>` | Record an evidence-based lead decision after the single self-fix | `plan-body-verification` "Round protocol" |
175
- | `okstra plan-verify --report <path>` | Score the plan-body gate; never tally votes in a script | `plan-body-verification` "Round protocol" |
175
+ | `okstra plan-verify --run-manifest <path> --narrative <reportNarrativePath> --state <path>` | Score the plan-body gate before report assembly, using that run's declared input format; never tally votes in a script | `plan-body-verification` "Round protocol" |
176
176
  | `okstra worktree-lock --worktree <dir> --command <text>` | Lead minor fix (implementation only, never in a run marked `verificationEvidenceVersion`): re-run each Tier 1 command and failing verifier check that covers a fixed finding, in the stage worktree, under its lock | `_implementation-deliverable.md` "Lead minor fix" |
177
177
 
178
178
  ### Phase 7 — persist
@@ -590,7 +590,7 @@ If convergence is disabled, `seed`/`finalize` produce the auto-disabled final st
590
590
 
591
591
  ### Authoring ownership (BLOCKING)
592
592
 
593
- If `Report writer worker` is in the selected roster (`recommendedWorkers` / `resultContract.workerRoles`), Lead dispatches it to author only `report-writer-narrative-<task-type>-<seq>.md`, its worker-result pointer, and its audit sidecar. The worker may read the complete run context but cannot write `final-report-*.data.json` or another role's ledger. After every required input exists, Phase 7 runs report assembly, which validates the role-owned inputs and atomically publishes the report record once. Phase 7 then renders the human HTML from that record. Contract v2 artifacts remain readable but no new run writes them. **Enforced:** report-writer dispatch completion paths in `scripts/okstra_ctl/dispatch_state.py`, granted artifacts in `scripts/okstra_ctl/dispatch_core.py`, and `scripts/okstra_ctl/report_assembly.py` `assemble_report`.
593
+ If `Report writer worker` is in the selected roster (`recommendedWorkers` / `resultContract.workerRoles`), Lead dispatches it to author only the input at the run manifest's `reportNarrativePath`, its worker-result pointer, and its audit sidecar. `reportAuthoringFormat=json-v1` selects standard JSON with ordinary Markdown inside description strings; an absent field retains `markdown-v1` and the existing narrative line grammar. Use the declared path and format, including its `.json` or `.md` extension. The worker may read the complete run context but cannot write `final-report-*.data.json` or another role's ledger. After every required input exists, Phase 7 runs report assembly, which validates the role-owned inputs and atomically publishes the report record once. Phase 7 then renders the human HTML from that record. Contract v2 artifacts remain readable but no new run writes them. **Enforced:** report-writer dispatch completion paths in `scripts/okstra_ctl/dispatch_state.py`, granted artifacts in `scripts/okstra_ctl/dispatch_core.py`, and `scripts/okstra_ctl/report_assembly.py` `assemble_report`.
594
594
 
595
595
  Before constructing the dispatch prompt, the lead MUST:
596
596
 
@@ -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.
@@ -55,6 +55,6 @@ Load the applicable coding conventions for every language the diff will touch, t
55
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
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
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, 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.
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 plain-English readability. More than 50 effective lines prompts that review, not an automatic split or failure; record the reason for retaining a cohesive longer function. 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.
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
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.
@@ -48,6 +48,7 @@ AgentAudience = Literal[
48
48
  "report-writer",
49
49
  "code-reviewer",
50
50
  "schedule-verifier",
51
+ "interface-reviewer",
51
52
  "business-flow-investigator",
52
53
  ]
53
54
 
@@ -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)
@@ -307,48 +326,66 @@ def _refreeze_contracts(args: argparse.Namespace) -> dict[str, object]:
307
326
  }
308
327
 
309
328
 
310
- def _resolve_operation(operation_id: str, count: int | None) -> dict[str, object]:
311
- """이 작업이 열 칸과 각 칸의 모델. 기술은 작업 이름만 알면 된다."""
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
+ """
312
338
  from ...model_pool import ModelPool
313
339
  from ...operation_invocation import (
314
340
  OperationPreparationError,
315
- resolve_operation_slots,
341
+ operation_contract_root,
342
+ resolve_operation_team,
343
+ slot_payload,
316
344
  )
317
- from ...paths import find_asset_root
318
345
  from ...registry.provider_registry import default_provider_registry
319
346
 
320
- root = find_asset_root(("agents", "operations"), is_present=Path.is_dir)
321
- if root is None:
322
- raise AgentPromptCliError(
323
- "operation contracts not found: no agents/operations under "
324
- "OKSTRA_HOME or this checkout"
325
- )
326
347
  try:
327
- slots = resolve_operation_slots(
328
- operation_id,
329
- contract_root=root,
330
- pool=ModelPool.from_registry(default_provider_registry()),
331
- 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(),
332
351
  )
333
352
  except OperationPreparationError as exc:
334
353
  raise AgentPromptCliError(str(exc)) from exc
354
+ if host_runtime:
355
+ _check_runnable(slots, host_runtime)
335
356
  return {
336
357
  "operation": operation_id,
337
358
  "dutyId": slots[0].duty_id,
338
359
  "roleId": slots[0].role_id,
339
360
  "count": len(slots),
340
- "slots": [
341
- {
342
- "ordinal": slot.ordinal,
343
- "provider": slot.provider_id,
344
- "modelRef": slot.model_ref,
345
- "model": slot.display_name,
346
- }
347
- for slot in slots
348
- ],
361
+ "slots": [{**slot_payload(slot), "source": source} for slot in slots],
349
362
  }
350
363
 
351
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
+
352
389
  def _materialize_batch_command(args: argparse.Namespace) -> int:
353
390
  payload = materialize_batch(args, _parser)
354
391
  if args.json:
@@ -380,7 +417,10 @@ def main(argv: list[str] | None = None) -> int:
380
417
  try:
381
418
  args = _parser().parse_args(argv)
382
419
  if args.command == "resolve-operation":
383
- 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")
384
424
  if args.json:
385
425
  _emit(payload, True)
386
426
  else:
@@ -393,7 +433,7 @@ def main(argv: list[str] | None = None) -> int:
393
433
  for slot in payload["slots"]:
394
434
  print(
395
435
  f" slot {slot['ordinal']}: "
396
- f"provider={slot['provider']} model={slot['modelRef']}"
436
+ f"provider={slot['provider']} model={slot['modelRef']} source={slot['source']}"
397
437
  )
398
438
  return 0
399
439
  if args.command == "jobs":
@@ -35,9 +35,9 @@ from ...report_corrections import (
35
35
  load_corrections,
36
36
  render_applied_narrative,
37
37
  )
38
- from ...report_inputs import report_narrative_path, uses_report_contract_v3
38
+ from ...report_inputs import report_authoring_format, report_narrative_path, uses_report_contract_v3
39
39
  from ...paths import STAGE_VALIDATOR_RELATIVE, find_asset_root
40
- from ...report_narrative import task_narrative_errors
40
+ from ...report_narrative import load_report_narrative, task_narrative_errors
41
41
  from ...report_synthesis_packet import (
42
42
  ReportSynthesisPacketError,
43
43
  ReportSynthesisPacket,
@@ -68,13 +68,13 @@ def run_corrections_check(
68
68
  if not uses_report_contract_v3(manifest):
69
69
  return CorrectionsCheck(ledger, (), None, False, {}, (
70
70
  "owner=lead correction=ledger path=- reason=corrections require report "
71
- "contract 3.0 (a Markdown narrative); this run uses an older contract",
71
+ "contract 3.0; this run uses an older contract",
72
72
  ))
73
73
  contract = manifest.get("agentContract")
74
74
  authorized = contract.get("authorizedPaths") if isinstance(contract, Mapping) else None
75
75
  authorized = authorized if isinstance(authorized, Mapping) else {}
76
76
  try:
77
- base_path = _authorized_path(
77
+ _authorized_path(
78
78
  project_root,
79
79
  str(ledger.get("baseNarrativePath") or ""),
80
80
  authorized.get("resultRoots"),
@@ -85,6 +85,19 @@ def run_corrections_check(
85
85
  return CorrectionsCheck(ledger, (), None, False, {}, (
86
86
  f"owner=lead correction=ledger path={ledger.get('baseNarrativePath')} reason={exc}",
87
87
  ))
88
+ # Keep the original spelling so the JSON boundary can inspect symlink components.
89
+ base_path = Path(str(ledger["baseNarrativePath"]))
90
+ if not base_path.is_absolute():
91
+ base_path = project_root / base_path
92
+ try:
93
+ input_format = report_authoring_format(manifest)
94
+ load_report_narrative(project_root, manifest, load_schema_version("3.0"),
95
+ path=base_path, structure_only=True,
96
+ allow_preserved_attempt=True)
97
+ except (OSError, UnicodeError, ValueError) as exc:
98
+ return CorrectionsCheck(ledger, (), None, False, {}, (
99
+ f"owner=lead correction=ledger path={base_path} reason=base narrative does not parse: {exc}",
100
+ ))
88
101
  try:
89
102
  packet = build_report_synthesis_packet(
90
103
  project_root=project_root,
@@ -109,6 +122,7 @@ def run_corrections_check(
109
122
  rewrite_results is None and any(item.get("kind") == "rewrite" for item in ledger["corrections"]),
110
123
  ),
111
124
  rewrite_results=rewrite_results,
125
+ input_format=input_format,
112
126
  )
113
127
 
114
128
 
@@ -195,8 +209,7 @@ def run_corrections_apply(
195
209
  """
196
210
  if not uses_report_contract_v3(manifest):
197
211
  raise AgentPromptCliError(
198
- "apply-corrections requires report contract 3.0 (a Markdown "
199
- "narrative); this run uses an older contract"
212
+ "apply-corrections requires report contract 3.0; this run uses an older contract"
200
213
  )
201
214
  narrative_path = report_narrative_path(project_root, manifest)
202
215
  events_value = manifest.get("leadEventsPath")
@@ -225,12 +238,14 @@ def run_corrections_apply(
225
238
  )
226
239
  return _apply_checked_corrections(
227
240
  project_root, manifest_path, narrative_path, corrections_path, check, rewrite_results_path,
241
+ input_format=report_authoring_format(manifest),
228
242
  )
229
243
 
230
244
 
231
245
  def _apply_checked_corrections(
232
246
  project_root: Path, manifest_path: Path, narrative_path: Path,
233
247
  corrections_path: Path, check: CorrectionsCheck, rewrite_results_path: Path | None,
248
+ *, input_format: str = "markdown-v1",
234
249
  ) -> dict[str, Any]:
235
250
  corrections_rel = _relative(project_root, corrections_path)
236
251
  if check.defects:
@@ -253,7 +268,7 @@ def _apply_checked_corrections(
253
268
  "baseNarrativePath is the live narrative "
254
269
  f"({_relative(project_root, narrative_path)}); applying would "
255
270
  "overwrite the only copy of the attempt being corrected. Copy it "
256
- "to worker-results/report-writer-narrative-a<N>-<task-type>-<seq>.md "
271
+ f"to worker-results/report-writer-narrative-a<N>-<task-type>-<seq>{narrative_path.suffix} "
257
272
  "first and point the ledger at that copy"
258
273
  )
259
274
  previous = _already_applied(project_root, manifest_path, corrections_rel)
@@ -265,7 +280,7 @@ def _apply_checked_corrections(
265
280
  )
266
281
  applied_ids = [str(item.get("id")) for item in check.corrections]
267
282
  narrative_rel = _relative(project_root, narrative_path)
268
- rendered = render_applied_narrative(check, load_schema_version("3.0"))
283
+ rendered = render_applied_narrative(check, load_schema_version("3.0"), input_format=input_format)
269
284
  if narrative_path.is_file() and narrative_path.read_text(encoding="utf-8") not in (
270
285
  base_path.read_text(encoding="utf-8"), rendered,
271
286
  ):
@@ -34,6 +34,8 @@ from ...assignment_environment import load_assignment_context
34
34
  from ..standalone import StandaloneInvocationRequest, prepare_standalone_invocation
35
35
  from ...code_review_invocation import CodeReviewInputs
36
36
  from ...path_hints import hydrate_active_run_context
37
+ from ...json_boundary import JsonBoundaryError, OUTSIDE_WORKER_RESULT_LANES
38
+ from ...phases.improvement_discovery.resolved_census import prepare_resolved_lens_census
37
39
  from ...worker_prompt_headers import worker_prompt_headers
38
40
  from ...worker_prompt_contract import (
39
41
  complete_reverify_instruction,
@@ -44,6 +46,7 @@ from ...worker_prompt_policy import (
44
46
  critic_assignment_ref,
45
47
  is_critic_verification,
46
48
  is_verification_dispatch_kind,
49
+ resolve_prompt_plan_for_manifest,
47
50
  )
48
51
  from ...paths import okstra_home
49
52
  from ...contract_refreeze import (
@@ -58,8 +61,8 @@ from ...initial_prompt_materialization import (
58
61
  )
59
62
  from ...final_report_paths import final_report_data_path
60
63
  from ...final_report_schema import load_schema_version
61
- from ...report_inputs import report_narrative_path, uses_report_contract_v3
62
- from ...report_narrative import NarrativeContractError, parse_narrative_structure
64
+ from ...report_inputs import report_authoring_format, report_narrative_path, uses_report_contract_v3
65
+ from ...report_narrative import NarrativeContractError, load_report_narrative
63
66
  from ...report_synthesis_packet import (
64
67
  ReportSynthesisPacketError,
65
68
  materialize_report_synthesis_packet,
@@ -314,6 +317,15 @@ def _materialize_run(
314
317
  active_context = hydrate_active_run_context(
315
318
  _read_json_object(active_context_path, "active run context")
316
319
  )
320
+ if args.dispatch_kind == "initial" and manifest.get("taskType") == "improvement-discovery":
321
+ try:
322
+ plan = resolve_prompt_plan_for_manifest(
323
+ manifest=manifest, worker_id=args.worker_id, dispatch_kind="initial",
324
+ )
325
+ if plan.audience == "analysis":
326
+ prepare_resolved_lens_census(project_root, manifest)
327
+ except (ValueError, JsonBoundaryError, OSError, UnicodeError) as exc:
328
+ raise AgentPromptCliError(str(exc)) from exc
317
329
  metadata_path = prompt_path.with_name(prompt_path.name + ".meta.json")
318
330
  generation = _reuse_or_seal_verifier_generation(
319
331
  args, project_root, manifest_path, manifest, active_context, metadata_path,
@@ -370,7 +382,7 @@ def _materialize_run(
370
382
  f"audience {args.audience} has no corrections ledger"
371
383
  )
372
384
  raise AgentPromptCliError(
373
- "--corrections requires report contract 3.0 (a Markdown narrative); "
385
+ "--corrections requires report contract 3.0; "
374
386
  "this run uses an older contract"
375
387
  )
376
388
  if args.audience in _RESOURCE_AUDIENCES and not is_reverify:
@@ -597,19 +609,20 @@ def _with_report_writer_sections(
597
609
  check,
598
610
  base_narrative_rel=str(check.ledger.get("baseNarrativePath") or ""),
599
611
  corrections_rel=_relative(project_root, corrections_path),
612
+ input_format=report_authoring_format(manifest),
600
613
  ))
601
614
  body = "## Inputs\n\nCorrection-only task: use the checked field values and evidence below."
602
615
  sections.extend(_render_correction_application(args, project_root, narrative_path, corrections_path, check))
603
616
  sections.append("")
604
617
  else:
605
- _refuse_free_form_correction(project_root, narrative_path)
618
+ _refuse_free_form_correction(project_root, narrative_path, manifest)
606
619
  preserved = _preserve_reauthored_narrative(
607
620
  project_root, narrative_path, invocation_id=str(args.invocation_id),
608
621
  )
609
622
  if preserved is not None:
610
623
  sections.extend(_render_previous_attempt_section(preserved))
611
624
  sections.append("")
612
- sections.extend(render_output_section())
625
+ sections.extend(render_output_section(input_format=report_authoring_format(manifest)))
613
626
  return body.rstrip("\n") + "\n\n" + "\n".join(sections) + "\n"
614
627
 
615
628
 
@@ -677,7 +690,9 @@ def _render_previous_attempt_section(preserved_rel: str) -> list[str]:
677
690
  ]
678
691
 
679
692
 
680
- def _refuse_free_form_correction(project_root: Path, narrative_path: Path) -> None:
693
+ def _refuse_free_form_correction(
694
+ project_root: Path, narrative_path: Path, manifest: Mapping[str, Any],
695
+ ) -> None:
681
696
  """서사가 이미 있고 구조가 읽히면 이 디스패치는 교정이다 — 원장 없이는 거절한다.
682
697
 
683
698
  구조가 읽히지 않는 서사(줄 문법·소유권 결함)는 교정 대상이 아니라 재저작
@@ -688,9 +703,12 @@ def _refuse_free_form_correction(project_root: Path, narrative_path: Path) -> No
688
703
  if not narrative_path.is_file():
689
704
  return
690
705
  try:
691
- parse_narrative_structure(
692
- narrative_path.read_text(encoding="utf-8"), load_schema_version("3.0"),
693
- )
706
+ load_report_narrative(project_root, manifest, load_schema_version("3.0"),
707
+ path=narrative_path, structure_only=True)
708
+ except JsonBoundaryError as exc:
709
+ if exc.reason == OUTSIDE_WORKER_RESULT_LANES:
710
+ raise AgentPromptCliError(str(exc)) from exc
711
+ return
694
712
  except NarrativeContractError:
695
713
  return
696
714
  narrative_rel = _relative(project_root, narrative_path)
@@ -705,7 +723,7 @@ def _refuse_free_form_correction(project_root: Path, narrative_path: Path) -> No
705
723
  "--corrections here. A ledger of only replace/remove/add/move entries needs no "
706
724
  "writer round: `okstra agent-prompt apply-corrections` writes the "
707
725
  "narrative and records the activity row. Only a narrative whose "
708
- "structure does not parse (line grammar, unknown top-level field) is "
726
+ "structure does not parse (declared syntax or writer ownership) is "
709
727
  "re-authored without a ledger; value defects are what the ledger fixes"
710
728
  )
711
729
 
@@ -12,6 +12,7 @@ from datetime import datetime, timezone
12
12
  from pathlib import Path
13
13
 
14
14
  from ..invocation import (
15
+ AgentInvocationError,
15
16
  AgentModelAssignment,
16
17
  agent_model_assignment_from_payload,
17
18
  materialize_standalone_result,
@@ -28,7 +29,6 @@ from ...dispatch_state import (
28
29
  from .emit import _emit
29
30
  from .inputs import (
30
31
  AgentPromptCliError,
31
- _is_relative_to,
32
32
  _mapping,
33
33
  _project_input,
34
34
  _project_root,
@@ -149,27 +149,24 @@ def _verify(args: argparse.Namespace) -> None:
149
149
 
150
150
 
151
151
  def _materialize_result(args: argparse.Namespace) -> None:
152
+ from ..standalone import standalone_returned_body
153
+
152
154
  project_root = _project_root(args.project_root)
153
155
  metadata_path = _project_input(project_root, args.metadata, "metadata")
154
- root = project_root / ".okstra" / "agent-invocations" / args.purpose
155
- temporary_root = root / ".tmp"
156
156
  returned_body_path = _project_input(
157
157
  project_root,
158
158
  args.returned_body_file,
159
159
  "returned body",
160
160
  )
161
- if not temporary_root.is_dir() or not _is_relative_to(
162
- returned_body_path,
163
- temporary_root.resolve(strict=True),
164
- ):
165
- raise AgentPromptCliError(
166
- "returned body file must be inside the standalone purpose .tmp directory"
167
- )
161
+ try:
162
+ returned_body = standalone_returned_body(project_root, args.purpose, returned_body_path)
163
+ except AgentInvocationError as exc:
164
+ raise AgentPromptCliError(str(exc)) from exc
168
165
  result = materialize_standalone_result(
169
166
  project_root=project_root,
170
167
  purpose=args.purpose,
171
168
  metadata_path=metadata_path,
172
- returned_body=returned_body_path.read_bytes(),
169
+ returned_body=returned_body,
173
170
  )
174
171
  _emit({
175
172
  "ok": True,
@@ -21,6 +21,18 @@ from .invocation import (
21
21
  )
22
22
 
23
23
 
24
+ def standalone_returned_body(project_root: Path, purpose: str, body_path: Path) -> bytes:
25
+ """Read a raw return only from the purpose's `.tmp/` directory."""
26
+ temporary_root = project_root / ".okstra" / "agent-invocations" / purpose / ".tmp"
27
+ if not temporary_root.is_dir() or not body_path.resolve(strict=True).is_relative_to(
28
+ temporary_root.resolve(strict=True),
29
+ ):
30
+ raise AgentInvocationError(
31
+ "returned body file must be inside the standalone purpose .tmp directory"
32
+ )
33
+ return body_path.read_bytes()
34
+
35
+
24
36
  @dataclass(frozen=True)
25
37
  class StandaloneInvocationRequest:
26
38
  project_root: Path