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
@@ -0,0 +1,212 @@
1
+ """Bind standalone reviews to selected frozen rules and source integrity."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, replace
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Mapping
7
+
8
+ from .json_boundary import load_owned_object, load_owned_object_snapshot
9
+ from .qa_procedures import content_digest
10
+ from .review_policy import (
11
+ code_review_guidance_paths,
12
+ review_policy_context,
13
+ render_review_rule_catalog,
14
+ render_selected_review_policy,
15
+ review_policy_errors,
16
+ select_review_policy,
17
+ )
18
+ from .review_verdicts import _head_tree, parse_review_census
19
+
20
+ if TYPE_CHECKING:
21
+ from .agent.invocation import AgentInvocationRequest
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class CodeReviewInputs:
26
+ policy_path: Path
27
+ census_path: Path
28
+ base: str
29
+ head: str
30
+ resources: tuple[str, ...] = ()
31
+
32
+
33
+ def _validate_census_binding(text: str, inputs: CodeReviewInputs, digest: str) -> None:
34
+ digest_lines = [line for line in text.splitlines() if line.startswith("Review policy digest: ")]
35
+ expected = "Review policy digest: " + digest
36
+ if digest_lines != [expected]:
37
+ raise ValueError("assigned census and shared review policy digest differ")
38
+ resource_lines = [line.removeprefix("Review resources: ").strip()
39
+ for line in text.splitlines() if line.startswith("Review resources: ")]
40
+ if len(resource_lines) != 1:
41
+ raise ValueError("assigned census requires one explicit resource selection")
42
+ declared = [] if resource_lines == ["-"] else [part.strip() for part in resource_lines[0].split(";")]
43
+ if len(set(declared)) != len(declared) or sorted(declared) != sorted(inputs.resources):
44
+ raise ValueError("review resource selection differs from the assigned census")
45
+
46
+
47
+ def _review_payload(request: AgentInvocationRequest) -> dict:
48
+ inputs = request.review_inputs
49
+ if inputs is None:
50
+ raise ValueError("standalone code review requires frozen policy, census, base and head")
51
+ root = request.project_root.resolve()
52
+ for path in (inputs.policy_path, inputs.census_path):
53
+ path.resolve(strict=True).relative_to(root)
54
+ tree = _head_tree(root, inputs.head)
55
+ base = _head_tree(root, inputs.base).commit
56
+ if tree._git("merge-base", "--is-ancestor", base, tree.commit).returncode:
57
+ raise ValueError("review base is not an ancestor of head")
58
+ census_text = inputs.census_path.read_text(encoding="utf-8")
59
+ stored_policy = load_owned_object_snapshot(
60
+ inputs.policy_path, artifact="shared frozen review policy",
61
+ schema={"type": "object"}, validate_cross_fields=review_policy_errors,
62
+ )
63
+ _validate_census_binding(census_text, inputs, content_digest(stored_policy.raw_bytes))
64
+ census = parse_review_census(census_text)
65
+ targets = tuple(dict.fromkeys(cell.target.partition(":")[0] for cell in census.cells.values()))
66
+ paths, manifests = review_policy_context(root, tree.commit, targets, base=base)
67
+ for target in targets:
68
+ exists_at_head = tree._git("cat-file", "-e", f"{tree.commit}:{target}").returncode == 0
69
+ (tree if exists_at_head else _head_tree(root, base)).line_count(target)
70
+ policy = stored_policy.value
71
+ guidance = code_review_guidance_paths(policy)
72
+ if len(guidance) != 3:
73
+ raise ValueError("frozen code-review protocol guidance is incomplete")
74
+ selected = select_review_policy(
75
+ policy, targets, project_paths=paths, manifest_contents=manifests,
76
+ guidance_paths=guidance,
77
+ resources=inputs.resources,
78
+ )
79
+ canonical = parse_review_census(
80
+ render_review_rule_catalog(selected) + "\n## Cells\n", allow_empty=True,
81
+ )
82
+ for group, rules in census.rules.items():
83
+ for rule in rules:
84
+ references = [part.strip() for part in census.references[rule].split(";")]
85
+ if (rule not in canonical.rules.get(group, ())
86
+ or canonical.references[rule] not in references):
87
+ raise ValueError(f"assigned census weakens the frozen rule catalog: {rule}")
88
+ return {"schemaVersion": 1, "base": base, "head": tree.commit,
89
+ "census": census_text, "policy": selected}
90
+
91
+
92
+ def bind_review_invocation(request: AgentInvocationRequest) -> AgentInvocationRequest:
93
+ from .agent.invocation import (
94
+ AgentInstructionSource, AgentInvocationError, _canonical_json, _publish_or_reuse_exact,
95
+ )
96
+ if request.run_manifest_path is not None or request.audience != "code-reviewer":
97
+ if request.review_inputs is not None:
98
+ raise AgentInvocationError("frozen code-review inputs require a standalone code reviewer")
99
+ return request
100
+ if request.purpose != "code-review":
101
+ raise AgentInvocationError("code reviewer requires purpose code-review")
102
+ from .code_review_integrity import capture_review_source
103
+
104
+ try:
105
+ payload = _review_payload(request)
106
+ root = request.project_root.resolve()
107
+ policy_path = request.prompt_path.parent / f"{request.invocation_id}.review-policy.json"
108
+ metadata = {"invocationId": request.invocation_id, "audience": request.audience,
109
+ "contractSource": {"dutyRootPath": request.duty_root.resolve().relative_to(root).as_posix()},
110
+ "instruction": {"sourcePaths": [{"kind": row.kind, "path": row.path}
111
+ for row in request.instruction.source_paths]}}
112
+ baseline_path, baseline_digest = capture_review_source(
113
+ root, request.prompt_path, request.metadata_path, metadata,
114
+ )
115
+ payload.update(sourceSnapshotPath=baseline_path, sourceSnapshotDigest=baseline_digest)
116
+ raw = _canonical_json(payload)
117
+ _publish_or_reuse_exact(policy_path, raw)
118
+ relative = policy_path.resolve().relative_to(root).as_posix()
119
+ supplement = (
120
+ "\n\n## Frozen code-review inputs\n\n"
121
+ f"Frozen code-review policy: {relative}\n"
122
+ f"Frozen code-review policy digest: {content_digest(raw)}\n"
123
+ f"Frozen source base: {payload['base']}\nFrozen source head: {payload['head']}\n"
124
+ "Apply the captured rule bodies below. Source paths identify provenance; "
125
+ "do not replace these bodies with live installed files.\n"
126
+ + render_selected_review_policy(payload["policy"])
127
+ + "\n## Assigned review census\n\n" + payload["census"]
128
+ )
129
+ instruction = replace(
130
+ request.instruction, body=request.instruction.body.rstrip() + supplement,
131
+ source_paths=(*request.instruction.source_paths,
132
+ AgentInstructionSource("project", relative),
133
+ AgentInstructionSource("project", baseline_path)),
134
+ )
135
+ return replace(request, instruction=instruction)
136
+ except (OSError, ValueError, KeyError) as exc:
137
+ raise AgentInvocationError(f"cannot bind frozen code-review inputs: {exc}") from exc
138
+
139
+
140
+ def review_policy_path(project: Path, metadata: Mapping) -> Path | None:
141
+ identity = metadata["invocationId"]
142
+ relative = f".okstra/agent-invocations/code-review/{identity}.review-policy.json"
143
+ sources = metadata["instruction"]["sourcePaths"]
144
+ if not any(row["kind"] == "project" and row["path"] == relative for row in sources):
145
+ return None
146
+ if metadata["audience"] != "code-reviewer" or metadata["contractSource"]["mode"] != "standalone":
147
+ raise ValueError("frozen code-review policy is bound to the wrong invocation")
148
+ return project / relative
149
+
150
+
151
+ def read_invocation_review_policy(project: Path, metadata: Mapping) -> dict | None:
152
+ path = review_policy_path(project, metadata)
153
+ if path is None:
154
+ return None
155
+ payload = load_owned_object(path, artifact="invocation frozen review policy")
156
+ fields = {"schemaVersion", "base", "head", "census", "policy",
157
+ "sourceSnapshotPath", "sourceSnapshotDigest"}
158
+ if (set(payload) != fields or payload["schemaVersion"] != 1
159
+ or review_policy_errors(payload["policy"])):
160
+ raise ValueError("invocation frozen review policy is invalid")
161
+ expected = path.with_name(f"{metadata['invocationId']}.review-source.json").relative_to(project).as_posix()
162
+ if payload["sourceSnapshotPath"] != expected:
163
+ raise ValueError("review source snapshot path is not canonical")
164
+ raw = (project / expected).read_bytes()
165
+ if content_digest(raw) != payload["sourceSnapshotDigest"]:
166
+ raise ValueError("review source snapshot digest changed")
167
+ return payload
168
+
169
+
170
+ def review_policy_errors_for_prompt(project: Path, metadata: Mapping, prompt: bytes) -> list[str]:
171
+ try:
172
+ path = review_policy_path(project, metadata)
173
+ if path is None:
174
+ return []
175
+ read_invocation_review_policy(project, metadata)
176
+ line = f"Frozen code-review policy digest: {content_digest(path.read_bytes())}"
177
+ if prompt.decode("utf-8").splitlines().count(line) != 1:
178
+ return ["frozen code-review policy differs from the prompt"]
179
+ except (OSError, ValueError, KeyError) as exc:
180
+ return [f"frozen code-review inputs are invalid: {exc}"]
181
+ return []
182
+
183
+
184
+ def complete_review_audit(project: Path, metadata_path: Path, metadata: Mapping) -> str | None:
185
+ from .code_review_integrity import finalize_review_integrity
186
+
187
+ payload = read_invocation_review_policy(project, metadata)
188
+ if payload is None:
189
+ return None
190
+ return finalize_review_integrity(
191
+ project, metadata_path, metadata,
192
+ payload["sourceSnapshotPath"], payload["sourceSnapshotDigest"],
193
+ )
194
+
195
+
196
+ def verify_review_completion(
197
+ project: Path, metadata_path: Path, metadata: Mapping, completion: Mapping,
198
+ ) -> None:
199
+ from .code_review_integrity import verify_review_integrity
200
+
201
+ payload = read_invocation_review_policy(project, metadata)
202
+ if payload is None:
203
+ if completion["schemaVersion"] != 1:
204
+ raise ValueError("unexpected review integrity completion")
205
+ return
206
+ if completion["schemaVersion"] != 2:
207
+ raise ValueError("frozen code review requires integrity-bound completion")
208
+ verify_review_integrity(
209
+ project, metadata_path, metadata,
210
+ payload["sourceSnapshotPath"], payload["sourceSnapshotDigest"],
211
+ completion["reviewAuditDigest"],
212
+ )
@@ -0,0 +1,381 @@
1
+ """Prepare every specialist invocation of a standalone code review in one call."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ from .code_review_census import ASSIGNMENT_AXES, subset_review_census, write_review_assignments
10
+ from .code_review_scope import review_scope, shared_review_policy
11
+ from .operation_invocation import require_distinct_providers
12
+
13
+ PURPOSE = "code-review"
14
+ BATCH_SCHEMA_VERSION = 1
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ReviewSlot:
19
+ ordinal: int
20
+ provider: str
21
+ model_ref: str
22
+ model: str
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ReviewSlots:
27
+ duty_id: str
28
+ role_id: str
29
+ slots: tuple[ReviewSlot, ...]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class AttemptRequest:
34
+ """One more attempt for a team and axis: full assignment when `cells` is empty."""
35
+
36
+ team: int
37
+ axis: str
38
+ kind: str
39
+ cells: tuple[str, ...] = ()
40
+ reasons: Mapping[str, str] | None = None
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class _Batch:
45
+ project: Path
46
+ root: Path
47
+ record: dict
48
+
49
+ def path(self, relative: str) -> Path:
50
+ return self.project / relative
51
+
52
+
53
+ def read_review_slots(path: Path) -> ReviewSlots:
54
+ """Read `okstra agent-prompt resolve-operation --operation code-review --json` output."""
55
+ payload = json.loads(path.read_text(encoding="utf-8"))
56
+ if not isinstance(payload, dict) or payload.get("operation") != PURPOSE:
57
+ raise ValueError("slots file is not a code-review resolve-operation result")
58
+ rows = payload.get("slots")
59
+ if not isinstance(rows, list) or not rows:
60
+ raise ValueError("slots file has no slots")
61
+ slots = []
62
+ for row in rows:
63
+ if not isinstance(row, dict) or not all(
64
+ isinstance(row.get(key), str) and row[key] for key in ("provider", "modelRef", "model")
65
+ ) or type(row.get("ordinal")) is not int:
66
+ raise ValueError("slots file has a malformed slot")
67
+ slots.append(ReviewSlot(row["ordinal"], row["provider"], row["modelRef"], row["model"]))
68
+ if len({slot.ordinal for slot in slots}) != len(slots):
69
+ raise ValueError("slots file repeats a team ordinal")
70
+ require_distinct_providers([slot.provider for slot in slots])
71
+ duty, role = payload.get("dutyId"), payload.get("roleId")
72
+ if not isinstance(duty, str) or not isinstance(role, str) or not duty or not role:
73
+ raise ValueError("slots file has no duty or role")
74
+ return ReviewSlots(duty, role, tuple(slots))
75
+
76
+
77
+ def invocation_id(review_id: str, ordinal: int, axis: str, attempt: int) -> str:
78
+ return f"{review_id}-t{ordinal}-{axis}-a{attempt}"
79
+
80
+
81
+ def prepare_review_batch(
82
+ *,
83
+ project_root: Path,
84
+ review_id: str,
85
+ census: Path,
86
+ policy: Path,
87
+ base: str,
88
+ head: str,
89
+ slots_path: Path,
90
+ brief: Path,
91
+ host_runtime: str,
92
+ resources: Sequence[str] = (),
93
+ previous_batch: Path | None = None,
94
+ ) -> Path:
95
+ """Write assigned censuses, prompts and the batch record; return the record path."""
96
+ from .agent.prompt_cli.inputs import _is_slug
97
+
98
+ project = project_root.resolve()
99
+ root = project / ".okstra" / "agent-invocations" / PURPOSE
100
+ if not _is_slug(review_id):
101
+ raise ValueError("review id must be a lowercase slug")
102
+ slots = read_review_slots(slots_path)
103
+ census = census.absolute()
104
+ if census.resolve(strict=True) != (root / f"{review_id}.census.md").resolve():
105
+ raise ValueError(f"census must be {root / f'{review_id}.census.md'}")
106
+ batch_path = root / f"{review_id}.batch.json"
107
+ shared_review_policy(census, policy)
108
+ assignments = write_review_assignments(project, census)
109
+ record = {
110
+ "schemaVersion": BATCH_SCHEMA_VERSION, "reviewId": review_id,
111
+ "projectRoot": str(project), "base": base, "head": head,
112
+ "census": _relative(census, project), "policy": _relative(policy.absolute(), project),
113
+ "resources": list(resources), "hostRuntime": host_runtime,
114
+ "dutyId": slots.duty_id, "roleId": slots.role_id,
115
+ "brief": brief.read_text(encoding="utf-8").rstrip("\n"), "items": [],
116
+ }
117
+ batch = _Batch(project, root, record)
118
+ prior = _prior_rounds(project, record, previous_batch) if previous_batch else {}
119
+ context = _assignment_context(record, [slot.provider for slot in slots.slots])
120
+ for slot in slots.slots:
121
+ for axis in ASSIGNMENT_AXES:
122
+ if axis in assignments:
123
+ record["items"].append(_prepare_item(
124
+ batch, context, slot.ordinal, slot.provider, slot.model_ref, axis, 1, "initial",
125
+ assignments[axis], "", prior.get((slot.ordinal, axis, slot.provider, slot.model_ref)),
126
+ ))
127
+ text = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
128
+ if batch_path.exists():
129
+ existing = json.loads(batch_path.read_text(encoding="utf-8"))
130
+ existing["items"] = [item for item in existing["items"] if item["attempt"] == 1]
131
+ if existing != record:
132
+ raise ValueError(f"existing file differs; choose a new review id: {batch_path}")
133
+ return batch_path
134
+ batch_path.write_text(text, encoding="utf-8")
135
+ return batch_path
136
+
137
+
138
+ def gap_fill_requests(
139
+ batch_record: Mapping, state: Mapping, rejected: Mapping[int, Sequence[str]],
140
+ ) -> tuple[list[AttemptRequest], list[str]]:
141
+ """Requests for every team and axis whose latest attempt left cells open.
142
+
143
+ Returns the requests and the `team/axis` pairs stopped because their last
144
+ gap-fill did not reduce the open cells.
145
+ """
146
+ census_cells = _cells_by_item(batch_record)
147
+ requests: list[AttemptRequest] = []
148
+ stopped: list[str] = []
149
+ for (team, axis), item in sorted(latest_items(batch_record).items()):
150
+ row = state["items"].get(item["invocationId"], {})
151
+ own = set(census_cells[item["invocationId"]])
152
+ rejects = [cell for cell in rejected.get(team, ()) if cell in _axis_cells(batch_record, team, axis)]
153
+ if row.get("state") in ("failed", "stalled"):
154
+ requests.append(AttemptRequest(team, axis, "gap-fill", tuple(sorted(own))))
155
+ continue
156
+ if row.get("state") != "completed":
157
+ continue
158
+ missing = dict(row["audit"]["missing"])
159
+ missing.update((cell, "rejected by the lead") for cell in rejects)
160
+ if not missing:
161
+ continue
162
+ if item["attempt"] > 1 and item.get("kind") == "gap-fill" and len(row["audit"]["missing"]) >= len(own):
163
+ stopped.append(f"{team}/{axis}")
164
+ continue
165
+ requests.append(AttemptRequest(team, axis, "gap-fill", tuple(sorted(missing)), missing))
166
+ return requests, stopped
167
+
168
+
169
+ def add_review_attempts(project_root: Path, batch_path: Path, state: Mapping,
170
+ requests: Sequence[AttemptRequest]) -> list[dict]:
171
+ """Prepare one new attempt per request and append it to the batch record.
172
+
173
+ The caller holds the review's state lock; the batch record only grows.
174
+ """
175
+ batch = _load(project_root, batch_path)
176
+ record = batch.record
177
+ latest = latest_items(record)
178
+ context = _assignment_context(record, sorted({item["provider"] for item in record["items"]}))
179
+ added = []
180
+ for request in requests:
181
+ previous = latest[(request.team, request.axis)]
182
+ attempt = max(item["attempt"] for item in record["items"]
183
+ if (item["team"], item["axis"]) == (request.team, request.axis)) + 1
184
+ full = batch.path(_first_attempt(record, request.team, request.axis)["census"])
185
+ census = full
186
+ if request.cells and set(request.cells) != set(_axis_cells(record, request.team, request.axis)):
187
+ census = batch.root / f"{record['reviewId']}.{request.axis}.t{request.team}.a{attempt}.census.md"
188
+ _write_exact(census, subset_review_census(full.read_text(encoding="utf-8"), request.cells))
189
+ item = _prepare_item(
190
+ batch, context, request.team, previous["provider"], previous["modelRef"], request.axis,
191
+ attempt, request.kind, census,
192
+ _continuation(batch, previous, state, request), None, previous["wrapper"],
193
+ )
194
+ record["items"].append(item)
195
+ added.append(item)
196
+ if added:
197
+ temporary = batch_path.with_name(batch_path.name + ".partial")
198
+ temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
199
+ temporary.replace(batch_path)
200
+ return added
201
+
202
+
203
+ def latest_items(record: Mapping) -> dict[tuple[int, str], dict]:
204
+ latest: dict[tuple[int, str], dict] = {}
205
+ for item in record["items"]:
206
+ key = (item["team"], item["axis"])
207
+ if key not in latest or item["attempt"] > latest[key]["attempt"]:
208
+ latest[key] = item
209
+ return latest
210
+
211
+
212
+ def render_batch_summary(batch_path: Path) -> str:
213
+ record = json.loads(batch_path.read_text(encoding="utf-8"))
214
+ rows = [f"Batch: {batch_path}\n", f"Items: {len(record['items'])}\n"]
215
+ for item in record["items"]:
216
+ rows.append(
217
+ f"Item: {item['invocationId']} | team {item['team']} | {item['modelRef']} | "
218
+ f"{item['axis']} | {item['prompt']}\n"
219
+ )
220
+ return "".join(rows)
221
+
222
+
223
+ def _prepare_item(
224
+ batch: _Batch, context, team: int, provider: str, model_ref: str, axis: str, attempt: int,
225
+ kind: str, census: Path, continuation: str, previous: Mapping | None,
226
+ wrapper: str | None = None,
227
+ ) -> dict:
228
+ from .agent.invocation import AgentInvocationError, verify_agent_invocation
229
+ from .agent.standalone import StandaloneInvocationRequest, prepare_standalone_invocation
230
+ from .code_review_invocation import CodeReviewInputs
231
+ from .registry.provider_registry import default_provider_registry
232
+
233
+ record, project, root = batch.record, batch.project, batch.root
234
+ policy = batch.path(record["policy"])
235
+ identity = invocation_id(record["reviewId"], team, axis, attempt)
236
+ prior = {}
237
+ if previous:
238
+ prior = {"previous_head": previous["head"], "previous_census": batch.path(previous["census"]),
239
+ "completions": [batch.path(path) for path in previous["completions"]]}
240
+ scope = review_scope(project, census, record["base"], record["head"], [],
241
+ policy=shared_review_policy(census, policy), **prior).render()
242
+ instruction = root / f"{identity}.instructions.md"
243
+ _write_exact(instruction, (
244
+ f"{record['brief']}\n\n## Assignment\n\n"
245
+ f"- Review ID: {record['reviewId']}\n"
246
+ f"- Model team: {team} ({model_ref})\n"
247
+ f"- Specialist axis: {axis}\n"
248
+ f"- Attempt: {attempt} ({kind})\n"
249
+ f"- Full census (context only): {record['census']}\n"
250
+ f"- Assigned census: {_relative(census, project)}\n\n"
251
+ f"{continuation}"
252
+ f"## Inspection scope\n\n```text\n{scope}```\n"
253
+ ))
254
+ try:
255
+ prepared = prepare_standalone_invocation(StandaloneInvocationRequest(
256
+ project_root=project, invocation_id=identity, audience=record["dutyId"],
257
+ purpose=PURPOSE, context=context, provider=provider,
258
+ model_role=record["roleId"], model=model_ref.split("/", 1)[1],
259
+ instruction_path=instruction, prompt_path=root / f"{identity}.prompt.md",
260
+ requested_runner="cli-wrapper",
261
+ review_inputs=CodeReviewInputs(policy, census, record["base"], record["head"],
262
+ tuple(record["resources"])),
263
+ ))
264
+ errors = verify_agent_invocation(
265
+ prepared.metadata_path, project_root=project, expected_run_manifest_path=None,
266
+ )
267
+ if errors:
268
+ raise ValueError("; ".join(errors))
269
+ except (AgentInvocationError, OSError, RuntimeError, ValueError) as exc:
270
+ done = ", ".join(str(item["invocationId"]) for item in record["items"]) or "none"
271
+ raise ValueError(f"{identity}: {exc}; already prepared and reused by an "
272
+ f"identical rerun: {done}") from exc
273
+ assignment = prepared.assignment
274
+ return {
275
+ "team": team, "axis": axis, "attempt": attempt, "kind": kind, "invocationId": identity,
276
+ "provider": provider, "modelRef": model_ref,
277
+ "modelExecutionValue": assignment.model_execution_value,
278
+ "runner": assignment.runner, "role": record["roleId"],
279
+ "wrapper": wrapper or default_provider_registry().resolve(provider).wrapper,
280
+ "census": _relative(census, project),
281
+ "instructions": _relative(instruction, project),
282
+ "prompt": _relative(prepared.prompt_path, project),
283
+ "metadata": _relative(prepared.metadata_path, project),
284
+ **({"previousBatch": previous["batch"]} if previous else {}),
285
+ }
286
+
287
+
288
+ def _continuation(batch: _Batch, previous: Mapping, state: Mapping, request: AttemptRequest) -> str:
289
+ from .agent.invocation import verify_standalone_completion
290
+
291
+ lines = [f"## Continuation\n\nThis attempt replaces attempt {previous['attempt']} "
292
+ f"({previous['invocationId']}) for the cells in the assigned census only.\n"]
293
+ for cell, reason in sorted((request.reasons or {}).items()):
294
+ lines.append(f"- {cell}: {reason}\n")
295
+ row = state["items"].get(previous["invocationId"], {})
296
+ if row.get("completion"):
297
+ body = verify_standalone_completion(
298
+ batch.path(row["completion"]), project_root=batch.project, expected_purpose=PURPOSE,
299
+ ).returned_body
300
+ lines.append(f"\nVerified result of attempt {previous['attempt']}:\n\n````text\n{body.rstrip()}\n````\n")
301
+ elif row.get("reason"):
302
+ lines.append(f"\nAttempt {previous['attempt']} ended without a usable result: {row['reason']}\n")
303
+ return "".join(lines) + "\n"
304
+
305
+
306
+ def _prior_rounds(project: Path, record: Mapping, previous_batch: Path) -> dict[tuple, dict]:
307
+ """Completions of a previous round that this round may offer as carry candidates."""
308
+ prior = _load(project, previous_batch)
309
+ old = prior.record
310
+ if old["base"] != record["base"] or old["policy"] != record["policy"]:
311
+ return {}
312
+ state_path = prior.root / f"{old['reviewId']}.state.json"
313
+ if not state_path.exists():
314
+ return {}
315
+ state = json.loads(state_path.read_text(encoding="utf-8"))
316
+ rounds: dict[tuple, dict] = {}
317
+ for (team, axis), first in ((key, _first_attempt(old, *key)) for key in latest_items(old)):
318
+ completions = [state["items"][item["invocationId"]]["completion"]
319
+ for item in sorted(old["items"], key=lambda item: -item["attempt"])
320
+ if (item["team"], item["axis"]) == (team, axis)
321
+ and state["items"].get(item["invocationId"], {}).get("state") == "completed"]
322
+ if completions:
323
+ rounds[(team, axis, first["provider"], first["modelRef"])] = {
324
+ "head": old["head"], "census": first["census"], "completions": completions,
325
+ "batch": _relative(previous_batch, project),
326
+ }
327
+ return rounds
328
+
329
+
330
+ def _assignment_context(record: Mapping, providers: Sequence[str]):
331
+ from .assignment_environment import load_assignment_context
332
+ from .dispatch_state import detect_terminal_backend
333
+
334
+ return load_assignment_context(
335
+ host_runtime=record["hostRuntime"], terminal_backend=detect_terminal_backend(),
336
+ execution_provider_ids=tuple(providers), include_native_provider=False,
337
+ )
338
+
339
+
340
+ def _load(project_root: Path, batch_path: Path) -> _Batch:
341
+ project = project_root.resolve()
342
+ root = project / ".okstra" / "agent-invocations" / PURPOSE
343
+ path = batch_path.resolve(strict=True)
344
+ if path.parent != root.resolve() or not path.name.endswith(".batch.json"):
345
+ raise ValueError("batch must be <review-id>.batch.json in the code-review artifact directory")
346
+ record = json.loads(path.read_text(encoding="utf-8"))
347
+ if record.get("schemaVersion") != BATCH_SCHEMA_VERSION or record.get("projectRoot") != str(project):
348
+ raise ValueError("batch belongs to another project root or schema")
349
+ return _Batch(project, root, record)
350
+
351
+
352
+ def _first_attempt(record: Mapping, team: int, axis: str) -> dict:
353
+ return next(item for item in record["items"]
354
+ if (item["team"], item["axis"], item["attempt"]) == (team, axis, 1))
355
+
356
+
357
+ def _axis_cells(record: Mapping, team: int, axis: str) -> set[str]:
358
+ from .review_verdicts import read_review_census
359
+
360
+ project = Path(record["projectRoot"])
361
+ return set(read_review_census(project / _first_attempt(record, team, axis)["census"]).cells)
362
+
363
+
364
+ def _cells_by_item(record: Mapping) -> dict[str, list[str]]:
365
+ from .review_verdicts import read_review_census
366
+
367
+ project = Path(record["projectRoot"])
368
+ return {item["invocationId"]: list(read_review_census(project / item["census"]).cells)
369
+ for item in record["items"]}
370
+
371
+
372
+ def _relative(path: Path, project: Path) -> str:
373
+ return path.resolve().relative_to(project).as_posix()
374
+
375
+
376
+ def _write_exact(path: Path, text: str) -> None:
377
+ if path.exists():
378
+ if path.read_text(encoding="utf-8") != text:
379
+ raise ValueError(f"existing file differs; choose a new review id: {path}")
380
+ return
381
+ path.write_text(text, encoding="utf-8")