okstra 0.227.0 → 0.228.1

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 (76) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/docs/architecture/storage-model.md +77 -0
  5. package/docs/cli.md +15 -3
  6. package/docs/project-structure-overview.md +12 -2
  7. package/package.json +1 -1
  8. package/runtime/BUILD.json +2 -2
  9. package/runtime/prompts/coding-preflight/clean-code.md +24 -18
  10. package/runtime/prompts/coding-preflight/overview.md +6 -6
  11. package/runtime/prompts/duties/code-reviewer.json +1 -0
  12. package/runtime/prompts/lead/convergence.md +5 -19
  13. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  14. package/runtime/prompts/profiles/_coding-conventions-preflight.md +1 -1
  15. package/runtime/python/okstra_ctl/adapters/verification_inputs.py +22 -0
  16. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +2 -2
  17. package/runtime/python/okstra_ctl/analysis_packet.py +52 -21
  18. package/runtime/python/okstra_ctl/approval_decisions.py +30 -1
  19. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +100 -66
  20. package/runtime/python/okstra_ctl/brief_sources.py +162 -44
  21. package/runtime/python/okstra_ctl/code_review_coverage.py +11 -1
  22. package/runtime/python/okstra_ctl/code_review_scope.py +157 -0
  23. package/runtime/python/okstra_ctl/code_review_target.py +46 -10
  24. package/runtime/python/okstra_ctl/conformance.py +9 -3
  25. package/runtime/python/okstra_ctl/design_surfaces.py +51 -19
  26. package/runtime/python/okstra_ctl/final_report_schema.py +37 -30
  27. package/runtime/python/okstra_ctl/fixed_text.py +31 -9
  28. package/runtime/python/okstra_ctl/implementation_direction.py +18 -0
  29. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +59 -21
  30. package/runtime/python/okstra_ctl/json_registry.py +3 -18
  31. package/runtime/python/okstra_ctl/manager_split.py +201 -84
  32. package/runtime/python/okstra_ctl/model_io/references.py +31 -1
  33. package/runtime/python/okstra_ctl/model_io/renderers.py +30 -1
  34. package/runtime/python/okstra_ctl/model_io_cli.py +9 -0
  35. package/runtime/python/okstra_ctl/path_hints.py +13 -1
  36. package/runtime/python/okstra_ctl/paths.py +4 -0
  37. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +87 -45
  38. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +2 -2
  39. package/runtime/python/okstra_ctl/phases/final_verification/spec.md +10 -2
  40. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +19 -11
  41. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-executor.md +3 -1
  42. package/runtime/python/okstra_ctl/phases/implementation/instructions/_implementation-verifier.md +3 -1
  43. package/runtime/python/okstra_ctl/phases/implementation/spec.md +14 -0
  44. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +2 -1
  45. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +1 -1
  46. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +53 -37
  47. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +1 -1
  48. package/runtime/python/okstra_ctl/plan_items.py +9 -11
  49. package/runtime/python/okstra_ctl/ports/verification_inputs.py +17 -0
  50. package/runtime/python/okstra_ctl/prior_planning.py +6 -17
  51. package/runtime/python/okstra_ctl/prior_run_summary.py +35 -0
  52. package/runtime/python/okstra_ctl/qa_commands.py +66 -1
  53. package/runtime/python/okstra_ctl/qa_commands_cli.py +67 -0
  54. package/runtime/python/okstra_ctl/qa_procedures.py +235 -0
  55. package/runtime/python/okstra_ctl/registry/verification_inputs_store.py +8 -0
  56. package/runtime/python/okstra_ctl/render.py +10 -0
  57. package/runtime/python/okstra_ctl/report_assembly.py +12 -12
  58. package/runtime/python/okstra_ctl/run.py +108 -5
  59. package/runtime/python/okstra_ctl/verification_input_ref.py +80 -0
  60. package/runtime/python/okstra_ctl/verification_input_types.py +32 -0
  61. package/runtime/python/okstra_ctl/verification_inputs.py +162 -0
  62. package/runtime/python/okstra_ctl/verification_plan.py +116 -0
  63. package/runtime/python/okstra_ctl/worker_prompt_body.py +12 -6
  64. package/runtime/python/okstra_ctl/worker_prompt_contract.py +5 -1
  65. package/runtime/python/okstra_ctl/worker_prompt_headers.py +50 -1
  66. package/runtime/python/okstra_project/dirs.py +22 -0
  67. package/runtime/python/okstra_project/resolver.py +10 -0
  68. package/runtime/schemas/final-report-v3.0.schema.json +5 -1
  69. package/runtime/skills/okstra-brief-gen/SKILL.md +10 -4
  70. package/runtime/skills/okstra-code-review/SKILL.md +39 -45
  71. package/runtime/skills/okstra-code-review/references/census-rules.md +14 -2
  72. package/runtime/skills/okstra-code-review/references/review-calibration.md +31 -8
  73. package/runtime/skills/okstra-manager/SKILL.md +2 -2
  74. package/runtime/skills/okstra-setup/SKILL.md +2 -0
  75. package/runtime/skills/okstra-setup/references/project-config.md +2 -0
  76. package/runtime/validators/validate-brief.py +21 -5
@@ -10,20 +10,37 @@ task worktree 는 체크아웃이라 프로젝트 루트의 git 미추적 파일
10
10
  from __future__ import annotations
11
11
 
12
12
  import argparse
13
+ import bisect
13
14
  import datetime as dt
15
+ import itertools
16
+ import os
14
17
  import re
15
18
  import subprocess
16
19
  import sys
17
20
  from pathlib import Path
18
21
 
19
- from .analysis_packet import BY_REFERENCE_FORMAT, _fence_mask, _section_map, file_source_entries
22
+ from .analysis_packet import (
23
+ BY_REFERENCE_FORMAT,
24
+ MAX_CITED_DOCUMENT_BYTES,
25
+ _fence_mask,
26
+ _section_map,
27
+ exceeds_cited_document_limit,
28
+ file_source_entries,
29
+ project_relative_ref,
30
+ )
20
31
 
21
32
  SOURCE_MATERIAL = "Source Material"
22
33
  ATTACH_FETCHED_VIA = "okstra brief-sources attach"
23
34
  _HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
24
35
  _FRONTMATTER_RE = re.compile(r"\A---\n.*?\n---\n", re.DOTALL)
25
36
  _TOKEN_RE = re.compile(r"[^\s`'\"()\[\]<>{},;|*]+")
26
- _LINE_SUFFIX_RE = re.compile(r"(?::\d+(?:-\d+)?|#L\d+(?:-L?\d+)?)\Z")
37
+ # Inline code, a double-quoted string and a Markdown link target can hold a path with
38
+ # spaces. A link target needs no closing `)`: requiring one made every unclosed `](`
39
+ # rescan the rest of the line. Code and quotes keep their closers, so a stray `"`
40
+ # (an inch mark) does not swallow the span after it.
41
+ _SPAN_RE = re.compile(r"`([^`\n]+)`|\"([^\"\n]+)\"|\]\(<?([^)>\n]*)")
42
+ _FRAGMENT_RE = re.compile(r"[#?].*\Z")
43
+ _LINE_SUFFIX_RE = re.compile(r":\d+(?:-\d+)?\Z")
27
44
  _SOURCE_NUMBER_RE = re.compile(r"\A### Source (\d+)\b")
28
45
  # okstra 자신의 산출물(브리프, 그룹 맥락, 보고서)은 okstra 가 직접 운반한다.
29
46
  _OKSTRA_HOME = ".okstra"
@@ -38,19 +55,17 @@ def _body_lines(text: str) -> list[str]:
38
55
 
39
56
  def _project_file(token: str, root: Path) -> str | None:
40
57
  """토큰이 프로젝트 루트 아래 파일을 가리키면 루트 기준 posix 경로를 돌려준다."""
41
- if "/" not in token or "://" in token:
58
+ if "://" in token:
42
59
  return None
43
- token = _LINE_SUFFIX_RE.sub("", token.rstrip(".:"))
44
- candidate = Path(token).expanduser()
45
- path = (candidate if candidate.is_absolute() else root / candidate).resolve()
46
- try:
47
- relative = path.relative_to(root)
48
- except ValueError:
60
+ token = _LINE_SUFFIX_RE.sub("", _FRAGMENT_RE.sub("", token.strip().rstrip(".:")))
61
+ relative = project_relative_ref(token, root)
62
+ if relative is None:
49
63
  return None
50
- if (not relative.parts or relative.parts[0] == _OKSTRA_HOME
64
+ path = root / relative
65
+ if (relative == "." or Path(relative).parts[0] == _OKSTRA_HOME
51
66
  or path.suffix.lower() not in DOCUMENT_SUFFIXES or not path.is_file()):
52
67
  return None
53
- return relative.as_posix()
68
+ return relative
54
69
 
55
70
 
56
71
  def _cited_in_body(text: str, root: Path) -> list[str]:
@@ -58,46 +73,92 @@ def _cited_in_body(text: str, root: Path) -> list[str]:
58
73
  lines = _body_lines(text)
59
74
  section = ""
60
75
  for line, fenced in zip(lines, _fence_mask(lines)):
61
- if fenced:
62
- continue
63
- if line.startswith("## "):
76
+ # A fenced `## ` line is quoted text, not a section boundary; fenced
77
+ # commands still cite paths.
78
+ if not fenced and line.startswith("## "):
64
79
  section = line[3:].strip()
65
80
  continue
66
81
  if section == SOURCE_MATERIAL:
67
82
  continue
68
- for token in _TOKEN_RE.findall(line):
69
- if (relative := _project_file(token, root)) is not None:
70
- paths.setdefault(relative)
83
+ for relative in _line_citations(line, root):
84
+ paths.setdefault(relative)
71
85
  return list(paths)
72
86
 
73
87
 
88
+ def _line_citations(line: str, root: Path) -> list[str]:
89
+ """Project documents one body line cites, in order of appearance.
90
+
91
+ A word inside a span that names a document is part of that path, not a
92
+ citation of its own (`spaces.md` in `` `docs/spec with spaces.md` ``).
93
+ """
94
+ found: list[tuple[int, str]] = []
95
+ covered: list[tuple[int, int]] = []
96
+ for match in _SPAN_RE.finditer(line):
97
+ for group_index, group in enumerate(match.groups(), 1):
98
+ if group and (relative := _project_file(group, root)) is not None:
99
+ found.append((match.start(group_index), relative))
100
+ covered.append((match.start(group_index), match.end(group_index)))
101
+ # Spans and tokens both come in line order, so one forward pointer finds the span
102
+ # that could cover each token.
103
+ span = 0
104
+ for match in _TOKEN_RE.finditer(line):
105
+ while span < len(covered) and covered[span][1] <= match.start():
106
+ span += 1
107
+ if span < len(covered) and covered[span][0] <= match.start():
108
+ continue
109
+ if (relative := _project_file(match.group(), root)) is not None:
110
+ found.append((match.start(), relative))
111
+ return [relative for _, relative in sorted(found)]
112
+
113
+
74
114
  def _sourced(text: str, root: Path) -> set[str]:
115
+ """Project files that Source Material file entries name, as prepare reads them."""
75
116
  source_material = _section_map(_HTML_COMMENT_RE.sub("", text)).get(SOURCE_MATERIAL, "")
76
117
  return {
77
118
  relative
78
119
  for ref, _ in file_source_entries(source_material)
79
- for token in _TOKEN_RE.findall(ref)
80
- if (relative := _project_file(token, root)) is not None
120
+ if (relative := project_relative_ref(ref, root)) is not None
81
121
  }
82
122
 
83
123
 
84
- def _git_tracked(root: Path, paths: list[str]) -> set[str] | None:
85
- """`paths` 중 git 이 추적하는 것. git 저장소가 아니면 None — worktree 가 없으니 검사할 것도 없다."""
86
- proc = subprocess.run(
87
- ["git", "-C", str(root), "ls-files", "-z", "--", *paths],
124
+ class GitQueryError(RuntimeError):
125
+ """git could not report which cited paths it tracks, inside a git work tree."""
126
+
127
+
128
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
129
+ # LC_ALL=C keeps the "not a git repository" message matchable in any locale.
130
+ return subprocess.run(
131
+ ["git", "-C", str(root), *args],
88
132
  capture_output=True,
89
133
  text=True,
90
134
  check=False,
135
+ env={**os.environ, "LC_ALL": "C"},
91
136
  )
92
- if proc.returncode != 0:
137
+
138
+
139
+ def _git_tracked(root: Path, paths: list[str]) -> set[str] | None:
140
+ """`paths` 중 git 이 추적하는 것. git 저장소가 아니면 None — worktree 가 없으니 검사할 것도 없다."""
141
+ inside = _git(root, "rev-parse", "--is-inside-work-tree")
142
+ if inside.returncode != 0:
143
+ if "not a git repository" in inside.stderr:
144
+ return None
145
+ raise GitQueryError(
146
+ f"git rev-parse --is-inside-work-tree in {root} failed: "
147
+ f"{inside.stderr.strip()}"
148
+ )
149
+ if inside.stdout.strip() != "true":
93
150
  return None
151
+ proc = _git(root, "ls-files", "-z", "--", *paths)
152
+ if proc.returncode != 0:
153
+ raise GitQueryError(f"git ls-files in {root} failed: {proc.stderr.strip()}")
94
154
  return {name for name in proc.stdout.split("\0") if name}
95
155
 
96
156
 
97
157
  def uncited_local_documents(text: str, project_root: Path) -> list[str]:
98
158
  """본문이 이름을 댄 git 미추적 프로젝트 파일 중 Source Material 의 file 항목이 없는 것."""
99
159
  root = project_root.resolve()
100
- cited = [path for path in _cited_in_body(text, root) if path not in _sourced(text, root)]
160
+ sourced = _sourced(text, root)
161
+ cited = [path for path in _cited_in_body(text, root) if path not in sourced]
101
162
  if not cited:
102
163
  return []
103
164
  tracked = _git_tracked(root, cited)
@@ -106,12 +167,26 @@ def uncited_local_documents(text: str, project_root: Path) -> list[str]:
106
167
  return [path for path in cited if path not in tracked]
107
168
 
108
169
 
109
- def _source_entry(index: int, ref: str, fetched_at: str) -> list[str]:
170
+ def too_large_to_cite(root: Path, relative: str) -> bool:
171
+ """Whether prepare refuses to copy this project file into the analysis packet."""
172
+ return exceeds_cited_document_limit((root / relative).stat().st_size)
173
+
174
+
175
+ TOO_LARGE_REASON = (
176
+ f"over {MAX_CITED_DOCUMENT_BYTES} bytes, which prepare does not copy into the "
177
+ "analysis packet; capture the cited part as-is in Source Material instead"
178
+ )
179
+
180
+
181
+ def by_reference_source_entry(
182
+ index: int, ref: str, fetched_via: str, fetched_at: str
183
+ ) -> list[str]:
184
+ """Lines of one `### Source N — file` entry that points at `ref`."""
110
185
  return [
111
186
  f"### Source {index} — file",
112
187
  "",
113
188
  f"- ref: {ref}",
114
- f"- fetched-via: {ATTACH_FETCHED_VIA}",
189
+ f"- fetched-via: {fetched_via}",
115
190
  f"- fetched-at: {fetched_at}",
116
191
  f"- format: {BY_REFERENCE_FORMAT}",
117
192
  "",
@@ -127,39 +202,82 @@ def attach_missing_sources(brief_path: Path, project_root: Path, *, now: dt.date
127
202
  missing = uncited_local_documents(text, project_root)
128
203
  if not missing:
129
204
  return []
205
+ root = project_root.resolve()
206
+ if large := [ref for ref in missing if too_large_to_cite(root, ref)]:
207
+ raise ValueError(f"{brief_path}: {', '.join(large)} {TOO_LARGE_REASON}")
130
208
  lines = text.split("\n")
131
- mask = _fence_mask(lines)
209
+ visible = _blank_html_comments(text).split("\n")
210
+ start, end = _source_material_bounds(visible, brief_path)
211
+ after = _insertion_line(text, visible, start, end)
212
+ first = _last_source_number(visible, start, end) + 1
213
+ entries = [""]
214
+ for number, ref in enumerate(missing, first):
215
+ entries.extend(by_reference_source_entry(
216
+ number, ref, ATTACH_FETCHED_VIA, now.strftime("%Y-%m-%d %H:%M")))
217
+ tail = lines[after + 1:]
218
+ if tail and not tail[0].strip():
219
+ entries.pop()
220
+ brief_path.write_text(
221
+ "\n".join([*lines[:after + 1], *entries, *tail]), encoding="utf-8"
222
+ )
223
+ return missing
224
+
225
+
226
+ def _blank_html_comments(text: str) -> str:
227
+ """`text` with comment characters replaced by spaces and its newlines kept.
228
+
229
+ Its lines align with the brief's, and its headings are the ones the
230
+ detector sees after it strips comments.
231
+ """
232
+ return _HTML_COMMENT_RE.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)
233
+
234
+
235
+ def _source_material_bounds(visible: list[str], brief_path: Path) -> tuple[int, int]:
236
+ """Lines of the `## Source Material` heading and the next `## ` heading (or EOF)."""
237
+ mask = _fence_mask(visible)
132
238
  start = next(
133
- (i for i, (line, fenced) in enumerate(zip(lines, mask))
239
+ (i for i, (line, fenced) in enumerate(zip(visible, mask))
134
240
  if not fenced and line.strip() == f"## {SOURCE_MATERIAL}"),
135
241
  None,
136
242
  )
137
243
  if start is None:
138
244
  raise ValueError(f"{brief_path}: no `## {SOURCE_MATERIAL}` section to attach to")
139
245
  end = next(
140
- (i for i in range(start + 1, len(lines)) if not mask[i] and lines[i].startswith("## ")),
141
- len(lines),
246
+ (i for i in range(start + 1, len(visible))
247
+ if not mask[i] and visible[i].startswith("## ")),
248
+ len(visible),
142
249
  )
250
+ return start, end
251
+
252
+
253
+ def _last_source_number(visible: list[str], start: int, end: int) -> int:
254
+ mask = _fence_mask(visible)
143
255
  numbers = [int(m.group(1)) for i in range(start + 1, end) if not mask[i]
144
- if (m := _SOURCE_NUMBER_RE.match(lines[i]))]
145
- while end > start + 1 and not lines[end - 1].strip():
146
- end -= 1
147
- stamp = now.strftime("%Y-%m-%d %H:%M")
148
- entries: list[str] = [""]
149
- for offset, ref in enumerate(missing, max(numbers, default=0) + 1):
150
- entries.extend(_source_entry(offset, ref, stamp))
151
- tail = lines[end:]
152
- while tail and not tail[0].strip():
153
- tail.pop(0)
154
- brief_path.write_text("\n".join([*lines[:end], *entries, *tail]), encoding="utf-8")
155
- return missing
256
+ if (m := _SOURCE_NUMBER_RE.match(visible[i]))]
257
+ return max(numbers, default=0)
258
+
259
+
260
+ def _insertion_line(text: str, visible: list[str], start: int, end: int) -> int:
261
+ """The section line after which new entries go.
262
+
263
+ It is the last line with visible text, or the line where a comment opened
264
+ on that line closes, so the entry neither enters the comment nor precedes
265
+ text the line still carries.
266
+ """
267
+ line = next((i for i in range(end - 1, start, -1) if visible[i].strip()), start)
268
+ offsets = itertools.accumulate(len(row) + 1 for row in visible)
269
+ newlines = [offset - 1 for offset in offsets]
270
+ for match in _HTML_COMMENT_RE.finditer(text):
271
+ if match.start() <= newlines[line] < match.end():
272
+ line = bisect.bisect_left(newlines, match.end() - 1)
273
+ return line
156
274
 
157
275
 
158
276
  def _attach_command(args: argparse.Namespace) -> int:
159
277
  brief = Path(args.brief).resolve()
160
278
  try:
161
279
  added = attach_missing_sources(brief, Path(args.project_root), now=dt.datetime.now())
162
- except ValueError as exc:
280
+ except (OSError, ValueError, GitQueryError) as exc:
163
281
  print(f"brief-sources: {exc}", file=sys.stderr)
164
282
  return 2
165
283
  if not added:
@@ -22,6 +22,7 @@ class ReviewCell:
22
22
  class ReviewCensus:
23
23
  rules: dict[str, tuple[str, ...]]
24
24
  cells: dict[str, ReviewCell]
25
+ references: dict[str, str]
25
26
 
26
27
 
27
28
  def _table_fields(line: str) -> list[str]:
@@ -34,6 +35,7 @@ def read_review_census(path: Path) -> ReviewCensus:
34
35
  rule_ids: set[str] = set()
35
36
  pairs: set[tuple[str, str]] = set()
36
37
  references: set[tuple[str, str]] = set()
38
+ rule_references: dict[str, str] = {}
37
39
  section = ""
38
40
  for line in path.read_text(encoding="utf-8").splitlines():
39
41
  if line.startswith("## "):
@@ -56,6 +58,7 @@ def read_review_census(path: Path) -> ReviewCensus:
56
58
  raise ValueError("unknown rule group")
57
59
  rule_ids.add(identity)
58
60
  references.add((value, reference))
61
+ rule_references[identity] = reference
59
62
  rules.setdefault(value, []).append(identity)
60
63
  else:
61
64
  if not re.fullmatch(r"C-CR-[0-9]+", identity) or identity in cells:
@@ -71,7 +74,9 @@ def read_review_census(path: Path) -> ReviewCensus:
71
74
  raise ValueError("census needs Rules and Cells tables")
72
75
  if any(cell.group not in rules for cell in cells.values()):
73
76
  raise ValueError("cell names an unknown rule group")
74
- 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
+ )
75
80
 
76
81
 
77
82
  def _keyed_values(text: str) -> dict[str, str]:
@@ -272,6 +277,11 @@ def check_review_coverage(
272
277
  if assignment is not None and current != assignment:
273
278
  raise AgentInvocationError("coverage cannot mix reviewer model assignments")
274
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")
275
285
  bodies.append(verified.returned_body)
276
286
  verdicts: dict[str, tuple[str, str]] = {}
277
287
  missing: dict[str, str] = {}
@@ -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
+ )
@@ -58,6 +58,16 @@ def _review_date(raw: str) -> str:
58
58
  return raw
59
59
 
60
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
+
61
71
  def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> dict:
62
72
  head = _git_out(repo, "rev-parse", branch)
63
73
  if not head:
@@ -66,12 +76,7 @@ def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> di
66
76
  raise StateError(
67
77
  "branch reviews require --base <branch-or-commit>", stage="args"
68
78
  )
69
- base_commit = _git_out(
70
- repo, "rev-parse", "--verify", "--quiet", "--end-of-options",
71
- f"{base}^{{commit}}",
72
- )
73
- if not base_commit:
74
- raise StateError(f"base {base!r} is not a commit", stage="base_missing")
79
+ base_commit = _resolve_base_commit(repo, base)
75
80
  review_path, seq = next_branch_review(branch_review_dir(repo, branch), review_date)
76
81
  return {
77
82
  "mode": "branch",
@@ -88,14 +93,15 @@ _CLI_EPILOG = r"""Usage:
88
93
  okstra code-review target --task-key <k> --stage <N> [--base <ref>] [--project-root <dir>] [--cwd <dir>] --json
89
94
  okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] --json
90
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> ...]
91
97
  okstra code-review check-lines --base <ref> --head <ref> --cite <path:line> [--cite ...] [--project-root <dir>]
92
98
 
93
99
  Output: JSON { ok, mode, worktreePath, branch, baseCommit, headCommit,
94
100
  reviewPath, round, reportLanguage }. `check-lines` prints `ok`, `not-changed`
95
101
  (with the file's changed lines) or `not-in-diff` per citation and exits 1 when
96
102
  any citation is not a line the range changed. `--base` sets the base in either mode. Without it, stage
97
- mode reads the base commit from the stage registry row. Branch mode requires
98
- an explicit base branch or commit and resolves it to a fixed commit. An empty
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
99
105
  worktreePath means the review reads the branch ref
100
106
  instead of a checked-out tree. This is read-only — it never creates
101
107
  directories or files. `check-coverage` reads each evidence file at `--head`, not
@@ -111,7 +117,7 @@ def _build_parser() -> argparse.ArgumentParser:
111
117
  prog="okstra code-review",
112
118
  description="Resolve a code review's diff range and result file path, or check finding citations."
113
119
  )
114
- parser.add_argument("command", choices=("target", "check-lines", "check-coverage"))
120
+ parser.add_argument("command", choices=("target", "check-lines", "check-coverage", "scope"))
115
121
  parser.add_argument("--task-key", default="", help="project-id:task-group:task-id")
116
122
  parser.add_argument("--stage", type=int, default=0, help="stage number to review")
117
123
  parser.add_argument("--branch", default="", help="branch to review")
@@ -131,6 +137,10 @@ def _build_parser() -> argparse.ArgumentParser:
131
137
  parser.add_argument("--census", default="", help="check-coverage: shared Rules and grouped Cells tables")
132
138
  parser.add_argument("--completion", action="append", default=[],
133
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)")
134
144
  parser.add_argument("--date", default="", help="YYYY-MM-DD for branch result naming")
135
145
  parser.add_argument("--project-root", default="", help="explicit project root")
136
146
  parser.add_argument("--cwd", default=".", help="cwd for project root resolution")
@@ -311,6 +321,8 @@ def main(argv: list[str] | None = None) -> int:
311
321
  print(render_code_review_target_text(payload) if args.text else json.dumps(payload))
312
322
  return 2
313
323
 
324
+ if args.command == "scope":
325
+ return _scope(args, Path(project_root))
314
326
  if args.command == "check-coverage":
315
327
  return _check_coverage(args, Path(project_root))
316
328
  if args.command == "check-lines":
@@ -340,6 +352,28 @@ def main(argv: list[str] | None = None) -> int:
340
352
  return 0
341
353
 
342
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
+
343
377
  # ---- stage 모드 해소 -------------------------------------------------------
344
378
  # 모듈 도크스트링이 "stage 규칙은 code_review_target_snapshot 이 소유한다" 고
345
379
  # 적어 두었지만 실제 함수는 okstra_project.state 에 있었고, 거기서 okstra_ctl 을
@@ -388,9 +422,11 @@ def code_review_target_snapshot(
388
422
  coords = (identity["projectId"], identity["taskGroup"], identity["taskId"])
389
423
  stage_row = worktree_registry.get_stage_row(*coords, stage) or {}
390
424
  worktree_view = _stage_worktree_view(project_root, stage_row, stage)
391
- 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(
392
426
  identity, stages, selected
393
427
  )
428
+ git_root = Path(worktree_view["worktreePath"] or project_root)
429
+ base_commit = _resolve_base_commit(git_root, base_ref)
394
430
  review_path, round_no = code_review_paths.next_stage_review(
395
431
  code_review_paths.stage_review_dir(
396
432
  project_root, identity["taskGroup"], identity["taskId"]
@@ -56,9 +56,15 @@ def normalize_conformance_script(
56
56
  호출부가 있다.
57
57
  """
58
58
  prefix = "<task_root>/"
59
- value = script[len(prefix):] if script.startswith(prefix) else script
60
- while value.startswith("./"):
61
- value = value[2:]
59
+ start = 0
60
+ while True:
61
+ if script.startswith(prefix, start):
62
+ start += len(prefix)
63
+ elif script.startswith("./", start):
64
+ start += 2
65
+ else:
66
+ break
67
+ value = script[start:]
62
68
  if task_root is not None and value.startswith(".okstra/"):
63
69
  for parent in task_root.resolve().parents:
64
70
  if parent.name == ".okstra" and task_root.resolve().is_relative_to(