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
@@ -1,269 +1,12 @@
1
1
  from __future__ import annotations
2
2
 
3
- import re
4
- import subprocess
5
3
  from collections.abc import Sequence
6
- from dataclasses import dataclass, field
7
- from pathlib import Path, PurePosixPath
4
+ from pathlib import Path
8
5
 
9
6
  from .agent.invocation import AgentInvocationError, verify_standalone_completion
10
- from .convergence_provenance import id_occurs_wordbounded
11
- from .coverage_census import CellVerdicts, split_coverage_verdict_section
7
+ from .coverage_census import CellVerdicts
12
8
  from .json_boundary import load_owned_object
13
-
14
-
15
- @dataclass(frozen=True)
16
- class ReviewCell:
17
- target: str
18
- group: str
19
-
20
-
21
- @dataclass(frozen=True)
22
- class ReviewCensus:
23
- rules: dict[str, tuple[str, ...]]
24
- cells: dict[str, ReviewCell]
25
- references: dict[str, str]
26
-
27
-
28
- def _table_fields(line: str) -> list[str]:
29
- # Markdown writes a literal pipe inside a table cell as `\|`.
30
- fields = re.split(r"(?<!\\)\|", line.strip().strip("|"))
31
- return [field.strip().replace("\\|", "|") for field in fields]
32
-
33
-
34
- def read_review_census(path: Path) -> ReviewCensus:
35
- rules: dict[str, list[str]] = {}
36
- cells: dict[str, ReviewCell] = {}
37
- rule_ids: set[str] = set()
38
- pairs: set[tuple[str, str]] = set()
39
- references: set[tuple[str, str]] = set()
40
- rule_references: dict[str, str] = {}
41
- section = ""
42
- for line in path.read_text(encoding="utf-8").splitlines():
43
- if line.startswith("## "):
44
- section = line.strip()
45
- if section not in ("## Rules", "## Cells") or not line.strip().startswith("|"):
46
- continue
47
- fields = _table_fields(line)
48
- header = fields[0] in ("Rule", "Cell")
49
- if header or all(re.fullmatch(r"[-:]+", f) for f in fields):
50
- continue
51
- if len(fields) != 3 or not all(fields):
52
- raise ValueError("malformed grouped census row")
53
- identity, value, reference = fields
54
- if section == "## Rules":
55
- if not re.fullmatch(r"[A-Z][A-Z0-9]*", identity) or identity in rule_ids:
56
- raise ValueError("invalid or duplicate rule ID")
57
- if (value, reference) in references:
58
- raise ValueError("duplicate group and rule reference")
59
- if value not in ("structural", "semantic", "state-and-tests", "general"):
60
- raise ValueError("unknown rule group")
61
- rule_ids.add(identity)
62
- references.add((value, reference))
63
- rule_references[identity] = reference
64
- rules.setdefault(value, []).append(identity)
65
- else:
66
- if not re.fullmatch(r"C-CR-[0-9]+", identity) or identity in cells:
67
- raise ValueError("invalid or duplicate cell ID")
68
- if (value, reference) in pairs:
69
- raise ValueError("duplicate target and group")
70
- target = PurePosixPath(value.partition(":")[0])
71
- if target.is_absolute() or ".." in target.parts:
72
- raise ValueError("target must be project-relative")
73
- pairs.add((value, reference))
74
- cells[identity] = ReviewCell(value, reference)
75
- if not rules or not cells:
76
- raise ValueError("census needs Rules and Cells tables")
77
- if any(cell.group not in rules for cell in cells.values()):
78
- raise ValueError("cell names an unknown rule group")
79
- return ReviewCensus(
80
- {group: tuple(ids) for group, ids in rules.items()}, cells, rule_references,
81
- )
82
-
83
-
84
- def _keyed_values(text: str) -> dict[str, str]:
85
- values: dict[str, str] = {}
86
- if text == "-":
87
- return values
88
- # Reviewers write prose reasons; only a semicolon before the next `RULE=` separates assignments.
89
- for entry in re.split(r";(?=\s*[A-Z][A-Z0-9]*=)", text):
90
- key, separator, value = entry.partition("=")
91
- key, value = key.strip(), value.strip()
92
- if not separator or not key or not value or key in values:
93
- raise ValueError(f"empty or duplicate rule assignment: {entry.strip()!r}")
94
- values[key] = value
95
- return values
96
-
97
-
98
- @dataclass
99
- class _HeadTree:
100
- """리뷰 대상 커밋이 담은 파일.
101
-
102
- 프로젝트 루트에는 다른 커밋이 체크아웃돼 있을 수 있다.
103
- """
104
-
105
- root: Path
106
- commit: str
107
- line_counts: dict[str, int] = field(default_factory=dict)
108
- base: _HeadTree | None = None
109
-
110
- def line_count(self, path: str) -> int:
111
- if path not in self.line_counts:
112
- self.line_counts[path] = self._read_line_count(path)
113
- return self.line_counts[path]
114
-
115
- def _git(self, *args: str) -> subprocess.CompletedProcess[bytes]:
116
- return subprocess.run(
117
- ["git", "--literal-pathspecs", "-C", str(self.root), *args],
118
- capture_output=True, check=False,
119
- )
120
-
121
- def _read_line_count(self, path: str) -> int:
122
- listing = self._git("ls-tree", "-z", self.commit, "--", path)
123
- if listing.returncode != 0:
124
- raise ValueError("cannot list the head commit")
125
- entries = [entry for entry in listing.stdout.split(b"\0") if entry]
126
- named = (entry.partition(b"\t") for entry in entries)
127
- matched = [
128
- meta.split() for meta, _, name in named
129
- if name.decode("utf-8", "surrogateescape") == path
130
- ]
131
- if not matched:
132
- raise ValueError("source evidence file does not exist at head")
133
- mode, kind, blob = matched[0]
134
- if kind != b"blob" or mode == b"120000":
135
- raise ValueError("source evidence is not a regular file at head")
136
- content = self._git("cat-file", "blob", blob.decode())
137
- if content.returncode != 0:
138
- raise ValueError("cannot read source evidence at head")
139
- return len(content.stdout.decode("utf-8").splitlines())
140
-
141
-
142
- def _head_tree(project_root: Path, head: str) -> _HeadTree:
143
- resolved = subprocess.run(
144
- ["git", "-C", str(project_root), "rev-parse", "--verify", "--quiet",
145
- "--end-of-options", f"{head}^{{commit}}"],
146
- capture_output=True, text=True, check=False,
147
- )
148
- if resolved.returncode != 0:
149
- raise ValueError(f"--head {head!r} is not a commit in {project_root}")
150
- return _HeadTree(project_root, resolved.stdout.strip())
151
-
152
-
153
- def _source_evidence(tree: _HeadTree, cell: ReviewCell, evidence: str) -> str:
154
- source = evidence.strip("`")
155
- if source.startswith("base:"):
156
- if tree.base is None:
157
- raise ValueError("base-side evidence requires --base")
158
- tree = tree.base
159
- source = source.removeprefix("base:")
160
- match = re.fullmatch(r"(.+?):(0|[1-9][0-9]*)`?(?: — .+)?", source)
161
- target = cell.target.partition(":")[0]
162
- if match is None or match[1] != target:
163
- raise ValueError("evidence must cite the target source path:line")
164
- relative = PurePosixPath(target)
165
- if relative.is_absolute() or ".." in relative.parts:
166
- raise ValueError("source evidence escapes project")
167
- count = tree.line_count(target)
168
- if int(match[2]) > count or (int(match[2]) == 0 and count != 0):
169
- raise ValueError("source evidence line does not exist at head")
170
- return evidence
171
-
172
-
173
- def _checked_rule_evidence(
174
- tree: _HeadTree, cell: ReviewCell, checked: Sequence[str], text: str,
175
- ) -> str:
176
- anchor, _, raw = text.partition(" :: ")
177
- _source_evidence(tree, cell, anchor)
178
- observations = _keyed_values(raw.strip() or "-")
179
- required = set(checked) & {"G2", "G3", "G5"} if cell.group == "general" else set()
180
- missing = required - observations.keys()
181
- if missing:
182
- raise ValueError("missing clean check evidence: " + ", ".join(sorted(missing)))
183
- if observations.keys() - set(checked):
184
- raise ValueError("clean check evidence names an unchecked rule")
185
- for observation in observations.values():
186
- match = re.fullmatch(r"(`?.+?:(?:0|[1-9][0-9]*)`?) (.+)", observation)
187
- if match is None:
188
- raise ValueError("clean check evidence needs source path:line and an observation")
189
- if re.fullmatch(r"(?:checked|clean|no issues?|none|n/?a)", match[2], re.I):
190
- raise ValueError("clean check evidence needs an observation, not a verdict label")
191
- citation = match[1].strip("`")
192
- source_cell = ReviewCell(citation.removeprefix("base:").partition(":")[0], cell.group)
193
- _source_evidence(tree, source_cell, citation)
194
- return text
195
-
196
-
197
- def _group_verdict(
198
- fields: Sequence[str], expected: Sequence[str], cell: ReviewCell,
199
- tree: _HeadTree, references: Sequence[str],
200
- ) -> tuple[str, str]:
201
- if len(fields) != 5:
202
- raise ValueError("expected Cell, Checked, N/A, Findings, Evidence columns")
203
- checked = [] if fields[1] == "-" else [rule.strip() for rule in fields[1].split(",")]
204
- excluded = _keyed_values(fields[2])
205
- findings = _keyed_values(fields[3])
206
- assigned = checked + list(excluded) + list(findings)
207
- if len(set(assigned)) != len(assigned):
208
- raise ValueError("duplicate or conflicting rule verdicts")
209
- unknown = set(assigned) - set(expected)
210
- if unknown:
211
- raise ValueError("unknown rules: " + ", ".join(sorted(unknown)))
212
- missing = set(expected) - set(assigned)
213
- if missing:
214
- raise ValueError("unchecked rules: " + ", ".join(sorted(missing)))
215
- for reason in excluded.values():
216
- if re.fullmatch(r"(?:[A-Z][0-9]+|[a-z]+:[0-9]+)", reason):
217
- raise ValueError("n/a needs an inline applicability reason, not an alias")
218
- for ids in findings.values():
219
- for item in ids.split(","):
220
- item = item.strip()
221
- if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", item):
222
- raise ValueError("invalid finding ID")
223
- if not any(id_occurs_wordbounded(body, item) for body in references):
224
- raise ValueError(f"finding {item} has no finding body")
225
- evidence = _checked_rule_evidence(tree, cell, checked, fields[4])
226
- if findings:
227
- return "finding", "; ".join(findings.values())
228
- if checked:
229
- return "clean", evidence
230
- return "n/a", "; ".join(excluded.values())
231
-
232
-
233
- def _group_results(
234
- body: str, census: ReviewCensus, tree: _HeadTree, references: Sequence[str],
235
- ) -> CellVerdicts:
236
- section, _ = split_coverage_verdict_section(body)
237
- verdicts: dict[str, tuple[str, str]] = {}
238
- reasons: dict[str, str] = {}
239
- seen: set[str] = set()
240
- unknown: list[str] = []
241
- for line in section:
242
- if not line.strip().startswith("|"):
243
- continue
244
- fields = _table_fields(line)
245
- identity = fields[0]
246
- if identity not in census.cells:
247
- if identity.startswith("C-") and identity not in unknown:
248
- unknown.append(identity)
249
- continue
250
- if identity in seen:
251
- verdicts.pop(identity, None)
252
- reasons[identity] = "duplicate cell row"
253
- continue
254
- seen.add(identity)
255
- cell = census.cells[identity]
256
- try:
257
- verdicts[identity] = _group_verdict(
258
- fields, census.rules[cell.group], cell, tree, references,
259
- )
260
- except (OSError, ValueError) as exc:
261
- reasons[identity] = str(exc)
262
- return CellVerdicts(
263
- verdicts,
264
- {key: reasons.get(key, "no grouped verdict row") for key in census.cells if key not in verdicts},
265
- tuple(unknown),
266
- )
9
+ from .review_verdicts import read_review_census, _head_tree, parse_review_verdicts
267
10
 
268
11
 
269
12
  def check_review_coverage(
@@ -297,17 +40,4 @@ def check_review_coverage(
297
40
  if heads and heads != [tree.commit]:
298
41
  raise ValueError("completion review head differs from --head")
299
42
  bodies.append(verified.returned_body)
300
- verdicts: dict[str, tuple[str, str]] = {}
301
- missing: dict[str, str] = {}
302
- unknown: list[str] = []
303
- references = [split_coverage_verdict_section(body)[1] for body in bodies]
304
- for body in bodies:
305
- parsed = _group_results(body, census, tree, references)
306
- unknown.extend(key for key in parsed.unknown if key not in unknown)
307
- for key, verdict in parsed.verdicts.items():
308
- verdicts.setdefault(key, verdict)
309
- missing.update(parsed.missing)
310
- return CellVerdicts(
311
- verdicts, {key: missing[key] for key in census.cells if key not in verdicts},
312
- tuple(unknown),
313
- )
43
+ return parse_review_verdicts(project_root, census, bodies, tree.commit, base=base)
@@ -0,0 +1,154 @@
1
+ """Immutable source/Git integrity evidence for standalone review completions."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import replace
5
+ from pathlib import Path
6
+ from typing import Any, Mapping
7
+
8
+ from .execution_mutation_audit import ExecutionMutationAudit, MutationSnapshot
9
+ from .json_boundary import load_owned_object_snapshot
10
+ from .qa_procedures import content_digest, safe_qa_path
11
+ from .standalone_review_audit import compare_standalone_review
12
+ from .verification_inputs import publish_verification_snapshot
13
+ from .write_policy import WritePolicy, build_standalone_review_write_contract
14
+
15
+
16
+ def capture_review_source(
17
+ project_root: Path, prompt_path: Path, metadata_path: Path,
18
+ metadata: Mapping[str, Any],
19
+ ) -> tuple[str, str]:
20
+ path = _review_path(project_root, metadata_path, metadata, ".review-source.json")
21
+ expected = _review_path(project_root, metadata_path, metadata, ".prompt.md")
22
+ if prompt_path.resolve() != expected.resolve():
23
+ raise ValueError("review source prompt does not match its invocation")
24
+ if path.exists():
25
+ _, digest = _read_baseline(project_root, path, None)
26
+ return path.relative_to(project_root.resolve()).as_posix(), digest
27
+ policy = _source_only_policy(project_root, metadata_path, metadata)
28
+ before = ExecutionMutationAudit().snapshot(
29
+ (policy,), orchestrator_paths=(path.parent,),
30
+ )
31
+ digest = _publish(project_root, path, before.to_payload(), "review source baseline")
32
+ return path.relative_to(project_root.resolve()).as_posix(), digest
33
+
34
+
35
+ def finalize_review_integrity(
36
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any],
37
+ baseline_path: str, baseline_digest: str,
38
+ ) -> str:
39
+ path = _review_path(project_root, metadata_path, metadata, ".review-audit.json")
40
+ before, _ = _bound_baseline(project_root, metadata_path, metadata,
41
+ baseline_path, baseline_digest)
42
+ policy = _source_only_policy(project_root, metadata_path, metadata)
43
+ if before.policy_digests != (policy.digest,):
44
+ raise ValueError("review source baseline policy differs from the invocation")
45
+ _require_completed_runner(project_root, metadata_path, metadata)
46
+ result = compare_standalone_review(before, policy, succeeded=True)
47
+ if result.status != "ok" or result.violations:
48
+ cause = "; ".join(result.violations) or result.status
49
+ raise ValueError("review source integrity failed: " + cause)
50
+ payload = {"schemaVersion": 1, "invocationId": metadata["invocationId"],
51
+ "sourceBaselinePath": baseline_path, "sourceBaselineDigest": baseline_digest,
52
+ "policyDigest": policy.digest, "writeAudit": result.change_summary()}
53
+ return _publish(project_root, path, payload, "review integrity audit")
54
+
55
+
56
+ def verify_review_integrity(
57
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any],
58
+ baseline_path: str, baseline_digest: str, audit_digest: str,
59
+ ) -> None:
60
+ before, _ = _bound_baseline(project_root, metadata_path, metadata,
61
+ baseline_path, baseline_digest)
62
+ path = _review_path(project_root, metadata_path, metadata, ".review-audit.json")
63
+ stored = load_owned_object_snapshot(path, artifact="review integrity audit")
64
+ if content_digest(stored.raw_bytes) != audit_digest:
65
+ raise ValueError("review integrity audit digest differs from completion")
66
+ audit = stored.value
67
+ if (set(audit) != {"schemaVersion", "invocationId", "sourceBaselinePath",
68
+ "sourceBaselineDigest", "policyDigest", "writeAudit"}
69
+ or audit["schemaVersion"] != 1 or audit["invocationId"] != metadata["invocationId"]
70
+ or audit["sourceBaselinePath"] != baseline_path
71
+ or audit["sourceBaselineDigest"] != baseline_digest
72
+ or before.policy_digests != (audit["policyDigest"],)):
73
+ raise ValueError("review integrity audit baseline binding differs")
74
+ summary = audit["writeAudit"]
75
+ if (not isinstance(summary, dict) or summary.get("mutationStatus") != "ok"
76
+ or summary.get("sourceChanged") is not False or summary.get("gitChanged") is not False
77
+ or summary.get("violations") != [] or summary.get("beforeDigest") != before.digest):
78
+ raise ValueError("review integrity audit is not a successful source check")
79
+
80
+
81
+ def _source_only_policy(
82
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any],
83
+ ) -> WritePolicy:
84
+ prompt = _review_path(project_root, metadata_path, metadata, ".prompt.md")
85
+ policy, _ = build_standalone_review_write_contract(
86
+ project_root, prompt, metadata_path, metadata,
87
+ )
88
+ return replace(policy, artifact_policy={
89
+ "allowedRoot": policy.artifact_policy["allowedRoot"], "allowedPaths": [],
90
+ })
91
+
92
+
93
+ def _bound_baseline(
94
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any],
95
+ relative: str, digest: str,
96
+ ) -> tuple[MutationSnapshot, str]:
97
+ path = _review_path(project_root, metadata_path, metadata, ".review-source.json")
98
+ if (not isinstance(digest, str)
99
+ or relative != path.relative_to(project_root.resolve()).as_posix()):
100
+ raise ValueError("review source baseline is not canonical")
101
+ return _read_baseline(project_root, path, digest)
102
+
103
+
104
+ def _read_baseline(
105
+ project_root: Path, path: Path, expected_digest: str | None,
106
+ ) -> tuple[MutationSnapshot, str]:
107
+ stored = load_owned_object_snapshot(path, artifact="review source baseline")
108
+ digest = content_digest(stored.raw_bytes)
109
+ if expected_digest is not None and digest != expected_digest:
110
+ raise ValueError("review source baseline digest differs from the invocation")
111
+ before = MutationSnapshot.from_payload(stored.value)
112
+ if before.root != project_root.resolve() or before.artifact_root != project_root.resolve():
113
+ raise ValueError("review source baseline belongs to another project")
114
+ return before, digest
115
+
116
+
117
+ def _review_path(
118
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any], suffix: str,
119
+ ) -> Path:
120
+ identity = metadata.get("invocationId")
121
+ if (metadata.get("audience") != "code-reviewer" or not isinstance(identity, str)
122
+ or metadata_path.name != identity + ".prompt.md.meta.json"):
123
+ raise ValueError("review integrity requires a canonical code-review invocation")
124
+ prefix = ".okstra/agent-invocations/code-review/" + identity
125
+ expected = safe_qa_path(project_root, prefix + ".prompt.md.meta.json")
126
+ if metadata_path.resolve() != expected.resolve():
127
+ raise ValueError("review metadata is not canonical")
128
+ return safe_qa_path(project_root, prefix + suffix)
129
+
130
+
131
+ def _require_completed_runner(
132
+ project_root: Path, metadata_path: Path, metadata: Mapping[str, Any],
133
+ ) -> None:
134
+ runner = metadata["modelAssignment"]["runner"]
135
+ if runner == "native-session":
136
+ return
137
+ if runner != "cli-wrapper":
138
+ raise ValueError("review integrity does not recognize the runner")
139
+ path = _review_path(project_root, metadata_path, metadata, ".prompt.md.status.json")
140
+ status = load_owned_object_snapshot(path, artifact="review worker status").value
141
+ summary = status.get("writeAudit")
142
+ if (status.get("standaloneInvocationId") != metadata["invocationId"]
143
+ or status.get("stage") != "exited" or type(status.get("exit_code")) is not int
144
+ or status["exit_code"] != 0 or not isinstance(summary, dict)
145
+ or summary.get("mutationStatus") != "ok" or summary.get("violations") != []):
146
+ raise ValueError("review worker has no successful write audit")
147
+
148
+
149
+ def _publish(project_root: Path, path: Path, payload: dict, artifact: str) -> str:
150
+ _, digest = publish_verification_snapshot(
151
+ project_root.resolve(), path, capture=lambda: payload, artifact=artifact,
152
+ schema={"type": "object"}, validate_cross_fields=lambda _: [], comparison_key=dict,
153
+ )
154
+ return digest
@@ -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
+ )