okstra 0.231.1 → 0.232.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 (126) hide show
  1. package/README.md +12 -0
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/memory/memory.mjs +9 -55
  5. package/dist/commands/memory/memory.mjs.map +1 -1
  6. package/dist/lib/memory-auto-register.d.mts +1 -0
  7. package/dist/lib/memory-auto-register.mjs +113 -0
  8. package/dist/lib/memory-auto-register.mjs.map +1 -0
  9. package/dist/lib/memory-entry-contract.d.mts +12 -0
  10. package/dist/lib/memory-entry-contract.mjs +46 -0
  11. package/dist/lib/memory-entry-contract.mjs.map +1 -0
  12. package/dist/lib/python-helper.d.mts +1 -1
  13. package/dist/lib/python-helper.mjs +3 -2
  14. package/dist/lib/python-helper.mjs.map +1 -1
  15. package/dist/lib/record-secrets.d.mts +1 -0
  16. package/dist/lib/record-secrets.mjs +28 -0
  17. package/dist/lib/record-secrets.mjs.map +1 -0
  18. package/dist/lib/types.d.mts +2 -1
  19. package/docs/architecture/storage-model.md +127 -0
  20. package/docs/architecture.md +7 -0
  21. package/docs/cli.md +234 -0
  22. package/docs/project-structure-overview.md +2 -1
  23. package/package.json +1 -1
  24. package/runtime/BUILD.json +2 -2
  25. package/runtime/agents/common.json +8 -8
  26. package/runtime/agents/roles/verifier.json +2 -4
  27. package/runtime/bin/okstra-provider-exec.py +10 -4
  28. package/runtime/prompts/coding-preflight/architectures/hexagonal.md +23 -30
  29. package/runtime/prompts/coding-preflight/authoring-checks.md +17 -0
  30. package/runtime/prompts/coding-preflight/clean-code.md +85 -281
  31. package/runtime/prompts/coding-preflight/frameworks/node-server.md +2 -3
  32. package/runtime/prompts/coding-preflight/languages/java.md +3 -5
  33. package/runtime/prompts/coding-preflight/languages/javascript-typescript.md +5 -12
  34. package/runtime/prompts/coding-preflight/languages/kotlin.md +2 -4
  35. package/runtime/prompts/coding-preflight/languages/python.md +2 -7
  36. package/runtime/prompts/coding-preflight/languages/rust.md +2 -8
  37. package/runtime/prompts/coding-preflight/languages/sql.md +2 -4
  38. package/runtime/prompts/coding-preflight/overview.md +25 -38
  39. package/runtime/prompts/coding-preflight/review-rules.json +30 -0
  40. package/runtime/prompts/duties/code-reviewer.json +15 -18
  41. package/runtime/prompts/duties/implementation-verifier.json +1 -0
  42. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  43. package/runtime/python/okstra_ctl/agent/invocation.py +121 -36
  44. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +6 -0
  45. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +30 -4
  46. package/runtime/python/okstra_ctl/agent/standalone.py +3 -0
  47. package/runtime/python/okstra_ctl/analysis_packet.py +2 -19
  48. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  49. package/runtime/python/okstra_ctl/code_review_census.py +71 -7
  50. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  51. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  52. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  53. package/runtime/python/okstra_ctl/code_review_scope.py +36 -9
  54. package/runtime/python/okstra_ctl/code_review_target.py +85 -11
  55. package/runtime/python/okstra_ctl/consumers.py +12 -9
  56. package/runtime/python/okstra_ctl/design_review.py +207 -0
  57. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  58. package/runtime/python/okstra_ctl/doctor.py +8 -25
  59. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  60. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  61. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  62. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  63. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  64. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  65. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  66. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  67. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  68. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  69. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  70. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +261 -0
  71. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  72. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  73. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  74. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  75. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  76. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  77. package/runtime/python/okstra_ctl/json_boundary.py +21 -2
  78. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  79. package/runtime/python/okstra_ctl/manager_cli.py +26 -0
  80. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  81. package/runtime/python/okstra_ctl/manager_sync.py +3 -22
  82. package/runtime/python/okstra_ctl/model_io/renderers.py +13 -2
  83. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  84. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  85. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +10 -0
  86. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +19 -6
  87. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +5 -3
  88. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +38 -10
  89. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  90. package/runtime/python/okstra_ctl/phases/implementation/spec.md +25 -0
  91. package/runtime/python/okstra_ctl/phases/implementation/validation.py +6 -0
  92. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +4 -0
  93. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  94. package/runtime/python/okstra_ctl/report_assembly.py +15 -0
  95. package/runtime/python/okstra_ctl/report_narrative.py +3 -0
  96. package/runtime/python/okstra_ctl/report_synthesis_packet.py +11 -2
  97. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  98. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  99. package/runtime/python/okstra_ctl/run.py +24 -1
  100. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  101. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  102. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  103. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  104. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  105. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  106. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  107. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  108. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  109. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  110. package/runtime/python/okstra_project/__init__.py +2 -0
  111. package/runtime/python/okstra_project/dirs.py +18 -0
  112. package/runtime/python/okstra_project/state.py +25 -20
  113. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  114. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  115. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  116. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  117. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  118. package/runtime/schemas/record-secret-patterns.json +41 -0
  119. package/runtime/skills/okstra-code-review/SKILL.md +71 -123
  120. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  121. package/runtime/skills/okstra-code-review/references/review-calibration.md +34 -54
  122. package/runtime/skills/okstra-manager/SKILL.md +7 -0
  123. package/runtime/skills/okstra-memory/SKILL.md +7 -0
  124. package/runtime/templates/implementation-worker-preamble.md +4 -9
  125. package/runtime/templates/worker-prompt-preamble.md +4 -12
  126. package/runtime/validators/validate-run.py +14 -2
@@ -0,0 +1,291 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import subprocess
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path, PurePosixPath
8
+
9
+ from .convergence_provenance import id_occurs_wordbounded
10
+ from .coverage_census import CellVerdicts, split_coverage_verdict_section
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ReviewCell:
15
+ target: str
16
+ group: str
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ReviewCensus:
21
+ rules: dict[str, tuple[str, ...]]
22
+ cells: dict[str, ReviewCell]
23
+ references: dict[str, str]
24
+
25
+
26
+ def _table_fields(line: str) -> list[str]:
27
+ # Markdown writes a literal pipe inside a table cell as `\|`.
28
+ fields = re.split(r"(?<!\\)\|", line.strip().strip("|"))
29
+ return [field.strip().replace("\\|", "|") for field in fields]
30
+
31
+
32
+ def read_review_census(path: Path, *, allow_empty: bool = False) -> ReviewCensus:
33
+ return parse_review_census(path.read_text(encoding="utf-8"), allow_empty=allow_empty)
34
+
35
+
36
+ def parse_review_census(text: str, *, allow_empty: bool = False) -> ReviewCensus:
37
+ rules: dict[str, list[str]] = {}
38
+ cells: dict[str, ReviewCell] = {}
39
+ rule_ids: set[str] = set()
40
+ pairs: set[tuple[str, str]] = set()
41
+ references: set[tuple[str, str]] = set()
42
+ rule_references: dict[str, str] = {}
43
+ section = ""
44
+ for line in text.splitlines():
45
+ if line.startswith("## "):
46
+ section = line.strip()
47
+ if section not in ("## Rules", "## Cells") or not line.strip().startswith("|"):
48
+ continue
49
+ fields = _table_fields(line)
50
+ header = fields[0] in ("Rule", "Cell")
51
+ if header or all(re.fullmatch(r"[-:]+", f) for f in fields):
52
+ continue
53
+ if len(fields) != 3 or not all(fields):
54
+ raise ValueError("malformed grouped census row")
55
+ identity, value, reference = fields
56
+ if section == "## Rules":
57
+ if not re.fullmatch(r"[A-Z][A-Z0-9]*", identity) or identity in rule_ids:
58
+ raise ValueError("invalid or duplicate rule ID")
59
+ if (value, reference) in references:
60
+ raise ValueError("duplicate group and rule reference")
61
+ if value not in ("structural", "semantic", "state-and-tests", "general"):
62
+ raise ValueError("unknown rule group")
63
+ rule_ids.add(identity)
64
+ references.add((value, reference))
65
+ rule_references[identity] = reference
66
+ rules.setdefault(value, []).append(identity)
67
+ else:
68
+ if not re.fullmatch(r"C-CR-[0-9]+", identity) or identity in cells:
69
+ raise ValueError("invalid or duplicate cell ID")
70
+ if (value, reference) in pairs:
71
+ raise ValueError("duplicate target and group")
72
+ target = PurePosixPath(value.partition(":")[0])
73
+ if target.is_absolute() or ".." in target.parts:
74
+ raise ValueError("target must be project-relative")
75
+ pairs.add((value, reference))
76
+ cells[identity] = ReviewCell(value, reference)
77
+ if not rules or (not cells and not allow_empty):
78
+ raise ValueError("census needs Rules and Cells tables")
79
+ if any(cell.group not in rules for cell in cells.values()):
80
+ raise ValueError("cell names an unknown rule group")
81
+ return ReviewCensus(
82
+ {group: tuple(ids) for group, ids in rules.items()}, cells, rule_references,
83
+ )
84
+
85
+
86
+ def _keyed_values(text: str) -> dict[str, str]:
87
+ values: dict[str, str] = {}
88
+ if text == "-":
89
+ return values
90
+ # Reviewers write prose reasons; only a semicolon before the next `RULE=` separates assignments.
91
+ for entry in re.split(r";(?=\s*[A-Z][A-Z0-9]*=)", text):
92
+ key, separator, value = entry.partition("=")
93
+ key, value = key.strip(), value.strip()
94
+ if not separator or not key or not value or key in values:
95
+ raise ValueError(f"empty or duplicate rule assignment: {entry.strip()!r}")
96
+ values[key] = value
97
+ return values
98
+
99
+
100
+ @dataclass
101
+ class _HeadTree:
102
+ """리뷰 대상 커밋이 담은 파일.
103
+
104
+ 프로젝트 루트에는 다른 커밋이 체크아웃돼 있을 수 있다.
105
+ """
106
+
107
+ root: Path
108
+ commit: str
109
+ line_counts: dict[str, int] = field(default_factory=dict)
110
+ base: _HeadTree | None = None
111
+
112
+ def line_count(self, path: str) -> int:
113
+ if path not in self.line_counts:
114
+ self.line_counts[path] = self._read_line_count(path)
115
+ return self.line_counts[path]
116
+
117
+ def _git(self, *args: str) -> subprocess.CompletedProcess[bytes]:
118
+ return subprocess.run(
119
+ ["git", "--literal-pathspecs", "-C", str(self.root), *args],
120
+ capture_output=True, check=False,
121
+ )
122
+
123
+ def _read_line_count(self, path: str) -> int:
124
+ listing = self._git("ls-tree", "-z", self.commit, "--", path)
125
+ if listing.returncode != 0:
126
+ raise ValueError("cannot list the head commit")
127
+ entries = [entry for entry in listing.stdout.split(b"\0") if entry]
128
+ named = (entry.partition(b"\t") for entry in entries)
129
+ matched = [
130
+ meta.split() for meta, _, name in named
131
+ if name.decode("utf-8", "surrogateescape") == path
132
+ ]
133
+ if not matched:
134
+ raise ValueError("source evidence file does not exist at head")
135
+ mode, kind, blob = matched[0]
136
+ if kind != b"blob" or mode == b"120000":
137
+ raise ValueError("source evidence is not a regular file at head")
138
+ content = self._git("cat-file", "blob", blob.decode())
139
+ if content.returncode != 0:
140
+ raise ValueError("cannot read source evidence at head")
141
+ return len(content.stdout.decode("utf-8").splitlines())
142
+
143
+
144
+ def _head_tree(project_root: Path, head: str) -> _HeadTree:
145
+ resolved = subprocess.run(
146
+ ["git", "-C", str(project_root), "rev-parse", "--verify", "--quiet",
147
+ "--end-of-options", f"{head}^{{commit}}"],
148
+ capture_output=True, text=True, check=False,
149
+ )
150
+ if resolved.returncode != 0:
151
+ raise ValueError(f"--head {head!r} is not a commit in {project_root}")
152
+ return _HeadTree(project_root, resolved.stdout.strip())
153
+
154
+
155
+ def _source_evidence(tree: _HeadTree, cell: ReviewCell, evidence: str) -> str:
156
+ source = evidence.strip("`")
157
+ if source.startswith("base:"):
158
+ if tree.base is None:
159
+ raise ValueError("base-side evidence requires --base")
160
+ tree = tree.base
161
+ source = source.removeprefix("base:")
162
+ target = cell.target.partition(":")[0]
163
+ match = re.fullmatch(re.escape(target) + r":(0|[1-9][0-9]*)`?(?:[ \t]+\S.*)?", source)
164
+ if match is None:
165
+ raise ValueError("evidence must cite the target source path:line")
166
+ relative = PurePosixPath(target)
167
+ if relative.is_absolute() or ".." in relative.parts:
168
+ raise ValueError("source evidence escapes project")
169
+ count = tree.line_count(target)
170
+ if int(match[1]) > count or (int(match[1]) == 0 and count != 0):
171
+ raise ValueError("source evidence line does not exist at head")
172
+ return evidence
173
+
174
+
175
+ def _checked_rule_evidence(
176
+ tree: _HeadTree, cell: ReviewCell, checked: Sequence[str], text: str,
177
+ ) -> str:
178
+ anchor, _, raw = text.partition(" :: ")
179
+ _source_evidence(tree, cell, anchor)
180
+ observations = _keyed_values(raw.strip() or "-")
181
+ required = set(checked) & {"G2", "G3", "G5"} if cell.group == "general" else set()
182
+ missing = required - observations.keys()
183
+ if missing:
184
+ raise ValueError("missing clean check evidence: " + ", ".join(sorted(missing)))
185
+ if observations.keys() - set(checked):
186
+ raise ValueError("clean check evidence names an unchecked rule")
187
+ for observation in observations.values():
188
+ match = re.fullmatch(r"(`?.+?:(?:0|[1-9][0-9]*)`?) (.+)", observation)
189
+ if match is None:
190
+ raise ValueError("clean check evidence needs source path:line and an observation")
191
+ if re.fullmatch(r"(?:checked|clean|no issues?|none|n/?a)", match[2], re.I):
192
+ raise ValueError("clean check evidence needs an observation, not a verdict label")
193
+ citation = match[1].strip("`")
194
+ source_cell = ReviewCell(citation.removeprefix("base:").partition(":")[0], cell.group)
195
+ _source_evidence(tree, source_cell, citation)
196
+ return text
197
+
198
+
199
+ def _group_verdict(
200
+ fields: Sequence[str], expected: Sequence[str], cell: ReviewCell,
201
+ tree: _HeadTree, references: Sequence[str],
202
+ ) -> tuple[str, str]:
203
+ if len(fields) != 5:
204
+ raise ValueError("expected Cell, Checked, N/A, Findings, Evidence columns")
205
+ checked = [] if fields[1] == "-" else [rule.strip() for rule in fields[1].split(",")]
206
+ excluded = _keyed_values(fields[2])
207
+ findings = _keyed_values(fields[3])
208
+ assigned = checked + list(excluded) + list(findings)
209
+ if len(set(assigned)) != len(assigned):
210
+ raise ValueError("duplicate or conflicting rule verdicts")
211
+ unknown = set(assigned) - set(expected)
212
+ if unknown:
213
+ raise ValueError("unknown rules: " + ", ".join(sorted(unknown)))
214
+ missing = set(expected) - set(assigned)
215
+ if missing:
216
+ raise ValueError("unchecked rules: " + ", ".join(sorted(missing)))
217
+ for reason in excluded.values():
218
+ if re.fullmatch(r"(?:[A-Z][0-9]+|[a-z]+:[0-9]+)", reason):
219
+ raise ValueError("n/a needs an inline applicability reason, not an alias")
220
+ for ids in findings.values():
221
+ for item in ids.split(","):
222
+ item = item.strip()
223
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", item):
224
+ raise ValueError("invalid finding ID")
225
+ if not any(id_occurs_wordbounded(body, item) for body in references):
226
+ raise ValueError(f"finding {item} has no finding body")
227
+ evidence = _checked_rule_evidence(tree, cell, checked, fields[4])
228
+ if findings:
229
+ return "finding", "; ".join(findings.values())
230
+ if checked:
231
+ return "clean", evidence
232
+ return "n/a", "; ".join(excluded.values())
233
+
234
+
235
+ def _group_results(
236
+ body: str, census: ReviewCensus, tree: _HeadTree, references: Sequence[str],
237
+ ) -> CellVerdicts:
238
+ section, _ = split_coverage_verdict_section(body)
239
+ verdicts: dict[str, tuple[str, str]] = {}
240
+ reasons: dict[str, str] = {}
241
+ seen: set[str] = set()
242
+ unknown: list[str] = []
243
+ for line in section:
244
+ if not line.strip().startswith("|"):
245
+ continue
246
+ fields = _table_fields(line)
247
+ identity = fields[0]
248
+ if identity not in census.cells:
249
+ if identity.startswith("C-") and identity not in unknown:
250
+ unknown.append(identity)
251
+ continue
252
+ if identity in seen:
253
+ verdicts.pop(identity, None)
254
+ reasons[identity] = "duplicate cell row"
255
+ continue
256
+ seen.add(identity)
257
+ cell = census.cells[identity]
258
+ try:
259
+ verdicts[identity] = _group_verdict(
260
+ fields, census.rules[cell.group], cell, tree, references,
261
+ )
262
+ except (OSError, ValueError) as exc:
263
+ reasons[identity] = str(exc)
264
+ return CellVerdicts(
265
+ verdicts,
266
+ {key: reasons.get(key, "no grouped verdict row") for key in census.cells if key not in verdicts},
267
+ tuple(unknown),
268
+ )
269
+
270
+
271
+
272
+ def parse_review_verdicts(
273
+ project: Path, census: ReviewCensus, bodies: Sequence[str], head: str, *, base: str = "",
274
+ ) -> CellVerdicts:
275
+ tree = _head_tree(project, head)
276
+ if base:
277
+ tree.base = _head_tree(project, base)
278
+ verdicts: dict[str, tuple[str, str]] = {}
279
+ missing: dict[str, str] = {}
280
+ unknown: list[str] = []
281
+ references = [split_coverage_verdict_section(body)[1] for body in bodies]
282
+ for body in bodies:
283
+ parsed = _group_results(body, census, tree, references)
284
+ unknown.extend(key for key in parsed.unknown if key not in unknown)
285
+ for key, verdict in parsed.verdicts.items():
286
+ verdicts.setdefault(key, verdict)
287
+ missing.update(parsed.missing)
288
+ return CellVerdicts(
289
+ verdicts, {key: missing[key] for key in census.cells if key not in verdicts},
290
+ tuple(unknown),
291
+ )
@@ -3414,6 +3414,8 @@ def _load_recorded_run_manifest_strict(
3414
3414
  def _verification_input_source(
3415
3415
  ctx: dict, reference: VerificationInputReference | None,
3416
3416
  ) -> Path | None:
3417
+ if ctx["TASK_TYPE"] == "implementation-planning":
3418
+ return Path(ctx.get("EXECUTOR_WORKTREE_PATH") or ctx["PROJECT_ROOT"]).resolve()
3417
3419
  source_key = ("EXECUTOR_WORKTREE_PATH" if ctx["TASK_TYPE"] == "implementation"
3418
3420
  else "VERIFICATION_WORKTREE_PATH")
3419
3421
  source_path = ctx.get(source_key, "")
@@ -3459,7 +3461,7 @@ def _validate_recorded_verification_inputs(
3459
3461
  def _prepare_verification_input_reference(
3460
3462
  ctx: dict, store: VerificationInputStore,
3461
3463
  ) -> None:
3462
- if ctx["TASK_TYPE"] not in QA_COMMAND_EXECUTING_TASK_TYPES:
3464
+ if ctx["TASK_TYPE"] not in (*QA_COMMAND_EXECUTING_TASK_TYPES, "implementation-planning"):
3463
3465
  return
3464
3466
  try:
3465
3467
  project_root = Path(ctx["PROJECT_ROOT"]).resolve()
@@ -4257,11 +4259,32 @@ def _prepare_mcp_block(
4257
4259
  return prepared.block
4258
4260
 
4259
4261
 
4262
+ def _validate_new_review_policy(inp: PrepareInputs, project: Path) -> None:
4263
+ from .review_policy import capture_review_policy
4264
+
4265
+ if inp.task_type not in (*QA_COMMAND_EXECUTING_TASK_TYPES, "implementation-planning"):
4266
+ return
4267
+ override = os.environ.get("OKSTRA_RUN_SEQ_OVERRIDE", "")
4268
+ if override.isdecimal() and int(override) > 0:
4269
+ ref = RunRef(project_root=project, task_group=inp.task_group, task_id=inp.task_id,
4270
+ task_type=inp.task_type, seq=int(override))
4271
+ recorded = [ref.manifest, *ref.run_dir.glob(f"stage-*/manifests/{ref.manifest.name}")]
4272
+ if any(path.is_file() for path in recorded):
4273
+ return
4274
+ try:
4275
+ config_path = project_json_path(project)
4276
+ config = load_owned_object(config_path, artifact="project config") if config_path.exists() else {}
4277
+ capture_review_policy(project, config)
4278
+ except (OSError, ValueError) as exc:
4279
+ raise PrepareError(f"review policy preflight failed: {exc}") from exc
4280
+
4281
+
4260
4282
  def prepare_task_bundle(inp: PrepareInputs) -> PrepareOutputs:
4261
4283
  """Produce a complete okstra task bundle on disk. See module docstring."""
4262
4284
  user_authorization = _prepare_user_authorization(inp)
4263
4285
  workspace_root = Path(inp.workspace_root)
4264
4286
  project_root = Path(inp.project_root)
4287
+ _validate_new_review_policy(inp, project_root)
4265
4288
  lead_runtime = _normalize_lead_runtime(inp.lead_runtime)
4266
4289
  lead_runtime_request = (inp.lead_runtime_request or lead_runtime).strip()
4267
4290
  runtime_resolution_json = (inp.runtime_resolution_json or "{}").strip()
@@ -108,6 +108,14 @@ def done_stage(
108
108
  head = carry_head_commit(carry)
109
109
  file_size_cap = _check_file_size(project_root, carry, head)
110
110
  report = report if report.is_absolute() else project_root / report
111
+ try:
112
+ from .design_review_evidence import validate_stage_design_report
113
+
114
+ rng = carry.get("stageCommitRange") or {}
115
+ validate_stage_design_report(project_root, report, stage, head=head,
116
+ base=str(rng.get("base") or ""), task_key=task_key)
117
+ except (OSError, ValueError) as exc:
118
+ raise StateError(f"design review prevents stage completion: {exc}", stage="design-review") from exc
111
119
  try:
112
120
  report_rel = report.relative_to(RunRef.from_report_path(report).run_dir).as_posix()
113
121
  except ValueError as exc:
@@ -169,6 +177,9 @@ over the 500-line limit or takes one past it (`okstra correction file-size`); a
169
177
  file already over 500 at the stage base may grow. Re-running with the
170
178
  same carry writes nothing new.
171
179
 
180
+ Input-4.0 runs also require the latest accepted report for this task/stage and
181
+ matching base/head, current sealed verifier results and complete design coverage.
182
+
172
183
  Output: JSON { ok, taskKey, stage, headCommit, carryPath, supersededCarryPath,
173
184
  reportPath, consumersPath, fileSizeCap }. Exit 1 on a refusal, 2 when
174
185
  PROJECT_ROOT cannot be resolved.
@@ -0,0 +1,28 @@
1
+ """Post-execution integrity checks for independent code review."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import replace
5
+
6
+ from .execution_mutation_audit import (
7
+ ExecutionMutationAudit,
8
+ MutationAuditResult,
9
+ MutationSnapshot,
10
+ )
11
+ from .write_policy import WritePolicy
12
+
13
+ REVIEW_WRITE_VIOLATION_EXIT_CODE = 77
14
+
15
+
16
+ def compare_standalone_review(
17
+ before: MutationSnapshot, policy: WritePolicy, *, succeeded: bool,
18
+ ) -> MutationAuditResult:
19
+ result = ExecutionMutationAudit().compare(
20
+ before, (policy,), attempt_succeeded=succeeded,
21
+ )
22
+ if result.untracked_paths:
23
+ result = replace(
24
+ result, status="contract-failed-unattributed", source_changed=True,
25
+ retry_allowed=False,
26
+ violations=(*result.violations, "readonly review created untracked source paths"),
27
+ )
28
+ return result
@@ -24,6 +24,10 @@ from .verification_inputs import (
24
24
  canonical_run_ref, publish_verification_snapshot, read_verification_inputs,
25
25
  )
26
26
  from .verification_target import read_verification_head
27
+ from .verification_input_types import DESIGN_REVIEW_INPUT_SCHEMA_VERSION
28
+ from .design_review import (
29
+ DesignReviewSnapshot, DESIGN_REVIEW_SCHEMA, capture_design_review,
30
+ )
27
31
 
28
32
 
29
33
  class _OptionalFrozenVerificationSource(TypedDict, total=False):
@@ -40,6 +44,7 @@ class FrozenVerificationSource(_OptionalFrozenVerificationSource):
40
44
 
41
45
  class _OptionalGenerationConformance(TypedDict, total=False):
42
46
  conformanceStages: list[int]
47
+ designReview: DesignReviewSnapshot
43
48
 
44
49
 
45
50
  class VerificationGenerationRecord(_OptionalGenerationConformance):
@@ -85,12 +90,23 @@ _SCHEMA = {
85
90
  "sourceRoot": _PATH, "source": _SOURCE, "artifactInputs": _FILES,
86
91
  "conformanceStages": {"type": "array",
87
92
  "items": {"type": "integer", "minimum": 1}},
93
+ "designReview": DESIGN_REVIEW_SCHEMA,
88
94
  },
89
95
  }
90
96
  _ARTIFACT = "verification generation"
91
97
 
92
98
 
93
99
  def _generation_errors(payload: dict[str, Any]) -> list[str]:
100
+ if "designReview" in payload:
101
+ from .review_verdicts import parse_review_census
102
+
103
+ review = payload["designReview"]
104
+ if payload["taskType"] != "implementation" or review["head"] != payload["head"]:
105
+ return ["design review must name this implementation head"]
106
+ try:
107
+ parse_review_census(review["census"], allow_empty=True)
108
+ except ValueError as exc:
109
+ return [f"invalid design review census: {exc}"]
94
110
  stages = payload.get("conformanceStages", [])
95
111
  if any(left >= right for left, right in pairwise(stages)):
96
112
  return ["generation conformance stages must be strictly increasing"]
@@ -177,7 +193,7 @@ def _capture_generation(
177
193
  if artifacts[relative] != digest:
178
194
  raise ValueError("verification conformance manifest changed during capture")
179
195
  read_verification_head(source_root, head)
180
- return {
196
+ result: VerificationGenerationRecord = {
181
197
  "schemaVersion": "1.0", "kind": "verification-generation",
182
198
  "generation": generation, "taskType": ref.task_type,
183
199
  "runManifestPath": ref.manifest.relative_to(project).as_posix(),
@@ -196,6 +212,12 @@ def _capture_generation(
196
212
  **({"conformanceStages": list(conformance.stages)}
197
213
  if conformance is not None else {}),
198
214
  }
215
+ if ref.task_type == "implementation" and inputs["schemaVersion"] == DESIGN_REVIEW_INPUT_SCHEMA_VERSION:
216
+ result["designReview"] = capture_design_review(
217
+ source_root, inputs["reviewBase"], head, inputs["reviewPolicy"],
218
+ ref.verification_generation(generation).with_suffix(".functions.json"),
219
+ )
220
+ return result
199
221
 
200
222
 
201
223
  def prepare_verification_generation(
@@ -5,6 +5,8 @@ from typing import Any, Literal, TypedDict
5
5
  INPUT_SCHEMA_VERSION: Literal["1.0"] = "1.0"
6
6
  INPUT_KIND: Literal["verification-inputs"] = "verification-inputs"
7
7
  PLAN_INPUT_SCHEMA_VERSION: Literal["2.0"] = "2.0"
8
+ REVIEW_INPUT_SCHEMA_VERSION: Literal["3.0"] = "3.0"
9
+ DESIGN_REVIEW_INPUT_SCHEMA_VERSION: Literal["4.0"] = "4.0"
8
10
 
9
11
 
10
12
  class FrozenProcedure(TypedDict):
@@ -12,6 +14,16 @@ class FrozenProcedure(TypedDict):
12
14
  digest: str
13
15
 
14
16
 
17
+ class _OptionalFrozenReviewPolicy(TypedDict, total=False):
18
+ authorPolicyDigest: str
19
+
20
+
21
+ class FrozenReviewPolicy(_OptionalFrozenReviewPolicy):
22
+ schemaVersion: str
23
+ architecture: str
24
+ sources: dict[str, FrozenProcedure]
25
+
26
+
15
27
  QaSourceStatus = Literal[
16
28
  "not-declared", "not-queried", "no-baseline", "unchanged", "changed",
17
29
  ]
@@ -39,6 +51,8 @@ class FrozenVerificationPlan(TypedDict):
39
51
 
40
52
 
41
53
  class _OptionalVerificationInputs(TypedDict, total=False):
54
+ reviewBase: str
55
+ reviewPolicy: FrozenReviewPolicy
42
56
  approvedPlan: FrozenVerificationPlan
43
57
  qaSourceObservations: dict[str, list[FrozenQaSourceObservation]]
44
58
  conformanceBaseline: dict[str, str]
@@ -46,7 +60,7 @@ class _OptionalVerificationInputs(TypedDict, total=False):
46
60
 
47
61
 
48
62
  class VerificationInputs(_OptionalVerificationInputs):
49
- schemaVersion: Literal["1.0", "2.0"]
63
+ schemaVersion: Literal["1.0", "2.0", "3.0", "4.0"]
50
64
  kind: Literal["verification-inputs"]
51
65
  sourceRoot: str
52
66
  qaCommands: dict[str, list[dict[str, Any]]]
@@ -10,6 +10,7 @@ from okstra_project.dirs import OKSTRA_DIR_NAME, json_lock_path, registry_lock
10
10
 
11
11
  from .json_boundary import load_owned_object_snapshot, write_owned_object_atomic
12
12
  from .paths import RunRef
13
+ from .review_policy import capture_review_policy, review_policy_errors
13
14
  from .qa_commands import (
14
15
  QA_COMMAND_EXECUTING_TASK_TYPES, QA_SOURCE_DIGEST_PATTERN, qa_relative_path_valid,
15
16
  validate_qa_commands,
@@ -22,12 +23,14 @@ from .qa_procedures import (
22
23
 
23
24
  from .verification_input_types import (
24
25
  INPUT_KIND, INPUT_SCHEMA_VERSION, PLAN_INPUT_SCHEMA_VERSION,
26
+ REVIEW_INPUT_SCHEMA_VERSION, DESIGN_REVIEW_INPUT_SCHEMA_VERSION,
25
27
  FrozenProcedure, VerificationInputs,
26
28
  )
27
29
  from .verification_conformance import capture_conformance_baseline
28
30
  from .verification_plan import (
29
31
  VERIFICATION_PLAN_SCHEMA, capture_verification_plan, verification_plan_errors,
30
32
  )
33
+ from .verification_target import read_worktree_head
31
34
 
32
35
  INPUT_ARTIFACT = "verification inputs"
33
36
  QA_INPUT_FIELDS = (
@@ -41,11 +44,14 @@ INPUT_SCHEMA = {
41
44
  "additionalProperties": False,
42
45
  "required": ["schemaVersion", "kind", "sourceRoot", "qaCommands", "procedures"],
43
46
  "properties": {
44
- "schemaVersion": {"enum": [INPUT_SCHEMA_VERSION, PLAN_INPUT_SCHEMA_VERSION]},
47
+ "schemaVersion": {"enum": [INPUT_SCHEMA_VERSION, PLAN_INPUT_SCHEMA_VERSION,
48
+ REVIEW_INPUT_SCHEMA_VERSION, DESIGN_REVIEW_INPUT_SCHEMA_VERSION]},
45
49
  "kind": {"const": INPUT_KIND},
46
50
  "sourceRoot": {"type": "string", "minLength": 1},
47
51
  "qaCommands": {"type": "object"},
48
52
  "procedures": {"type": "object"},
53
+ "reviewPolicy": {"type": "object"},
54
+ "reviewBase": {"type": "string", "pattern": "^[0-9a-f]{40}([0-9a-f]{24})?$"},
49
55
  "approvedPlan": VERIFICATION_PLAN_SCHEMA,
50
56
  "qaSourceObservations": {"type": "object"},
51
57
  "conformanceBaseline": {
@@ -101,6 +107,16 @@ def _verification_source_errors(
101
107
 
102
108
 
103
109
  def _verification_input_errors(payload: dict[str, Any]) -> list[str]:
110
+ if payload["schemaVersion"] == DESIGN_REVIEW_INPUT_SCHEMA_VERSION and not {"reviewBase", "approvedPlan"}.issubset(payload):
111
+ return ["verification inputs 4.0 requires reviewBase and approvedPlan"]
112
+ if payload["schemaVersion"] != DESIGN_REVIEW_INPUT_SCHEMA_VERSION and "reviewBase" in payload:
113
+ return ["reviewBase requires verification inputs 4.0"]
114
+ if payload["schemaVersion"] in (REVIEW_INPUT_SCHEMA_VERSION, DESIGN_REVIEW_INPUT_SCHEMA_VERSION) and "reviewPolicy" not in payload:
115
+ return ["review policy: verification inputs 3.0 requires reviewPolicy"]
116
+ if "reviewPolicy" in payload:
117
+ policy_errors = review_policy_errors(payload["reviewPolicy"])
118
+ if policy_errors:
119
+ return policy_errors
104
120
  has_plan = "approvedPlan" in payload
105
121
  if payload["schemaVersion"] == PLAN_INPUT_SCHEMA_VERSION and not has_plan:
106
122
  return ["verification inputs 2.0 requires approvedPlan"]
@@ -167,7 +183,8 @@ def _conformance_baseline_errors(payload: Mapping[str, Any]) -> list[str]:
167
183
  def capture_verification_inputs(
168
184
  project: Path, source: Path, *, approved_plan: Path | None = None,
169
185
  ) -> VerificationInputs:
170
- declared = load_qa_config(project).get("qaCommands") or {}
186
+ config = load_qa_config(project)
187
+ declared = config.get("qaCommands") or {}
171
188
  read_digest = new_qa_source_digest_reader()
172
189
  commands = {
173
190
  category: [{key: entry[key] for key in QA_INPUT_FIELDS if key in entry}
@@ -185,9 +202,10 @@ def capture_verification_inputs(
185
202
  "body": raw.decode("utf-8"), "digest": content_digest(raw),
186
203
  }
187
204
  payload: VerificationInputs = {
188
- "schemaVersion": INPUT_SCHEMA_VERSION, "kind": INPUT_KIND,
205
+ "schemaVersion": REVIEW_INPUT_SCHEMA_VERSION, "kind": INPUT_KIND,
189
206
  "sourceRoot": str(source.resolve()), "qaCommands": commands,
190
207
  "procedures": procedures,
208
+ "reviewPolicy": capture_review_policy(project, config),
191
209
  "qaSourceObservations": {
192
210
  category: [{**observe_qa_sources(source, entry, read_digest),
193
211
  "entryDigest": canonical_json_digest(entry)}
@@ -196,7 +214,6 @@ def capture_verification_inputs(
196
214
  },
197
215
  }
198
216
  if approved_plan is not None:
199
- payload["schemaVersion"] = PLAN_INPUT_SCHEMA_VERSION
200
217
  payload["approvedPlan"] = capture_verification_plan(approved_plan)
201
218
  return payload
202
219
 
@@ -288,8 +305,8 @@ def canonical_run_ref(project: Path, ref: RunRef) -> RunRef:
288
305
  def prepare_verification_inputs(
289
306
  project: Path, source: Path, ref: RunRef, *, approved_plan: Path | None = None,
290
307
  ) -> tuple[Path, str]:
291
- if ref.task_type not in QA_COMMAND_EXECUTING_TASK_TYPES:
292
- raise ValueError("verification inputs require a QA-executing phase")
308
+ if ref.task_type not in (*QA_COMMAND_EXECUTING_TASK_TYPES, "implementation-planning"):
309
+ raise ValueError("verification inputs require a QA-executing or planning phase")
293
310
  payload = capture_verification_inputs(project, source, approved_plan=approved_plan)
294
311
  if conformance_baseline_required(ref.task_type, payload):
295
312
  # The executor may rename or delete an earlier stage's script; only the
@@ -303,6 +320,11 @@ def prepare_verification_inputs(
303
320
  # Runs without the evidence contract keep preparing over a malformed
304
321
  # manifest; the recorded cause lets a marked seal refuse it by name.
305
322
  payload["conformanceBaselineError"] = str(exc)
323
+ if approved_plan is not None and ref.task_type in ("implementation", "final-verification"):
324
+ if not evidence_contract_applies(payload):
325
+ raise ValueError("design-review inputs require stable QA ids and a valid conformance baseline")
326
+ payload["schemaVersion"] = DESIGN_REVIEW_INPUT_SCHEMA_VERSION
327
+ payload["reviewBase"] = read_worktree_head(source)
306
328
  return publish_verification_snapshot(
307
329
  project, ref.verification_inputs, capture=partial(dict, payload),
308
330
  artifact=INPUT_ARTIFACT, schema=INPUT_SCHEMA,
@@ -9,13 +9,14 @@ from okstra_project.dirs import OKSTRA_DIR_NAME
9
9
  from .qa_commands import (
10
10
  QA_SOURCE_DIGEST_PATTERN, QA_VERIFIER_AUDIENCE_BY_TASK_TYPE, qa_relative_path_valid,
11
11
  )
12
- from .qa_procedures import safe_qa_path
12
+ from .qa_procedures import canonical_json_digest, safe_qa_path
13
13
  from .verification_generation import (
14
14
  VERIFICATION_GENERATION_PATH_MAX_LENGTH, VerificationGenerationRecord,
15
15
  read_verification_generation,
16
16
  )
17
17
  from .verification_input_ref import VerificationInputReference
18
18
  from .verification_inputs import read_verification_inputs
19
+ from .verification_input_types import DESIGN_REVIEW_INPUT_SCHEMA_VERSION
19
20
 
20
21
  VERIFICATION_EVIDENCE_VERSION = "1.0"
21
22
  VERIFICATION_GENERATION_HEADER_PREFIXES = (
@@ -118,6 +119,11 @@ def _read_bound_generation(
118
119
  )
119
120
  if record["sourceRoot"] != inputs["sourceRoot"]:
120
121
  raise ValueError("verification generation source differs from frozen inputs")
122
+ if inputs["schemaVersion"] == DESIGN_REVIEW_INPUT_SCHEMA_VERSION and task_type == "implementation":
123
+ review = record.get("designReview")
124
+ if (review is None or review["base"] != inputs["reviewBase"]
125
+ or review["policyDigest"] != canonical_json_digest(inputs["reviewPolicy"])):
126
+ raise ValueError("design review differs from frozen review base or policy")
121
127
  return record
122
128
 
123
129
 
@@ -74,6 +74,8 @@ def read_verification_target(project_root: Path, relative: str) -> dict | None:
74
74
  if stages_match
75
75
  else set()
76
76
  )
77
+ parsed["reports"] = {int(stage): path for stage, path in
78
+ re.findall(r"^ - stage (\d+): `([^`]+)`$", body, re.M)}
77
79
  return parsed
78
80
 
79
81