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
@@ -17,7 +17,7 @@ from .contract_graph import (
17
17
  ContractGraphValidator,
18
18
  ContractSelection,
19
19
  )
20
- from .model_pool import ModelPool
20
+ from .model_pool import ModelPool, ResolvedModel
21
21
 
22
22
 
23
23
  class OperationPreparationError(ValueError):
@@ -37,20 +37,8 @@ class OperationSlot:
37
37
  display_name: str
38
38
 
39
39
 
40
- def resolve_operation_slots(
41
- operation_id: str,
42
- *,
43
- contract_root: Path,
44
- pool: ModelPool,
45
- count: int | None = None,
46
- ) -> Sequence[OperationSlot]:
47
- """작업 계약이 요구하는 칸과 각 칸의 모델.
48
-
49
- 모델은 런과 같은 기본값 사슬에서 고른다. 서로 다른 모델 참조를 요구한
50
- 수만큼 채우지 못하면 여기서 멈춘다 — 같은 모델을 반복하거나 워커 수를
51
- 몰래 줄이면 그 작업이 요구한 교차검증이 조용히 사라진다. `count` 는
52
- 호출자가 계약 상한 안에서 명시적으로 고른 수다.
53
- """
40
+ def _operation_contract(operation_id: str, contract_root: Path) -> tuple[str, str, int]:
41
+ """The operation's duty, role and worker ceiling."""
54
42
  graph_root = ContractGraphRoot.from_base(contract_root)
55
43
  try:
56
44
  graph = ContractGraphValidator().validate(
@@ -65,31 +53,222 @@ def resolve_operation_slots(
65
53
  f"unknown operation: {operation_id} (known: {known})"
66
54
  )
67
55
  duty_id = str(operation.payload["dutyId"])
56
+ return duty_id, graph.duties[duty_id].role_id, int(operation.payload["count"])
57
+
58
+
59
+ def operation_ceiling(operation_id: str, *, contract_root: Path) -> int:
60
+ """The most workers the operation contract allows."""
61
+ return _operation_contract(operation_id, contract_root)[2]
62
+
63
+
64
+ def resolve_operation_slots(
65
+ operation_id: str,
66
+ *,
67
+ contract_root: Path,
68
+ pool: ModelPool,
69
+ count: int | None = None,
70
+ deprioritized_provider: str | None = None,
71
+ ) -> Sequence[OperationSlot]:
72
+ """작업 계약이 요구하는 칸과 각 칸의 모델.
73
+
74
+ 모델은 런과 같은 기본값 사슬에서 고른다. 서로 다른 모델 참조를 요구한
75
+ 수만큼 채우지 못하면 여기서 멈춘다 — 같은 모델을 반복하거나 워커 수를
76
+ 몰래 줄이면 그 작업이 요구한 교차검증이 조용히 사라진다. `count` 는
77
+ 호출자가 계약 상한 안에서 명시적으로 고른 수다. `deprioritized_provider`
78
+ 의 모델은 다른 공급자의 후보 뒤로 미룬다(같은 공급자 안의 순서는 유지).
79
+ """
80
+ duty_id, role_id, ceiling = _operation_contract(operation_id, contract_root)
68
81
  # 계약의 수는 상한이다. 더 적게 여는 것은 호출자가 명시할 때만이다.
69
- ceiling = int(operation.payload["count"])
70
82
  if count is None:
71
83
  count = ceiling
72
84
  elif not 1 <= count <= ceiling:
73
85
  raise OperationPreparationError(
74
86
  f"operation {operation_id!r} takes a count from 1 to {ceiling}, got {count}"
75
87
  )
76
- role_id = graph.duties[duty_id].role_id
77
88
 
78
89
  candidates = pool.default_candidates(role_id)
90
+ if deprioritized_provider is not None:
91
+ candidates = tuple(sorted(candidates, key=lambda model: model.provider_id == deprioritized_provider))
79
92
  if len(candidates) < count:
80
93
  raise OperationPreparationError(
81
94
  f"operation {operation_id!r} requires {count} distinct models for role "
82
95
  f"{role_id!r}, available {len(candidates)}"
83
96
  )
84
- slots = []
85
- for ordinal, model in enumerate(candidates[:count], start=1):
86
- slots.append(OperationSlot(
87
- operation_id=operation_id,
88
- duty_id=duty_id,
89
- role_id=role_id,
90
- ordinal=ordinal,
91
- model_ref=str(model.model_ref),
92
- provider_id=model.provider_id,
97
+ return _numbered_slots(operation_id, duty_id, role_id, candidates[:count])
98
+
99
+
100
+ def _numbered_slots(
101
+ operation_id: str, duty_id: str, role_id: str, models: Sequence[ResolvedModel],
102
+ ) -> tuple[OperationSlot, ...]:
103
+ return tuple(
104
+ OperationSlot(
105
+ operation_id=operation_id, duty_id=duty_id, role_id=role_id, ordinal=ordinal,
106
+ model_ref=str(model.model_ref), provider_id=model.provider_id,
93
107
  display_name=model.display_name,
94
- ))
95
- return tuple(slots)
108
+ )
109
+ for ordinal, model in enumerate(models, start=1)
110
+ )
111
+
112
+
113
+ def operation_contract_root() -> Path:
114
+ """The directory holding `operations/<id>.json` contracts for this runtime."""
115
+ from .paths import find_asset_root
116
+
117
+ root = find_asset_root(("agents", "operations"), is_present=Path.is_dir)
118
+ if root is None:
119
+ raise OperationPreparationError(
120
+ "operation contracts not found: no agents/operations under OKSTRA_HOME or this checkout"
121
+ )
122
+ return root
123
+
124
+
125
+ def require_distinct_providers(providers: Sequence[str]) -> None:
126
+ """Every team needs its own provider.
127
+
128
+ The operation asks for cross-model verification, and two models of one
129
+ provider do not provide it.
130
+ """
131
+ if len(set(providers)) != len(providers):
132
+ raise OperationPreparationError(
133
+ "every team needs a different provider, got " + ", ".join(providers)
134
+ )
135
+
136
+
137
+ def resolve_model_reference(pool: ModelPool, value: str) -> ResolvedModel:
138
+ """A `provider/model` reference, or a provider alias such as `claude/opus`."""
139
+ from .domain.provider import UnknownModelError
140
+
141
+ try:
142
+ return pool.resolve(value)
143
+ except UnknownModelError:
144
+ provider, sep, alias = value.partition("/")
145
+ if not sep or not alias:
146
+ raise
147
+ return pool.resolve_alias(provider, alias)
148
+
149
+
150
+ def resolve_operation_models(
151
+ operation_id: str, references: Sequence[str], *, contract_root: Path, pool: ModelPool,
152
+ ) -> tuple[str, str, tuple[ResolvedModel, ...]]:
153
+ """The duty, role and models a caller chose for an operation, one per team, in order."""
154
+ from .domain.provider import UnknownModelError
155
+
156
+ duty_id, role_id, ceiling = _operation_contract(operation_id, contract_root)
157
+ if not references:
158
+ raise OperationPreparationError(f"operation {operation_id!r} needs at least one model")
159
+ if len(references) > ceiling:
160
+ raise OperationPreparationError(
161
+ f"operation {operation_id!r} takes at most {ceiling} models, got {len(references)}"
162
+ )
163
+ try:
164
+ models = [resolve_model_reference(pool, value) for value in references]
165
+ except UnknownModelError as exc:
166
+ raise OperationPreparationError(str(exc)) from exc
167
+ require_distinct_providers([model.provider_id for model in models])
168
+ for model in models:
169
+ if not pool.resolve_provider(model.provider_id).supports_role(role_id):
170
+ raise OperationPreparationError(
171
+ f"provider {model.provider_id!r} does not support role {role_id!r}"
172
+ )
173
+ availability = pool.availability(str(model.model_ref), role_id)
174
+ if not availability.available:
175
+ raise OperationPreparationError(
176
+ f"model {model.model_ref} is not available: {availability.reason}"
177
+ )
178
+ return duty_id, role_id, tuple(models)
179
+
180
+
181
+ def select_operation_models(
182
+ operation_id: str, flags: Sequence[str], count: int | None, *, contract_root: Path, cwd: Path,
183
+ ) -> tuple[tuple[str, ...], str]:
184
+ """Which model references an operation's teams use, and where they came from.
185
+
186
+ Flags win, then project and then global `operationModels`, then adapter
187
+ defaults (an empty tuple with source `bundled`). A count is checked
188
+ against the contract range first; with flags it must equal their number,
189
+ with a config list it takes that many from the front.
190
+ """
191
+ ceiling = operation_ceiling(operation_id, contract_root=contract_root)
192
+ if count is not None and not 1 <= count <= ceiling:
193
+ raise OperationPreparationError(
194
+ f"operation {operation_id!r} takes a count from 1 to {ceiling}, got {count}"
195
+ )
196
+ if flags:
197
+ if count is not None and count != len(flags):
198
+ raise OperationPreparationError("--count differs from the number of --model values")
199
+ return tuple(flags), "flag"
200
+ configured, scope = operation_model_defaults(operation_id, cwd)
201
+ if not configured or count is None:
202
+ return configured, scope
203
+ if count > len(configured):
204
+ raise OperationPreparationError(
205
+ f"{scope} operationModels names {len(configured)} models, fewer than --count {count}"
206
+ )
207
+ return configured[:count], scope
208
+
209
+
210
+ def resolve_operation_team(
211
+ operation_id: str, flags: Sequence[str], count: int | None, *,
212
+ contract_root: Path, pool: ModelPool, cwd: Path,
213
+ ) -> tuple[tuple[OperationSlot, ...], str]:
214
+ """The operation's slots for the selected models, and the models' source."""
215
+ references, source = select_operation_models(
216
+ operation_id, flags, count, contract_root=contract_root, cwd=cwd,
217
+ )
218
+ if not references:
219
+ return tuple(resolve_operation_slots(
220
+ operation_id, contract_root=contract_root, pool=pool, count=count,
221
+ )), source
222
+ duty_id, role_id, models = resolve_operation_models(
223
+ operation_id, references, contract_root=contract_root, pool=pool,
224
+ )
225
+ return _numbered_slots(operation_id, duty_id, role_id, models), source
226
+
227
+
228
+ def operation_model_defaults(operation_id: str, cwd: Path) -> tuple[tuple[str, ...], str]:
229
+ """The models `operationModels` names for an operation, and the scope that named them.
230
+
231
+ Project config wins over global config; neither merges with the other.
232
+ An empty tuple with scope `bundled` means no config names the operation.
233
+ """
234
+ from okstra_project.dirs import okstra_home
235
+
236
+ from .model_defaults import ModelDefaultScopes, default_candidates, default_scope
237
+
238
+ scopes = ModelDefaultScopes(
239
+ project=_operation_models(_project_config(cwd)),
240
+ global_=_operation_models(okstra_home() / "config.json"),
241
+ bundled={},
242
+ )
243
+ refs = default_candidates(operation_id, scopes)
244
+ return refs, default_scope(operation_id, scopes) or "bundled"
245
+
246
+
247
+ def _project_config(cwd: Path) -> Path:
248
+ from okstra_project import project_json_path, resolve_project_root
249
+
250
+ try:
251
+ return project_json_path(resolve_project_root(cwd=str(cwd)))
252
+ except Exception:
253
+ return cwd / ".okstra" / "project.json"
254
+
255
+
256
+ def _operation_models(path: Path) -> dict[str, tuple[str, ...]]:
257
+ from .json_boundary import load_owned_object
258
+ from .model_defaults import ModelDefaultError, parse_model_lists
259
+
260
+ payload = load_owned_object(path, artifact="model configuration") if path.is_file() else {}
261
+ try:
262
+ return parse_model_lists(payload, "operationModels", path)
263
+ except ModelDefaultError as exc:
264
+ raise OperationPreparationError(str(exc)) from exc
265
+
266
+
267
+ def slot_payload(slot: OperationSlot) -> dict[str, object]:
268
+ """The JSON row callers print for one slot."""
269
+ return {
270
+ "ordinal": slot.ordinal,
271
+ "provider": slot.provider_id,
272
+ "modelRef": slot.model_ref,
273
+ "model": slot.display_name,
274
+ }
@@ -19,6 +19,7 @@ from .paths import (
19
19
  task_timeline_file,
20
20
  )
21
21
  from .worker_artifacts import worker_artifact_paths
22
+ from .report_contract import report_authoring_format, report_authoring_suffix
22
23
  from .verification_input_ref import (
23
24
  VerificationInputReference, artifact_fields, artifact_fields_from_context,
24
25
  )
@@ -322,6 +323,8 @@ def _hydrate_active_source_artifacts(ctx: Mapping[str, str]) -> dict[str, str]:
322
323
 
323
324
  def _compact_run_hints(ctx: Mapping[str, Any]) -> dict[str, Any]:
324
325
  return {
326
+ "reportAuthoringFormat": ctx.get("REPORT_AUTHORING_FORMAT", "markdown-v1"),
327
+ "usageAccountingPolicy": ctx.get("USAGE_ACCOUNTING_POLICY", "strict"),
325
328
  "runRoot": ctx.get("RUN_DIR_RELATIVE_PATH", ""),
326
329
  "stage": ctx.get("RUN_STAGE", ""),
327
330
  "fileSuffix": ctx.get("RUN_FILE_SUFFIX", ""),
@@ -342,10 +345,14 @@ def _hydrate_from_hints(
342
345
  hints: Mapping[str, Any],
343
346
  timestamps: Any,
344
347
  ) -> dict[str, Any]:
348
+ from okstra_token_usage.policy import usage_accounting_policy
349
+
345
350
  paths = _build_path_set(identity, hints)
346
351
  filenames = _filename_fields(paths)
347
352
  relative = _relative_fields(paths["project_root"], paths)
348
353
  return {
354
+ "REPORT_AUTHORING_FORMAT": paths["report_authoring_format"],
355
+ "USAGE_ACCOUNTING_POLICY": usage_accounting_policy(_mapping(hints.get("run"))),
349
356
  **_identity_fields(identity),
350
357
  **_runtime_fields(paths),
351
358
  **_absolute_fields(paths),
@@ -361,12 +368,14 @@ def _build_path_set(identity: Mapping[str, Any], hints: Mapping[str, Any]) -> di
361
368
  workspace_root = Path(str(identity.get("workspaceRoot", "")))
362
369
  project_hints = _mapping(hints.get("project"))
363
370
  run_hints = _mapping(hints.get("run"))
371
+ authoring_format = report_authoring_format(run_hints)
364
372
  task_root = _project_path(project_root, _task_root_hint(hints))
365
373
  run_root = _project_path(project_root, str(run_hints.get("runRoot", "")))
366
374
  task_type_segment = _segment(identity, "taskType")
367
375
  sequences = _sequences(run_hints)
368
376
  suffixes = _suffixes(task_type_segment, sequences)
369
377
  paths = {
378
+ "report_authoring_format": authoring_format,
370
379
  "project_root": project_root,
371
380
  "workspace_root": workspace_root,
372
381
  "okstra_root": _project_path(project_root, str(project_hints.get("okstraRoot", OKSTRA_RELATIVE))),
@@ -382,7 +391,7 @@ def _build_path_set(identity: Mapping[str, Any], hints: Mapping[str, Any]) -> di
382
391
  "suffixes": suffixes,
383
392
  }
384
393
  paths.update(_task_path_set(task_root))
385
- paths.update(_run_path_set(run_root, task_type_segment, sequences, suffixes))
394
+ paths.update(_run_path_set(run_root, task_type_segment, sequences, suffixes, authoring_format))
386
395
  paths.update(_discovery_path_set(paths["discovery_dir"]))
387
396
  return paths
388
397
 
@@ -413,6 +422,7 @@ def _run_path_set(
413
422
  task_type_segment: str,
414
423
  sequences: Mapping[str, str],
415
424
  suffixes: Mapping[str, str],
425
+ authoring_format: str,
416
426
  ) -> dict[str, Path]:
417
427
  run_prompts = run_dir / "prompts"
418
428
  worker_results = run_dir / "worker-results"
@@ -434,7 +444,7 @@ def _run_path_set(
434
444
  if task_type_segment == "implementation"
435
445
  else run_dir / "carry"
436
446
  ),
437
- **_run_files(run_dir, run_prompts, worker_results, task_type_segment, sequences, suffixes),
447
+ **_run_files(run_dir, run_prompts, worker_results, task_type_segment, sequences, suffixes, authoring_format),
438
448
  }
439
449
 
440
450
 
@@ -445,6 +455,7 @@ def _run_files(
445
455
  task_type_segment: str,
446
456
  sequences: Mapping[str, str],
447
457
  suffixes: Mapping[str, str],
458
+ authoring_format: str,
448
459
  ) -> dict[str, Path]:
449
460
  run_manifests = run_dir / "manifests"
450
461
  run_state = run_dir / "state"
@@ -478,7 +489,7 @@ def _run_files(
478
489
  "codex_worker_result": worker_results / f"codex-worker{suffixes['worker_results']}.md",
479
490
  "antigravity_worker_result": worker_results / f"antigravity-worker{suffixes['worker_results']}.md",
480
491
  "report_writer_worker_result": worker_results / f"report-writer-worker{suffixes['worker_results']}.md",
481
- "report_writer_narrative": worker_results / f"report-writer-narrative{suffixes['worker_results']}.md",
492
+ "report_writer_narrative": worker_results / f"report-writer-narrative{suffixes['worker_results']}{report_authoring_suffix(authoring_format)}",
482
493
  "approval_decisions": run_state / f"approval-decisions-{task_type_segment}-{sequences['state']}.json",
483
494
  "design_preparation": run_state / f"design-preparation-{task_type_segment}-{sequences['state']}.json",
484
495
  "plan_body_verification": run_state / f"plan-body-verification-{task_type_segment}-{sequences['state']}.json",
@@ -557,6 +557,7 @@ def compute_run_paths(
557
557
  task_type: str,
558
558
  run_seq_override: Optional[int] = None,
559
559
  stage: Optional[int] = None,
560
+ report_authoring_format: str = "markdown-v1",
560
561
  ) -> dict:
561
562
  """주어진 identity 와 task-type 에 대해 모든 path/segment 값을 계산해
562
563
  dict 로 돌려준다. 부수효과 없음.
@@ -688,7 +689,10 @@ def compute_run_paths(
688
689
  codex_worker_result = worker_results / f"codex-worker{suffixes['worker_results']}.md"
689
690
  antigravity_worker_result = worker_results / f"antigravity-worker{suffixes['worker_results']}.md"
690
691
  report_writer_worker_result = worker_results / f"report-writer-worker{suffixes['worker_results']}.md"
691
- report_writer_narrative = worker_results / f"report-writer-narrative{suffixes['worker_results']}.md"
692
+ from .report_contract import report_authoring_suffix
693
+
694
+ authoring_suffix = report_authoring_suffix(report_authoring_format)
695
+ report_writer_narrative = worker_results / f"report-writer-narrative{suffixes['worker_results']}{authoring_suffix}"
692
696
  approval_decisions = run_state / f"approval-decisions-{task_type_segment}-{seqs['state']}.json"
693
697
  design_preparation = run_state / f"design-preparation-{task_type_segment}-{seqs['state']}.json"
694
698
  plan_body_verification = run_state / f"plan-body-verification-{task_type_segment}-{seqs['state']}.json"
@@ -714,6 +718,7 @@ def compute_run_paths(
714
718
  ).joinpath(*RUN_VALIDATOR_RELATIVE)
715
719
 
716
720
  abs_paths = {
721
+ "REPORT_AUTHORING_FORMAT": report_authoring_format,
717
722
  "PROJECT_ID": project_id,
718
723
  "PROJECT_ROOT": str(project_root),
719
724
  "WORKSPACE_ROOT": str(workspace_root),
@@ -31,6 +31,7 @@ class PhaseRecord:
31
31
  migrated: bool
32
32
  view_module: str
33
33
  view_function: str
34
+ requires_host_rules: bool
34
35
 
35
36
 
36
37
  def _view(package_name: str, function: str, *, phase_package: bool) -> tuple[str, str]:
@@ -44,9 +45,11 @@ def _record(
44
45
  package_name: str,
45
46
  migrated: bool,
46
47
  view_function: str,
48
+ *,
49
+ requires_host_rules: bool = False,
47
50
  ) -> PhaseRecord:
48
51
  module, function = _view(package_name, view_function, phase_package=migrated)
49
- return PhaseRecord(task_type, package_name, migrated, module, function)
52
+ return PhaseRecord(task_type, package_name, migrated, module, function, requires_host_rules)
50
53
 
51
54
 
52
55
  # 이전되지 않은 단계는 기존 ``prompts/profiles`` 위치를 명시적으로 쓴다.
@@ -67,8 +70,14 @@ PHASES: tuple[PhaseRecord, ...] = (
67
70
  True,
68
71
  "build_implementation_option_selection_view",
69
72
  ),
70
- _record("implementation-planning", "implementation_planning", True, "build_implementation_planning_view"),
71
- _record("implementation", "implementation", True, "build_implementation_view"),
73
+ _record(
74
+ "implementation-planning", "implementation_planning", True,
75
+ "build_implementation_planning_view", requires_host_rules=True,
76
+ ),
77
+ _record(
78
+ "implementation", "implementation", True,
79
+ "build_implementation_view", requires_host_rules=True,
80
+ ),
72
81
  _record("final-verification", "final_verification", True, "build_final_verification_view"),
73
82
  _record("release-handoff", "release_handoff", True, "build_release_handoff_view"),
74
83
  _record("discussion", "discussion", True, "build_discussion_view"),
@@ -224,13 +233,21 @@ def _report_template_filename(task_type: str, logical_name: str) -> str | None:
224
233
 
225
234
 
226
235
 
227
- def host_rules(asset_root: Path, task_type: str) -> Path:
228
- """선택된 단계의 호스트 지침을 같은 자산 루트에서 찾는다."""
236
+ def host_rules(asset_root: Path, task_type: str) -> Path | None:
237
+ """선언된 단계의 호스트 지침을 같은 자산 루트에서 찾고 누락을 거부한다."""
229
238
  record = phase_record(task_type)
239
+ if not record.requires_host_rules:
240
+ return None
230
241
  root = package_root(asset_root) if record.migrated else None
231
242
  if root is not None:
232
- return root / "phases" / record.package_name / "host-rules.md"
233
- return asset_root / "prompts" / "host-orchestration" / f"{task_type}.md"
243
+ path = root / "phases" / record.package_name / "host-rules.md"
244
+ else:
245
+ path = asset_root / "prompts" / "host-orchestration" / f"{task_type}.md"
246
+ if not path.is_file():
247
+ raise PhaseAssetError(
248
+ f"host orchestration rules file not found for task-type {task_type}: {path}"
249
+ )
250
+ return path
234
251
 
235
252
 
236
253
  def profile_sidecar(asset_root: Path, logical_name: str) -> Path:
@@ -16,6 +16,26 @@ from okstra_ctl.report_execution_evidence import (
16
16
  )
17
17
  from okstra_ctl.verification_target import TARGET_FIELD_RES, read_verification_target
18
18
 
19
+
20
+ def validate_implementation_review_evidence(project: Path, manifest_path: Path) -> None:
21
+ from dataclasses import replace
22
+ from okstra_ctl.design_review_evidence import design_review_required, validate_stage_design_report
23
+ from okstra_ctl.json_boundary import load_owned_object
24
+ from okstra_ctl.paths import RunRef
25
+
26
+ manifest = load_owned_object(manifest_path, artifact="run manifest")
27
+ if manifest.get("taskType") != "final-verification" or not design_review_required(project, manifest):
28
+ return
29
+ target = read_verification_target(project, str(manifest.get("verificationTargetPath") or ""))
30
+ if target is None or set(target["reports"]) != target["stages"]:
31
+ raise ValueError("final verification requires every source implementation review report")
32
+ ref = RunRef.from_manifest(manifest_path, manifest).sibling("implementation")
33
+ for stage, location in target["reports"].items():
34
+ report = Path(location)
35
+ if not report.is_absolute():
36
+ report = project / report if location.startswith(".okstra/") else replace(ref, stage=stage).run_dir / report
37
+ validate_stage_design_report(project, report, stage, task_key=str(manifest["taskKey"]))
38
+
19
39
  _ADDED_SURFACE_NO_CALLER_RE = re.compile(r"^\s*none\b", re.IGNORECASE)
20
40
 
21
41
 
@@ -6,9 +6,9 @@ to recover a stale stage SHA, and what the chaining queue does when the next
6
6
  stage is not ready. They are not lead phase rules — the lead's rules live in
7
7
  `prompts/profiles/`.
8
8
 
9
- This file is the single source. Two surfaces are generated from it: the
10
- `okstra-run` skill body (marker block, synced by `tools/sync-skill-fragments.mjs`)
11
- and each run's `instruction-set/host-orchestration-rules.md`. Edit here.
9
+ This file is the single source. The wizard returns its path for the host to read
10
+ before preparation. Each run's `instruction-set/host-orchestration-rules.md` is
11
+ generated from it at prepare time. Edit here.
12
12
 
13
13
  ### Step 5.1 (implementation only): blocking local conformance waiver offer
14
14
 
@@ -6,6 +6,16 @@ are collected and convergence finished. Phase 1-5 do not need it.
6
6
 
7
7
  # Implementation profile — Deliverable sidecar
8
8
 
9
+ For verification-input 4.0 runs, report assembly owns `verifierResults[].designReview`
10
+ and derives verifier verdicts from sealed current returns. Do not author that evidence
11
+ or remove its findings to obtain acceptance. Every configured verifier owes its own
12
+ complete function/rule accounting. On a correction round, the full stage is inspected
13
+ again and earlier blocking findings receive explicit `Design Carry` dispositions;
14
+ their history and the bases for accepted risks remain in the report. `stage-done`
15
+ requires the same accepted task/stage/base/head evidence. Enforcement is in
16
+ `design_review_evidence.py`, report assembly and stage completion; legacy inputs
17
+ retain their existing contract.
18
+
9
19
  > **When to read**: lead reads this file ONCE at the start of Phase 6 (after Phase 5.5 convergence completes, before constructing the report-writer dispatch prompt). Carries the final-report deliverable shape, the lead minor fix, lead's post-stage persistence rules, and the self-review checklist.
10
20
 
11
21
  ## Required deliverable shape (final report, in addition to the standard sections)
@@ -27,27 +27,42 @@ Do not scan holistically and stop when it "looks fine". Work the matrix exhausti
27
27
 
28
28
  ## Method — enumerate the diff, then walk every (file × applicable-rule) cell
29
29
 
30
- 1. **List every changed file:** `git diff --name-only <stage-base>..HEAD`. That list is your worklist — cover it to the end; no sampling.
30
+ Use the captured `review-rules.json` IDs and `clean-code.md` "Finding evidence
31
+ and grading" for every finding. Apply M1 and M2 to each changed function, including
32
+ named test helpers. Establish an observable defect, an explicit applicable project
33
+ rule breach or a concrete design or maintenance impact; a preferred name or flow
34
+ alone is insufficient. Correct execution does not waive an established violation.
35
+ Return a plan conflict when the authorized placement cannot
36
+ satisfy the rules; do not retain a violation solely to obey a file restriction.
37
+ Resolve conflicts by `overview.md` policy precedence: explicit repository
38
+ instructions and declared architecture, the common pack, then surrounding code
39
+ conventions. Existing violations alone do not waive an explicit rule.
40
+
41
+ 1. **List every changed file:** `git diff --name-only <stage-base>..HEAD`. Apply the shared census exclusion policy and record each exclusion with its reason; executable configuration is not excluded by extension alone. Cover the retained worklist to the end; no sampling.
31
42
  2. **Classify each file and select its rule set** from the conventions the preflight already loaded (do NOT re-derive the rules here — read them from the routed pack):
32
- - any source file → `clean-code.md`: truthful + standalone names, one identifier one meaning per file (a key parameter must not take the name a sibling signature gives the entity), plain-English summary test, single-purpose ≤50-line functions, DRY (incl. scattered domain literals + documented forks), YAGNI, no magic numbers, shallow nesting, comments explain why.
33
- - The YAGNI cell also counts callers, not just their existence: an abstraction layer this diff *introduces* — helper module, strategy / factory / builder, indirection or wrapper layer, interface or abstract base — with exactly **one** caller after the change is an inline candidate under `overview.md` core principle 2 ("name the second caller now, or inline"). Collapse it into that call site unless one of four exits applies and you record which: the approved plan declares it as a test seam or variation-point extraction, the project-context preflight projection declares hexagonal architecture and it is a port at the domain boundary, it breaks a real import cycle, or its single caller is a published package's public API. A function extracted only to get a body under the 50-line cap is not this finding.
43
+ - any file retained by the shared census exclusion policy → applicable `clean-code.md` checks: truthful + standalone names, one identifier one meaning per file (a key parameter must not take the name a sibling signature gives the entity), cohesive responsibility, manageable complexity and consistent abstraction levels, DRY (incl. scattered domain literals + documented forks), YAGNI, meaningful names for policy values and units, control flow whose decisions and exit paths can be followed, comments explain why. Function size, deep nesting and inline phases prompt closer review; counts alone are not findings or reasons to extract code.
44
+ - The YAGNI cell also counts callers, not just their existence: an abstraction layer this diff *introduces* — helper module, strategy / factory / builder, indirection or wrapper layer, interface or abstract base — with exactly **one** caller after the change is an inline candidate under `overview.md` core principle 2 ("name the second caller now, or inline"). Collapse it into that call site unless one of four exits applies and you record which: the approved plan declares it as a test seam or variation-point extraction, the project-context preflight projection declares hexagonal architecture and it is a port at the domain boundary, it breaks a real import cycle, or its single caller is a published package's public API. This targets reusable layers, not a local helper that names a cohesive step or separates mixed abstraction levels; line count alone does not justify extraction.
34
45
  - The YAGNI cell is a grep, not an impression: for every identifier this diff adds — and every one whose last caller it removes — search the whole repository and name the caller you found. A declaration-only, test-only, or commented-out hit is not a caller. Zero callers means delete it here (or fold an added parameter back into its single call site), unless the approved plan reserves it for a named later stage or something outside project code calls it (framework entrypoint, implemented interface method, migration hook, published-package API) — in which case record that justification in the audit note. Fixing it now is cheaper than the verifier's Static design gate, where the same finding is blocking and fails the stage (`_implementation-verifier.md` "Caller-less identifier").
35
46
  - a file that wraps a third-party / library call → `clean-code.md` "Wrapping a third-party call": the wrapper adds behaviour the library does not already provide (read the installed library source before keeping a recovery branch — a `catch` repeating the library's own retry recovers nothing), no comment names a condition the call site does not establish, and a rethrow keeps the original error as `cause`.
36
47
  - a file that decides, mutates, or persists state → `clean-code.md` "Mutation and state boundaries": decide on the direct identifier rather than a status/flag proxy, capture before-state in one snapshot ahead of the mutating boundary, update only this work's owned fields on an existing row, re-read state before calling a zero-affected-rows write success or failure, put priority-between-inputs in a named domain function, and keep error messages to what was actually observed. Also check that no state union/enum was re-declared beside an authoritative one the domain or a dependency exports.
37
- - test file (`*.spec.*` / `*.test.*` / `test_*.py` / `*_test.go` …) → `clean-code.md` "Testing discipline": no self-mocking of the SUT, behavioral (outcome) assertions not interaction-only, no tautological delegation assertion, no effect claimed under its own mock, shared-fixture defaults left on the ordinary path, setup values that actually separate the scenarios, every new test helper/mock used by a test in this same diff, no positional mock-argument access (`rg 'mock\.calls'`), every branch this diff adds covered by a test that fails when the branch body is deleted, assertions on the last write to a record rather than an intermediate one, and test titles naming their unit plus the single condition each case isolates.
38
- - port / adapter / domain file, when the hexagonal overlay is loaded → `architectures/hexagonal.md`: no business logic in a port body, adapter methods are I/O only (no post-fetch filtering on domain state, no `findValid*`/`findActive*` names hiding a rule), domain objects declared under the domain boundary, no changed domain file importing an ORM / framework / adapter / service (read the import list — mechanical), and a service dependency you add or modify goes through a port rather than a concrete adapter (advisory only while the project has not declared `architecture.style = hexagonal` in `.okstra/project.json` — record it with the port sketch; blocking under that declaration, so fix it in place before the commit rather than record-and-pass, exactly as `_implementation-verifier.md` re-grades this same diff. Either way, the codebase already injecting concrete classes is the debt this pays down, not a reason to skip it).
39
- - a service file, when the hexagonal overlay is loaded → `architectures/hexagonal.md` Rule H6: a decision this diff puts in a service — an `if`/`else` chain over domain fields, a business formula, a private method named for a domain concept — belongs in a domain function. Orchestration control flow, DTO mapping and calling a domain predicate are not violations.
48
+ - test file (`*.spec.*` / `*.test.*` / `test_*.py` / `*_test.go` …) → `clean-code.md` "Testing discipline": no self-mocking of the SUT, behavioral (outcome) assertions not interaction-only, no tautological delegation assertion, no effect claimed under its own mock, shared-fixture defaults left on the ordinary path, setup values that actually separate the scenarios, every new test helper/mock used by a test in this same diff, no positional mock-argument access (`rg 'mock\.calls'`), retained or strengthened tests distinguishing changed core behavior and meaningful failures, selective mutation checks where regression detection is uncertain or project rules require them, assertions on the last write to a record rather than an intermediate one, and test titles naming their unit plus the single condition each case isolates.
49
+ - port / adapter / domain file, when the hexagonal overlay is loaded → `architectures/hexagonal.md`: ports declare contracts rather than implement business decisions; the domain owns policy, and adapters may execute its query specifications efficiently. Do not infer a violation from complex SQL, domain-oriented query names or post-fetch processing alone, or require `findAll` plus in-memory filtering. Check domain placement, inward dependencies and touched concrete-adapter dependencies under the policy precedence above. Apply H1–H6 when the overlay is selected by declaration or layout; H5 alone retains its undeclared-style advisory exception.
50
+ - a service file, when the hexagonal overlay is loaded → `architectures/hexagonal.md` Rule H6: inspect whether changed service code implements a business decision rather than orchestrating a domain-owned one. A private method's domain-oriented name alone is not evidence. Orchestration control flow, DTO mapping and calling a domain predicate are not violations.
40
51
  - a file that reads input from outside the process (request body, query, header, upload, message, webhook) or acts on its behalf → `clean-code.md` "Untrusted input and security": a size/count bound rejects oversized input before any check that grows faster than the input (a validator that runs every rule, such as class-validator without `stopAtFirstError`, does not stop at a failed `@ArrayMaxSize`), input reaches SQL / shell / paths / server-side fetches / templates / regexes only through parameters, allowlists or escaping, a new entry point carries the auth guard and compares the caller with the owner of an input-chosen id, no secret or personal data reaches code, logs or responses, and nothing evaluates or unsafely deserializes input.
41
52
  - every changed source file → `clean-code.md` "Trace what this change can do wrong": walk the error, partial, concurrent and selection paths this diff creates to their end — past the failures the plan lists, and including where a cleaning `try` registers its cleanup target relative to each call that can throw — and fix wherever a wrong result comes out. Name the input that produces it — if you cannot name one, there is nothing to fix here and you move on rather than restructuring code that works.
42
53
  A file can hold several roles — apply every rule set that fits it.
43
54
  3. **Decide clean-or-finding for each cell.** Read the full file when a rule needs context (never judge a port/adapter/domain or a naming rule from the hunk alone).
44
- 4. **Fix each finding in place** before the commit. When a readability finding is real, the fix is a named helper or named intermediate value — sketch the cleaner shape (a few lines) in your audit note, then apply it. When the fix is genuinely out of this stage's scope, record it as an `Out-of-plan` note instead of silently leaving it.
55
+ 4. **Fix each finding in place** before the commit. For an evidenced readability problem, sketch how the fix resolves its concrete consequence in your audit note, then apply it. Choose the smallest suitable change, such as a clearer condition, a named value or a cohesive helper. When the fix is genuinely out of this stage's scope, record it as an `Out-of-plan` note instead of silently leaving it.
45
56
 
46
57
  ## Coverage footer (BLOCKING deliverable)
47
58
 
48
59
  End your audit-sidecar entry for this sweep with a one-line `Coverage:` footer naming each file you examined, the rule set(s) you applied to it, **and the outcome of each** — `clean` when you looked and found nothing, or `fixed <n>` when you fixed findings in place:
49
60
 
50
- `Coverage: users.service.ts [names: clean, plain-english: fixed 1], users.repository.adapter.ts [hexagonal: fixed 1, names: clean], users.service.spec.ts [testing-discipline: clean]`
61
+ Account for excluded files with their shared-census exclusion reasons in the same
62
+ footer. Examined files plus excluded files cover the complete changed-file list;
63
+ an exclusion does not claim a clean inspection.
64
+
65
+ `Coverage: users.service.ts [names: clean, cohesion: fixed 1], users.repository.adapter.ts [hexagonal: fixed 1, names: clean], users.service.spec.ts [testing-discipline: clean]; excluded: README.md [prose documentation]`
51
66
 
52
67
  `clean` is a result you assert, not a blank you leave. Naming the rule set without its outcome reads identically whether you checked it or skipped it, which is exactly what this footer exists to distinguish — the completion self-check and any reviewer read it to confirm nothing in the diff was skipped. A sweep with no footer, or a footer whose entries carry no outcome, is an unfinished sweep.
53
68
 
@@ -15,14 +15,16 @@ changed files (`git diff --name-only <stage-base>..HEAD`) and, for the per-file
15
15
  items, write the confirming evidence per file, not one global "✓". If any item
16
16
  fails, fix it or surface the violation — do not claim done on a failing item.
17
17
 
18
- - diff-review done: the `Pre-commit diff review sweep` ran over the full diff and its `Coverage:` footer is in your audit sidecar — every changed file named, with each applied rule set carrying its outcome (`clean` or `fixed <n>`). No footer, or entries with no outcome → the sweep is unfinished; do not claim done.
19
- - functions: every new/edited function ≤50 effective lines, single purpose — cite the longest function's actual line count, not "all under 50"
18
+ - diff-review done: the `Pre-commit diff review sweep` accounted for the full diff in its `Coverage:` footer — every examined file names its applied rule sets and outcomes (`clean` or `fixed <n>`), and every excluded file names its shared-census exclusion reason. Examined plus excluded files equal the changed-file list; excluded files are not clean inspections. A missing footer, inspection outcome or exclusion reason leaves the sweep unfinished.
19
+ - functions: review responsibility, cohesion, complexity and abstraction levels in every new/substantially edited function; more than 50 effective lines is an inspection signal, not a failure. Cite the concrete issue fixed or the rationale for retaining a cohesive longer function; follow any explicit repository limit
20
+ - grading: use the shared catalog IDs and `clean-code.md` "Finding evidence and grading". No unresolved current `must-fix` or `should-fix`, including M1/M2 design violations. Preserve `nit`, justified `park` and plan conflicts with their evidence; executor self-check is not independent verifier evidence.
20
21
  - file size: no source or test file this diff adds ends over 500 physical lines, and no file at 500 or fewer at the stage base ends over 500 (a file already over 500 may grow; that is advisory) — paste the output of `okstra correction file-size --base <stage-base>`; it must end `QA-RESULT: PASS`. Aim for 300: for each `FILE-SIZE-ADVISORY:` line it prints, split the file or say why not. A responsibility that would push a file over goes into its own new module or test file
21
- - conventions: applied the routed pack + project patterns (name which ones)
22
+ - conventions: name the explicit repository instructions, declared architecture, routed pack and surrounding patterns applied, in that precedence order; a surrounding pattern does not waive an explicit architecture rule
22
23
  - names & comments: names say what, comments say why; no obvious-restatement comments; no truthful-name violations
23
24
  - verification: ran the actual build/test — paste the exact command line and its real exit code / output tail, never a paraphrased "tests pass"
24
25
  - acceptance: each implemented plan step's `Acceptance:` condition is observably met — cite the RED→GREEN test (or the command output) proving it per step, not one global "acceptance met"; and each `Test case (success|boundary|failure)` the plan declared for this stage has a matching test in the diff (name the test), so declared edge/failure cases are not silently uncovered
25
- - mutation check: enumerate every branch this diff adds (`catch`, guard, early return, `else`), plus at least one test it added or changed. For each entry, break what it covers on purpose — delete the branch body, return the wrong value, skip the write — confirm a test FAILS, then restore; cite the branch (or test) and the observed failure per entry, not one global "mutation verified". A branch whose deletion leaves the suite green is untested, not covered — an untested recovery path is indistinguishable from one that cannot fire. "Verified" claimed without this check plus the real command output above is not a verified claim
26
+ - quality outcomes: apply the captured `clean-code.md` "Five simultaneous quality outcomes" to the actual diff. Preserve each applicable expectation, performance/resource bound, safety/security check and its evidence in the acceptance and verification results above. Name missing or waived evidence; do not infer all five outcomes from a green command or complete coverage table
27
+ - regression evidence: map changed core behavior and meaningful failure outcomes to retained or strengthened tests and their actual command results. Use targeted mutation checks where regression detection remains uncertain, especially for security, concurrency or recovery, or where explicit project rules require them. For each selected mutation, cite the changed behavior and focused test failure, restore the source and rerun the test; preserve selected or required checks not performed as unverified. Follow `clean-code.md` "Testing discipline" rather than enumerating every syntactic branch for manual mutation
26
28
  - cleanup: no dead or commented-out code left behind, and no caller-less identifier — list every identifier this diff added or whose last caller it removed, and cite the caller you grepped for each one (or the plan step / non-project-code contract point that justifies keeping it with none). "No new identifiers" is a valid answer; a global "cleaned up" is not
27
29
 
28
30
  Close with a `Self-check coverage:` line naming the files you verified the