okstra 0.225.1 → 0.227.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 (99) hide show
  1. package/README.md +1 -0
  2. package/dist/cli-registry.mjs +6 -0
  3. package/dist/cli-registry.mjs.map +1 -1
  4. package/dist/commands/execute/render-bundle.mjs +5 -0
  5. package/dist/commands/execute/render-bundle.mjs.map +1 -1
  6. package/dist/commands/execute/wizard.mjs +12 -15
  7. package/dist/commands/execute/wizard.mjs.map +1 -1
  8. package/docs/cli.md +46 -6
  9. package/docs/project-structure-overview.md +3 -1
  10. package/package.json +1 -1
  11. package/runtime/BUILD.json +2 -2
  12. package/runtime/agents/operations/code-review.json +1 -1
  13. package/runtime/bin/lib/okstra/cli.sh +5 -1
  14. package/runtime/bin/lib/okstra/globals.sh +1 -0
  15. package/runtime/bin/lib/okstra/usage.sh +3 -0
  16. package/runtime/bin/okstra.sh +2 -0
  17. package/runtime/prompts/duties/technical-verification-worker.json +2 -1
  18. package/runtime/prompts/lead/convergence.md +4 -1
  19. package/runtime/prompts/lead/okstra-lead-contract.md +1 -1
  20. package/runtime/prompts/lead/phase-routing.md +7 -3
  21. package/runtime/prompts/lead/team-contract.md +1 -1
  22. package/runtime/prompts/wizard/prompts.ko.json +59 -0
  23. package/runtime/python/okstra_ctl/adapters/providers/codex/adapter.py +5 -0
  24. package/runtime/python/okstra_ctl/adapters/worker_defaults.py +63 -0
  25. package/runtime/python/okstra_ctl/agent/prompt_cli/cli.py +3 -0
  26. package/runtime/python/okstra_ctl/agent/prompt_cli/corrections.py +5 -0
  27. package/runtime/python/okstra_ctl/analysis_packet.py +108 -2
  28. package/runtime/python/okstra_ctl/approved_plan_stage_extract.py +206 -0
  29. package/runtime/python/okstra_ctl/brief_sources.py +200 -0
  30. package/runtime/python/okstra_ctl/business_flow/store.py +15 -2
  31. package/runtime/python/okstra_ctl/cmux.py +18 -3
  32. package/runtime/python/okstra_ctl/code_review_coverage.py +70 -18
  33. package/runtime/python/okstra_ctl/code_review_target.py +77 -53
  34. package/runtime/python/okstra_ctl/convergence_critic_prompt.py +4 -1
  35. package/runtime/python/okstra_ctl/correction_cli.py +6 -5
  36. package/runtime/python/okstra_ctl/correction_round.py +1 -1
  37. package/runtime/python/okstra_ctl/design_surfaces.py +19 -7
  38. package/runtime/python/okstra_ctl/domain/worker_defaults.py +106 -0
  39. package/runtime/python/okstra_ctl/execution_mutation_audit.py +20 -18
  40. package/runtime/python/okstra_ctl/file_size_cap.py +56 -6
  41. package/runtime/python/okstra_ctl/implementation_direction.py +10 -0
  42. package/runtime/python/okstra_ctl/initial_prompt_materialization.py +41 -0
  43. package/runtime/python/okstra_ctl/manager_split.py +185 -27
  44. package/runtime/python/okstra_ctl/next_phase.py +3 -1
  45. package/runtime/python/okstra_ctl/phases/final_verification/prior_blockers.py +128 -0
  46. package/runtime/python/okstra_ctl/phases/final_verification/profile.md +8 -5
  47. package/runtime/python/okstra_ctl/phases/final_verification/report_assets/final-verification.template.html +1 -1
  48. package/runtime/python/okstra_ctl/phases/final_verification/validation.py +84 -0
  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 +2 -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 +2 -2
  53. package/runtime/python/okstra_ctl/phases/implementation_option_selection/authoring.py +13 -5
  54. package/runtime/python/okstra_ctl/phases/implementation_option_selection/boundary.json +1 -1
  55. package/runtime/python/okstra_ctl/phases/implementation_option_selection/entry.py +67 -0
  56. package/runtime/python/okstra_ctl/phases/implementation_option_selection/profile.md +4 -2
  57. package/runtime/python/okstra_ctl/phases/implementation_option_selection/report_assets/implementation-option-selection.template.html +2 -1
  58. package/runtime/python/okstra_ctl/phases/implementation_option_selection/validation.py +127 -18
  59. package/runtime/python/okstra_ctl/phases/implementation_planning/authoring.py +22 -0
  60. package/runtime/python/okstra_ctl/phases/implementation_planning/instructions/plan-body-verification.md +1 -1
  61. package/runtime/python/okstra_ctl/phases/implementation_planning/profile.md +2 -1
  62. package/runtime/python/okstra_ctl/phases/technical_verification/profile.md +2 -2
  63. package/runtime/python/okstra_ctl/ports/worker_defaults.py +25 -0
  64. package/runtime/python/okstra_ctl/registry/worker_defaults_store.py +8 -0
  65. package/runtime/python/okstra_ctl/report_assembly.py +23 -2
  66. package/runtime/python/okstra_ctl/report_views.py +2 -1
  67. package/runtime/python/okstra_ctl/run.py +61 -2
  68. package/runtime/python/okstra_ctl/run_context.py +13 -8
  69. package/runtime/python/okstra_ctl/stage_done.py +5 -4
  70. package/runtime/python/okstra_ctl/wizard/cli.py +16 -4
  71. package/runtime/python/okstra_ctl/wizard/confirmation.py +27 -0
  72. package/runtime/python/okstra_ctl/wizard/engine.py +25 -3
  73. package/runtime/python/okstra_ctl/wizard/ids.py +29 -0
  74. package/runtime/python/okstra_ctl/wizard/registry.py +21 -0
  75. package/runtime/python/okstra_ctl/wizard/render.py +6 -2
  76. package/runtime/python/okstra_ctl/wizard/roles.py +73 -23
  77. package/runtime/python/okstra_ctl/wizard/sources.py +33 -11
  78. package/runtime/python/okstra_ctl/wizard/state.py +59 -14
  79. package/runtime/python/okstra_ctl/wizard/steps_options.py +74 -9
  80. package/runtime/python/okstra_ctl/wizard/steps_roles.py +5 -3
  81. package/runtime/python/okstra_ctl/wizard/worker_settings.py +334 -0
  82. package/runtime/python/okstra_ctl/worker_defaults.py +135 -0
  83. package/runtime/python/okstra_ctl/worker_prompt_body.py +21 -1
  84. package/runtime/python/okstra_ctl/worker_prompt_headers.py +11 -4
  85. package/runtime/python/okstra_ctl/worker_prompt_policy.py +3 -0
  86. package/runtime/python/okstra_ctl/write_policy.py +33 -18
  87. package/runtime/schemas/final-report-v2.0.schema.json +74 -0
  88. package/runtime/schemas/final-report-v3.0.schema.json +99 -2
  89. package/runtime/skills/okstra-brief-gen/SKILL.md +26 -0
  90. package/runtime/skills/okstra-code-review/SKILL.md +25 -23
  91. package/runtime/skills/okstra-code-review/references/review-calibration.md +2 -2
  92. package/runtime/skills/okstra-manager/SKILL.md +15 -2
  93. package/runtime/skills/okstra-run/SKILL.md +21 -1
  94. package/runtime/templates/reports/brief.template.md +10 -1
  95. package/runtime/templates/reports/html/i18n/en.json +8 -0
  96. package/runtime/templates/reports/html/i18n/ko.json +8 -0
  97. package/runtime/templates/worker-prompt-preamble.md +1 -1
  98. package/runtime/validators/validate-brief.py +39 -1
  99. package/runtime/validators/validate-run.py +5 -0
@@ -0,0 +1,200 @@
1
+ """브리프 본문이 인용한 로컬 문서와 Source Material 항목을 맞춘다.
2
+
3
+ task worktree 는 체크아웃이라 프로젝트 루트의 git 미추적 파일(`.project-docs/` 스펙)이
4
+ 없다. prepare 는 Source Material 의 `### Source N — file` 항목만 읽어 패킷에 싣으므로
5
+ (`analysis_packet.cited_documents_block`), 본문에만 이름이 나온 미추적 문서는 워커에게
6
+ 닿지 않는다(fontradar dev-11562). `uncited_local_documents` 는 그런 경로를 찾고,
7
+ `validators/validate-brief.py` 가 이를 거절한다. `attach_missing_sources` 는 기존
8
+ 브리프에 빠진 항목을 `format: by-reference` 로 덧붙인다. 다른 줄은 바꾸지 않는다.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import datetime as dt
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ from .analysis_packet import BY_REFERENCE_FORMAT, _fence_mask, _section_map, file_source_entries
20
+
21
+ SOURCE_MATERIAL = "Source Material"
22
+ ATTACH_FETCHED_VIA = "okstra brief-sources attach"
23
+ _HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
24
+ _FRONTMATTER_RE = re.compile(r"\A---\n.*?\n---\n", re.DOTALL)
25
+ _TOKEN_RE = re.compile(r"[^\s`'\"()\[\]<>{},;|*]+")
26
+ _LINE_SUFFIX_RE = re.compile(r"(?::\d+(?:-\d+)?|#L\d+(?:-L?\d+)?)\Z")
27
+ _SOURCE_NUMBER_RE = re.compile(r"\A### Source (\d+)\b")
28
+ # okstra 자신의 산출물(브리프, 그룹 맥락, 보고서)은 okstra 가 직접 운반한다.
29
+ _OKSTRA_HOME = ".okstra"
30
+ # 문서만 본다. 미추적 코드 경로(`node_modules/` 타입 선언 등)는 설치로 다시 생기는 근거라
31
+ # 브리프의 출처 문서가 아니다.
32
+ DOCUMENT_SUFFIXES = frozenset({".md", ".markdown", ".txt", ".rst", ".adoc"})
33
+
34
+
35
+ def _body_lines(text: str) -> list[str]:
36
+ return _FRONTMATTER_RE.sub("", _HTML_COMMENT_RE.sub("", text), count=1).splitlines()
37
+
38
+
39
+ def _project_file(token: str, root: Path) -> str | None:
40
+ """토큰이 프로젝트 루트 아래 파일을 가리키면 루트 기준 posix 경로를 돌려준다."""
41
+ if "/" not in token or "://" in token:
42
+ 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:
49
+ return None
50
+ if (not relative.parts or relative.parts[0] == _OKSTRA_HOME
51
+ or path.suffix.lower() not in DOCUMENT_SUFFIXES or not path.is_file()):
52
+ return None
53
+ return relative.as_posix()
54
+
55
+
56
+ def _cited_in_body(text: str, root: Path) -> list[str]:
57
+ paths: dict[str, None] = {}
58
+ lines = _body_lines(text)
59
+ section = ""
60
+ for line, fenced in zip(lines, _fence_mask(lines)):
61
+ if fenced:
62
+ continue
63
+ if line.startswith("## "):
64
+ section = line[3:].strip()
65
+ continue
66
+ if section == SOURCE_MATERIAL:
67
+ continue
68
+ for token in _TOKEN_RE.findall(line):
69
+ if (relative := _project_file(token, root)) is not None:
70
+ paths.setdefault(relative)
71
+ return list(paths)
72
+
73
+
74
+ def _sourced(text: str, root: Path) -> set[str]:
75
+ source_material = _section_map(_HTML_COMMENT_RE.sub("", text)).get(SOURCE_MATERIAL, "")
76
+ return {
77
+ relative
78
+ 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
81
+ }
82
+
83
+
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],
88
+ capture_output=True,
89
+ text=True,
90
+ check=False,
91
+ )
92
+ if proc.returncode != 0:
93
+ return None
94
+ return {name for name in proc.stdout.split("\0") if name}
95
+
96
+
97
+ def uncited_local_documents(text: str, project_root: Path) -> list[str]:
98
+ """본문이 이름을 댄 git 미추적 프로젝트 파일 중 Source Material 의 file 항목이 없는 것."""
99
+ root = project_root.resolve()
100
+ cited = [path for path in _cited_in_body(text, root) if path not in _sourced(text, root)]
101
+ if not cited:
102
+ return []
103
+ tracked = _git_tracked(root, cited)
104
+ if tracked is None:
105
+ return []
106
+ return [path for path in cited if path not in tracked]
107
+
108
+
109
+ def _source_entry(index: int, ref: str, fetched_at: str) -> list[str]:
110
+ return [
111
+ f"### Source {index} — file",
112
+ "",
113
+ f"- ref: {ref}",
114
+ f"- fetched-via: {ATTACH_FETCHED_VIA}",
115
+ f"- fetched-at: {fetched_at}",
116
+ f"- format: {BY_REFERENCE_FORMAT}",
117
+ "",
118
+ "```",
119
+ "```",
120
+ "",
121
+ ]
122
+
123
+
124
+ def attach_missing_sources(brief_path: Path, project_root: Path, *, now: dt.datetime) -> list[str]:
125
+ """빠진 file 항목을 Source Material 끝에 덧붙이고 덧붙인 경로를 돌려준다."""
126
+ text = brief_path.read_text(encoding="utf-8")
127
+ missing = uncited_local_documents(text, project_root)
128
+ if not missing:
129
+ return []
130
+ lines = text.split("\n")
131
+ mask = _fence_mask(lines)
132
+ start = next(
133
+ (i for i, (line, fenced) in enumerate(zip(lines, mask))
134
+ if not fenced and line.strip() == f"## {SOURCE_MATERIAL}"),
135
+ None,
136
+ )
137
+ if start is None:
138
+ raise ValueError(f"{brief_path}: no `## {SOURCE_MATERIAL}` section to attach to")
139
+ end = next(
140
+ (i for i in range(start + 1, len(lines)) if not mask[i] and lines[i].startswith("## ")),
141
+ len(lines),
142
+ )
143
+ 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
156
+
157
+
158
+ def _attach_command(args: argparse.Namespace) -> int:
159
+ brief = Path(args.brief).resolve()
160
+ try:
161
+ added = attach_missing_sources(brief, Path(args.project_root), now=dt.datetime.now())
162
+ except ValueError as exc:
163
+ print(f"brief-sources: {exc}", file=sys.stderr)
164
+ return 2
165
+ if not added:
166
+ print(f"brief-sources: nothing to attach in {brief}")
167
+ return 0
168
+ print(f"brief-sources: attached {len(added)} Source Material entr{'y' if len(added) == 1 else 'ies'} to {brief}")
169
+ for path in added:
170
+ print(f" - {path} (format: {BY_REFERENCE_FORMAT})")
171
+ print("Every later prepare copies these files read-only into the analysis packet's `## Cited Local Documents`.")
172
+ return 0
173
+
174
+
175
+ def build_parser() -> argparse.ArgumentParser:
176
+ parser = argparse.ArgumentParser(
177
+ prog="okstra brief-sources",
178
+ description=(
179
+ "Give every untracked project file a brief's body cites its own "
180
+ "Source Material entry, so runs copy it into the analysis packet."
181
+ ),
182
+ )
183
+ sub = parser.add_subparsers(dest="command", required=True)
184
+ attach = sub.add_parser(
185
+ "attach",
186
+ help="append a by-reference `### Source N — file` entry for each cited untracked file; edits nothing else",
187
+ )
188
+ attach.add_argument("--project-root", required=True, help="project root that holds `.okstra/`")
189
+ attach.add_argument("--brief", required=True, help="brief markdown file to upgrade in place")
190
+ attach.set_defaults(func=_attach_command)
191
+ return parser
192
+
193
+
194
+ def main(argv: list[str] | None = None) -> int:
195
+ args = build_parser().parse_args(argv)
196
+ return args.func(args)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ sys.exit(main())
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import re
4
+ from collections import Counter
4
5
  from pathlib import Path
5
6
  from typing import Any, cast
6
7
 
@@ -27,6 +28,7 @@ from .contracts import (
27
28
  from .source import candidate_projects, capture_project
28
29
 
29
30
  CONFIRMED_LEVELS = frozenset({"static", "execution-verified"})
31
+ PACKET_CLAIM_LIMIT = 40
30
32
 
31
33
 
32
34
  def task_link_path(project_root: Path, task_key: str) -> Path:
@@ -355,17 +357,22 @@ def knowledge_packet(
355
357
  result = query_knowledge(project_root, question, source_root)
356
358
  except (OSError, BusinessFlowError, JsonBoundaryError) as exc:
357
359
  return f"## Shared Business Knowledge\n\nKnowledge unavailable: {exc}\n"
360
+ # 질문이 task-brief 전체라 토큰 매칭이 거의 모든 claim 을 고르므로, 선택 결과는
361
+ # 관련도 순위가 아니다. 이 프로젝트가 기록한 claim 을 앞세우고 나머지는 조회로 넘긴다.
362
+ own = str(project_root.resolve())
363
+ claims = sorted(result["claims"], key=lambda row: row["ownerRoot"] != own)
364
+ shown, omitted = claims[:PACKET_CLAIM_LIMIT], claims[PACKET_CLAIM_LIMIT:]
358
365
  lines = [
359
366
  "## Shared Business Knowledge",
360
367
  "",
361
368
  "Preserve level, freshness, conflict and provenance. Recheck historical facts before relying on them.",
362
369
  "",
363
370
  ]
364
- if not result["claims"]:
371
+ if not claims:
365
372
  lines.append(
366
373
  "No related stored claims were selected. Inspect source and use additional lookup when new business terms emerge."
367
374
  )
368
- for row in result["claims"]:
375
+ for row in shown:
369
376
  lines.extend(
370
377
  [
371
378
  f"- `{row['id']}`: {row['value']}",
@@ -377,6 +384,12 @@ def knowledge_packet(
377
384
  f" - Evidence: `{item['projectId']}:{item['path']}:{item['line']}`"
378
385
  for item in row["evidence"]
379
386
  )
387
+ if omitted:
388
+ counts = Counter(row["business"] for row in omitted)
389
+ lines.append(
390
+ f"- {len(omitted)} more selected claims are omitted; look them up by business: "
391
+ + ", ".join(f"`{name}` ({count})" for name, count in counts.most_common())
392
+ )
380
393
  lines.extend(f"- Knowledge read error: {error}" for error in result["errors"])
381
394
  lines.extend(
382
395
  [
@@ -12,6 +12,7 @@ import shlex
12
12
  import shutil
13
13
  import socket
14
14
  import subprocess
15
+ import time
15
16
  from dataclasses import dataclass
16
17
  from pathlib import Path
17
18
  from typing import Any, Collection, Mapping, Sequence
@@ -73,6 +74,13 @@ SOCKET_UNREACHABLE = "unreachable"
73
74
 
74
75
  SOCKET_PROBE_TIMEOUT_SECONDS = 2
75
76
 
77
+ # 막 분할한 창에 보낸 `respawn-pane` 이 답 없이 소켓이 닫히는 경우가 있다. 실측
78
+ # 2026-10-29, dev-11562 두 run: 탭 이름은 붙었는데 창에는 첫 로그인 셸만 남았다.
79
+ # 그 창은 워커를 시작하지 않았으므로 같은 명령을 다시 보내도 워커가 둘이 되지 않는다.
80
+ TRANSIENT_SOCKET_ERROR = "Socket closed before reply"
81
+ RESPAWN_ATTEMPTS = 3
82
+ RESPAWN_RETRY_DELAY_SECONDS = 0.5
83
+
76
84
  # cmux 가 돌려주는 식별자가 UUID 인지 ref 인지 가리는 자리. ref 는 번호가 다시
77
85
  # 매겨지므로 원장에 남길 수 없다.
78
86
  _UUID_PATTERN = re.compile(r"[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}")
@@ -851,9 +859,16 @@ def _exec_worker(surface_uuid: str, *, cwd: Path, command: Sequence[str]) -> Non
851
859
  line = worker_command_line(
852
860
  cwd=cwd, argv=command, path_value=shim_free_worker_path()
853
861
  )
854
- started = run_cmux(["respawn-pane", "--surface", surface_uuid, "--command", line])
855
- if started.returncode != 0:
856
- raise RuntimeError(started.stderr.strip() or "cmux could not start the worker")
862
+ for attempt in range(1, RESPAWN_ATTEMPTS + 1):
863
+ started = run_cmux(["respawn-pane", "--surface", surface_uuid, "--command", line])
864
+ if started.returncode == 0:
865
+ return
866
+ error = started.stderr.strip()
867
+ if TRANSIENT_SOCKET_ERROR not in error or attempt == RESPAWN_ATTEMPTS:
868
+ raise RuntimeError(
869
+ f"respawn-pane: {error or 'cmux could not start the worker'}"
870
+ )
871
+ time.sleep(RESPAWN_RETRY_DELAY_SECONDS)
857
872
 
858
873
 
859
874
  def _size_lead_pane(
@@ -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
@@ -86,28 +87,78 @@ def _keyed_values(text: str) -> dict[str, str]:
86
87
  return values
87
88
 
88
89
 
89
- def _source_evidence(project_root: Path, cell: ReviewCell, evidence: str) -> str:
90
+ @dataclass
91
+ class _HeadTree:
92
+ """리뷰 대상 커밋이 담은 파일.
93
+
94
+ 프로젝트 루트에는 다른 커밋이 체크아웃돼 있을 수 있다.
95
+ """
96
+
97
+ root: Path
98
+ commit: str
99
+ line_counts: dict[str, int] = field(default_factory=dict)
100
+
101
+ def line_count(self, path: str) -> int:
102
+ if path not in self.line_counts:
103
+ self.line_counts[path] = self._read_line_count(path)
104
+ return self.line_counts[path]
105
+
106
+ def _git(self, *args: str) -> subprocess.CompletedProcess[bytes]:
107
+ return subprocess.run(
108
+ ["git", "--literal-pathspecs", "-C", str(self.root), *args],
109
+ capture_output=True, check=False,
110
+ )
111
+
112
+ def _read_line_count(self, path: str) -> int:
113
+ listing = self._git("ls-tree", "-z", self.commit, "--", path)
114
+ if listing.returncode != 0:
115
+ raise ValueError("cannot list the head commit")
116
+ entries = [entry for entry in listing.stdout.split(b"\0") if entry]
117
+ named = (entry.partition(b"\t") for entry in entries)
118
+ matched = [
119
+ meta.split() for meta, _, name in named
120
+ if name.decode("utf-8", "surrogateescape") == path
121
+ ]
122
+ if not matched:
123
+ raise ValueError("source evidence file does not exist at head")
124
+ mode, kind, blob = matched[0]
125
+ if kind != b"blob" or mode == b"120000":
126
+ raise ValueError("source evidence is not a regular file at head")
127
+ content = self._git("cat-file", "blob", blob.decode())
128
+ if content.returncode != 0:
129
+ raise ValueError("cannot read source evidence at head")
130
+ return len(content.stdout.decode("utf-8").splitlines())
131
+
132
+
133
+ def _head_tree(project_root: Path, head: str) -> _HeadTree:
134
+ resolved = subprocess.run(
135
+ ["git", "-C", str(project_root), "rev-parse", "--verify", "--quiet",
136
+ "--end-of-options", f"{head}^{{commit}}"],
137
+ capture_output=True, text=True, check=False,
138
+ )
139
+ if resolved.returncode != 0:
140
+ raise ValueError(f"--head {head!r} is not a commit in {project_root}")
141
+ return _HeadTree(project_root, resolved.stdout.strip())
142
+
143
+
144
+ def _source_evidence(tree: _HeadTree, cell: ReviewCell, evidence: str) -> str:
90
145
  match = re.fullmatch(r"(.+?):([1-9][0-9]*)`?(?: — .+)?", evidence.strip("`"))
91
146
  target = cell.target.partition(":")[0]
92
147
  if match is None or match[1] != target:
93
148
  raise ValueError("evidence must cite the target source path:line")
94
149
  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())):
150
+ if relative.is_absolute() or ".." in relative.parts:
98
151
  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")
152
+ if int(match[2]) > tree.line_count(target):
153
+ raise ValueError("source evidence line does not exist at head")
103
154
  return evidence
104
155
 
105
156
 
106
157
  def _checked_rule_evidence(
107
- project_root: Path, cell: ReviewCell, checked: Sequence[str], text: str,
158
+ tree: _HeadTree, cell: ReviewCell, checked: Sequence[str], text: str,
108
159
  ) -> str:
109
160
  anchor, _, raw = text.partition(" :: ")
110
- _source_evidence(project_root, cell, anchor)
161
+ _source_evidence(tree, cell, anchor)
111
162
  observations = _keyed_values(raw.strip() or "-")
112
163
  required = set(checked) & {"G2", "G3", "G5"} if cell.group == "general" else set()
113
164
  missing = required - observations.keys()
@@ -123,13 +174,13 @@ def _checked_rule_evidence(
123
174
  raise ValueError("clean check evidence needs an observation, not a verdict label")
124
175
  citation = match[1].strip("`")
125
176
  source_cell = ReviewCell(citation.partition(":")[0], cell.group)
126
- _source_evidence(project_root, source_cell, citation)
177
+ _source_evidence(tree, source_cell, citation)
127
178
  return text
128
179
 
129
180
 
130
181
  def _group_verdict(
131
182
  fields: Sequence[str], expected: Sequence[str], cell: ReviewCell,
132
- project_root: Path, references: Sequence[str],
183
+ tree: _HeadTree, references: Sequence[str],
133
184
  ) -> tuple[str, str]:
134
185
  if len(fields) != 5:
135
186
  raise ValueError("expected Cell, Checked, N/A, Findings, Evidence columns")
@@ -155,7 +206,7 @@ def _group_verdict(
155
206
  raise ValueError("invalid finding ID")
156
207
  if not any(id_occurs_wordbounded(body, item) for body in references):
157
208
  raise ValueError(f"finding {item} has no finding body")
158
- evidence = _checked_rule_evidence(project_root, cell, checked, fields[4])
209
+ evidence = _checked_rule_evidence(tree, cell, checked, fields[4])
159
210
  if findings:
160
211
  return "finding", "; ".join(findings.values())
161
212
  if checked:
@@ -164,7 +215,7 @@ def _group_verdict(
164
215
 
165
216
 
166
217
  def _group_results(
167
- body: str, census: ReviewCensus, project_root: Path, references: Sequence[str],
218
+ body: str, census: ReviewCensus, tree: _HeadTree, references: Sequence[str],
168
219
  ) -> CellVerdicts:
169
220
  section, _ = split_coverage_verdict_section(body)
170
221
  verdicts: dict[str, tuple[str, str]] = {}
@@ -188,7 +239,7 @@ def _group_results(
188
239
  cell = census.cells[identity]
189
240
  try:
190
241
  verdicts[identity] = _group_verdict(
191
- fields, census.rules[cell.group], cell, project_root, references,
242
+ fields, census.rules[cell.group], cell, tree, references,
192
243
  )
193
244
  except (OSError, ValueError) as exc:
194
245
  reasons[identity] = str(exc)
@@ -200,9 +251,10 @@ def _group_results(
200
251
 
201
252
 
202
253
  def check_review_coverage(
203
- project_root: Path, census_path: Path, completions: Sequence[Path],
254
+ project_root: Path, census_path: Path, completions: Sequence[Path], head: str,
204
255
  ) -> CellVerdicts:
205
256
  census = read_review_census(census_path)
257
+ tree = _head_tree(project_root, head)
206
258
  if not completions or len(set(completions)) != len(completions):
207
259
  raise ValueError("pass distinct completion paths for one reviewer")
208
260
  bodies: list[str] = []
@@ -226,7 +278,7 @@ def check_review_coverage(
226
278
  unknown: list[str] = []
227
279
  references = [split_coverage_verdict_section(body)[1] for body in bodies]
228
280
  for body in bodies:
229
- parsed = _group_results(body, census, project_root, references)
281
+ parsed = _group_results(body, census, tree, references)
230
282
  unknown.extend(key for key in parsed.unknown if key not in unknown)
231
283
  for key, verdict in parsed.verdicts.items():
232
284
  verdicts.setdefault(key, verdict)
@@ -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
 
@@ -86,11 +62,20 @@ def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> di
86
62
  head = _git_out(repo, "rev-parse", branch)
87
63
  if not head:
88
64
  raise StateError(f"branch {branch!r} not found", stage="branch_missing")
89
- base_commit = base or _merge_base(repo, branch)
65
+ if not base:
66
+ raise StateError(
67
+ "branch reviews require --base <branch-or-commit>", stage="args"
68
+ )
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")
90
75
  review_path, seq = next_branch_review(branch_review_dir(repo, branch), review_date)
91
76
  return {
92
77
  "mode": "branch",
93
- "worktreePath": str(repo),
78
+ "worktreePath": "",
94
79
  "branch": branch,
95
80
  "baseCommit": base_commit,
96
81
  "headCommit": head,
@@ -101,19 +86,21 @@ def _branch_snapshot(repo: Path, branch: str, base: str, review_date: str) -> di
101
86
 
102
87
  _CLI_EPILOG = r"""Usage:
103
88
  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>]
89
+ okstra code-review target --branch <name> --base <ref> [--date <YYYY-MM-DD>] [--project-root <dir>] --json
90
+ okstra code-review check-coverage --head <ref> --census <table-path> --completion <completion-path> [--completion ...] [--project-root <dir>]
106
91
  okstra code-review check-lines --base <ref> --head <ref> --cite <path:line> [--cite ...] [--project-root <dir>]
107
92
 
108
93
  Output: JSON { ok, mode, worktreePath, branch, baseCommit, headCommit,
109
94
  reviewPath, round, reportLanguage }. `check-lines` prints `ok`, `not-changed`
110
95
  (with the file's changed lines) or `not-in-diff` per citation and exits 1 when
111
96
  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
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
99
+ worktreePath means the review reads the branch ref
114
100
  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.
101
+ directories or files. `check-coverage` reads each evidence file at `--head`, not
102
+ the working tree, prints covered cells, missing rules and unknown cells, and exits
103
+ 1 for incomplete coverage and 2 for invalid input or completion evidence.
117
104
  """
118
105
 
119
106
 
@@ -130,9 +117,13 @@ def _build_parser() -> argparse.ArgumentParser:
130
117
  parser.add_argument("--branch", default="", help="branch to review")
131
118
  parser.add_argument(
132
119
  "--base", default="",
133
- help="explicit base ref; overrides the stage registry base or the branch merge-base",
120
+ help=("required base branch or commit in branch mode; "
121
+ "overrides the stage registry base"),
122
+ )
123
+ parser.add_argument(
124
+ "--head", default="",
125
+ help="check-lines, check-coverage: head ref of the reviewed range",
134
126
  )
135
- parser.add_argument("--head", default="", help="check-lines: head ref of the reviewed range")
136
127
  parser.add_argument(
137
128
  "--cite", action="append", default=[],
138
129
  help="check-lines: a finding's `path:line` (repeatable)",
@@ -183,28 +174,59 @@ def render_code_review_target_text(payload: dict) -> str:
183
174
  return "".join(rows)
184
175
 
185
176
 
186
- _HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
177
+ _HUNK_RE = re.compile(
178
+ r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE,
179
+ )
187
180
 
188
181
 
189
182
  def changed_lines(repo: Path, base: str, head: str) -> dict[str, set[int]]:
190
183
  """Head-side line numbers each file's diff touched.
191
184
 
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.
185
+ A deletion within a surviving file anchors on the line before the cut.
186
+ A deleted file has no head-side citation.
194
187
  """
195
- diff = _git_out(repo, "diff", "-U0", "--no-color", f"{base}..{head}")
188
+ options = (
189
+ "--no-ext-diff", "--no-color", "--submodule=short", "-M",
190
+ )
191
+ named = subprocess.run(
192
+ ["git", "-C", str(repo), "diff", "--name-status", "-z", *options,
193
+ f"{base}..{head}", "--"],
194
+ capture_output=True, check=False,
195
+ )
196
+ if named.returncode != 0:
197
+ raise StateError(
198
+ os.fsdecode(named.stderr).strip() or "cannot list changed paths",
199
+ stage="diff",
200
+ )
201
+ fields = iter(named.stdout.rstrip(b"\0").split(b"\0"))
196
202
  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())
203
+ for status in fields:
204
+ if not status:
205
+ continue
206
+ paths = [os.fsdecode(next(fields))]
207
+ selection = [f"{base}..{head}", "--", f":(literal){paths[0]}"]
208
+ if status.startswith((b"R", b"C")):
209
+ paths.append(os.fsdecode(next(fields)))
210
+ selection = [f"{base}:{paths[0]}", f"{head}:{paths[1]}", "--"]
211
+ if status == b"D":
202
212
  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)})
213
+ patch = subprocess.run(
214
+ ["git", "-C", str(repo), "diff", "-U0", *options, *selection],
215
+ capture_output=True, check=False,
216
+ )
217
+ if patch.returncode != 0:
218
+ raise StateError(os.fsdecode(patch.stderr).strip(), stage="diff")
219
+ touched = lines.setdefault(paths[-1], set())
220
+ for section in os.fsdecode(patch.stdout).split("\ndiff --git "):
221
+ header_lines = section.partition("\n@@ ")[0].split("\n")
222
+ if "+++ /dev/null" in header_lines:
223
+ continue
224
+ for match in _HUNK_RE.finditer(section):
225
+ start = int(match[1])
226
+ count = 1 if match[2] is None else int(match[2])
227
+ touched.update(
228
+ range(start, start + count) if count else {max(start, 1)}
229
+ )
208
230
  return lines
209
231
 
210
232
 
@@ -258,12 +280,14 @@ def _check_coverage(args: argparse.Namespace, project_root: Path) -> int:
258
280
  from .agent.invocation import AgentInvocationError
259
281
  from .code_review_coverage import check_review_coverage
260
282
 
261
- if not args.census or not args.completion:
262
- print("check-coverage: pass --census and at least one --completion", file=sys.stderr)
283
+ if not args.census or not args.head or not args.completion:
284
+ print("check-coverage: pass --census, --head and at least one --completion",
285
+ file=sys.stderr)
263
286
  return 2
264
287
  try:
265
288
  result = check_review_coverage(
266
289
  project_root, Path(args.census), [Path(path) for path in args.completion],
290
+ args.head,
267
291
  )
268
292
  except (OSError, ValueError, AgentInvocationError) as exc:
269
293
  print(f"check-coverage: {exc}", file=sys.stderr)