okstra 0.231.0 → 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 (143) hide show
  1. package/README.md +15 -3
  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 +129 -2
  20. package/docs/architecture.md +11 -2
  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/lead/convergence.md +3 -3
  43. package/runtime/prompts/lead/okstra-lead-contract.md +2 -2
  44. package/runtime/prompts/lead/report-writer.md +1 -1
  45. package/runtime/prompts/lead/team-contract.md +1 -1
  46. package/runtime/prompts/profiles/_clarification-recommendation.md +3 -2
  47. package/runtime/prompts/profiles/_coding-conventions-preflight.md +41 -6
  48. package/runtime/python/okstra_ctl/agent/invocation.py +121 -36
  49. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +6 -0
  50. package/runtime/python/okstra_ctl/agent/prompt_cli/materialize.py +30 -4
  51. package/runtime/python/okstra_ctl/agent/standalone.py +3 -0
  52. package/runtime/python/okstra_ctl/analysis_packet.py +2 -19
  53. package/runtime/python/okstra_ctl/approval_decisions.py +16 -0
  54. package/runtime/python/okstra_ctl/attempt_evidence.py +10 -0
  55. package/runtime/python/okstra_ctl/business_flow/invocation.py +35 -3
  56. package/runtime/python/okstra_ctl/code_review_census.py +71 -7
  57. package/runtime/python/okstra_ctl/code_review_coverage.py +4 -274
  58. package/runtime/python/okstra_ctl/code_review_integrity.py +154 -0
  59. package/runtime/python/okstra_ctl/code_review_invocation.py +212 -0
  60. package/runtime/python/okstra_ctl/code_review_scope.py +36 -9
  61. package/runtime/python/okstra_ctl/code_review_target.py +85 -11
  62. package/runtime/python/okstra_ctl/consumers.py +12 -9
  63. package/runtime/python/okstra_ctl/convergence.py +112 -20
  64. package/runtime/python/okstra_ctl/convergence_engine.py +1 -0
  65. package/runtime/python/okstra_ctl/convergence_provenance.py +27 -11
  66. package/runtime/python/okstra_ctl/correction_round.py +6 -1
  67. package/runtime/python/okstra_ctl/design_review.py +207 -0
  68. package/runtime/python/okstra_ctl/design_review_evidence.py +297 -0
  69. package/runtime/python/okstra_ctl/dispatch_checkpoints.py +28 -5
  70. package/runtime/python/okstra_ctl/dispatch_core.py +3 -11
  71. package/runtime/python/okstra_ctl/doctor.py +8 -25
  72. package/runtime/python/okstra_ctl/doyouknow/__init__.py +9 -0
  73. package/runtime/python/okstra_ctl/doyouknow/cli.py +91 -0
  74. package/runtime/python/okstra_ctl/doyouknow/config.py +58 -0
  75. package/runtime/python/okstra_ctl/doyouknow/contracts.py +184 -0
  76. package/runtime/python/okstra_ctl/doyouknow/identity.py +22 -0
  77. package/runtime/python/okstra_ctl/doyouknow/paths.py +22 -0
  78. package/runtime/python/okstra_ctl/doyouknow/pending.py +72 -0
  79. package/runtime/python/okstra_ctl/doyouknow/registration.py +260 -0
  80. package/runtime/python/okstra_ctl/doyouknow/source_contracts.py +128 -0
  81. package/runtime/python/okstra_ctl/doyouknow/source_store.py +172 -0
  82. package/runtime/python/okstra_ctl/doyouknow/sources/io.py +36 -0
  83. package/runtime/python/okstra_ctl/doyouknow/sources/manager.py +261 -0
  84. package/runtime/python/okstra_ctl/doyouknow/sources/memory.py +179 -0
  85. package/runtime/python/okstra_ctl/doyouknow/sources/task.py +95 -0
  86. package/runtime/python/okstra_ctl/doyouknow/store.py +260 -0
  87. package/runtime/python/okstra_ctl/doyouknow/sync.py +58 -0
  88. package/runtime/python/okstra_ctl/execution_mutation_audit.py +18 -2
  89. package/runtime/python/okstra_ctl/file_size_cap.py +3 -4
  90. package/runtime/python/okstra_ctl/json_boundary.py +21 -2
  91. package/runtime/python/okstra_ctl/jsonl.py +21 -0
  92. package/runtime/python/okstra_ctl/manager_cli.py +26 -0
  93. package/runtime/python/okstra_ctl/manager_registration.py +29 -0
  94. package/runtime/python/okstra_ctl/manager_sync.py +3 -22
  95. package/runtime/python/okstra_ctl/model_io/renderers.py +13 -2
  96. package/runtime/python/okstra_ctl/model_io_cli.py +7 -1
  97. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +20 -0
  98. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +12 -2
  99. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-diff-review.md +19 -6
  100. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +5 -3
  101. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +39 -11
  102. package/runtime/python/okstra_ctl/phases/implementation/report_assets/implementation.template.html +13 -0
  103. package/runtime/python/okstra_ctl/phases/implementation/spec.md +26 -1
  104. package/runtime/python/okstra_ctl/phases/implementation/validation.py +86 -2
  105. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +4 -0
  106. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  107. package/runtime/python/okstra_ctl/report_assembly.py +15 -0
  108. package/runtime/python/okstra_ctl/report_narrative.py +3 -0
  109. package/runtime/python/okstra_ctl/report_prose_keys.py +7 -0
  110. package/runtime/python/okstra_ctl/report_synthesis_packet.py +19 -2
  111. package/runtime/python/okstra_ctl/review_policy.py +359 -0
  112. package/runtime/python/okstra_ctl/review_verdicts.py +291 -0
  113. package/runtime/python/okstra_ctl/run.py +24 -1
  114. package/runtime/python/okstra_ctl/stage_done.py +11 -0
  115. package/runtime/python/okstra_ctl/standalone_review_audit.py +28 -0
  116. package/runtime/python/okstra_ctl/team.py +3 -1
  117. package/runtime/python/okstra_ctl/verification_generation.py +23 -1
  118. package/runtime/python/okstra_ctl/verification_input_types.py +15 -1
  119. package/runtime/python/okstra_ctl/verification_inputs.py +28 -6
  120. package/runtime/python/okstra_ctl/verification_invocation.py +7 -1
  121. package/runtime/python/okstra_ctl/verification_target.py +2 -0
  122. package/runtime/python/okstra_ctl/worker_dispatch.py +3 -1
  123. package/runtime/python/okstra_ctl/worker_prompt_headers.py +24 -9
  124. package/runtime/python/okstra_ctl/worker_runner.py +66 -10
  125. package/runtime/python/okstra_ctl/wrapper_status.py +16 -0
  126. package/runtime/python/okstra_ctl/write_policy.py +34 -1
  127. package/runtime/python/okstra_project/__init__.py +2 -0
  128. package/runtime/python/okstra_project/dirs.py +18 -0
  129. package/runtime/python/okstra_project/state.py +25 -20
  130. package/runtime/schemas/doyouknow-config-v1.schema.json +20 -0
  131. package/runtime/schemas/doyouknow-v1.schema.json +65 -0
  132. package/runtime/schemas/final-report-v2.0.schema.json +157 -0
  133. package/runtime/schemas/final-report-v3.0.schema.json +157 -0
  134. package/runtime/schemas/memory-entry-contract-v1.json +11 -0
  135. package/runtime/schemas/record-secret-patterns.json +41 -0
  136. package/runtime/skills/okstra-code-review/SKILL.md +71 -123
  137. package/runtime/skills/okstra-code-review/references/census-rules.md +29 -105
  138. package/runtime/skills/okstra-code-review/references/review-calibration.md +34 -54
  139. package/runtime/skills/okstra-manager/SKILL.md +7 -0
  140. package/runtime/skills/okstra-memory/SKILL.md +7 -0
  141. package/runtime/templates/implementation-worker-preamble.md +4 -9
  142. package/runtime/templates/worker-prompt-preamble.md +4 -12
  143. package/runtime/validators/validate-run.py +17 -8
@@ -2,12 +2,14 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import ast
5
+ import json
5
6
  import re
6
7
  import subprocess
7
8
  from dataclasses import dataclass
8
9
  from pathlib import Path, PurePosixPath
10
+ from collections.abc import Mapping
9
11
 
10
- from .code_review_coverage import read_review_census
12
+ from .review_verdicts import read_review_census
11
13
 
12
14
  _GROUPS = ("structural", "semantic", "state-and-tests", "general")
13
15
  _FILE_GROUPS = {
@@ -20,7 +22,7 @@ _LOCKFILES = {
20
22
  "Cargo.lock", "uv.lock", "Gemfile.lock", "composer.lock",
21
23
  }
22
24
  _GENERATED_ROOTS = ("dist/", "runtime/", "build/")
23
- _DATA_SUFFIXES = {".json", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".csv"}
25
+ _DATA_SUFFIXES = {".csv"}
24
26
  _PROSE_SUFFIXES = {".md", ".markdown", ".rst", ".txt"}
25
27
  _UNPARSED_CODE_SUFFIXES = {
26
28
  ".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".tsx", ".jsx", ".sh", ".bash",
@@ -43,8 +45,9 @@ class CensusResult:
43
45
  def build_review_census(
44
46
  repo: Path, base: str, head: str, rules_source: Path,
45
47
  changed: dict[str, set[int]], *, previous: Path | None = None,
48
+ frozen_rules: str | None = None, inventory: Mapping[str, object] | None = None,
46
49
  ) -> CensusResult:
47
- rules = _rules_section(rules_source.read_text(encoding="utf-8"))
50
+ rules = _rules_section(rules_source) if frozen_rules is None else frozen_rules
48
51
  files = _changed_files(repo, base, head)
49
52
  cells: list[tuple[str, str]] = []
50
53
  exclusions: list[tuple[str, str]] = []
@@ -57,13 +60,23 @@ def build_review_census(
57
60
  continue
58
61
  kind = "test" if _TEST_PATH.search(path) else "source"
59
62
  cells.extend((path, group) for group in _FILE_GROUPS[kind])
60
- if kind == "test" or path not in changed:
63
+ if path not in changed:
61
64
  continue
62
65
  suffix = PurePosixPath(path).suffix
63
66
  if suffix == ".py":
64
67
  functions.extend(_changed_functions(repo, head, path, changed[path]))
65
68
  elif suffix in _UNPARSED_CODE_SUFFIXES:
66
- unresolved.append(path)
69
+ if inventory is None or path not in inventory:
70
+ unresolved.append(path)
71
+ else:
72
+ functions.extend(_supplement_functions(repo, head, path, changed[path],
73
+ inventory[path]))
74
+ if inventory is not None:
75
+ eligible = {path for path, _ in files if path in changed
76
+ and PurePosixPath(path).suffix in _UNPARSED_CODE_SUFFIXES
77
+ and _exclusion(path, False) is None}
78
+ if inventory.keys() - eligible:
79
+ raise ValueError("function inventory names files outside the unresolved census")
67
80
  cells.extend((target, "semantic") for target in functions)
68
81
  ordered = sorted(cells, key=lambda cell: _GROUPS.index(cell[1]))
69
82
  ids, retired, new = _assign_ids(ordered, previous)
@@ -72,7 +85,10 @@ def build_review_census(
72
85
  return CensusResult(text, tuple(unresolved))
73
86
 
74
87
 
75
- def _rules_section(text: str) -> str:
88
+ def _rules_section(source: Path) -> str:
89
+ text = source.read_text(encoding="utf-8")
90
+ if source.suffix == ".json":
91
+ return render_rule_catalog(text, source.parent)
76
92
  start = text.find("## Rules")
77
93
  if start < 0:
78
94
  raise ValueError("rules source has no ## Rules table")
@@ -80,6 +96,52 @@ def _rules_section(text: str) -> str:
80
96
  return text[start:] if end < 0 else text[start:end + 1]
81
97
 
82
98
 
99
+ def render_rule_catalog(text: str, parent: Path, *, include_architecture: bool = True) -> str:
100
+ catalog = json.loads(text)
101
+ if (not isinstance(catalog, dict) or catalog.get("schemaVersion") != "1.0"
102
+ or not isinstance(catalog.get("rules"), dict)):
103
+ raise ValueError("unsupported review rule catalog")
104
+ rows = ["## Rules", "| Rule | Group | Reference |", "|---|---|---|"]
105
+ for identity, definition in catalog["rules"].items():
106
+ if (not isinstance(definition, list) or len(definition) != 2
107
+ or not all(isinstance(value, str) for value in definition)):
108
+ raise ValueError(f"invalid review rule: {identity}")
109
+ group, reference = definition
110
+ if not include_architecture and identity in {"S5", "S6", "S7", "S8", "S9", "S10"}:
111
+ continue
112
+ path, _, heading = reference.partition("#")
113
+ rows.append(f"| {identity} | {group} | {parent / path}#{heading} |")
114
+ return "\n".join(rows)
115
+
116
+
117
+ def _supplement_functions(
118
+ repo: Path, head: str, path: str, lines: set[int], entry: object,
119
+ ) -> list[str]:
120
+ if (not isinstance(entry, dict) or set(entry) != {"functions", "rationale"}
121
+ or not isinstance(entry["rationale"], str) or not entry["rationale"].strip()
122
+ or not isinstance(entry["functions"], list)):
123
+ raise ValueError(f"function inventory needs functions and a completeness rationale: {path}")
124
+ source = subprocess.run(["git", "-C", str(repo), "show", f"{head}:{path}"],
125
+ capture_output=True, text=True, check=True).stdout.splitlines()
126
+ targets: list[str] = []
127
+ seen: set[tuple[int, int, str]] = set()
128
+ for row in entry["functions"]:
129
+ if not isinstance(row, dict) or set(row) != {"start", "end", "name"}:
130
+ raise ValueError(f"invalid function inventory row: {path}")
131
+ start, end, name = row["start"], row["end"], row["name"]
132
+ if (type(start) is not int or type(end) is not int
133
+ or not 1 <= start <= end <= len(source)
134
+ or not isinstance(name, str) or not re.fullmatch(r"[\w.$<>:-]+", name)):
135
+ raise ValueError(f"invalid function inventory span or name: {path}")
136
+ identity = (start, end, name)
137
+ if identity in seen:
138
+ raise ValueError(f"duplicate function inventory row: {path}")
139
+ seen.add(identity)
140
+ if lines.intersection(range(start, end + 1)):
141
+ targets.append(f"{path}:{start} {name}")
142
+ return targets
143
+
144
+
83
145
  def _changed_files(repo: Path, base: str, head: str) -> list[tuple[str, bool]]:
84
146
  listed = subprocess.run(
85
147
  ["git", "-C", str(repo), "diff", "--numstat", "-z", "-M", "--no-ext-diff",
@@ -111,8 +173,10 @@ def _exclusion(path: str, binary: bool) -> str | None:
111
173
  return "generated build output"
112
174
  if binary:
113
175
  return "binary file"
176
+ if name in ("AGENTS.md", "CLAUDE.md"):
177
+ return None
114
178
  if suffix in _DATA_SUFFIXES:
115
- return "configuration or data without executable project code"
179
+ return "data without executable project code"
116
180
  if suffix in _PROSE_SUFFIXES:
117
181
  return "prose documentation without executable or agent-directive content"
118
182
  return None
@@ -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