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
@@ -93,7 +93,13 @@ _CLI_EPILOG = r"""Usage:
93
93
  okstra code-review target --task-key <k> --stage <N> [--base <ref>] [--project-root <dir>] [--cwd <dir>] --json
94
94
  okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] --json
95
95
  okstra code-review check-coverage --head <ref> [--base <ref>] --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
96
- okstra code-review scope --base <ref> --head <ref> --census <path> --policy <path> [--previous-head <ref> --previous-census <path> --completion <path> ...]
96
+ okstra code-review census --base <ref> --head <ref> --rules <review-rules.json> --out <artifact-path> [--policy <path> ...] [--run-manifest <path>] [--resource <pack-relative-resource> ...]
97
+ okstra code-review assign --census <review-id>.census.md [--project-root <dir>]
98
+ okstra code-review prepare --review-id <id> --census <id>.census.md --review-policy <path> --base <commit> --head <commit> --slots <slots.json> --brief <path> --host-runtime <host> [--resource <id> ...]
99
+ okstra code-review start --batch <id>.batch.json [--max-calls <n>]
100
+ okstra code-review await --batch <id>.batch.json --timeout-seconds <s>
101
+ okstra code-review gap-fill --batch <id>.batch.json [--reject <team>:<cell-id> ...]
102
+ okstra code-review scope --base <ref> --head <ref> --census <path> --review-policy <shared-policy-path> [--policy <captured-path> ...] [--previous-head <ref> --previous-census <path> --completion <path> ...]
97
103
  okstra code-review check-lines --base <ref> --head <ref> --cite <path:line> [--cite ...] [--project-root <dir>]
98
104
 
99
105
  Output: JSON { ok, mode, worktreePath, branch, baseCommit, headCommit,
@@ -107,9 +113,25 @@ instead of a checked-out tree. This is read-only — it never creates
107
113
  directories or files. `check-coverage` reads head evidence at `--head` and explicit
108
114
  base evidence at `--base`, never the working tree, prints covered cells, missing rules and unknown cells, and exits
109
115
  1 for incomplete coverage and 2 for invalid input or completion evidence.
110
- `census` writes the range's census to `--out`, copying the Rules table from
111
- `--rules` and keeping IDs from `--previous-census`; it exits 1 when changed
112
- non-Python code still needs function cells added by hand.
116
+ `census` writes the range's census to `--out` and keeps IDs from
117
+ `--previous-census`. It publishes one immutable policy at <out>.policy.json,
118
+ prints its Review policy path/digest, and selects its shared catalog with the
119
+ captured architecture. --run-manifest reuses frozen implementation rules;
120
+ --policy captures additional applied standards. It exits 1 when changed
121
+ non-Python code still needs function cells added by hand. `assign` writes one
122
+ <review-id>.<axis>.census.md per axis that has cells beside the census and
123
+ prints each axis's cell count and path (`-` for an axis without cells); an
124
+ existing assignment is reused only when identical. `prepare` assigns the census,
125
+ then scopes, materializes (cli-wrapper runner) and verifies one prompt per model
126
+ team and axis, and writes <review-id>.batch.json. `start` launches each
127
+ prepared wrapper in its own session under a supervisor that records the exit;
128
+ `await` finalizes, verifies and audits finished items, prints ALL_DONE (exit 0
129
+ complete, 1 incomplete) or POLL_TIMEOUT (exit 75), and can be called again;
130
+ it retries a wrapper that exited nonzero without a body once and repairs a
131
+ format-only rejection once. `gap-fill` prepares the next attempt for open or
132
+ rejected cells (run `start` next) and prints NO_PROGRESS for a team/axis whose
133
+ last gap-fill closed nothing. Scope reads frozen
134
+ policy bodies; legacy scope without --review-policy requires --policy files.
113
135
  """
114
136
 
115
137
 
@@ -122,7 +144,7 @@ def _build_parser() -> argparse.ArgumentParser:
122
144
  )
123
145
  parser.add_argument(
124
146
  "command",
125
- choices=("target", "check-lines", "check-coverage", "scope", "census"),
147
+ choices=("target", "check-lines", "check-coverage", "scope", "census", "assign", "prepare", "start", "await", "gap-fill"),
126
148
  )
127
149
  parser.add_argument("--task-key", default="", help="project-id:task-group:task-id")
128
150
  parser.add_argument("--stage", type=int, default=0, help="stage number to review")
@@ -147,10 +169,27 @@ def _build_parser() -> argparse.ArgumentParser:
147
169
  parser.add_argument("--previous-census", default="",
148
170
  help="scope, census: previous full census")
149
171
  parser.add_argument("--rules", default="",
150
- help="census: file whose ## Rules table the census copies")
172
+ help="census: canonical shared review-rules.json provenance")
151
173
  parser.add_argument("--out", default="", help="census: file to write the census to")
152
174
  parser.add_argument("--policy", action="append", default=[],
153
- help="scope: policy/calibration source to fingerprint (repeatable)")
175
+ help="census: additional policy to freeze; scope: captured policy to fingerprint")
176
+ parser.add_argument("--review-policy", default="", help="scope: shared frozen review policy")
177
+ parser.add_argument("--run-manifest", default="", help="census: reuse this run's frozen review policy")
178
+ parser.add_argument("--resource", action="append", default=[],
179
+ help="census, prepare: additional captured pack-relative rule resource")
180
+ parser.add_argument("--review-id", default="", help="prepare: slug naming this review round")
181
+ parser.add_argument("--slots", default="", help="prepare: resolve-operation --json output")
182
+ parser.add_argument("--brief", default="", help="prepare: shared specialist brief")
183
+ parser.add_argument("--host-runtime", default="", help="prepare: registered host id")
184
+ parser.add_argument("--batch", default="", help="start, await, gap-fill: <review-id>.batch.json")
185
+ parser.add_argument("--previous-batch", default="",
186
+ help="prepare: previous round's batch whose completions become carry candidates")
187
+ parser.add_argument("--reject", action="append", default=[],
188
+ help="gap-fill: <team>:<cell-id> whose verdict the lead rejected")
189
+ parser.add_argument("--max-calls", type=int, default=None,
190
+ help="start: refuse to exceed this many started calls for the review")
191
+ parser.add_argument("--timeout-seconds", type=float, default=None,
192
+ help="await: stop waiting after this many seconds and print POLL_TIMEOUT")
154
193
  parser.add_argument("--date", default="", help="YYYY-MM-DD for branch result naming")
155
194
  parser.add_argument("--project-root", default="", help="explicit project root")
156
195
  parser.add_argument("--cwd", default=".", help="cwd for project root resolution")
@@ -353,6 +392,14 @@ def main(argv: list[str] | None = None) -> int:
353
392
  return _scope(args, Path(project_root))
354
393
  if args.command == "census":
355
394
  return _census(args, Path(project_root))
395
+ if args.command == "assign":
396
+ return _assign(args, Path(project_root))
397
+ if args.command == "prepare":
398
+ return _prepare(args, Path(project_root))
399
+ if args.command in ("start", "await"):
400
+ return _run(args, Path(project_root))
401
+ if args.command == "gap-fill":
402
+ return _gap_fill(args, Path(project_root))
356
403
  if args.command == "check-coverage":
357
404
  return _check_coverage(args, Path(project_root))
358
405
  if args.command == "check-lines":
@@ -385,33 +432,183 @@ def main(argv: list[str] | None = None) -> int:
385
432
  def _census(args: argparse.Namespace, project_root: Path) -> int:
386
433
  from .code_review_census import build_review_census
387
434
  from .code_review_coverage import read_review_census
435
+ from .review_policy import render_review_rule_catalog, select_review_policy
388
436
 
389
437
  if not (args.base and args.head and args.rules and args.out):
390
438
  print("census: pass --base, --head, --rules and --out", file=sys.stderr)
391
439
  return 2
392
440
  try:
441
+ if Path(args.rules).name != "review-rules.json":
442
+ raise ValueError("census requires the shared review-rules.json; add project standards with --policy")
443
+ out = Path(args.out).absolute()
444
+ policy_path, policy, digest = _census_review_policy(args, project_root, out)
445
+ changed = changed_lines(project_root, args.base, args.head)
446
+ from .review_policy import review_policy_context
447
+
448
+ paths, manifests = review_policy_context(project_root, args.head, tuple(changed), base=args.base)
449
+ selected = select_review_policy(
450
+ policy, tuple(changed), project_paths=paths, manifest_contents=manifests,
451
+ resources=args.resource,
452
+ )
393
453
  result = build_review_census(
394
454
  project_root, args.base, args.head, Path(args.rules),
395
- changed_lines(project_root, args.base, args.head),
455
+ changed, frozen_rules=render_review_rule_catalog(selected),
396
456
  previous=Path(args.previous_census) if args.previous_census else None,
397
457
  )
398
- out = Path(args.out)
399
- out.write_text(result.text, encoding="utf-8")
458
+ selection = (f"Review policy digest: {digest}\nReview resources: "
459
+ + ("; ".join(args.resource) or "-") + "\n")
460
+ out.write_text(selection + result.text, encoding="utf-8")
400
461
  read_review_census(out)
401
462
  except (OSError, ValueError, SyntaxError, StateError,
402
463
  subprocess.CalledProcessError) as exc:
403
464
  print(f"census: {exc}", file=sys.stderr)
404
465
  return 2
466
+ print(f"Review policy: {policy_path}")
467
+ print(selection, end="")
405
468
  print(result.text, end="")
406
469
  return 1 if result.unresolved else 0
407
470
 
408
471
 
472
+ def _assign(args: argparse.Namespace, project_root: Path) -> int:
473
+ from .code_review_census import ASSIGNMENT_AXES, write_review_assignments
474
+ from .review_verdicts import read_review_census
475
+
476
+ if not args.census:
477
+ print("assign: pass --census <review-id>.census.md", file=sys.stderr)
478
+ return 2
479
+ try:
480
+ outputs = write_review_assignments(project_root, Path(args.census).absolute())
481
+ counts = {axis: len(read_review_census(path).cells) for axis, path in outputs.items()}
482
+ except (OSError, ValueError) as exc:
483
+ print(f"assign: {exc}", file=sys.stderr)
484
+ return 2
485
+ for axis in ASSIGNMENT_AXES:
486
+ print(f"Axis: {axis}")
487
+ print(f"Cells: {counts.get(axis, 0)}")
488
+ print(f"Census: {outputs.get(axis, '-')}")
489
+ return 0
490
+
491
+
492
+ def _prepare(args: argparse.Namespace, project_root: Path) -> int:
493
+ from .code_review_prepare import prepare_review_batch, render_batch_summary
494
+
495
+ required = (args.review_id, args.census, args.review_policy, args.base, args.head,
496
+ args.slots, args.brief, args.host_runtime)
497
+ if not all(required):
498
+ print("prepare: pass --review-id, --census, --review-policy, --base, --head, "
499
+ "--slots, --brief and --host-runtime", file=sys.stderr)
500
+ return 2
501
+ try:
502
+ batch = prepare_review_batch(
503
+ project_root=project_root, review_id=args.review_id, census=Path(args.census),
504
+ policy=Path(args.review_policy).absolute(), base=args.base, head=args.head,
505
+ slots_path=Path(args.slots), brief=Path(args.brief),
506
+ host_runtime=args.host_runtime, resources=args.resource,
507
+ previous_batch=Path(args.previous_batch) if args.previous_batch else None,
508
+ )
509
+ except (OSError, ValueError) as exc:
510
+ print(f"prepare: {exc}", file=sys.stderr)
511
+ return 2
512
+ print(render_batch_summary(batch), end="")
513
+ return 0
514
+
515
+
516
+ def _run(args: argparse.Namespace, project_root: Path) -> int:
517
+ from .code_review_run import await_review_batch, render_state, start_review_batch
518
+
519
+ if not args.batch or (args.command == "await" and args.timeout_seconds is None):
520
+ print(f"{args.command}: pass --batch" + (" and --timeout-seconds" if args.command == "await" else ""),
521
+ file=sys.stderr)
522
+ return 2
523
+ batch = Path(args.batch)
524
+ try:
525
+ if args.command == "start":
526
+ print(render_state(batch, start_review_batch(project_root, batch, max_calls=args.max_calls)),
527
+ end="")
528
+ return 0
529
+ result = await_review_batch(project_root, batch, timeout_seconds=args.timeout_seconds)
530
+ except (OSError, ValueError) as exc:
531
+ print(f"{args.command}: {exc}", file=sys.stderr)
532
+ return 2
533
+ print(render_state(batch, result), end="")
534
+ if not result.done:
535
+ return 75
536
+ return 0 if result.complete else 1
537
+
538
+
539
+ def _gap_fill(args: argparse.Namespace, project_root: Path) -> int:
540
+ from .code_review_prepare import add_review_attempts, gap_fill_requests
541
+ from .code_review_run import _load_batch, _locked_state
542
+
543
+ if not args.batch:
544
+ print("gap-fill: pass --batch", file=sys.stderr)
545
+ return 2
546
+ try:
547
+ rejected: dict[int, list[str]] = {}
548
+ for value in args.reject:
549
+ team, sep, cell = value.partition(":")
550
+ if not sep or not team.isdigit() or not cell:
551
+ raise ValueError(f"--reject takes <team>:<cell-id>, got {value!r}")
552
+ rejected.setdefault(int(team), []).append(cell)
553
+ project, batch = _load_batch(project_root, Path(args.batch))
554
+ with _locked_state(project, batch) as state:
555
+ requests, stopped = gap_fill_requests(batch, state, rejected)
556
+ added = add_review_attempts(project, Path(args.batch), state, requests)
557
+ except (OSError, ValueError) as exc:
558
+ print(f"gap-fill: {exc}", file=sys.stderr)
559
+ return 2
560
+ for item in added:
561
+ print(f"Item: {item['invocationId']} | team {item['team']} | {item['axis']} | {item['census']}")
562
+ for pair in stopped:
563
+ print(f"NO_PROGRESS: {pair}")
564
+ print(f"Added: {len(added)}")
565
+ return 1 if stopped else 0
566
+
567
+
568
+ def _census_review_policy(
569
+ args: argparse.Namespace, project: Path, out: Path,
570
+ ) -> tuple[Path, dict, str]:
571
+ from .qa_procedures import canonical_json_digest, load_qa_config, content_digest, safe_qa_path
572
+ from .review_policy import capture_code_review_policy, publish_review_policy, read_review_policy
573
+ from .verification_input_ref import VerificationInputReference
574
+ from .verification_inputs import read_verification_inputs
575
+ from .json_boundary import load_owned_object
576
+
577
+ destination = Path(str(out) + ".policy.json")
578
+ if not destination.is_relative_to(project.absolute() / ".okstra"):
579
+ raise ValueError("review census and policy must remain in project artifacts")
580
+ safe_qa_path(project, destination.relative_to(project.absolute()).as_posix())
581
+ extra = tuple(Path(path).expanduser().absolute() for path in args.policy)
582
+ frozen = None
583
+ if args.run_manifest:
584
+ manifest = load_owned_object(Path(args.run_manifest), artifact="run manifest")
585
+ reference = VerificationInputReference.required_from_artifact_fields(manifest)
586
+ inputs = read_verification_inputs(safe_qa_path(project, reference.relative_path), reference.digest)
587
+ if "reviewPolicy" not in inputs:
588
+ raise ValueError("the selected run has no frozen review policy")
589
+ frozen = inputs["reviewPolicy"]
590
+ if destination.exists():
591
+ policy = read_review_policy(destination)
592
+ if any(str(path) not in policy["sources"] for path in extra):
593
+ raise ValueError("additional policy is absent from the immutable review policy")
594
+ if frozen is not None:
595
+ if "authorPolicyDigest" not in policy:
596
+ raise ValueError("immutable review policy has no author policy identity; use a new census output")
597
+ if policy["authorPolicyDigest"] != canonical_json_digest(frozen):
598
+ raise ValueError("the selected run differs from the immutable review policy")
599
+ return destination, policy, content_digest(destination.read_bytes())
600
+ policy = capture_code_review_policy(project, {} if frozen is not None else load_qa_config(project),
601
+ additional_sources=extra, policy=frozen)
602
+ path, digest = publish_review_policy(project, destination, policy)
603
+ return path, policy, digest
604
+
605
+
409
606
  def _scope(args: argparse.Namespace, project_root: Path) -> int:
410
607
  from .agent.invocation import AgentInvocationError
411
- from .code_review_scope import review_scope
608
+ from .code_review_scope import review_scope, shared_review_policy
412
609
 
413
- if not (args.base and args.head and args.census and args.policy):
414
- print("scope: pass --base, --head, --census and --policy", file=sys.stderr)
610
+ if not (args.base and args.head and args.census and (args.policy or args.review_policy)):
611
+ print("scope: pass --base, --head, --census and --review-policy or --policy", file=sys.stderr)
415
612
  return 2
416
613
  try:
417
614
  result = review_scope(
@@ -420,6 +617,8 @@ def _scope(args: argparse.Namespace, project_root: Path) -> int:
420
617
  previous_head=args.previous_head,
421
618
  previous_census=Path(args.previous_census) if args.previous_census else None,
422
619
  completions=[Path(path) for path in args.completion],
620
+ policy=shared_review_policy(Path(args.census), Path(args.review_policy))
621
+ if args.review_policy else None,
423
622
  )
424
623
  except (OSError, ValueError, AgentInvocationError) as exc:
425
624
  print(f"scope: {exc}", file=sys.stderr)
@@ -141,6 +141,10 @@ def append_consumer(plan_run_root: Path, *, impl_task_key: str, stage: int,
141
141
  status, force_reappend,
142
142
  fields.get("head_commit"),
143
143
  fields.get("source")):
144
+ if status == "done" and not fields.get("reconciled"):
145
+ from .design_review_evidence import validate_design_completion
146
+
147
+ validate_design_completion(plan_run_root, impl_task_key, stage, str(fields.get("head_commit") or ""))
144
148
  record: Dict[str, Any] = {
145
149
  "impl_task_key": impl_task_key,
146
150
  "stage": stage,
@@ -432,15 +436,14 @@ def backfill_done_from_carry(plan_run_root: Path) -> int:
432
436
  carry_path = str(cf.relative_to(task_root))
433
437
  except ValueError:
434
438
  carry_path = str(cf)
435
- append_consumer(
436
- plan_run_root,
437
- impl_task_key=impl_key,
438
- stage=stage,
439
- status="done",
440
- head_commit=head,
441
- carry_path=carry_path,
442
- source="carry-backfill",
443
- )
439
+ try:
440
+ append_consumer(
441
+ plan_run_root, impl_task_key=impl_key, stage=stage, status="done",
442
+ head_commit=head, carry_path=carry_path, source="carry-backfill",
443
+ )
444
+ except ValueError:
445
+ # expected-miss: a pending or invalid design review leaves the stage unsettled.
446
+ continue
444
447
  settled_stages.add(stage)
445
448
  recovered += 1
446
449
  return recovered
@@ -20,7 +20,7 @@ from typing import Any, Mapping, Sequence
20
20
 
21
21
  from .convergence_provenance import id_occurs_wordbounded
22
22
  from .json_boundary import JsonBoundaryError, load_owned_object
23
- from .phases.improvement_discovery.lenses import LENSES
23
+ from .phases.improvement_discovery.lenses import LENSES, validate_priority_lenses
24
24
  from .scope_provenance import brief_end_state_id_sequence
25
25
 
26
26
 
@@ -89,6 +89,7 @@ def build_census(
89
89
  aspects: Sequence[Aspect],
90
90
  requirement_ids: Sequence[str],
91
91
  changed_files: Sequence[str] = (),
92
+ selected_lenses: Sequence[str] | None = None,
92
93
  ) -> dict[str, Any]:
93
94
  """Every cell for this run, in the order a worker should walk them."""
94
95
  cells: list[dict[str, str]] = []
@@ -114,8 +115,14 @@ def build_census(
114
115
  for index, path in enumerate(sorted(set(filter(None, changed_files))), start=1):
115
116
  for aspect in by_scope["file"]:
116
117
  add(f"C-F-{index:03d}-{aspect.slug}", aspect, path)
118
+ lenses = LENSES
119
+ if selected_lenses is not None:
120
+ try:
121
+ lenses = validate_priority_lenses(selected_lenses)
122
+ except ValueError as exc:
123
+ raise CensusError(str(exc)) from exc
117
124
  for aspect in by_scope["lens"]:
118
- for lens in LENSES:
125
+ for lens in lenses:
119
126
  add(f"C-L-{lens}", aspect, lens)
120
127
  return {
121
128
  "schemaVersion": CENSUS_SCHEMA_VERSION,
@@ -130,6 +137,7 @@ def census_for_run(
130
137
  profile_text: str,
131
138
  brief_path: Path,
132
139
  changed_files: Sequence[str] = (),
140
+ selected_lenses: Sequence[str] | None = None,
133
141
  ) -> dict[str, Any] | None:
134
142
  """The run's census, or ``None`` when the phase profile declares none."""
135
143
  aspects = parse_census_aspects(profile_text)
@@ -140,6 +148,7 @@ def census_for_run(
140
148
  aspects=aspects,
141
149
  requirement_ids=brief_end_state_id_sequence(brief_path),
142
150
  changed_files=changed_files,
151
+ selected_lenses=selected_lenses,
143
152
  )
144
153
 
145
154
 
@@ -0,0 +1,207 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from collections.abc import Mapping
8
+ from typing import Any, TYPE_CHECKING, TypedDict
9
+
10
+ from .json_boundary import load_owned_object, write_owned_object_atomic
11
+ from .qa_procedures import canonical_json_digest
12
+ from .verification_input_types import FrozenReviewPolicy
13
+
14
+ if TYPE_CHECKING:
15
+ from .coverage_census import CellVerdicts
16
+ from .review_verdicts import ReviewCensus
17
+
18
+
19
+ class DesignReviewSnapshot(TypedDict):
20
+ base: str
21
+ head: str
22
+ policyDigest: str
23
+ census: str
24
+ manualInventory: dict[str, Any]
25
+ blockingSeverities: list[str]
26
+ blockingTiming: str
27
+
28
+
29
+ DESIGN_REVIEW_SCHEMA = {
30
+ "type": "object", "additionalProperties": False,
31
+ "required": list(DesignReviewSnapshot.__required_keys__),
32
+ "properties": {
33
+ "base": {"type": "string"}, "head": {"type": "string"},
34
+ "policyDigest": {"type": "string"}, "census": {"type": "string"},
35
+ "manualInventory": {"type": "object"},
36
+ "blockingSeverities": {"type": "array", "items": {"type": "string"}},
37
+ "blockingTiming": {"type": "string"},
38
+ },
39
+ }
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class DesignReviewResult:
44
+ coverage: CellVerdicts
45
+ findings: tuple[dict[str, str], ...]
46
+ blocking_findings: tuple[str, ...]
47
+
48
+ @property
49
+ def blocking(self) -> bool:
50
+ return bool(self.coverage.missing or self.coverage.unknown or self.blocking_findings)
51
+
52
+
53
+ def capture_design_review(
54
+ source: Path, base: str, head: str, policy: FrozenReviewPolicy, inventory_path: Path,
55
+ ) -> DesignReviewSnapshot:
56
+ from .code_review_census import build_review_census
57
+ from .code_review_target import changed_lines
58
+ from .review_verdicts import parse_review_census
59
+ from .review_policy import (
60
+ review_policy_catalog_path, review_policy_context, select_review_policy,
61
+ render_review_rule_catalog,
62
+ )
63
+
64
+ catalog_path = review_policy_catalog_path(policy)
65
+ catalog = json.loads(policy["sources"][str(catalog_path)]["body"])
66
+ changed = changed_lines(source, base, head)
67
+ paths, manifests = review_policy_context(source, head, tuple(changed), base=base)
68
+ selected = select_review_policy(policy, tuple(changed), project_paths=paths,
69
+ manifest_contents=manifests)
70
+ rules = render_review_rule_catalog(selected)
71
+ initial = build_review_census(source, base, head, catalog_path, changed, frozen_rules=rules)
72
+ inventory: dict[str, Any] = {}
73
+ if initial.unresolved:
74
+ inventory = _read_function_inventory(inventory_path, base, head, initial.unresolved)
75
+ result = build_review_census(source, base, head, catalog_path, changed,
76
+ frozen_rules=rules, inventory=inventory)
77
+ if result.unresolved:
78
+ raise ValueError("design review has unresolved function boundaries")
79
+ parse_review_census(result.text, allow_empty=True)
80
+ return {"base": base, "head": head, "policyDigest": canonical_json_digest(policy),
81
+ "census": result.text, "manualInventory": inventory,
82
+ "blockingSeverities": catalog["blockingSeverities"],
83
+ "blockingTiming": catalog["blockingTiming"]}
84
+
85
+
86
+ def _read_function_inventory(
87
+ path: Path, base: str, head: str, unresolved: tuple[str, ...],
88
+ ) -> dict[str, Any]:
89
+ if not path.exists():
90
+ write_owned_object_atomic(path, {"base": base, "head": head,
91
+ "files": {name: None for name in unresolved}},
92
+ artifact="function inventory")
93
+ raise ValueError(f"complete the function inventory before verifier dispatch: {path}")
94
+ payload = load_owned_object(path, artifact="function inventory")
95
+ if (set(payload) != {"base", "head", "files"} or payload["base"] != base
96
+ or payload["head"] != head or not isinstance(payload["files"], dict)
97
+ or set(payload["files"]) != set(unresolved)):
98
+ raise ValueError(f"function inventory must match this base, head and unresolved files: {path}")
99
+ return payload["files"]
100
+
101
+
102
+ def review_binding_lines(snapshot: DesignReviewSnapshot) -> tuple[str, ...]:
103
+ return (f"Review base: {snapshot['base']}", f"Review head: {snapshot['head']}",
104
+ f"Review rules: {snapshot['policyDigest']}",
105
+ f"Review census: {canonical_json_digest(snapshot)}")
106
+
107
+
108
+ def render_design_review(snapshot: DesignReviewSnapshot) -> str:
109
+ return ("\n## Frozen Design Review\n\n" + "\n".join(review_binding_lines(snapshot))
110
+ + "\n\n" + snapshot["census"]
111
+ + "\nIndependently inspect every cell and rule. Return the four binding lines verbatim, "
112
+ "one Coverage Verdicts row per cell (Cell | Checked | N/A | Findings | Evidence), "
113
+ "using only the rules assigned to that cell's Group in the Rules table. Account for "
114
+ "each assigned rule exactly once across Checked (comma-separated IDs), N/A "
115
+ "(RULE=reason) and Findings (RULE=finding-ID). Separate assignments with semicolons "
116
+ "and multiple finding IDs for one rule with commas. Use `-` for an empty field; "
117
+ "do not add rules from other groups even as N/A. Evidence starts with that cell's "
118
+ "literal target path:line, optionally backtick-quoted, followed by an optional "
119
+ "observation with a space or ` — ` separator. Do not use line ranges or replace "
120
+ "the target anchor with another file. Return the table under `## Coverage Verdicts` "
121
+ "and one `## Design Findings` section with a JSON array, including `[]` when empty. "
122
+ "Each finding has string fields id, cell, rule, kind (execution-error/design-violation), "
123
+ "severity (must-fix/should-fix/nit), timing (now/park), source (path:line), consequence, "
124
+ "fix, disposition (open/fixed/accepted-risk/rejected), basis. Give a reachable failing "
125
+ "input for an execution error or a rule violation and design impact for a design finding. "
126
+ "Every coverage finding ID must match its cell/rule in that array. Checked G2/G3/G5 "
127
+ "include `RULE=path:line observation` assignments after ` :: ` in Evidence, "
128
+ "separated with semicolons. Include observations only for checked rules; "
129
+ "N/A and Findings already explain their rules. Follow the coding-preflight "
130
+ "grading rubric; current open blocking findings force FAIL. Missing cells or rules "
131
+ "are incomplete, never clean. Other workers' results and executor self-check do not "
132
+ "satisfy your coverage. Also return exactly one `Verifier verdict: PASS|CONCERNS|FAIL` "
133
+ "line with the overall result, including command failures. Manual inventory completeness "
134
+ "remains lead judgment.\n")
135
+
136
+
137
+ def parse_design_review(
138
+ source: Path, snapshot: DesignReviewSnapshot, body: str,
139
+ ) -> DesignReviewResult:
140
+ from .review_verdicts import parse_review_census, parse_review_verdicts
141
+
142
+ for line in review_binding_lines(snapshot):
143
+ if body.splitlines().count(line) != 1:
144
+ raise ValueError("design review baseline missing or different: " + line.partition(":")[0])
145
+ census = parse_review_census(snapshot["census"], allow_empty=True)
146
+ coverage = parse_review_verdicts(source, census, [body], snapshot["head"], base=snapshot["base"])
147
+ matches = re.findall(r"^## Design Findings\s*\n```json\s*\n(.*?)\n```", body, re.M | re.S)
148
+ if len(matches) != 1:
149
+ raise ValueError("design review needs one Design Findings JSON array, including []")
150
+ findings = json.loads(matches[0])
151
+ if not isinstance(findings, list):
152
+ raise ValueError("design findings must be an array")
153
+ indexed: dict[str, dict[str, str]] = {}
154
+ for finding in findings:
155
+ _validate_finding(source, snapshot, census, finding)
156
+ if finding["id"] in indexed:
157
+ raise ValueError("duplicate design finding ID")
158
+ indexed[finding["id"]] = finding
159
+ _match_finding_rows(body, indexed)
160
+ blocking = tuple(row["id"] for row in indexed.values()
161
+ if row["severity"] in snapshot["blockingSeverities"]
162
+ and row["timing"] == snapshot["blockingTiming"]
163
+ and row["disposition"] == "open")
164
+ return DesignReviewResult(coverage, tuple(indexed.values()), blocking)
165
+
166
+
167
+ def _validate_finding(source: Path, snapshot: DesignReviewSnapshot, census: ReviewCensus,
168
+ finding: object) -> None:
169
+ from .review_verdicts import _head_tree, _source_evidence
170
+
171
+ fields = {"id", "cell", "rule", "kind", "severity", "timing", "source",
172
+ "consequence", "fix", "disposition", "basis"}
173
+ if (not isinstance(finding, dict) or set(finding) != fields
174
+ or any(not isinstance(value, str) or not value.strip() for value in finding.values())):
175
+ raise ValueError("design finding requires non-blank typed evidence and disposition fields")
176
+ cell = census.cells.get(finding["cell"])
177
+ if cell is None or finding["rule"] not in census.rules[cell.group]:
178
+ raise ValueError("design finding names an unknown cell or rule")
179
+ if (finding["kind"] not in ("execution-error", "design-violation")
180
+ or finding["severity"] not in ("must-fix", "should-fix", "nit")
181
+ or finding["timing"] not in ("now", "park")
182
+ or finding["disposition"] not in ("open", "fixed", "accepted-risk", "rejected")):
183
+ raise ValueError("design finding has an invalid grade or disposition")
184
+ tree = _head_tree(source, snapshot["head"])
185
+ tree.base = _head_tree(source, snapshot["base"])
186
+ _source_evidence(tree, cell, finding["source"])
187
+
188
+
189
+ def _match_finding_rows(body: str, findings: Mapping[str, Mapping[str, str]]) -> None:
190
+ from .review_verdicts import _keyed_values, _table_fields
191
+
192
+ section = body.partition("## Coverage Verdicts")[2].split("\n## ", 1)[0]
193
+ mentioned: set[str] = set()
194
+ for line in section.splitlines():
195
+ if not line.strip().startswith("|"):
196
+ continue
197
+ fields = _table_fields(line)
198
+ if not fields[0].startswith("C-CR-") or len(fields) != 5:
199
+ continue
200
+ for rule, ids in _keyed_values(fields[3]).items():
201
+ for identity in (value.strip() for value in ids.split(",")):
202
+ finding = findings.get(identity)
203
+ if finding is None or finding["cell"] != fields[0] or finding["rule"] != rule:
204
+ raise ValueError("coverage finding differs from Design Findings")
205
+ mentioned.add(identity)
206
+ if mentioned != findings.keys():
207
+ raise ValueError("Design Findings contains findings absent from coverage")