okstra 0.232.0 → 0.234.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/README.md +19 -283
  2. package/dist/cli-registry.mjs +14 -1
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.d.mts +6 -1
  5. package/dist/commands/execute/render-bundle.mjs +139 -32
  6. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  7. package/dist/commands/lifecycle/config.mjs +6 -74
  8. package/dist/commands/lifecycle/config.mjs.map +1 -1
  9. package/dist/commands/trace/capacity.d.mts +12 -0
  10. package/dist/commands/trace/capacity.mjs +21 -0
  11. package/dist/commands/trace/capacity.mjs.map +1 -0
  12. package/dist/commands/trace/model.d.mts +89 -0
  13. package/dist/commands/trace/model.mjs +251 -0
  14. package/dist/commands/trace/model.mjs.map +1 -0
  15. package/dist/commands/trace/progression.d.mts +11 -0
  16. package/dist/commands/trace/progression.mjs +194 -0
  17. package/dist/commands/trace/progression.mjs.map +1 -0
  18. package/dist/commands/trace/review.d.mts +7 -0
  19. package/dist/commands/trace/review.mjs +51 -0
  20. package/dist/commands/trace/review.mjs.map +1 -0
  21. package/dist/commands/trace/task-link.d.mts +18 -0
  22. package/dist/commands/trace/task-link.mjs +72 -0
  23. package/dist/commands/trace/task-link.mjs.map +1 -0
  24. package/dist/commands/trace/trace.d.mts +1 -0
  25. package/dist/commands/trace/trace.mjs +293 -0
  26. package/dist/commands/trace/trace.mjs.map +1 -0
  27. package/dist/lib/bounded-file.d.mts +1 -0
  28. package/dist/lib/bounded-file.mjs +36 -0
  29. package/dist/lib/bounded-file.mjs.map +1 -0
  30. package/dist/lib/config-store.d.mts +34 -0
  31. package/dist/lib/config-store.mjs +70 -0
  32. package/dist/lib/config-store.mjs.map +1 -0
  33. package/dist/lib/file-lock.mjs +4 -5
  34. package/dist/lib/file-lock.mjs.map +1 -1
  35. package/dist/lib/input-limit.d.mts +4 -0
  36. package/dist/lib/input-limit.mjs +8 -0
  37. package/dist/lib/input-limit.mjs.map +1 -0
  38. package/dist/lib/memory-auto-register.mjs +2 -17
  39. package/dist/lib/memory-auto-register.mjs.map +1 -1
  40. package/dist/lib/report-language-tag.d.mts +1 -0
  41. package/dist/lib/report-language-tag.mjs +4 -0
  42. package/dist/lib/report-language-tag.mjs.map +1 -0
  43. package/dist/lib/report-language.d.mts +1 -0
  44. package/dist/lib/report-language.mjs +50 -0
  45. package/dist/lib/report-language.mjs.map +1 -0
  46. package/dist/lib/skill-catalog.mjs +3 -0
  47. package/dist/lib/skill-catalog.mjs.map +1 -1
  48. package/docs/architecture/storage-model.md +55 -5
  49. package/docs/architecture.md +10 -4
  50. package/docs/cli.md +320 -3
  51. package/docs/contributor-change-matrix.md +1 -2
  52. package/docs/project-structure-overview.md +34 -43
  53. package/package.json +1 -1
  54. package/runtime/BUILD.json +2 -2
  55. package/runtime/agents/operations/trace-interface-review.json +6 -0
  56. package/runtime/agents/operations/trace-scope-review.json +6 -0
  57. package/runtime/prompts/coding-preflight/authoring-checks.md +1 -1
  58. package/runtime/prompts/coding-preflight/clean-code.md +18 -20
  59. package/runtime/prompts/coding-preflight/overview.md +1 -1
  60. package/runtime/prompts/duties/code-reviewer.json +1 -1
  61. package/runtime/prompts/duties/interface-reviewer.json +32 -0
  62. package/runtime/prompts/host-orchestration/README.md +18 -9
  63. package/runtime/prompts/launch.template.md +3 -2
  64. package/runtime/prompts/lead/context-loader.md +2 -0
  65. package/runtime/prompts/lead/okstra-lead-contract.md +7 -7
  66. package/runtime/prompts/lead/report-writer.md +6 -6
  67. package/runtime/prompts/profiles/_coding-conventions-preflight.md +2 -2
  68. package/runtime/prompts/profiles/_common-contract.md +1 -1
  69. package/runtime/python/okstra_ctl/agent/invocation.py +1 -0
  70. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +66 -26
  71. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +23 -8
  72. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +28 -10
  73. package/runtime/python/okstra_ctl/agent/prompt_cli/results.py +8 -11
  74. package/runtime/python/okstra_ctl/agent/standalone.py +12 -0
  75. package/runtime/python/okstra_ctl/analysis_packet.py +22 -11
  76. package/runtime/python/okstra_ctl/business_flow/cli.py +60 -6
  77. package/runtime/python/okstra_ctl/business_flow/contracts.py +12 -1
  78. package/runtime/python/okstra_ctl/business_flow/engine.py +17 -5
  79. package/runtime/python/okstra_ctl/business_flow/history.py +60 -0
  80. package/runtime/python/okstra_ctl/business_flow/source.py +35 -2
  81. package/runtime/python/okstra_ctl/business_flow/store.py +51 -14
  82. package/runtime/python/okstra_ctl/business_flow/sweep.py +124 -0
  83. package/runtime/python/okstra_ctl/code_review_census.py +93 -2
  84. package/runtime/python/okstra_ctl/code_review_prepare.py +381 -0
  85. package/runtime/python/okstra_ctl/code_review_run.py +384 -0
  86. package/runtime/python/okstra_ctl/code_review_scope.py +13 -0
  87. package/runtime/python/okstra_ctl/code_review_supervisor.py +41 -0
  88. package/runtime/python/okstra_ctl/code_review_target.py +140 -15
  89. package/runtime/python/okstra_ctl/coverage_census.py +11 -2
  90. package/runtime/python/okstra_ctl/design_snapshot.py +16 -9
  91. package/runtime/python/okstra_ctl/direct_work.py +45 -3
  92. package/runtime/python/okstra_ctl/dispatch_core.py +31 -15
  93. package/runtime/python/okstra_ctl/dispatch_state.py +9 -2
  94. package/runtime/python/okstra_ctl/domain/role.py +1 -0
  95. package/runtime/python/okstra_ctl/doyouknow/cli.py +9 -9
  96. package/runtime/python/okstra_ctl/doyouknow/config.py +2 -2
  97. package/runtime/python/okstra_ctl/doyouknow/group_view.py +152 -0
  98. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +4 -3
  99. package/runtime/python/okstra_ctl/doyouknow/source_store.py +2 -2
  100. package/runtime/python/okstra_ctl/doyouknow/sources/business.py +116 -0
  101. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +48 -9
  102. package/runtime/python/okstra_ctl/doyouknow/sync.py +34 -9
  103. package/runtime/python/okstra_ctl/final_report_schema.py +37 -34
  104. package/runtime/python/okstra_ctl/fixed_text.py +10 -0
  105. package/runtime/python/okstra_ctl/incremental_carry.py +6 -7
  106. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +9 -2
  107. package/runtime/python/okstra_ctl/json_boundary.py +33 -6
  108. package/runtime/python/okstra_ctl/manager_cli.py +122 -1
  109. package/runtime/python/okstra_ctl/manager_journal.py +126 -0
  110. package/runtime/python/okstra_ctl/manager_launch.py +3 -3
  111. package/runtime/python/okstra_ctl/manager_log.py +221 -0
  112. package/runtime/python/okstra_ctl/manager_paths.py +8 -0
  113. package/runtime/python/okstra_ctl/manager_resume.py +59 -0
  114. package/runtime/python/okstra_ctl/manager_split.py +2 -2
  115. package/runtime/python/okstra_ctl/manager_store.py +116 -17
  116. package/runtime/python/okstra_ctl/manager_sync.py +42 -3
  117. package/runtime/python/okstra_ctl/manager_view.py +35 -2
  118. package/runtime/python/okstra_ctl/material.py +2 -0
  119. package/runtime/python/okstra_ctl/model_cli.py +64 -14
  120. package/runtime/python/okstra_ctl/model_defaults.py +22 -0
  121. package/runtime/python/okstra_ctl/model_io/renderers.py +3 -0
  122. package/runtime/python/okstra_ctl/operation_invocation.py +207 -28
  123. package/runtime/python/okstra_ctl/path_hints.py +14 -3
  124. package/runtime/python/okstra_ctl/paths.py +6 -1
  125. package/runtime/python/okstra_ctl/phases/catalog.py +24 -7
  126. package/runtime/python/okstra_ctl/phases/implementation/host-rules.md +3 -3
  127. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +8 -6
  128. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  129. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  130. package/runtime/python/okstra_ctl/phases/implementation_option_selection/votes.py +11 -11
  131. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +12 -9
  132. package/runtime/python/okstra_ctl/phases/implementation_planning/host-rules.md +3 -6
  133. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +12 -10
  134. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +5 -5
  135. package/runtime/python/okstra_ctl/phases/improvement_discovery/lenses.py +12 -0
  136. package/runtime/python/okstra_ctl/phases/improvement_discovery/profile.md +7 -6
  137. package/runtime/python/okstra_ctl/phases/improvement_discovery/resolved_census.py +159 -0
  138. package/runtime/python/okstra_ctl/phases/improvement_discovery/spec.md +5 -2
  139. package/runtime/python/okstra_ctl/phases/improvement_discovery/validation.py +21 -7
  140. package/runtime/python/okstra_ctl/phases/release_handoff/boundary.json +1 -1
  141. package/runtime/python/okstra_ctl/phases/release_handoff/profile.md +4 -1
  142. package/runtime/python/okstra_ctl/plan_verify_cli.py +6 -4
  143. package/runtime/python/okstra_ctl/project_group.py +175 -0
  144. package/runtime/python/okstra_ctl/project_group_cli.py +62 -0
  145. package/runtime/python/okstra_ctl/render.py +28 -2
  146. package/runtime/python/okstra_ctl/report_assembly.py +38 -11
  147. package/runtime/python/okstra_ctl/report_contract.py +26 -0
  148. package/runtime/python/okstra_ctl/report_corrections.py +36 -20
  149. package/runtime/python/okstra_ctl/report_inputs.py +1 -0
  150. package/runtime/python/okstra_ctl/report_language.py +4 -1
  151. package/runtime/python/okstra_ctl/report_narrative.py +179 -7
  152. package/runtime/python/okstra_ctl/report_projections.py +64 -18
  153. package/runtime/python/okstra_ctl/report_synthesis_packet.py +86 -36
  154. package/runtime/python/okstra_ctl/run.py +43 -35
  155. package/runtime/python/okstra_ctl/run_context.py +10 -1
  156. package/runtime/python/okstra_ctl/set_work_status.py +4 -15
  157. package/runtime/python/okstra_ctl/task_list_cli.py +34 -8
  158. package/runtime/python/okstra_ctl/task_query.py +239 -0
  159. package/runtime/python/okstra_ctl/trace_review.py +264 -0
  160. package/runtime/python/okstra_ctl/trace_tasks.py +197 -0
  161. package/runtime/python/okstra_ctl/user_authorization.py +14 -0
  162. package/runtime/python/okstra_ctl/wizard/confirmation.py +7 -3
  163. package/runtime/python/okstra_ctl/wizard/launch.py +52 -0
  164. package/runtime/python/okstra_ctl/wizard/launch_cli.py +39 -0
  165. package/runtime/python/okstra_ctl/wizard/outcome.py +17 -16
  166. package/runtime/python/okstra_ctl/wizard/registry.py +1 -1
  167. package/runtime/python/okstra_ctl/wizard/render.py +8 -0
  168. package/runtime/python/okstra_ctl/wizard/state.py +2 -1
  169. package/runtime/python/okstra_project/state.py +20 -0
  170. package/runtime/python/okstra_token_usage/blocks.py +74 -0
  171. package/runtime/python/okstra_token_usage/cli.py +23 -10
  172. package/runtime/python/okstra_token_usage/collect.py +25 -22
  173. package/runtime/python/okstra_token_usage/policy.py +193 -0
  174. package/runtime/schemas/business-flow-v1.schema.json +3 -0
  175. package/runtime/schemas/doyouknow-config-v1.schema.json +1 -1
  176. package/runtime/schemas/report-synthesis-packet-v1.0.schema.json +1 -1
  177. package/runtime/skills/_fragments/wizard-confirm-step.md +1 -1
  178. package/runtime/skills/_fragments/wizard-preflight.md +1 -1
  179. package/runtime/skills/_fragments/wizard-prompt-loop.md +3 -5
  180. package/runtime/skills/_fragments/wizard-relay-protocol.md +1 -1
  181. package/runtime/skills/_fragments/wizard-render-bundle.md +15 -29
  182. package/runtime/skills/okstra-brief-gen/SKILL.md +7 -7
  183. package/runtime/skills/okstra-brief-gen/references/tracker-recursion.md +1 -1
  184. package/runtime/skills/okstra-code-review/SKILL.md +58 -50
  185. package/runtime/skills/okstra-code-review/references/census-rules.md +6 -6
  186. package/runtime/skills/okstra-code-review/references/review-calibration.md +8 -12
  187. package/runtime/skills/okstra-discussion/SKILL.md +22 -38
  188. package/runtime/skills/okstra-explain-flow/SKILL.md +33 -4
  189. package/runtime/skills/okstra-manager/SKILL.md +24 -0
  190. package/runtime/skills/okstra-memory/SKILL.md +1 -1
  191. package/runtime/skills/okstra-pr-gen/SKILL.md +1 -1
  192. package/runtime/skills/okstra-run/SKILL.md +55 -183
  193. package/runtime/skills/okstra-schedule-gen/SKILL.md +9 -13
  194. package/runtime/skills/okstra-setup/SKILL.md +3 -2
  195. package/runtime/skills/okstra-setup/references/project-config.md +2 -4
  196. package/runtime/skills/okstra-tdd/SKILL.md +187 -0
  197. package/runtime/skills/okstra-user-response/SKILL.md +4 -2
  198. package/runtime/templates/doyouknow/group-view.css +103 -0
  199. package/runtime/templates/doyouknow/group-view.js +317 -0
  200. package/runtime/templates/doyouknow/group-view.template.html +72 -0
  201. package/runtime/templates/manager/view.template.html +4 -0
  202. package/runtime/templates/report-writer-prompt-preamble.md +15 -3
  203. package/runtime/templates/trace/trace.template.md +42 -0
  204. package/runtime/validators/checks/fixtures-02.py +25 -33
  205. package/runtime/validators/validate-run.py +93 -36
@@ -7,9 +7,9 @@ import re
7
7
  import subprocess
8
8
  from dataclasses import dataclass
9
9
  from pathlib import Path, PurePosixPath
10
- from collections.abc import Mapping
10
+ from collections.abc import Mapping, Sequence
11
11
 
12
- from .review_verdicts import read_review_census
12
+ from .review_verdicts import _table_fields, parse_review_census, read_review_census
13
13
 
14
14
  _GROUPS = ("structural", "semantic", "state-and-tests", "general")
15
15
  _FILE_GROUPS = {
@@ -256,3 +256,94 @@ def _render(
256
256
  "- New: " + (", ".join(new) or "-"),
257
257
  ]
258
258
  return "\n".join(rows) + "\n"
259
+
260
+
261
+ # Specialist order of the review workflow; each specialist owns one axis.
262
+ ASSIGNMENT_AXES = ("structural", "semantic", "general", "state-and-tests")
263
+
264
+
265
+ def split_review_census(text: str) -> dict[str, str]:
266
+ """Split a full census into one assigned census per axis that has cells.
267
+
268
+ Every line outside the Cells table is kept verbatim, so each assignment
269
+ carries the same policy digest, resource selection and rule catalog.
270
+ """
271
+ full = parse_review_census(text)
272
+ kept: dict[str, list[str]] = {axis: [] for axis in ASSIGNMENT_AXES}
273
+ section = ""
274
+ for line in text.splitlines(keepends=True):
275
+ if line.startswith("## "):
276
+ section = line.strip()
277
+ group = _cell_row_group(line) if section == "## Cells" else None
278
+ for axis, lines in kept.items():
279
+ if group is None or group == axis:
280
+ lines.append(line)
281
+ assigned: dict[str, str] = {}
282
+ for axis in ASSIGNMENT_AXES:
283
+ if not any(cell.group == axis for cell in full.cells.values()):
284
+ continue
285
+ assigned[axis] = "".join(kept[axis])
286
+ _check_partition(full, assigned)
287
+ return assigned
288
+
289
+
290
+ def _cell_row_group(line: str) -> str | None:
291
+ if not line.strip().startswith("|"):
292
+ return None
293
+ fields = _table_fields(line)
294
+ if len(fields) != 3 or fields[0] == "Cell" or all(re.fullmatch(r"[-:]+", f) for f in fields):
295
+ return None
296
+ return fields[2]
297
+
298
+
299
+ def _check_partition(full, assigned: Mapping[str, str]) -> None:
300
+ owners: dict[str, str] = {}
301
+ for axis, text in assigned.items():
302
+ part = parse_review_census(text)
303
+ if part.rules != full.rules or part.references != full.references:
304
+ raise ValueError(f"assigned {axis} census changes the rule catalog")
305
+ for identity, cell in part.cells.items():
306
+ if cell.group != axis or identity in owners or full.cells.get(identity) != cell:
307
+ raise ValueError(f"assigned {axis} census does not own cell {identity}")
308
+ owners[identity] = axis
309
+ if set(owners) != set(full.cells):
310
+ missing = sorted(set(full.cells) - set(owners))
311
+ raise ValueError("assigned censuses leave cells unowned: " + ", ".join(missing))
312
+
313
+
314
+ def write_review_assignments(project_root: Path, census: Path) -> dict[str, Path]:
315
+ """Write `<review-id>.<axis>.census.md` beside a `<review-id>.census.md` in `.okstra/`."""
316
+ if not census.name.endswith(".census.md"):
317
+ raise ValueError("census file must be named <review-id>.census.md")
318
+ census.resolve(strict=True).relative_to((project_root / ".okstra").resolve())
319
+ stem = census.name.removesuffix(".census.md")
320
+ assigned = split_review_census(census.read_text(encoding="utf-8"))
321
+ outputs = {axis: census.with_name(f"{stem}.{axis}.census.md") for axis in assigned}
322
+ for axis, out in outputs.items():
323
+ if out.exists() and out.read_text(encoding="utf-8") != assigned[axis]:
324
+ raise ValueError(f"existing assignment differs; choose a new review id: {out}")
325
+ for axis, out in outputs.items():
326
+ out.write_text(assigned[axis], encoding="utf-8")
327
+ return outputs
328
+
329
+
330
+ def subset_review_census(text: str, cell_ids: Sequence[str]) -> str:
331
+ """Keep only the named Cells rows; every other line stays verbatim."""
332
+ full = parse_review_census(text)
333
+ unknown = sorted(set(cell_ids) - set(full.cells))
334
+ if unknown or not cell_ids:
335
+ raise ValueError("cell subset names no cell or unknown cells: " + ", ".join(unknown))
336
+ wanted = set(cell_ids)
337
+ kept: list[str] = []
338
+ section = ""
339
+ for line in text.splitlines(keepends=True):
340
+ if line.startswith("## "):
341
+ section = line.strip()
342
+ if section == "## Cells" and _cell_row_group(line) is not None:
343
+ if _table_fields(line)[0] not in wanted:
344
+ continue
345
+ kept.append(line)
346
+ subset = "".join(kept)
347
+ if set(parse_review_census(subset).cells) != wanted:
348
+ raise ValueError("cell subset lost a requested cell")
349
+ return subset
@@ -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")