okstra 0.226.0 → 0.228.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 (103) hide show
  1. package/README.md +2 -1
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/wizard.mjs +12 -15
  5. package/dist/commands/execute/wizard.mjs.map +1 -1
  6. package/docs/architecture/storage-model.md +77 -0
  7. package/docs/cli.md +43 -7
  8. package/docs/project-structure-overview.md +13 -3
  9. package/package.json +1 -1
  10. package/runtime/BUILD.json +2 -2
  11. package/runtime/agents/operations/code-review.json +1 -1
  12. package/runtime/prompts/duties/code-reviewer.json +1 -0
  13. package/runtime/prompts/lead/convergence.md +5 -19
  14. package/runtime/prompts/lead/okstra-lead-contract.md +2 -2
  15. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  16. package/runtime/prompts/wizard/prompts.ko.json +44 -0
  17. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  18. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +63 -0
  19. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +3 -0
  20. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +5 -0
  21. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  22. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  23. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  24. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  25. package/runtime/python/okstra_ctl/code_review_coverage.py +81 -19
  26. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  27. package/runtime/python/okstra_ctl/code_review_target.py +115 -55
  28. package/runtime/python/okstra_ctl/conformance.py +9 -3
  29. package/runtime/python/okstra_ctl/correction_cli.py +6 -5
  30. package/runtime/python/okstra_ctl/correction_round.py +1 -1
  31. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  32. package/runtime/python/okstra_ctl/domain/worker_defaults.py +106 -0
  33. package/runtime/python/okstra_ctl/file_size_cap.py +56 -6
  34. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  35. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  36. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  37. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  38. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  39. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  40. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  41. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  42. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  43. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  44. package/runtime/python/okstra_ctl/paths.py +4 -0
  45. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  46. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  47. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  48. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  49. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-deliverable.md +2 -2
  50. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +4 -2
  51. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-self-check.md +1 -1
  52. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +5 -3
  53. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  54. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  55. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  56. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  57. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +22 -0
  58. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  59. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  60. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  61. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  62. package/runtime/python/okstra_ctl/ports/worker_defaults.py +25 -0
  63. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  64. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  65. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  66. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  67. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  68. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  69. package/runtime/python/okstra_ctl/registry/worker_defaults_store.py +8 -0
  70. package/runtime/python/okstra_ctl/render.py +10 -0
  71. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  72. package/runtime/python/okstra_ctl/run.py +123 -6
  73. package/runtime/python/okstra_ctl/stage_done.py +5 -4
  74. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  75. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  76. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  77. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  78. package/runtime/python/okstra_ctl/wizard/cli.py +16 -4
  79. package/runtime/python/okstra_ctl/wizard/confirmation.py +21 -0
  80. package/runtime/python/okstra_ctl/wizard/engine.py +25 -3
  81. package/runtime/python/okstra_ctl/wizard/ids.py +23 -0
  82. package/runtime/python/okstra_ctl/wizard/render.py +2 -2
  83. package/runtime/python/okstra_ctl/wizard/roles.py +73 -23
  84. package/runtime/python/okstra_ctl/wizard/state.py +55 -14
  85. package/runtime/python/okstra_ctl/wizard/steps_roles.py +5 -3
  86. package/runtime/python/okstra_ctl/wizard/worker_settings.py +334 -0
  87. package/runtime/python/okstra_ctl/worker_defaults.py +135 -0
  88. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  89. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  90. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  91. package/runtime/python/okstra_ctl/write_policy.py +33 -18
  92. package/runtime/python/okstra_project/dirs.py +22 -0
  93. package/runtime/python/okstra_project/resolver.py +10 -0
  94. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  95. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  96. package/runtime/skills/okstra-code-review/SKILL.md +59 -63
  97. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  98. package/runtime/skills/okstra-code-review/references/review-calibration.md +32 -9
  99. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  100. package/runtime/skills/okstra-run/SKILL.md +21 -1
  101. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  102. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  103. package/runtime/validators/validate-brief.py +21 -5
@@ -1,8 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
+ import subprocess
4
5
  from collections.abc import Sequence
5
- from dataclasses import dataclass
6
+ from dataclasses import dataclass, field
6
7
  from pathlib import Path, PurePosixPath
7
8
 
8
9
  from .agent.invocation import AgentInvocationError, verify_standalone_completion
@@ -21,6 +22,7 @@ class ReviewCell:
21
22
  class ReviewCensus:
22
23
  rules: dict[str, tuple[str, ...]]
23
24
  cells: dict[str, ReviewCell]
25
+ references: dict[str, str]
24
26
 
25
27
 
26
28
  def _table_fields(line: str) -> list[str]:
@@ -33,6 +35,7 @@ def read_review_census(path: Path) -> ReviewCensus:
33
35
  rule_ids: set[str] = set()
34
36
  pairs: set[tuple[str, str]] = set()
35
37
  references: set[tuple[str, str]] = set()
38
+ rule_references: dict[str, str] = {}
36
39
  section = ""
37
40
  for line in path.read_text(encoding="utf-8").splitlines():
38
41
  if line.startswith("## "):
@@ -55,6 +58,7 @@ def read_review_census(path: Path) -> ReviewCensus:
55
58
  raise ValueError("unknown rule group")
56
59
  rule_ids.add(identity)
57
60
  references.add((value, reference))
61
+ rule_references[identity] = reference
58
62
  rules.setdefault(value, []).append(identity)
59
63
  else:
60
64
  if not re.fullmatch(r"C-CR-[0-9]+", identity) or identity in cells:
@@ -70,7 +74,9 @@ def read_review_census(path: Path) -> ReviewCensus:
70
74
  raise ValueError("census needs Rules and Cells tables")
71
75
  if any(cell.group not in rules for cell in cells.values()):
72
76
  raise ValueError("cell names an unknown rule group")
73
- return ReviewCensus({group: tuple(ids) for group, ids in rules.items()}, cells)
77
+ return ReviewCensus(
78
+ {group: tuple(ids) for group, ids in rules.items()}, cells, rule_references,
79
+ )
74
80
 
75
81
 
76
82
  def _keyed_values(text: str) -> dict[str, str]:
@@ -86,28 +92,78 @@ def _keyed_values(text: str) -> dict[str, str]:
86
92
  return values
87
93
 
88
94
 
89
- def _source_evidence(project_root: Path, cell: ReviewCell, evidence: str) -> str:
95
+ @dataclass
96
+ class _HeadTree:
97
+ """리뷰 대상 커밋이 담은 파일.
98
+
99
+ 프로젝트 루트에는 다른 커밋이 체크아웃돼 있을 수 있다.
100
+ """
101
+
102
+ root: Path
103
+ commit: str
104
+ line_counts: dict[str, int] = field(default_factory=dict)
105
+
106
+ def line_count(self, path: str) -> int:
107
+ if path not in self.line_counts:
108
+ self.line_counts[path] = self._read_line_count(path)
109
+ return self.line_counts[path]
110
+
111
+ def _git(self, *args: str) -> subprocess.CompletedProcess[bytes]:
112
+ return subprocess.run(
113
+ ["git", "--literal-pathspecs", "-C", str(self.root), *args],
114
+ capture_output=True, check=False,
115
+ )
116
+
117
+ def _read_line_count(self, path: str) -> int:
118
+ listing = self._git("ls-tree", "-z", self.commit, "--", path)
119
+ if listing.returncode != 0:
120
+ raise ValueError("cannot list the head commit")
121
+ entries = [entry for entry in listing.stdout.split(b"\0") if entry]
122
+ named = (entry.partition(b"\t") for entry in entries)
123
+ matched = [
124
+ meta.split() for meta, _, name in named
125
+ if name.decode("utf-8", "surrogateescape") == path
126
+ ]
127
+ if not matched:
128
+ raise ValueError("source evidence file does not exist at head")
129
+ mode, kind, blob = matched[0]
130
+ if kind != b"blob" or mode == b"120000":
131
+ raise ValueError("source evidence is not a regular file at head")
132
+ content = self._git("cat-file", "blob", blob.decode())
133
+ if content.returncode != 0:
134
+ raise ValueError("cannot read source evidence at head")
135
+ return len(content.stdout.decode("utf-8").splitlines())
136
+
137
+
138
+ def _head_tree(project_root: Path, head: str) -> _HeadTree:
139
+ resolved = subprocess.run(
140
+ ["git", "-C", str(project_root), "rev-parse", "--verify", "--quiet",
141
+ "--end-of-options", f"{head}^{{commit}}"],
142
+ capture_output=True, text=True, check=False,
143
+ )
144
+ if resolved.returncode != 0:
145
+ raise ValueError(f"--head {head!r} is not a commit in {project_root}")
146
+ return _HeadTree(project_root, resolved.stdout.strip())
147
+
148
+
149
+ def _source_evidence(tree: _HeadTree, cell: ReviewCell, evidence: str) -> str:
90
150
  match = re.fullmatch(r"(.+?):([1-9][0-9]*)`?(?: — .+)?", evidence.strip("`"))
91
151
  target = cell.target.partition(":")[0]
92
152
  if match is None or match[1] != target:
93
153
  raise ValueError("evidence must cite the target source path:line")
94
154
  relative = PurePosixPath(target)
95
- source = (project_root / target).resolve()
96
- if (relative.is_absolute() or ".." in relative.parts
97
- or not source.is_relative_to(project_root.resolve())):
155
+ if relative.is_absolute() or ".." in relative.parts:
98
156
  raise ValueError("source evidence escapes project")
99
- if not source.is_file():
100
- raise ValueError("source evidence file does not exist")
101
- if int(match[2]) > len(source.read_text(encoding="utf-8").splitlines()):
102
- raise ValueError("source evidence line does not exist")
157
+ if int(match[2]) > tree.line_count(target):
158
+ raise ValueError("source evidence line does not exist at head")
103
159
  return evidence
104
160
 
105
161
 
106
162
  def _checked_rule_evidence(
107
- project_root: Path, cell: ReviewCell, checked: Sequence[str], text: str,
163
+ tree: _HeadTree, cell: ReviewCell, checked: Sequence[str], text: str,
108
164
  ) -> str:
109
165
  anchor, _, raw = text.partition(" :: ")
110
- _source_evidence(project_root, cell, anchor)
166
+ _source_evidence(tree, cell, anchor)
111
167
  observations = _keyed_values(raw.strip() or "-")
112
168
  required = set(checked) & {"G2", "G3", "G5"} if cell.group == "general" else set()
113
169
  missing = required - observations.keys()
@@ -123,13 +179,13 @@ def _checked_rule_evidence(
123
179
  raise ValueError("clean check evidence needs an observation, not a verdict label")
124
180
  citation = match[1].strip("`")
125
181
  source_cell = ReviewCell(citation.partition(":")[0], cell.group)
126
- _source_evidence(project_root, source_cell, citation)
182
+ _source_evidence(tree, source_cell, citation)
127
183
  return text
128
184
 
129
185
 
130
186
  def _group_verdict(
131
187
  fields: Sequence[str], expected: Sequence[str], cell: ReviewCell,
132
- project_root: Path, references: Sequence[str],
188
+ tree: _HeadTree, references: Sequence[str],
133
189
  ) -> tuple[str, str]:
134
190
  if len(fields) != 5:
135
191
  raise ValueError("expected Cell, Checked, N/A, Findings, Evidence columns")
@@ -155,7 +211,7 @@ def _group_verdict(
155
211
  raise ValueError("invalid finding ID")
156
212
  if not any(id_occurs_wordbounded(body, item) for body in references):
157
213
  raise ValueError(f"finding {item} has no finding body")
158
- evidence = _checked_rule_evidence(project_root, cell, checked, fields[4])
214
+ evidence = _checked_rule_evidence(tree, cell, checked, fields[4])
159
215
  if findings:
160
216
  return "finding", "; ".join(findings.values())
161
217
  if checked:
@@ -164,7 +220,7 @@ def _group_verdict(
164
220
 
165
221
 
166
222
  def _group_results(
167
- body: str, census: ReviewCensus, project_root: Path, references: Sequence[str],
223
+ body: str, census: ReviewCensus, tree: _HeadTree, references: Sequence[str],
168
224
  ) -> CellVerdicts:
169
225
  section, _ = split_coverage_verdict_section(body)
170
226
  verdicts: dict[str, tuple[str, str]] = {}
@@ -188,7 +244,7 @@ def _group_results(
188
244
  cell = census.cells[identity]
189
245
  try:
190
246
  verdicts[identity] = _group_verdict(
191
- fields, census.rules[cell.group], cell, project_root, references,
247
+ fields, census.rules[cell.group], cell, tree, references,
192
248
  )
193
249
  except (OSError, ValueError) as exc:
194
250
  reasons[identity] = str(exc)
@@ -200,9 +256,10 @@ def _group_results(
200
256
 
201
257
 
202
258
  def check_review_coverage(
203
- project_root: Path, census_path: Path, completions: Sequence[Path],
259
+ project_root: Path, census_path: Path, completions: Sequence[Path], head: str,
204
260
  ) -> CellVerdicts:
205
261
  census = read_review_census(census_path)
262
+ tree = _head_tree(project_root, head)
206
263
  if not completions or len(set(completions)) != len(completions):
207
264
  raise ValueError("pass distinct completion paths for one reviewer")
208
265
  bodies: list[str] = []
@@ -220,13 +277,18 @@ def check_review_coverage(
220
277
  if assignment is not None and current != assignment:
221
278
  raise AgentInvocationError("coverage cannot mix reviewer model assignments")
222
279
  assignment = current
280
+ heads = [line.removeprefix("Review head: ")
281
+ for line in verified.returned_body.splitlines()
282
+ if line.startswith("Review head: ")]
283
+ if heads and heads != [tree.commit]:
284
+ raise ValueError("completion review head differs from --head")
223
285
  bodies.append(verified.returned_body)
224
286
  verdicts: dict[str, tuple[str, str]] = {}
225
287
  missing: dict[str, str] = {}
226
288
  unknown: list[str] = []
227
289
  references = [split_coverage_verdict_section(body)[1] for body in bodies]
228
290
  for body in bodies:
229
- parsed = _group_results(body, census, project_root, references)
291
+ parsed = _group_results(body, census, tree, references)
230
292
  unknown.extend(key for key in parsed.unknown if key not in unknown)
231
293
  for key, verdict in parsed.verdicts.items():
232
294
  verdicts.setdefault(key, verdict)
@@ -0,0 +1,157 @@
1
+ """Conservative carry candidates; current reviewers still attest the impact boundary."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path, PurePosixPath
8
+
9
+ from .agent.invocation import verify_standalone_completion
10
+ from .fixed_text import scalar
11
+ from .code_review_coverage import (
12
+ ReviewCensus, _HeadTree, _head_tree, _table_fields, check_review_coverage,
13
+ read_review_census,
14
+ )
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class ReviewScope:
19
+ baseline: str
20
+ recheck: tuple[str, ...]
21
+ carry: tuple[str, ...]
22
+ reason: str
23
+
24
+ def render(self) -> str:
25
+ mode = "incremental" if self.carry else "full"
26
+ return (
27
+ f"Scope: {mode}\nReason: {scalar(self.reason)}\n{self.baseline}"
28
+ f"Recheck: {', '.join(self.recheck) or '-'}\n"
29
+ f"Carry candidates: {', '.join(self.carry) or '-'}\n"
30
+ )
31
+
32
+
33
+ def _rule_digest(census: ReviewCensus, policies: list[Path]) -> str:
34
+ digest = hashlib.sha256()
35
+ values = [repr(census.rules), repr(census.references)]
36
+ for reference in census.references.values():
37
+ for location in reference.split(";"):
38
+ name = re.sub(r":\d+(?:-\d+)?$", "", location.strip().partition("#")[0])
39
+ values.append(
40
+ hashlib.sha256(Path(name).expanduser().read_bytes()).hexdigest()
41
+ )
42
+ values.extend(hashlib.sha256(path.read_bytes()).hexdigest() for path in policies)
43
+ for value in values:
44
+ digest.update(value.encode() + b"\0")
45
+ return digest.hexdigest()
46
+
47
+
48
+ def _dependencies(body: str, census: ReviewCensus) -> dict[str, set[str]]:
49
+ dependencies: dict[str, set[str]] = {}
50
+ section = ""
51
+ for line in body.splitlines():
52
+ if line.startswith("## "):
53
+ section = line.strip()
54
+ if section != "## Review Dependencies" or not line.startswith("|"):
55
+ continue
56
+ fields = _table_fields(line)
57
+ if fields[0] == "Cell" or all(re.fullmatch(r"[-:]+", f) for f in fields):
58
+ continue
59
+ if len(fields) != 2 or fields[0] not in census.cells or fields[0] in dependencies:
60
+ raise ValueError("invalid or duplicate dependency cell")
61
+ paths = {part.strip() for part in fields[1].split(";")}
62
+ if any(not p or PurePosixPath(p).is_absolute() or ".." in PurePosixPath(p).parts
63
+ for p in paths):
64
+ raise ValueError("dependencies must be literal repository-relative paths")
65
+ dependencies[fields[0]] = paths
66
+ return dependencies
67
+
68
+
69
+ def _prior_inputs(
70
+ root: Path, completions: list[Path], census: ReviewCensus, baseline: str,
71
+ ) -> dict[str, set[str]]:
72
+ dependencies: dict[str, set[str]] = {}
73
+ for completion in completions:
74
+ body = verify_standalone_completion(
75
+ completion, project_root=root, expected_purpose="code-review",
76
+ ).returned_body
77
+ for line in baseline.splitlines():
78
+ if body.splitlines().count(line) != 1:
79
+ raise ValueError("previous baseline missing or different")
80
+ for cell, sources in _dependencies(body, census).items():
81
+ dependencies.setdefault(cell, set()).update(sources)
82
+ return dependencies
83
+
84
+
85
+ def review_scope(
86
+ root: Path, census_path: Path, base: str, head: str, policies: list[Path], *,
87
+ previous_head: str = "", previous_census: Path | None = None,
88
+ completions: list[Path] | None = None,
89
+ ) -> ReviewScope:
90
+ census = read_review_census(census_path)
91
+ current = _head_tree(root, head)
92
+ base_commit = _head_tree(root, base).commit
93
+ if current._git("merge-base", "--is-ancestor", base_commit, current.commit).returncode:
94
+ raise ValueError("review base is not an ancestor of head")
95
+ rules = _rule_digest(census, policies)
96
+ baseline = (
97
+ f"Review base: {base_commit}\nReview head: {current.commit}\n"
98
+ f"Review rules: {rules}\n"
99
+ )
100
+ def full(reason: str) -> ReviewScope:
101
+ return ReviewScope(baseline, tuple(census.cells), (), reason)
102
+
103
+ if not previous_head or previous_census is None or not completions:
104
+ return full("no complete previous review inputs")
105
+ prior = _head_tree(root, previous_head)
106
+ ancestry = current._git("merge-base", "--is-ancestor", prior.commit, current.commit)
107
+ if ancestry.returncode != 0:
108
+ return full("previous head is not an ancestor")
109
+ old = read_review_census(previous_census)
110
+ if old.rules != census.rules or old.references != census.references:
111
+ return full("rule catalog changed")
112
+ verdicts = check_review_coverage(root, previous_census, completions, prior.commit)
113
+ if verdicts.missing or verdicts.unknown:
114
+ return full("previous review coverage is incomplete")
115
+ try:
116
+ dependencies = _prior_inputs(
117
+ root, completions, old,
118
+ baseline.replace(f"Review head: {current.commit}", f"Review head: {prior.commit}"),
119
+ )
120
+ for sources in dependencies.values():
121
+ for source in sources:
122
+ prior.line_count(source)
123
+ except ValueError as exc:
124
+ return full(str(exc))
125
+ return _partition(current, prior.commit, census, old, verdicts.verdicts,
126
+ dependencies, baseline)
127
+
128
+
129
+ def _partition(
130
+ current: _HeadTree, previous: str, census: ReviewCensus, old: ReviewCensus,
131
+ verdicts: dict[str, tuple[str, str]], dependencies: dict[str, set[str]], baseline: str,
132
+ ) -> ReviewScope:
133
+ delta = current._git("diff", "--no-ext-diff", "--no-renames", "--name-only", "-z",
134
+ previous, current.commit, "--")
135
+ if delta.returncode != 0:
136
+ raise ValueError("cannot read review delta")
137
+ changed = {p.decode("utf-8", "surrogateescape") for p in delta.stdout.split(b"\0") if p}
138
+ known = set().union(*dependencies.values()) if dependencies else set()
139
+ unknown = changed - known
140
+ carry = []
141
+ for identity, cell in census.cells.items():
142
+ sources = dependencies.get(identity, set())
143
+ target = cell.target.partition(":")[0]
144
+ if (not unknown and old.cells.get(identity) == cell and target in sources
145
+ and not changed.intersection(sources)
146
+ and verdicts.get(identity, ("missing", ""))[0] in ("clean", "n/a")):
147
+ carry.append(identity)
148
+ reason = ("unmapped changed inputs: " + ", ".join(sorted(unknown))) if unknown else (
149
+ "review changed dependencies and prior findings; attest carry boundaries"
150
+ )
151
+ carry_ids = set(carry)
152
+ return ReviewScope(
153
+ baseline,
154
+ tuple(key for key in census.cells if key not in carry_ids),
155
+ tuple(carry),
156
+ reason,
157
+ )
@@ -2,14 +2,15 @@
2
2
 
3
3
  두 모드를 한 진입점에 모아 스킬이 base 커밋도, 리뷰 파일 경로도, 회차도 다시
4
4
  유도하지 않게 한다. stage 모드는 read side 에 그대로 위임하고, branch 모드만
5
- 여기서 해소한다 — caller 가 base 를 지정하지 않으면 기본 브랜치와의
6
- merge-base 를 쓴다. 이 모듈은 인자 검증과 JSON 정형화만 하고, 경로·회차 조립은
5
+ 여기서 해소한다 — branch 모드는 caller 가 명시적으로 지정한 기준을 쓴다.
6
+ 이 모듈은 인자 검증과 JSON 정형화만 하고, 경로·회차 조립은
7
7
  code_review_paths 가, stage 규칙은 code_review_target_snapshot 이 소유한다.
8
8
  """
9
9
  from __future__ import annotations
10
10
 
11
11
  import argparse
12
12
  import json
13
+ import os
13
14
  import re
14
15
  import subprocess
15
16
  import sys
@@ -30,8 +31,6 @@ from .stage_map import StageMapError, load_latest_plan_stage_map
30
31
  from .fixed_text import line, scalar
31
32
  from .report_language import ReportLanguageError, resolve_report_language
32
33
 
33
- DEFAULT_BRANCH_CANDIDATES = ("main", "master")
34
-
35
34
  _DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
36
35
 
37
36
 
@@ -45,29 +44,6 @@ def _git_out(repo: Path, *args: str) -> str:
45
44
  return result.stdout.strip() if result.returncode == 0 else ""
46
45
 
47
46
 
48
- def _default_branch_ref(repo: Path) -> str:
49
- """merge-base 를 잴 기준 ref — origin/HEAD 가 있으면 그것, 없으면 관례 이름."""
50
- remote_head = _git_out(repo, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD")
51
- if remote_head:
52
- return remote_head
53
- for candidate in DEFAULT_BRANCH_CANDIDATES:
54
- if _git_out(repo, "rev-parse", "--verify", "--quiet", candidate):
55
- return candidate
56
- return ""
57
-
58
-
59
- def _merge_base(repo: Path, branch: str) -> str:
60
- default_ref = _default_branch_ref(repo)
61
- merge_base = _git_out(repo, "merge-base", default_ref, branch) if default_ref else ""
62
- if not merge_base:
63
- raise StateError(
64
- f"no merge-base for {branch!r} against the default branch — "
65
- "pass --base explicitly",
66
- stage="base_unresolved",
67
- )
68
- return merge_base
69
-
70
-
71
47
  def _review_date(raw: str) -> str:
72
48
  """branch 결과 파일명에 쓸 날짜.
73
49
 
@@ -82,15 +58,29 @@ def _review_date(raw: str) -> str:
82
58
  return raw
83
59
 
84
60
 
61
+ def _resolve_base_commit(repo: Path, base: str) -> str:
62
+ base_commit = _git_out(
63
+ repo, "rev-parse", "--verify", "--quiet", "--end-of-options",
64
+ f"{base}^{{commit}}",
65
+ )
66
+ if not base_commit:
67
+ raise StateError(f"base {base!r} is not a commit", stage="base_missing")
68
+ return base_commit
69
+
70
+
85
71
  def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> dict:
86
72
  head = _git_out(repo, "rev-parse", branch)
87
73
  if not head:
88
74
  raise StateError(f"branch {branch!r} not found", stage="branch_missing")
89
- base_commit = base or _merge_base(repo, branch)
75
+ if not base:
76
+ raise StateError(
77
+ "branch reviews require --base <branch-or-commit>", stage="args"
78
+ )
79
+ base_commit = _resolve_base_commit(repo, base)
90
80
  review_path, seq = next_branch_review(branch_review_dir(repo, branch), review_date)
91
81
  return {
92
82
  "mode": "branch",
93
- "worktreePath": str(repo),
83
+ "worktreePath": "",
94
84
  "branch": branch,
95
85
  "baseCommit": base_commit,
96
86
  "headCommit": head,
@@ -101,19 +91,22 @@ def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> di
101
91
 
102
92
  _CLI_EPILOG = r"""Usage:
103
93
  okstra code-review target --task-key <k> --stage <N> [--base <ref>] [--project-root <dir>] [--cwd <dir>] --json
104
- okstra code-review target --branch <name> [--base <ref>] [--date <YYYY-MM-DD>] [--project-root <dir>] --json
105
- okstra code-review check-coverage --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
94
+ okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] --json
95
+ okstra code-review check-coverage --head <ref> --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
96
+ okstra code-review scope --base <ref> --head <ref> --census <path> --policy <path> [--previous-head <ref> --previous-census <path> --completion <path> ...]
106
97
  okstra code-review check-lines --base <ref> --head <ref> --cite <path:line> [--cite ...] [--project-root <dir>]
107
98
 
108
99
  Output: JSON { ok, mode, worktreePath, branch, baseCommit, headCommit,
109
100
  reviewPath, round, reportLanguage }. `check-lines` prints `ok`, `not-changed`
110
101
  (with the file's changed lines) or `not-in-diff` per citation and exits 1 when
111
102
  any citation is not a line the range changed. `--base` sets the base in either mode. Without it, stage
112
- mode reads the base commit from the stage registry row and branch mode falls
113
- back to the merge-base with the default branch. An empty worktreePath means the review reads the branch ref
103
+ mode selects the base from the stage registry row. Both modes resolve the
104
+ selected base to a fixed commit; branch mode requires an explicit base. An empty
105
+ worktreePath means the review reads the branch ref
114
106
  instead of a checked-out tree. This is read-only — it never creates
115
- directories or files. `check-coverage` prints covered cells, missing rules and unknown cells;
116
- it exits 1 for incomplete coverage and 2 for invalid input or completion evidence.
107
+ directories or files. `check-coverage` reads each evidence file at `--head`, not
108
+ the working tree, prints covered cells, missing rules and unknown cells, and exits
109
+ 1 for incomplete coverage and 2 for invalid input or completion evidence.
117
110
  """
118
111
 
119
112
 
@@ -124,15 +117,19 @@ def _build_parser() -> argparse.ArgumentParser:
124
117
  prog="okstra code-review",
125
118
  description="Resolve a code review's diff range and result file path, or check finding citations."
126
119
  )
127
- parser.add_argument("command", choices=("target", "check-lines", "check-coverage"))
120
+ parser.add_argument("command", choices=("target", "check-lines", "check-coverage", "scope"))
128
121
  parser.add_argument("--task-key", default="", help="project-id:task-group:task-id")
129
122
  parser.add_argument("--stage", type=int, default=0, help="stage number to review")
130
123
  parser.add_argument("--branch", default="", help="branch to review")
131
124
  parser.add_argument(
132
125
  "--base", default="",
133
- help="explicit base ref; overrides the stage registry base or the branch merge-base",
126
+ help=("required base branch or commit in branch mode; "
127
+ "overrides the stage registry base"),
128
+ )
129
+ parser.add_argument(
130
+ "--head", default="",
131
+ help="check-lines, check-coverage: head ref of the reviewed range",
134
132
  )
135
- parser.add_argument("--head", default="", help="check-lines: head ref of the reviewed range")
136
133
  parser.add_argument(
137
134
  "--cite", action="append", default=[],
138
135
  help="check-lines: a finding's `path:line` (repeatable)",
@@ -140,6 +137,10 @@ def _build_parser() -> argparse.ArgumentParser:
140
137
  parser.add_argument("--census", default="", help="check-coverage: shared Rules and grouped Cells tables")
141
138
  parser.add_argument("--completion", action="append", default=[],
142
139
  help="check-coverage: verified reviewer completion (repeat for gap-fills)")
140
+ parser.add_argument("--previous-head", default="", help="scope: previous reviewed commit")
141
+ parser.add_argument("--previous-census", default="", help="scope: previous full census")
142
+ parser.add_argument("--policy", action="append", default=[],
143
+ help="scope: policy/calibration source to fingerprint (repeatable)")
143
144
  parser.add_argument("--date", default="", help="YYYY-MM-DD for branch result naming")
144
145
  parser.add_argument("--project-root", default="", help="explicit project root")
145
146
  parser.add_argument("--cwd", default=".", help="cwd for project root resolution")
@@ -183,28 +184,59 @@ def render_code_review_target_text(payload: dict) -> str:
183
184
  return "".join(rows)
184
185
 
185
186
 
186
- _HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
187
+ _HUNK_RE = re.compile(
188
+ r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE,
189
+ )
187
190
 
188
191
 
189
192
  def changed_lines(repo: Path, base: str, head: str) -> dict[str, set[int]]:
190
193
  """Head-side line numbers each file's diff touched.
191
194
 
192
- A pure deletion changes no head line, so it anchors on the line before the
193
- cut — the line a reviewer quotes when it points at what was removed.
195
+ A deletion within a surviving file anchors on the line before the cut.
196
+ A deleted file has no head-side citation.
194
197
  """
195
- diff = _git_out(repo, "diff", "-U0", "--no-color", f"{base}..{head}")
198
+ options = (
199
+ "--no-ext-diff", "--no-color", "--submodule=short", "-M",
200
+ )
201
+ named = subprocess.run(
202
+ ["git", "-C", str(repo), "diff", "--name-status", "-z", *options,
203
+ f"{base}..{head}", "--"],
204
+ capture_output=True, check=False,
205
+ )
206
+ if named.returncode != 0:
207
+ raise StateError(
208
+ os.fsdecode(named.stderr).strip() or "cannot list changed paths",
209
+ stage="diff",
210
+ )
211
+ fields = iter(named.stdout.rstrip(b"\0").split(b"\0"))
196
212
  lines: dict[str, set[int]] = {}
197
- current: set[int] | None = None
198
- for row in diff.splitlines():
199
- if row.startswith("+++ "):
200
- path = row[4:]
201
- current = None if path == "/dev/null" else lines.setdefault(path[2:], set())
213
+ for status in fields:
214
+ if not status:
215
+ continue
216
+ paths = [os.fsdecode(next(fields))]
217
+ selection = [f"{base}..{head}", "--", f":(literal){paths[0]}"]
218
+ if status.startswith((b"R", b"C")):
219
+ paths.append(os.fsdecode(next(fields)))
220
+ selection = [f"{base}:{paths[0]}", f"{head}:{paths[1]}", "--"]
221
+ if status == b"D":
202
222
  continue
203
- match = _HUNK_RE.match(row)
204
- if match and current is not None:
205
- start = int(match[1])
206
- count = 1 if match[2] is None else int(match[2])
207
- current.update(range(start, start + count) if count else {max(start, 1)})
223
+ patch = subprocess.run(
224
+ ["git", "-C", str(repo), "diff", "-U0", *options, *selection],
225
+ capture_output=True, check=False,
226
+ )
227
+ if patch.returncode != 0:
228
+ raise StateError(os.fsdecode(patch.stderr).strip(), stage="diff")
229
+ touched = lines.setdefault(paths[-1], set())
230
+ for section in os.fsdecode(patch.stdout).split("\ndiff --git "):
231
+ header_lines = section.partition("\n@@ ")[0].split("\n")
232
+ if "+++ /dev/null" in header_lines:
233
+ continue
234
+ for match in _HUNK_RE.finditer(section):
235
+ start = int(match[1])
236
+ count = 1 if match[2] is None else int(match[2])
237
+ touched.update(
238
+ range(start, start + count) if count else {max(start, 1)}
239
+ )
208
240
  return lines
209
241
 
210
242
 
@@ -258,12 +290,14 @@ def _check_coverage(args: argparse.Namespace, project_root: Path) -> int:
258
290
  from .agent.invocation import AgentInvocationError
259
291
  from .code_review_coverage import check_review_coverage
260
292
 
261
- if not args.census or not args.completion:
262
- print("check-coverage: pass --census and at least one --completion", file=sys.stderr)
293
+ if not args.census or not args.head or not args.completion:
294
+ print("check-coverage: pass --census, --head and at least one --completion",
295
+ file=sys.stderr)
263
296
  return 2
264
297
  try:
265
298
  result = check_review_coverage(
266
299
  project_root, Path(args.census), [Path(path) for path in args.completion],
300
+ args.head,
267
301
  )
268
302
  except (OSError, ValueError, AgentInvocationError) as exc:
269
303
  print(f"check-coverage: {exc}", file=sys.stderr)
@@ -287,6 +321,8 @@ def main(argv: list[str] | None = None) -> int:
287
321
  print(render_code_review_target_text(payload) if args.text else json.dumps(payload))
288
322
  return 2
289
323
 
324
+ if args.command == "scope":
325
+ return _scope(args, Path(project_root))
290
326
  if args.command == "check-coverage":
291
327
  return _check_coverage(args, Path(project_root))
292
328
  if args.command == "check-lines":
@@ -316,6 +352,28 @@ def main(argv: list[str] | None = None) -> int:
316
352
  return 0
317
353
 
318
354
 
355
+ def _scope(args: argparse.Namespace, project_root: Path) -> int:
356
+ from .agent.invocation import AgentInvocationError
357
+ from .code_review_scope import review_scope
358
+
359
+ if not (args.base and args.head and args.census and args.policy):
360
+ print("scope: pass --base, --head, --census and --policy", file=sys.stderr)
361
+ return 2
362
+ try:
363
+ result = review_scope(
364
+ project_root, Path(args.census), args.base, args.head,
365
+ [Path(path).expanduser() for path in args.policy],
366
+ previous_head=args.previous_head,
367
+ previous_census=Path(args.previous_census) if args.previous_census else None,
368
+ completions=[Path(path) for path in args.completion],
369
+ )
370
+ except (OSError, ValueError, AgentInvocationError) as exc:
371
+ print(f"scope: {exc}", file=sys.stderr)
372
+ return 2
373
+ print(result.render(), end="")
374
+ return 0
375
+
376
+
319
377
  # ---- stage 모드 해소 -------------------------------------------------------
320
378
  # 모듈 도크스트링이 "stage 규칙은 code_review_target_snapshot 이 소유한다" 고
321
379
  # 적어 두었지만 실제 함수는 okstra_project.state 에 있었고, 거기서 okstra_ctl 을
@@ -364,9 +422,11 @@ def code_review_target_snapshot(
364
422
  coords = (identity["projectId"], identity["taskGroup"], identity["taskId"])
365
423
  stage_row = worktree_registry.get_stage_row(*coords, stage) or {}
366
424
  worktree_view = _stage_worktree_view(project_root, stage_row, stage)
367
- base_commit = base or stage_row.get("base_ref") or _legacy_stage_base_commit(
425
+ base_ref = base or stage_row.get("base_ref") or _legacy_stage_base_commit(
368
426
  identity, stages, selected
369
427
  )
428
+ git_root = Path(worktree_view["worktreePath"] or project_root)
429
+ base_commit = _resolve_base_commit(git_root, base_ref)
370
430
  review_path, round_no = code_review_paths.next_stage_review(
371
431
  code_review_paths.stage_review_dir(
372
432
  project_root, identity["taskGroup"], identity["taskId"]