@elvis1513/auto-coding-skill 4.2.6 → 4.2.8

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.
@@ -15,12 +15,17 @@ import io
15
15
  import json
16
16
  import os
17
17
  import posixpath
18
+ import queue
18
19
  import re
20
+ import shlex
19
21
  import shutil
20
22
  import signal
21
23
  import socket
24
+ import stat
22
25
  import subprocess
23
26
  import sys
27
+ import tempfile
28
+ import threading
24
29
  import time
25
30
  import tomllib
26
31
  import urllib.parse
@@ -48,8 +53,10 @@ _GENERATED_NOISE_PATTERNS = [
48
53
  ]
49
54
  _AGENT_CONTRACT_VERSION = 1
50
55
  _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
51
- _FOCUSED_REVIEW_TIMEOUT_SECONDS = 90
52
- _DEEP_REVIEW_TIMEOUT_SECONDS = 300
56
+ _FOCUSED_REVIEW_TIMEOUT_SECONDS = 150
57
+ _DEEP_REVIEW_TIMEOUT_SECONDS = 360
58
+ _REVIEW_STARTUP_TIMEOUT_SECONDS = 30.0
59
+ _REVIEW_RUNTIME_ATTEMPT_LIMIT = 2
53
60
  _REVIEW_RUNTIME_FIELDS = (
54
61
  "runtime_state",
55
62
  "runtime_started_at",
@@ -58,8 +65,19 @@ _REVIEW_RUNTIME_FIELDS = (
58
65
  "runtime_exit_code",
59
66
  "runtime_command_sha256",
60
67
  "runtime_receipt_path",
68
+ "runtime_event_log_path",
69
+ "runtime_receipt_sha256",
70
+ "runtime_event_log_sha256",
71
+ "runtime_result_sha256",
72
+ "runtime_attempt_count",
73
+ "runtime_failure_kind",
74
+ "runtime_override_path",
75
+ "runtime_override_sha256",
61
76
  )
62
77
  _REVIEW_OUTPUT_MAX_BYTES = 1024 * 1024
78
+ _REVIEW_DIFF_ARTIFACT_FORMAT = "git-binary-patch-v1"
79
+ _REVIEW_DIFF_ARTIFACT_MAX_BYTES = 64 * 1024 * 1024
80
+ _REVIEW_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
63
81
  _DEEP_REVIEW_CATEGORIES = {
64
82
  "api",
65
83
  "auth",
@@ -71,13 +89,78 @@ _DEEP_REVIEW_CATEGORIES = {
71
89
  }
72
90
 
73
91
 
74
- class _ReviewerRuntimeTimeout(RuntimeError):
92
+ class _ReviewerRuntimeFailure(RuntimeError):
93
+ """Base class for supervised Reviewer runtime failures with safe diagnostics."""
94
+
95
+ def __init__(self, message: str, diagnostics: Optional[dict] = None) -> None:
96
+ super().__init__(message)
97
+ self.diagnostics = diagnostics or {}
98
+ self.stdout = _text(self.diagnostics.get("stdout"))
99
+ self.stderr = _text(self.diagnostics.get("stderr"))
100
+
101
+
102
+ class _ReviewerRuntimeTimeout(_ReviewerRuntimeFailure):
75
103
  """Raised after the supervised Reviewer process group has been stopped."""
76
104
 
77
- def __init__(self, stdout: str = "", stderr: str = "") -> None:
78
- super().__init__("Reviewer runtime exceeded its assignment deadline.")
79
- self.stdout = stdout
80
- self.stderr = stderr
105
+ def __init__(self, diagnostics: Optional[dict] = None) -> None:
106
+ super().__init__(
107
+ "Reviewer analysis exceeded its assignment deadline.",
108
+ diagnostics,
109
+ )
110
+
111
+
112
+ class _ReviewerRuntimeUnavailable(_ReviewerRuntimeFailure):
113
+ """Raised when no semantic Reviewer event arrives during startup."""
114
+
115
+ def __init__(self, diagnostics: Optional[dict] = None) -> None:
116
+ super().__init__(
117
+ "Reviewer runtime produced no semantic event before its startup deadline.",
118
+ diagnostics,
119
+ )
120
+
121
+
122
+ class _ReviewerRuntimeOutputLimit(_ReviewerRuntimeFailure):
123
+ """Raised after bounded Reviewer output exceeds the private diagnostic limit."""
124
+
125
+ def __init__(self, diagnostics: Optional[dict] = None) -> None:
126
+ super().__init__("Reviewer runtime output exceeded its bounded limit.", diagnostics)
127
+
128
+
129
+ class _ReviewerRuntimeInternalError(_ReviewerRuntimeFailure):
130
+ """Raised after an internal supervision failure has stopped the process group."""
131
+
132
+ def __init__(self, diagnostics: Optional[dict] = None) -> None:
133
+ super().__init__("Reviewer runtime supervision failed safely.", diagnostics)
134
+
135
+
136
+ def _review_startup_timeout_seconds() -> float:
137
+ raw = _text(os.environ.get("AUTOCODING_REVIEW_STARTUP_TIMEOUT_SECONDS"))
138
+ if not raw:
139
+ return _REVIEW_STARTUP_TIMEOUT_SECONDS
140
+ try:
141
+ value = float(raw)
142
+ except ValueError as exc:
143
+ raise APError(
144
+ "AUTOCODING_REVIEW_STARTUP_TIMEOUT_SECONDS must be a positive number."
145
+ ) from exc
146
+ if value <= 0:
147
+ raise APError(
148
+ "AUTOCODING_REVIEW_STARTUP_TIMEOUT_SECONDS must be a positive number."
149
+ )
150
+ return min(value, _REVIEW_STARTUP_TIMEOUT_SECONDS)
151
+
152
+
153
+ def _review_diff_artifact_limit() -> int:
154
+ raw = _text(os.environ.get("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES"))
155
+ if not raw:
156
+ return _REVIEW_DIFF_ARTIFACT_MAX_BYTES
157
+ try:
158
+ requested = int(raw)
159
+ except ValueError as exc:
160
+ raise APError("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES must be a positive integer.") from exc
161
+ if requested < 1:
162
+ raise APError("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES must be a positive integer.")
163
+ return min(requested, _REVIEW_DIFF_ARTIFACT_MAX_BYTES)
81
164
  _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
82
165
  _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
83
166
  _FINAL_GATE_CACHE_SCHEMA = 1
@@ -85,7 +168,7 @@ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
85
168
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
86
169
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
87
170
  "schema_version": 1,
88
- "managed_versions": {"agents": "4.2.6", "engineering": "4.2.6"},
171
+ "managed_versions": {"agents": "4.2.8", "engineering": "4.2.8"},
89
172
  "known_official_engineering_body_sha256": [
90
173
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
91
174
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -1148,8 +1231,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
1148
1231
  if _text(workflow_cfg.get("completion")).lower() != "push":
1149
1232
  workflow_cfg["completion"] = "push"
1150
1233
  changed.append("workflow.completion")
1151
- if _text(workflow_cfg.get("skill_version")) != "4.2.6":
1152
- workflow_cfg["skill_version"] = "4.2.6"
1234
+ if _text(workflow_cfg.get("skill_version")) != "4.2.8":
1235
+ workflow_cfg["skill_version"] = "4.2.8"
1153
1236
  changed.append("workflow.skill_version")
1154
1237
 
1155
1238
  commands_cfg = cfg.setdefault("commands", {})
@@ -1462,16 +1545,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
1462
1545
  if current_agents:
1463
1546
  archive_dir = repo / "docs" / "archive" / "workflow"
1464
1547
  archive_header = (
1465
- "# Archived AGENTS.md before auto-coding-skill 4.2.6\n\n"
1548
+ "# Archived AGENTS.md before auto-coding-skill 4.2.8\n\n"
1466
1549
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
1467
1550
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
1468
1551
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
1469
1552
  )
1470
1553
  archive_content = archive_header + current_agents
1471
- archive = archive_dir / "AGENTS.pre-4.2.6.md"
1554
+ archive = archive_dir / "AGENTS.pre-4.2.8.md"
1472
1555
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
1473
1556
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
1474
- archive = archive_dir / f"AGENTS.pre-4.2.6-{digest}.md"
1557
+ archive = archive_dir / f"AGENTS.pre-4.2.8-{digest}.md"
1475
1558
  if not archive.exists():
1476
1559
  add_action("policy", archive, "archive", "historical and non-authoritative")
1477
1560
  if write:
@@ -2518,6 +2601,7 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
2518
2601
  "approved",
2519
2602
  "changes-requested",
2520
2603
  "blocked",
2604
+ "runtime-bypassed",
2521
2605
  }:
2522
2606
  raise APError(f"Task {task_id} has an invalid review contract.")
2523
2607
  review_required = manifest.get("review_required", schema < 3)
@@ -2572,12 +2656,125 @@ def _save_task_manifest(repo: Path, manifest: dict, *, strict_worktree: bool = F
2572
2656
  raise
2573
2657
 
2574
2658
 
2659
+ def _guard_review_directory(path: Path, common_dir: Path, *, create: bool) -> None:
2660
+ if path.is_symlink():
2661
+ raise APError(f"Refusing symlinked Git-local review storage: {path}")
2662
+ if path.exists():
2663
+ try:
2664
+ metadata = path.lstat()
2665
+ except OSError as exc:
2666
+ raise APError(f"Cannot inspect Git-local review storage: {path}: {exc}") from exc
2667
+ if not stat.S_ISDIR(metadata.st_mode):
2668
+ raise APError(f"Git-local review storage must be a directory: {path}")
2669
+ elif create:
2670
+ try:
2671
+ path.mkdir(mode=0o700)
2672
+ except FileExistsError:
2673
+ _guard_review_directory(path, common_dir, create=False)
2674
+ except OSError as exc:
2675
+ raise APError(f"Cannot create Git-local review storage: {path}: {exc}") from exc
2676
+ try:
2677
+ resolved = path.resolve()
2678
+ resolved.relative_to(common_dir)
2679
+ except (OSError, ValueError) as exc:
2680
+ raise APError(f"Git-local review storage escapes the Git common directory: {path}") from exc
2681
+ if os.name == "posix" and path.exists():
2682
+ try:
2683
+ path.chmod(0o700)
2684
+ except OSError as exc:
2685
+ raise APError(f"Cannot protect Git-local review storage: {path}: {exc}") from exc
2686
+
2687
+
2688
+ def _task_review_root(repo: Path, *, create: bool = False) -> Path:
2689
+ common_dir = _git_common_dir(repo).resolve()
2690
+ state_root = common_dir / "auto-coding-skill"
2691
+ review_root = state_root / "reviews"
2692
+ _guard_review_directory(state_root, common_dir, create=create)
2693
+ if state_root.exists():
2694
+ _guard_review_directory(review_root, common_dir, create=create)
2695
+ return review_root
2696
+
2697
+
2698
+ def _task_review_dir(repo: Path, task_id: str, *, create: bool = False) -> Path:
2699
+ common_dir = _git_common_dir(repo).resolve()
2700
+ review_root = _task_review_root(repo, create=create)
2701
+ review_dir = review_root / _validate_task_id(task_id)
2702
+ if review_root.exists():
2703
+ _guard_review_directory(review_dir, common_dir, create=create)
2704
+ return review_dir
2705
+
2706
+
2707
+ def _process_is_running(pid: int) -> bool:
2708
+ if pid <= 0:
2709
+ return False
2710
+ try:
2711
+ os.kill(pid, 0)
2712
+ except ProcessLookupError:
2713
+ return False
2714
+ except PermissionError:
2715
+ return True
2716
+ except OSError:
2717
+ return False
2718
+ return True
2719
+
2720
+
2721
+ def _cleanup_stale_review_snapshots(root: Path, *, legacy_root: bool = False) -> None:
2722
+ if not root.exists() or root.is_symlink():
2723
+ return
2724
+ now = time.time()
2725
+ for candidate in sorted(root.glob(".snapshot-*")):
2726
+ if not candidate.is_dir() or candidate.is_symlink():
2727
+ continue
2728
+ match = re.fullmatch(r"\.snapshot-(\d+)-[A-Za-z0-9_-]+", candidate.name)
2729
+ if match and _process_is_running(int(match.group(1))):
2730
+ continue
2731
+ if not match:
2732
+ try:
2733
+ age_seconds = now - candidate.stat().st_mtime
2734
+ except OSError:
2735
+ continue
2736
+ if not legacy_root or age_seconds < 3600:
2737
+ continue
2738
+ try:
2739
+ shutil.rmtree(candidate)
2740
+ except OSError as exc:
2741
+ raise APError(f"Cannot remove stale Git-local review snapshot: {candidate}: {exc}") from exc
2742
+
2743
+
2744
+ def _delete_task_review_artifacts(repo: Path, task_id: str) -> None:
2745
+ review_dir = _task_review_dir(repo, task_id)
2746
+ if review_dir.is_symlink():
2747
+ raise APError(f"Refusing to remove symlinked Git-local review state: {review_dir}")
2748
+ if not review_dir.exists():
2749
+ return
2750
+ try:
2751
+ shutil.rmtree(review_dir)
2752
+ except OSError as exc:
2753
+ raise APError(f"Cannot remove Git-local review state: {review_dir}: {exc}") from exc
2754
+
2755
+
2575
2756
  def _delete_task_manifest(repo: Path, manifest: dict) -> None:
2576
2757
  task_id = _validate_task_id(_text(manifest.get("task_id")))
2758
+ registry_path = _task_registry_path(repo, task_id)
2759
+ try:
2760
+ registry_path.unlink(missing_ok=True)
2761
+ except OSError as exc:
2762
+ raise APError(f"Cannot remove task registry state: {registry_path}: {exc}") from exc
2763
+
2764
+ # Registry deletion is the authoritative lifecycle transition. Review
2765
+ # evidence is deliberately removed afterwards so a registry failure never
2766
+ # leaves a live task without the immutable artifact that justified it. If
2767
+ # artifact cleanup fails, task-prune can safely retry it as orphaned state.
2577
2768
  worktree_value = _text(manifest.get("worktree_path"))
2578
2769
  if worktree_value and Path(worktree_value).exists():
2579
2770
  _clear_final_gate_receipt(Path(worktree_value))
2580
- _task_registry_path(repo, task_id).unlink(missing_ok=True)
2771
+ try:
2772
+ _delete_task_review_artifacts(repo, task_id)
2773
+ except APError as exc:
2774
+ print(
2775
+ f"[task-cleanup] warning: registry removed but Git-local review state remains for task-prune: {exc}",
2776
+ file=sys.stderr,
2777
+ )
2581
2778
 
2582
2779
 
2583
2780
  def _current_branch(repo: Path) -> str:
@@ -3062,15 +3259,41 @@ def _task_staging_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
3062
3259
  return paths
3063
3260
 
3064
3261
 
3065
- def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3262
+ def _review_snapshot_git(
3263
+ repo: Path,
3264
+ arguments: list[str],
3265
+ env: dict[str, str],
3266
+ ) -> str:
3267
+ completed = subprocess.run(
3268
+ ["git", *arguments],
3269
+ cwd=str(repo),
3270
+ env=env,
3271
+ text=True,
3272
+ capture_output=True,
3273
+ check=False,
3274
+ )
3275
+ if completed.returncode != 0:
3276
+ raise APError(
3277
+ f"Cannot capture immutable task review snapshot ({completed.returncode}): "
3278
+ f"git {' '.join(arguments)}\nSTDOUT:\n{completed.stdout}\nSTDERR:\n{completed.stderr}"
3279
+ )
3280
+ return completed.stdout
3281
+
3282
+
3283
+ def _task_review_paths(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> list[str]:
3066
3284
  base_sha = _text(manifest.get("base_sha"))
3067
3285
  owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
3068
3286
  managed = set(_task_managed_paths(cfg or _load_cfg(repo), manifest))
3069
- paths = [
3287
+ return [
3070
3288
  path
3071
3289
  for path in _task_changed_paths_from_base(repo, base_sha)
3072
3290
  if path not in managed and _path_is_owned(path, owned)
3073
3291
  ]
3292
+
3293
+
3294
+ def _task_review_fingerprint_for_tree(manifest: dict, paths: list[str], tree_sha: str) -> str:
3295
+ base_sha = _text(manifest.get("base_sha"))
3296
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
3074
3297
  digest = hashlib.sha256()
3075
3298
  digest.update(
3076
3299
  (
@@ -3082,21 +3305,188 @@ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = N
3082
3305
  digest.update(f"owned:{owned_path}\0".encode("utf-8", errors="surrogateescape"))
3083
3306
  for rel in paths:
3084
3307
  digest.update(f"path:{rel}\0".encode("utf-8", errors="surrogateescape"))
3308
+ digest.update(f"tree:{tree_sha}\0".encode("ascii"))
3309
+ return digest.hexdigest()
3310
+
3311
+
3312
+ def _require_bounded_review_snapshot_input(repo: Path, paths: list[str]) -> None:
3313
+ limit = _review_diff_artifact_limit()
3314
+ total = 0
3315
+ for rel in paths:
3085
3316
  path = repo / rel
3086
3317
  try:
3087
- mode = path.lstat().st_mode
3088
- except OSError:
3089
- digest.update(b"missing\0")
3318
+ metadata = path.lstat()
3319
+ except FileNotFoundError:
3090
3320
  continue
3091
- digest.update(f"mode:{mode:o}\0".encode("ascii"))
3092
- if path.is_symlink():
3093
- digest.update(os.readlink(path).encode("utf-8", errors="surrogateescape"))
3094
- elif path.is_file():
3095
- digest.update(path.read_bytes())
3096
- else:
3097
- digest.update(b"non-file")
3098
- digest.update(b"\0")
3099
- return digest.hexdigest()
3321
+ except OSError as exc:
3322
+ raise APError(f"Cannot size review snapshot input {rel}: {exc}") from exc
3323
+ if stat.S_ISREG(metadata.st_mode):
3324
+ total += metadata.st_size
3325
+ elif stat.S_ISLNK(metadata.st_mode):
3326
+ try:
3327
+ total += len(os.readlink(path).encode("utf-8", errors="surrogateescape"))
3328
+ except OSError as exc:
3329
+ raise APError(f"Cannot size review snapshot symlink {rel}: {exc}") from exc
3330
+ if total > limit:
3331
+ raise APError(
3332
+ "Task-owned review snapshot input exceeds the 64 MiB safety limit; "
3333
+ "narrow the task-owned scope or use a project-specific large-artifact review path."
3334
+ )
3335
+
3336
+
3337
+ def _task_review_snapshot(
3338
+ repo: Path,
3339
+ manifest: dict,
3340
+ cfg: Optional[dict] = None,
3341
+ *,
3342
+ include_patch: bool = False,
3343
+ ) -> dict:
3344
+ base_sha = _text(manifest.get("base_sha"))
3345
+ paths = _task_review_paths(repo, manifest, cfg)
3346
+ _require_bounded_review_snapshot_input(repo, paths)
3347
+ task_id = _validate_task_id(_text(manifest.get("task_id")))
3348
+ review_root = _task_review_dir(repo, task_id, create=True)
3349
+ _cleanup_stale_review_snapshots(review_root)
3350
+ snapshot_root = Path(
3351
+ tempfile.mkdtemp(prefix=f".snapshot-{os.getpid()}-", dir=review_root)
3352
+ )
3353
+ if os.name == "posix":
3354
+ snapshot_root.chmod(0o700)
3355
+ index_path = snapshot_root / "index"
3356
+ object_dir = snapshot_root / "objects"
3357
+ object_dir.mkdir(mode=0o700)
3358
+ env = os.environ.copy()
3359
+ inherited_alternates = _text(env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES"))
3360
+ alternates = [str((_git_common_dir(repo) / "objects").resolve())]
3361
+ if inherited_alternates:
3362
+ alternates.append(inherited_alternates)
3363
+ env.update(
3364
+ {
3365
+ "GIT_INDEX_FILE": str(index_path),
3366
+ "GIT_OBJECT_DIRECTORY": str(object_dir),
3367
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": os.pathsep.join(alternates),
3368
+ "GIT_PAGER": "cat",
3369
+ }
3370
+ )
3371
+ try:
3372
+ _review_snapshot_git(repo, ["read-tree", base_sha], env)
3373
+ for start in range(0, len(paths), 100):
3374
+ _review_snapshot_git(
3375
+ repo,
3376
+ ["add", "-A", "--", *paths[start : start + 100]],
3377
+ env,
3378
+ )
3379
+ tree_sha = _text(_review_snapshot_git(repo, ["write-tree"], env))
3380
+ if not tree_sha:
3381
+ raise APError("Cannot capture immutable task review snapshot tree.")
3382
+ patch = b""
3383
+ if include_patch:
3384
+ patch_path = snapshot_root / "review.patch"
3385
+ patch_arguments = [
3386
+ "git",
3387
+ "diff",
3388
+ "--binary",
3389
+ "--full-index",
3390
+ "--no-renames",
3391
+ "--no-ext-diff",
3392
+ "--no-textconv",
3393
+ "--no-color",
3394
+ "--diff-algorithm=myers",
3395
+ "--no-indent-heuristic",
3396
+ "--src-prefix=a/",
3397
+ "--dst-prefix=b/",
3398
+ base_sha,
3399
+ tree_sha,
3400
+ "--",
3401
+ ]
3402
+ patch_limit = _review_diff_artifact_limit()
3403
+ stderr_path = snapshot_root / "review.stderr"
3404
+ process: Optional[subprocess.Popen[bytes]] = None
3405
+ try:
3406
+ with patch_path.open("wb") as handle, stderr_path.open("wb") as stderr_handle:
3407
+ process = subprocess.Popen(
3408
+ patch_arguments,
3409
+ cwd=str(repo),
3410
+ env=env,
3411
+ stdout=subprocess.PIPE,
3412
+ stderr=stderr_handle,
3413
+ )
3414
+ if process.stdout is None:
3415
+ raise APError("Cannot capture immutable task review patch output.")
3416
+ patch_size = 0
3417
+ while True:
3418
+ chunk = process.stdout.read(64 * 1024)
3419
+ if not chunk:
3420
+ break
3421
+ patch_size += len(chunk)
3422
+ if patch_size > patch_limit:
3423
+ if process.poll() is None:
3424
+ process.terminate()
3425
+ try:
3426
+ process.wait(timeout=2)
3427
+ except subprocess.TimeoutExpired:
3428
+ process.kill()
3429
+ process.wait(timeout=2)
3430
+ raise APError(
3431
+ "Immutable task review patch exceeds the 64 MiB safety limit; "
3432
+ "narrow the task-owned scope or review the large artifact through a project-specific path."
3433
+ )
3434
+ handle.write(chunk)
3435
+ handle.flush()
3436
+ os.fsync(handle.fileno())
3437
+ returncode = process.wait()
3438
+ except OSError as exc:
3439
+ if process is not None and process.poll() is None:
3440
+ process.kill()
3441
+ process.wait()
3442
+ raise APError(f"Cannot render immutable task review patch: {exc}") from exc
3443
+ if returncode != 0:
3444
+ raise APError(
3445
+ "Cannot render immutable task review patch "
3446
+ f"({returncode}): {stderr_path.read_text(encoding='utf-8', errors='replace')}"
3447
+ )
3448
+ patch = patch_path.read_bytes()
3449
+ finally:
3450
+ try:
3451
+ shutil.rmtree(snapshot_root)
3452
+ except OSError as exc:
3453
+ raise APError(
3454
+ f"Cannot remove temporary Git-local review snapshot state: {snapshot_root}: {exc}"
3455
+ ) from exc
3456
+
3457
+ return {
3458
+ "fingerprint": _task_review_fingerprint_for_tree(manifest, paths, tree_sha),
3459
+ "tree_sha": tree_sha,
3460
+ "paths": paths,
3461
+ "patch": patch,
3462
+ "patch_sha256": hashlib.sha256(patch).hexdigest() if include_patch else "",
3463
+ }
3464
+
3465
+
3466
+ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3467
+ return _text(_task_review_snapshot(repo, manifest, cfg).get("fingerprint"))
3468
+
3469
+
3470
+ def _staged_task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3471
+ tree_sha = _text(run(["git", "write-tree"], cwd=repo).stdout)
3472
+ if not tree_sha:
3473
+ raise APError("Cannot bind the staged task tree to its approved review.")
3474
+ return _task_review_fingerprint_for_tree(
3475
+ manifest,
3476
+ _task_review_paths(repo, manifest, cfg),
3477
+ tree_sha,
3478
+ )
3479
+
3480
+
3481
+ def _require_staged_review_matches(repo: Path, cfg: dict, manifest: dict) -> None:
3482
+ if not bool(manifest.get("review_required", int(manifest.get("schema") or 2) < 3)):
3483
+ return
3484
+ approved = _text((manifest.get("review") or {}).get("diff_fingerprint"))
3485
+ staged = _staged_task_review_fingerprint(repo, manifest, cfg)
3486
+ if staged != approved:
3487
+ raise APError(
3488
+ "The exact staged tree does not match the immutable review clearance snapshot; refusing to commit."
3489
+ )
3100
3490
 
3101
3491
 
3102
3492
  def _invalidate_task_review(manifest: dict, reason: str) -> None:
@@ -3150,6 +3540,78 @@ def _require_dependencies(repo: Path, manifest: dict, ancestor_ref: str) -> None
3150
3540
  )
3151
3541
 
3152
3542
 
3543
+ def _validate_review_runtime_override(repo: Path, manifest: dict, fingerprint: str) -> dict:
3544
+ review = manifest.get("review") or {}
3545
+ override_path = _review_runtime_override_path(
3546
+ repo,
3547
+ _text(manifest.get("task_id")),
3548
+ fingerprint,
3549
+ ).resolve()
3550
+ if Path(_text(review.get("runtime_override_path"))).resolve() != override_path:
3551
+ raise APError("Reviewer runtime override path does not match Git-local task state.")
3552
+ override_sha256 = _text(review.get("runtime_override_sha256"))
3553
+ payload_bytes = _read_private_review_file(override_path, "runtime override")
3554
+ if hashlib.sha256(payload_bytes).hexdigest() != override_sha256:
3555
+ raise APError("Reviewer runtime override SHA-256 binding is invalid.")
3556
+ try:
3557
+ payload = json.loads(payload_bytes.decode("utf-8"))
3558
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
3559
+ raise APError("Reviewer runtime override is invalid JSON.") from exc
3560
+ if not isinstance(payload, dict):
3561
+ raise APError("Reviewer runtime override must contain one JSON object.")
3562
+ expected = {
3563
+ "schema": 1,
3564
+ "task_id": _text(manifest.get("task_id")),
3565
+ "diff_fingerprint": fingerprint,
3566
+ "assignment_sha256": _text(review.get("assignment_sha256")),
3567
+ "diff_artifact_sha256": _text(review.get("diff_artifact_sha256")),
3568
+ "runtime_receipt_path": _text(review.get("runtime_receipt_path")),
3569
+ }
3570
+ mismatched = [field for field, value in expected.items() if payload.get(field) != value]
3571
+ if mismatched:
3572
+ raise APError(
3573
+ "Reviewer runtime override does not match task state: " + ", ".join(mismatched)
3574
+ )
3575
+ if payload.get("user_authorized") is not True:
3576
+ raise APError("Reviewer runtime override lacks explicit user authorization.")
3577
+ if not _text(payload.get("authorized_by")) or not _text(payload.get("reason")):
3578
+ raise APError("Reviewer runtime override authorization audit is incomplete.")
3579
+ evidence = payload.get("evidence")
3580
+ if not isinstance(evidence, list) or not evidence or not all(
3581
+ isinstance(item, str) and item for item in evidence
3582
+ ):
3583
+ raise APError("Reviewer runtime override requires non-empty evidence.")
3584
+ receipt_path = Path(_text(payload.get("runtime_receipt_path"))).resolve()
3585
+ expected_result_path, expected_receipt_path = _review_runtime_paths(
3586
+ repo,
3587
+ _text(manifest.get("task_id")),
3588
+ fingerprint,
3589
+ )
3590
+ del expected_result_path
3591
+ if receipt_path != expected_receipt_path.resolve():
3592
+ raise APError("Reviewer runtime override receipt path is not canonical.")
3593
+ receipt_sha256 = _private_review_file_sha256(receipt_path, "runtime receipt")
3594
+ if receipt_sha256 != _text(payload.get("runtime_receipt_sha256")):
3595
+ raise APError("Reviewer runtime override receipt SHA-256 binding is invalid.")
3596
+ failure_state = _text(payload.get("runtime_failure_state"))
3597
+ if failure_state not in {"runtime-unavailable", "analysis-timed-out"}:
3598
+ raise APError("Reviewer runtime override cannot cover this failure state.")
3599
+ assignment_path = Path(_text(review.get("assignment_path"))).resolve()
3600
+ assignment = _load_bound_review_assignment(repo, manifest, assignment_path)
3601
+ receipt = _validate_bound_review_runtime_receipt(
3602
+ repo,
3603
+ manifest,
3604
+ assignment,
3605
+ receipt_path,
3606
+ failure_state,
3607
+ )
3608
+ if _text(receipt.get("status")) != failure_state:
3609
+ raise APError("Reviewer runtime override failure state does not match its receipt.")
3610
+ if failure_state == "runtime-unavailable" and len(receipt.get("attempts") or []) != _REVIEW_RUNTIME_ATTEMPT_LIMIT:
3611
+ raise APError("Reviewer runtime-unavailable override requires exhausted startup attempts.")
3612
+ return payload
3613
+
3614
+
3153
3615
  def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
3154
3616
  unowned = _task_unowned_paths(repo, cfg, manifest)
3155
3617
  if unowned:
@@ -3158,12 +3620,36 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
3158
3620
  if not bool(manifest.get("review_required", int(manifest.get("schema") or 2) < 3)):
3159
3621
  return fingerprint
3160
3622
  review = manifest.get("review") or {}
3161
- if _text(review.get("verdict")) != "approved":
3162
- raise APError("Task review must be approved before commit-push or integration.")
3623
+ verdict = _text(review.get("verdict"))
3624
+ if verdict not in {"approved", "runtime-bypassed"}:
3625
+ raise APError(
3626
+ "Task review must be approved or carry an explicit runtime bypass before commit-push or integration."
3627
+ )
3163
3628
  if _text(review.get("diff_fingerprint")) != fingerprint:
3164
3629
  raise APError("Approved review fingerprint is stale for the current owned diff.")
3165
3630
  if _text(review.get("diff_base")) != _text(manifest.get("base_sha")):
3166
3631
  raise APError("Approved review base is stale for the current task base.")
3632
+ assignment_path = _text(review.get("assignment_path"))
3633
+ if not assignment_path:
3634
+ raise APError("Approved review has no immutable diff assignment.")
3635
+ expected_assignment_path = _review_assignment_path(
3636
+ repo,
3637
+ _text(manifest.get("task_id")),
3638
+ fingerprint,
3639
+ ).resolve()
3640
+ if Path(assignment_path).resolve() != expected_assignment_path:
3641
+ raise APError("Approved review assignment path does not match Git-local task state.")
3642
+ assignment = _load_bound_review_assignment(
3643
+ repo,
3644
+ manifest,
3645
+ expected_assignment_path,
3646
+ )
3647
+ for field in ("diff_artifact_path", "diff_artifact_sha256", "diff_artifact_format"):
3648
+ if assignment.get(field) != review.get(field):
3649
+ raise APError(f"Approved review {field} binding does not match its assignment.")
3650
+ _validate_review_diff_artifact(repo, assignment)
3651
+ if verdict == "runtime-bypassed":
3652
+ _validate_review_runtime_override(repo, manifest, fingerprint)
3167
3653
  return fingerprint
3168
3654
 
3169
3655
 
@@ -6566,6 +7052,9 @@ def _agent_contract_shape() -> tuple[dict, list[str]]:
6566
7052
  "diff_base",
6567
7053
  "diff_head",
6568
7054
  "diff_fingerprint",
7055
+ "diff_artifact_path",
7056
+ "diff_artifact_sha256",
7057
+ "diff_artifact_format",
6569
7058
  "owning_fixer",
6570
7059
  "review_depth",
6571
7060
  "timeout_seconds",
@@ -6884,7 +7373,7 @@ def _normalize_reviewer_runtime_result(assignment: dict, payload: dict) -> dict:
6884
7373
  return _validate_orchestration_contract("result", result)
6885
7374
 
6886
7375
 
6887
- def _reviewer_agent_instructions(worktree: Path) -> str:
7376
+ def _reviewer_agent_config(worktree: Path) -> dict:
6888
7377
  candidates = [
6889
7378
  worktree / ".agents" / "agents" / "reviewer.toml",
6890
7379
  _skill_root().parent.parent / "agents" / "reviewer.toml",
@@ -6898,18 +7387,35 @@ def _reviewer_agent_instructions(worktree: Path) -> str:
6898
7387
  raise APError(f"Cannot load managed Reviewer Agent config: {path}: {exc}") from exc
6899
7388
  instructions = _text(payload.get("developer_instructions"))
6900
7389
  if instructions:
6901
- return instructions
6902
- return (
6903
- "Act as an independent read-only code reviewer. Review only the supplied "
6904
- "assignment and return one JSON object with an approved, changes-requested, "
6905
- "or blocked verdict. Do not modify files."
6906
- )
7390
+ model = _text(payload.get("model"))
7391
+ if model and any(char in model for char in "\0\r\n"):
7392
+ raise APError(f"Managed Reviewer model contains invalid characters: {path}")
7393
+ return {
7394
+ "instructions": instructions,
7395
+ "model": model,
7396
+ "config_path": str(path),
7397
+ }
7398
+ return {
7399
+ "instructions": (
7400
+ "Act as an independent read-only code reviewer. Review only the supplied "
7401
+ "assignment and return one JSON object with an approved, changes-requested, "
7402
+ "or blocked verdict. Do not modify files."
7403
+ ),
7404
+ "model": "",
7405
+ "config_path": "",
7406
+ }
7407
+
7408
+
7409
+ def _reviewer_agent_instructions(worktree: Path) -> str:
7410
+ return _text(_reviewer_agent_config(worktree).get("instructions"))
6907
7411
 
6908
7412
 
6909
7413
  def _codex_reviewer_command(
6910
7414
  worktree: Path,
6911
7415
  assignment_path: Path,
6912
7416
  result_path: Path,
7417
+ *,
7418
+ review_depth: str = "deep",
6913
7419
  ) -> list[str]:
6914
7420
  codex = shutil.which("codex")
6915
7421
  if not codex:
@@ -6917,19 +7423,40 @@ def _codex_reviewer_command(
6917
7423
  "The supervised Reviewer runtime requires the Codex CLI on PATH. "
6918
7424
  "Install Codex or run review-assignment and use another deadline-capable host."
6919
7425
  )
6920
- instructions = _reviewer_agent_instructions(worktree)
7426
+ agent_config = _reviewer_agent_config(worktree)
7427
+ instructions = _text(agent_config.get("instructions"))
7428
+ model = _text(agent_config.get("model"))
7429
+ depth = _text(review_depth).lower()
7430
+ if depth not in {"focused", "deep"}:
7431
+ raise APError(f"Unsupported Reviewer depth: {review_depth!r}")
7432
+ reasoning_effort = "high" if depth == "focused" else "xhigh"
7433
+ artifact_command = shlex.join(
7434
+ [
7435
+ "python3",
7436
+ "docs/tools/autopipeline/ap.py",
7437
+ "review-artifact",
7438
+ "--file",
7439
+ str(assignment_path),
7440
+ ]
7441
+ )
6921
7442
  prompt = (
6922
7443
  f"Review the exact assignment at {assignment_path}. "
6923
- "Stay inside its diff, identity, and deadline. Use "
7444
+ f"Before analysis, run `{artifact_command}`; it verifies diff_artifact_path, "
7445
+ "mode 0600, and diff_artifact_sha256, then emits the immutable patch. "
7446
+ "Review that emitted patch and never substitute a live git diff or diff_base..diff_head. "
7447
+ "Stay inside its identity and deadline. Use "
6924
7448
  "`python3 docs/tools/autopipeline/ap.py agent-result-template --file "
6925
7449
  f"{assignment_path} --verdict <approved|changes-requested|blocked>` when useful. "
6926
7450
  "Return only one JSON object as the final response; do not modify files."
6927
7451
  )
6928
- return [
7452
+ command = [
6929
7453
  codex,
6930
7454
  "-a",
6931
7455
  "never",
6932
7456
  "exec",
7457
+ "--json",
7458
+ "--color",
7459
+ "never",
6933
7460
  "--ephemeral",
6934
7461
  "--ignore-user-config",
6935
7462
  "-C",
@@ -6937,36 +7464,226 @@ def _codex_reviewer_command(
6937
7464
  "-s",
6938
7465
  "read-only",
6939
7466
  "-c",
6940
- 'model_reasoning_effort="xhigh"',
7467
+ f'model_reasoning_effort="{reasoning_effort}"',
6941
7468
  "-c",
6942
7469
  "developer_instructions=" + json.dumps(instructions, ensure_ascii=False),
6943
7470
  "-o",
6944
7471
  str(result_path),
6945
- prompt,
6946
7472
  ]
7473
+ if model:
7474
+ command.extend(["--model", model])
7475
+ command.append(prompt)
7476
+ return command
6947
7477
 
6948
7478
 
6949
- def _terminate_reviewer_process(process: subprocess.Popen[str]) -> tuple[str, str]:
6950
- if process.poll() is None:
7479
+ def _terminate_reviewer_process(process: subprocess.Popen[str]) -> None:
7480
+ if os.name == "posix":
6951
7481
  try:
6952
- if os.name == "posix":
6953
- os.killpg(process.pid, signal.SIGTERM)
6954
- else:
6955
- process.terminate()
6956
- except ProcessLookupError:
7482
+ os.killpg(process.pid, signal.SIGTERM)
7483
+ except (ProcessLookupError, PermissionError):
7484
+ pass
7485
+ try:
7486
+ process.wait(timeout=0.1)
7487
+ except subprocess.TimeoutExpired:
7488
+ pass
7489
+ deadline = time.monotonic() + 2
7490
+ while time.monotonic() < deadline:
7491
+ try:
7492
+ os.killpg(process.pid, 0)
7493
+ except ProcessLookupError:
7494
+ break
7495
+ except PermissionError:
7496
+ break
7497
+ time.sleep(0.05)
7498
+ try:
7499
+ os.killpg(process.pid, 0)
7500
+ except (ProcessLookupError, PermissionError):
7501
+ pass
7502
+ else:
7503
+ try:
7504
+ os.killpg(process.pid, signal.SIGKILL)
7505
+ except (ProcessLookupError, PermissionError):
7506
+ pass
7507
+ try:
7508
+ process.wait(timeout=2)
7509
+ except subprocess.TimeoutExpired:
6957
7510
  pass
7511
+ return
7512
+ if process.poll() is None:
7513
+ process.terminate()
6958
7514
  try:
6959
- stdout, stderr = process.communicate(timeout=2)
7515
+ process.wait(timeout=2)
6960
7516
  except subprocess.TimeoutExpired:
7517
+ if process.poll() is None:
7518
+ process.kill()
6961
7519
  try:
6962
- if os.name == "posix":
6963
- os.killpg(process.pid, signal.SIGKILL)
6964
- else:
6965
- process.kill()
6966
- except ProcessLookupError:
7520
+ process.wait(timeout=2)
7521
+ except subprocess.TimeoutExpired:
6967
7522
  pass
6968
- stdout, stderr = process.communicate()
6969
- return stdout or "", stderr or ""
7523
+
7524
+
7525
+ def _reviewer_diagnostic_categories(value: str) -> list[str]:
7526
+ lowered = value.lower()
7527
+ patterns = {
7528
+ "authentication": ("unauthorized", "forbidden", "login", "401", "403"),
7529
+ "model-discovery": ("available models", "model list", "model unavailable"),
7530
+ "network-disconnect": ("stream disconnected", "connection reset", "connection closed"),
7531
+ "permission": ("operation not permitted", "permission denied", "readonly database"),
7532
+ "rate-limit": ("rate limit", "too many requests", "429"),
7533
+ "state-database": ("state_", "sqlite", "database"),
7534
+ "timeout": ("timed out", "timeout"),
7535
+ "tls": ("tls", "certificate", "handshake eof"),
7536
+ }
7537
+ return sorted(
7538
+ category
7539
+ for category, needles in patterns.items()
7540
+ if any(needle in lowered for needle in needles)
7541
+ )
7542
+
7543
+
7544
+ def _reviewer_event_metadata(stream: str, line: str, timestamp: str) -> tuple[dict, bool]:
7545
+ encoded = line.encode("utf-8", errors="replace")
7546
+ record = {
7547
+ "timestamp": timestamp,
7548
+ "stream": stream,
7549
+ "bytes": len(encoded),
7550
+ "sha256": hashlib.sha256(encoded).hexdigest(),
7551
+ }
7552
+ if stream == "stderr":
7553
+ record["event_type"] = "diagnostic"
7554
+ record["categories"] = _reviewer_diagnostic_categories(line)
7555
+ return record, False
7556
+ try:
7557
+ payload = json.loads(line)
7558
+ except json.JSONDecodeError:
7559
+ record["event_type"] = "stdout-non-json"
7560
+ return record, False
7561
+ if not isinstance(payload, dict):
7562
+ record["event_type"] = "stdout-non-object"
7563
+ return record, False
7564
+ event_type = _text(payload.get("type")) or "unknown-json-event"
7565
+ record["event_type"] = event_type
7566
+ item = payload.get("item")
7567
+ if isinstance(item, dict) and _text(item.get("type")):
7568
+ record["item_type"] = _text(item.get("type"))
7569
+ semantic = event_type != "thread.started"
7570
+ return record, semantic
7571
+
7572
+
7573
+ def _reviewer_phase(event_type: str) -> str:
7574
+ if event_type == "thread.started":
7575
+ return "runtime-started"
7576
+ if event_type == "turn.started":
7577
+ return "analysis-started"
7578
+ if event_type.startswith("item."):
7579
+ return "analyzing"
7580
+ if event_type == "turn.completed":
7581
+ return "finalizing"
7582
+ if event_type in {"error", "turn.failed"}:
7583
+ return "runtime-error"
7584
+ return "runtime-event"
7585
+
7586
+
7587
+ def _append_reviewer_output(parts: list[str], current_bytes: int, value: str) -> int:
7588
+ encoded = value.encode("utf-8", errors="replace")
7589
+ if current_bytes + len(encoded) > _REVIEW_OUTPUT_MAX_BYTES:
7590
+ raise _ReviewerRuntimeOutputLimit()
7591
+ parts.append(value)
7592
+ return current_bytes + len(encoded)
7593
+
7594
+
7595
+ def _reviewer_stream_reader(
7596
+ stream: object,
7597
+ stream_name: str,
7598
+ output_queue: queue.Queue,
7599
+ stop_event: threading.Event,
7600
+ semantic_seen: threading.Event,
7601
+ ) -> None:
7602
+ def emit(raw: bytes) -> None:
7603
+ line = raw.decode("utf-8", errors="replace")
7604
+ timestamp = _now_iso()
7605
+ if stream_name == "stdout" and _reviewer_event_metadata(
7606
+ stream_name,
7607
+ line,
7608
+ timestamp,
7609
+ )[1]:
7610
+ semantic_seen.set()
7611
+ while not stop_event.is_set():
7612
+ try:
7613
+ output_queue.put((stream_name, line, timestamp), timeout=0.05)
7614
+ return
7615
+ except queue.Full:
7616
+ continue
7617
+
7618
+ try:
7619
+ if os.name == "posix":
7620
+ descriptor = stream.fileno() # type: ignore[attr-defined]
7621
+ os.set_blocking(descriptor, False)
7622
+ pending = b""
7623
+ while not stop_event.is_set():
7624
+ try:
7625
+ chunk = os.read(descriptor, 65536)
7626
+ except (BlockingIOError, InterruptedError):
7627
+ stop_event.wait(0.02)
7628
+ continue
7629
+ if not chunk:
7630
+ break
7631
+ pending += chunk
7632
+ while b"\n" in pending:
7633
+ raw, pending = pending.split(b"\n", 1)
7634
+ emit(raw + b"\n")
7635
+ if len(pending) > _REVIEW_OUTPUT_MAX_BYTES:
7636
+ emit(pending)
7637
+ pending = b""
7638
+ if pending and not stop_event.is_set():
7639
+ emit(pending)
7640
+ else:
7641
+ while not stop_event.is_set():
7642
+ raw = stream.readline(_REVIEW_OUTPUT_MAX_BYTES + 1) # type: ignore[attr-defined]
7643
+ if raw == b"":
7644
+ break
7645
+ emit(raw)
7646
+ except (OSError, ValueError):
7647
+ pass
7648
+ finally:
7649
+ while not stop_event.is_set():
7650
+ try:
7651
+ output_queue.put((stream_name, None, _now_iso()), timeout=0.05)
7652
+ break
7653
+ except queue.Full:
7654
+ continue
7655
+
7656
+
7657
+ def _reviewer_attempt_diagnostics(
7658
+ *,
7659
+ started_at: str,
7660
+ finished_at: str,
7661
+ stdout: str,
7662
+ stderr: str,
7663
+ first_event_at: str,
7664
+ last_event_at: str,
7665
+ last_event_type: str,
7666
+ event_count: int,
7667
+ phase: str,
7668
+ exit_code: Optional[int],
7669
+ ) -> dict:
7670
+ return {
7671
+ "started_at": started_at,
7672
+ "finished_at": finished_at,
7673
+ "first_event_at": first_event_at,
7674
+ "last_event_at": last_event_at,
7675
+ "last_event_type": last_event_type,
7676
+ "event_count": event_count,
7677
+ "phase": phase,
7678
+ "exit_code": exit_code,
7679
+ "stdout_bytes": len(stdout.encode("utf-8", errors="replace")),
7680
+ "stderr_bytes": len(stderr.encode("utf-8", errors="replace")),
7681
+ "stdout_sha256": hashlib.sha256(stdout.encode("utf-8", errors="replace")).hexdigest(),
7682
+ "stderr_sha256": hashlib.sha256(stderr.encode("utf-8", errors="replace")).hexdigest(),
7683
+ "diagnostic_categories": _reviewer_diagnostic_categories(stderr),
7684
+ "stdout": stdout,
7685
+ "stderr": stderr,
7686
+ }
6970
7687
 
6971
7688
 
6972
7689
  def _run_supervised_reviewer_process(
@@ -6975,30 +7692,224 @@ def _run_supervised_reviewer_process(
6975
7692
  cwd: Path,
6976
7693
  env: dict[str, str],
6977
7694
  timeout_seconds: float,
6978
- ) -> subprocess.CompletedProcess[str]:
7695
+ startup_timeout_seconds: Optional[float] = None,
7696
+ event_writer: Optional[object] = None,
7697
+ ) -> tuple[subprocess.CompletedProcess[str], dict]:
6979
7698
  if timeout_seconds <= 0:
6980
7699
  raise _ReviewerRuntimeTimeout()
6981
- process = subprocess.Popen(
6982
- command,
6983
- cwd=str(cwd),
6984
- env=env,
6985
- stdin=subprocess.DEVNULL,
6986
- stdout=subprocess.PIPE,
6987
- stderr=subprocess.PIPE,
6988
- text=True,
6989
- start_new_session=True,
7700
+ startup_timeout = min(
7701
+ startup_timeout_seconds or _review_startup_timeout_seconds(),
7702
+ timeout_seconds,
6990
7703
  )
7704
+ started_at = _now_iso()
7705
+ started_monotonic = time.monotonic()
6991
7706
  try:
6992
- stdout, stderr = process.communicate(timeout=timeout_seconds)
6993
- except subprocess.TimeoutExpired as exc:
6994
- stdout, stderr = _terminate_reviewer_process(process)
6995
- raise _ReviewerRuntimeTimeout(stdout, stderr) from exc
6996
- return subprocess.CompletedProcess(
7707
+ process = subprocess.Popen(
7708
+ command,
7709
+ cwd=str(cwd),
7710
+ env=env,
7711
+ stdin=subprocess.DEVNULL,
7712
+ stdout=subprocess.PIPE,
7713
+ stderr=subprocess.PIPE,
7714
+ text=False,
7715
+ bufsize=0,
7716
+ start_new_session=True,
7717
+ )
7718
+ except OSError as exc:
7719
+ diagnostics = _reviewer_attempt_diagnostics(
7720
+ started_at=started_at,
7721
+ finished_at=_now_iso(),
7722
+ stdout="",
7723
+ stderr=str(exc),
7724
+ first_event_at="",
7725
+ last_event_at="",
7726
+ last_event_type="",
7727
+ event_count=0,
7728
+ phase="spawn-failed",
7729
+ exit_code=None,
7730
+ )
7731
+ raise _ReviewerRuntimeUnavailable(diagnostics) from exc
7732
+ if process.stdout is None or process.stderr is None:
7733
+ _terminate_reviewer_process(process)
7734
+ raise _ReviewerRuntimeUnavailable()
7735
+
7736
+ output_queue: queue.Queue = queue.Queue(maxsize=256)
7737
+ stop_event = threading.Event()
7738
+ semantic_seen = threading.Event()
7739
+ readers = [
7740
+ threading.Thread(
7741
+ target=_reviewer_stream_reader,
7742
+ args=(process.stdout, "stdout", output_queue, stop_event, semantic_seen),
7743
+ name=f"reviewer-stream-{process.pid}-stdout",
7744
+ daemon=True,
7745
+ ),
7746
+ threading.Thread(
7747
+ target=_reviewer_stream_reader,
7748
+ args=(process.stderr, "stderr", output_queue, stop_event, semantic_seen),
7749
+ name=f"reviewer-stream-{process.pid}-stderr",
7750
+ daemon=True,
7751
+ ),
7752
+ ]
7753
+ for reader in readers:
7754
+ reader.start()
7755
+
7756
+ stdout_parts: list[str] = []
7757
+ stderr_parts: list[str] = []
7758
+ stdout_bytes = 0
7759
+ stderr_bytes = 0
7760
+ closed_streams: set[str] = set()
7761
+ first_event_at = ""
7762
+ last_event_at = ""
7763
+ last_event_type = ""
7764
+ event_count = 0
7765
+ phase = "starting"
7766
+ failure: Optional[type[_ReviewerRuntimeFailure]] = None
7767
+ supervision_error: Optional[Exception] = None
7768
+
7769
+ def consume(item: tuple[str, Optional[str], str], *, write_event: bool = True) -> None:
7770
+ nonlocal stdout_bytes, stderr_bytes, first_event_at, last_event_at
7771
+ nonlocal last_event_type, event_count, phase
7772
+ stream_name, line, timestamp = item
7773
+ if line is None:
7774
+ closed_streams.add(stream_name)
7775
+ return
7776
+ if stream_name == "stdout":
7777
+ stdout_bytes = _append_reviewer_output(stdout_parts, stdout_bytes, line)
7778
+ else:
7779
+ stderr_bytes = _append_reviewer_output(stderr_parts, stderr_bytes, line)
7780
+ record, semantic = _reviewer_event_metadata(stream_name, line, timestamp)
7781
+ if write_event and event_writer is not None:
7782
+ event_writer.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")
7783
+ event_writer.flush()
7784
+ if stream_name == "stdout" and record["event_type"] not in {
7785
+ "stdout-non-json",
7786
+ "stdout-non-object",
7787
+ }:
7788
+ event_count += 1
7789
+ last_event_at = timestamp
7790
+ last_event_type = _text(record.get("event_type"))
7791
+ phase = _reviewer_phase(last_event_type)
7792
+ if semantic and not first_event_at:
7793
+ first_event_at = timestamp
7794
+
7795
+ try:
7796
+ while len(closed_streams) < 2 or process.poll() is None:
7797
+ try:
7798
+ item = output_queue.get(timeout=0.05)
7799
+ except queue.Empty:
7800
+ item = None
7801
+ if item is not None:
7802
+ consume(item)
7803
+ elapsed = time.monotonic() - started_monotonic
7804
+ if elapsed >= timeout_seconds:
7805
+ failure = _ReviewerRuntimeTimeout
7806
+ break
7807
+ if (
7808
+ not first_event_at
7809
+ and not semantic_seen.is_set()
7810
+ and elapsed >= startup_timeout
7811
+ ):
7812
+ failure = _ReviewerRuntimeUnavailable
7813
+ break
7814
+ except _ReviewerRuntimeOutputLimit:
7815
+ failure = _ReviewerRuntimeOutputLimit
7816
+ except (OSError, ValueError) as exc:
7817
+ failure = _ReviewerRuntimeInternalError
7818
+ supervision_error = exc
7819
+ phase = "supervision-failed"
7820
+ finally:
7821
+ if failure is not None or process.poll() is None:
7822
+ try:
7823
+ _terminate_reviewer_process(process)
7824
+ except OSError as exc:
7825
+ failure = _ReviewerRuntimeInternalError
7826
+ supervision_error = supervision_error or exc
7827
+ phase = "process-cleanup-failed"
7828
+ tail_deadline = time.monotonic() + 0.5
7829
+ while any(reader.is_alive() for reader in readers) and time.monotonic() < tail_deadline:
7830
+ try:
7831
+ item = output_queue.get(timeout=0.02)
7832
+ except queue.Empty:
7833
+ continue
7834
+ try:
7835
+ consume(item, write_event=supervision_error is None)
7836
+ except _ReviewerRuntimeOutputLimit:
7837
+ failure = _ReviewerRuntimeOutputLimit
7838
+ except (OSError, ValueError) as exc:
7839
+ failure = _ReviewerRuntimeInternalError
7840
+ supervision_error = supervision_error or exc
7841
+ phase = "supervision-failed"
7842
+ stop_event.set()
7843
+ drain_deadline = time.monotonic() + 2
7844
+ while any(reader.is_alive() for reader in readers) and time.monotonic() < drain_deadline:
7845
+ try:
7846
+ item = output_queue.get(timeout=0.05)
7847
+ except queue.Empty:
7848
+ continue
7849
+ try:
7850
+ consume(item, write_event=supervision_error is None)
7851
+ except _ReviewerRuntimeOutputLimit:
7852
+ failure = _ReviewerRuntimeOutputLimit
7853
+ except (OSError, ValueError) as exc:
7854
+ failure = _ReviewerRuntimeInternalError
7855
+ supervision_error = supervision_error or exc
7856
+ phase = "supervision-failed"
7857
+ for reader in readers:
7858
+ reader.join(timeout=0.2)
7859
+ if not any(reader.is_alive() for reader in readers):
7860
+ for stream in (process.stdout, process.stderr):
7861
+ try:
7862
+ stream.close()
7863
+ except (OSError, ValueError):
7864
+ pass
7865
+ while True:
7866
+ try:
7867
+ item = output_queue.get_nowait()
7868
+ except queue.Empty:
7869
+ break
7870
+ try:
7871
+ consume(item, write_event=supervision_error is None)
7872
+ except _ReviewerRuntimeOutputLimit:
7873
+ failure = _ReviewerRuntimeOutputLimit
7874
+ except (OSError, ValueError) as exc:
7875
+ failure = _ReviewerRuntimeInternalError
7876
+ supervision_error = supervision_error or exc
7877
+ phase = "supervision-failed"
7878
+
7879
+ if any(reader.is_alive() for reader in readers):
7880
+ failure = _ReviewerRuntimeInternalError
7881
+ phase = "reader-cleanup-failed"
7882
+ if failure is _ReviewerRuntimeUnavailable and first_event_at:
7883
+ failure = _ReviewerRuntimeTimeout
7884
+
7885
+ stdout = "".join(stdout_parts)
7886
+ stderr = "".join(stderr_parts)
7887
+ diagnostics = _reviewer_attempt_diagnostics(
7888
+ started_at=started_at,
7889
+ finished_at=_now_iso(),
7890
+ stdout=stdout,
7891
+ stderr=stderr,
7892
+ first_event_at=first_event_at,
7893
+ last_event_at=last_event_at,
7894
+ last_event_type=last_event_type,
7895
+ event_count=event_count,
7896
+ phase=phase,
7897
+ exit_code=process.returncode,
7898
+ )
7899
+ if failure is not None:
7900
+ error = failure(diagnostics)
7901
+ if supervision_error is not None:
7902
+ raise error from supervision_error
7903
+ raise error
7904
+ if not first_event_at:
7905
+ raise _ReviewerRuntimeUnavailable(diagnostics)
7906
+ completed = subprocess.CompletedProcess(
6997
7907
  command,
6998
7908
  int(process.returncode or 0),
6999
- stdout or "",
7000
- stderr or "",
7909
+ stdout,
7910
+ stderr,
7001
7911
  )
7912
+ return completed, diagnostics
7002
7913
 
7003
7914
 
7004
7915
  def _validate_agent_plan(plan: dict) -> dict:
@@ -10145,6 +11056,220 @@ def _parse_iso_timestamp(value: object, field: str) -> _dt.datetime:
10145
11056
  return parsed.astimezone(_dt.timezone.utc)
10146
11057
 
10147
11058
 
11059
+ def _review_assignment_path(control_repo: Path, task_id: str, fingerprint: str) -> Path:
11060
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11061
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11062
+ return _task_review_dir(control_repo, task_id) / f"{fingerprint}.assignment.json"
11063
+
11064
+
11065
+ def _review_diff_artifact_path(control_repo: Path, task_id: str, fingerprint: str) -> Path:
11066
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11067
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11068
+ return _task_review_dir(control_repo, task_id) / f"{fingerprint}.patch"
11069
+
11070
+
11071
+ def _guard_review_file_parent(path: Path) -> None:
11072
+ task_dir = path.parent
11073
+ review_root = task_dir.parent
11074
+ state_root = review_root.parent
11075
+ common_dir = state_root.parent.resolve()
11076
+ if review_root.name != "reviews" or state_root.name != "auto-coding-skill":
11077
+ raise APError(f"Review file path is outside canonical Git-local storage: {path}")
11078
+ for directory in (state_root, review_root, task_dir):
11079
+ _guard_review_directory(directory, common_dir, create=False)
11080
+ try:
11081
+ task_dir.resolve().relative_to(common_dir)
11082
+ except (OSError, ValueError) as exc:
11083
+ raise APError(f"Review file path escapes the Git common directory: {path}") from exc
11084
+ if path.is_symlink():
11085
+ raise APError(f"Refusing symlinked Git-local review file: {path}")
11086
+
11087
+
11088
+ def _write_private_bytes(path: Path, payload: bytes) -> None:
11089
+ _guard_review_file_parent(path)
11090
+ temporary_name = f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
11091
+ if os.name == "posix":
11092
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
11093
+ directory_fd = -1
11094
+ try:
11095
+ directory_fd = os.open(path.parent, directory_flags)
11096
+ descriptor = os.open(
11097
+ temporary_name,
11098
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
11099
+ 0o600,
11100
+ dir_fd=directory_fd,
11101
+ )
11102
+ with os.fdopen(descriptor, "wb") as handle:
11103
+ handle.write(payload)
11104
+ handle.flush()
11105
+ os.fsync(handle.fileno())
11106
+ os.replace(
11107
+ temporary_name,
11108
+ path.name,
11109
+ src_dir_fd=directory_fd,
11110
+ dst_dir_fd=directory_fd,
11111
+ )
11112
+ os.fsync(directory_fd)
11113
+ except OSError as exc:
11114
+ if directory_fd >= 0:
11115
+ try:
11116
+ os.unlink(temporary_name, dir_fd=directory_fd)
11117
+ except OSError:
11118
+ pass
11119
+ raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
11120
+ finally:
11121
+ if directory_fd >= 0:
11122
+ os.close(directory_fd)
11123
+ return
11124
+
11125
+ temporary = path.with_name(temporary_name)
11126
+ try:
11127
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
11128
+ with os.fdopen(descriptor, "wb") as handle:
11129
+ handle.write(payload)
11130
+ handle.flush()
11131
+ os.fsync(handle.fileno())
11132
+ os.replace(temporary, path)
11133
+ except OSError as exc:
11134
+ temporary.unlink(missing_ok=True)
11135
+ raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
11136
+
11137
+
11138
+ def _read_private_review_file(path: Path, label: str) -> bytes:
11139
+ _guard_review_file_parent(path)
11140
+ if os.name == "posix":
11141
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
11142
+ directory_fd = -1
11143
+ file_fd = -1
11144
+ try:
11145
+ directory_fd = os.open(path.parent, directory_flags)
11146
+ file_fd = os.open(
11147
+ path.name,
11148
+ os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0),
11149
+ dir_fd=directory_fd,
11150
+ )
11151
+ metadata = os.fstat(file_fd)
11152
+ if not stat.S_ISREG(metadata.st_mode):
11153
+ raise APError(f"Review {label} must be a regular Git-local file: {path}")
11154
+ if stat.S_IMODE(metadata.st_mode) != 0o600:
11155
+ raise APError(f"Review {label} must use mode 0600: {path}")
11156
+ with os.fdopen(file_fd, "rb") as handle:
11157
+ file_fd = -1
11158
+ return handle.read()
11159
+ except APError:
11160
+ raise
11161
+ except OSError as exc:
11162
+ raise APError(f"Cannot read review {label}: {path}: {exc}") from exc
11163
+ finally:
11164
+ if file_fd >= 0:
11165
+ os.close(file_fd)
11166
+ if directory_fd >= 0:
11167
+ os.close(directory_fd)
11168
+
11169
+ try:
11170
+ metadata = path.lstat()
11171
+ if not stat.S_ISREG(metadata.st_mode) or path.is_symlink():
11172
+ raise APError(f"Review {label} must be a regular Git-local file: {path}")
11173
+ return path.read_bytes()
11174
+ except APError:
11175
+ raise
11176
+ except OSError as exc:
11177
+ raise APError(f"Cannot read review {label}: {path}: {exc}") from exc
11178
+
11179
+
11180
+ def _read_verified_private_review_file(path: Path, expected_sha256: str, label: str) -> bytes:
11181
+ if not _REVIEW_SHA256_RE.fullmatch(_text(expected_sha256)):
11182
+ raise APError(f"Review {label} has an invalid SHA-256 binding.")
11183
+ payload = _read_private_review_file(path, label)
11184
+ actual_sha256 = hashlib.sha256(payload).hexdigest()
11185
+ if actual_sha256 != expected_sha256:
11186
+ raise APError(
11187
+ f"Review {label} SHA-256 mismatch: expected={expected_sha256}, actual={actual_sha256}."
11188
+ )
11189
+ return payload
11190
+
11191
+
11192
+ def _review_assignment_file_sha256(path: Path) -> str:
11193
+ return hashlib.sha256(_read_private_review_file(path, "assignment")).hexdigest()
11194
+
11195
+
11196
+ def _read_private_review_json(path: Path, label: str) -> Optional[dict]:
11197
+ try:
11198
+ payload = json.loads(_read_private_review_file(path, label).decode("utf-8"))
11199
+ except (json.JSONDecodeError, UnicodeDecodeError):
11200
+ return None
11201
+ return payload if isinstance(payload, dict) else None
11202
+
11203
+
11204
+ def _load_bound_review_assignment(
11205
+ control_repo: Path,
11206
+ manifest: dict,
11207
+ assignment_path: Path,
11208
+ ) -> dict:
11209
+ review = manifest.get("review") or {}
11210
+ fingerprint = _text(review.get("diff_fingerprint"))
11211
+ expected_path = _review_assignment_path(
11212
+ control_repo,
11213
+ _text(manifest.get("task_id")),
11214
+ fingerprint,
11215
+ ).resolve()
11216
+ if assignment_path.resolve() != expected_path:
11217
+ raise APError("Review assignment path does not match canonical Git-local task state.")
11218
+ if _text(review.get("assignment_path")) and Path(_text(review.get("assignment_path"))).resolve() != expected_path:
11219
+ raise APError("Review assignment manifest path does not match canonical Git-local task state.")
11220
+ expected_sha256 = _text(review.get("assignment_sha256"))
11221
+ if not _REVIEW_SHA256_RE.fullmatch(expected_sha256):
11222
+ raise APError("Review assignment has no valid manifest SHA-256 binding.")
11223
+ payload = _read_private_review_file(expected_path, "assignment")
11224
+ if len(payload) > 1024 * 1024:
11225
+ raise APError("Review assignment exceeds the 1 MiB contract limit.")
11226
+ actual_sha256 = hashlib.sha256(payload).hexdigest()
11227
+ if actual_sha256 != expected_sha256:
11228
+ raise APError(
11229
+ f"Review assignment SHA-256 mismatch: expected={expected_sha256}, actual={actual_sha256}."
11230
+ )
11231
+ try:
11232
+ assignment = json.loads(payload.decode("utf-8"))
11233
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
11234
+ raise APError("Review assignment file is invalid JSON.") from exc
11235
+ if not isinstance(assignment, dict):
11236
+ raise APError("Review assignment file must contain one JSON object.")
11237
+ _validate_orchestration_contract("assignment", assignment)
11238
+ if _text(assignment.get("task_id")) != _text(manifest.get("task_id")):
11239
+ raise APError("Review assignment task identity does not match its manifest.")
11240
+ if _text(assignment.get("diff_fingerprint")) != fingerprint:
11241
+ raise APError("Review assignment fingerprint does not match its manifest.")
11242
+ return assignment
11243
+
11244
+
11245
+ def _persist_review_diff_artifact(path: Path, payload: bytes, expected_sha256: str) -> None:
11246
+ if hashlib.sha256(payload).hexdigest() != expected_sha256:
11247
+ raise APError("Generated review diff artifact SHA-256 is inconsistent.")
11248
+ if path.exists() or path.is_symlink():
11249
+ existing = _read_verified_private_review_file(path, expected_sha256, "diff artifact")
11250
+ if existing != payload:
11251
+ raise APError("Existing immutable review diff artifact does not match the current snapshot.")
11252
+ return
11253
+ _write_private_bytes(path, payload)
11254
+ _read_verified_private_review_file(path, expected_sha256, "diff artifact")
11255
+
11256
+
11257
+ def _validate_review_diff_artifact(control_repo: Path, assignment: dict) -> bytes:
11258
+ task_id = _validate_task_id(_text(assignment.get("task_id")))
11259
+ fingerprint = _text(assignment.get("diff_fingerprint"))
11260
+ expected_path = _review_diff_artifact_path(control_repo, task_id, fingerprint).resolve()
11261
+ supplied_path = Path(_text(assignment.get("diff_artifact_path"))).resolve()
11262
+ if supplied_path != expected_path:
11263
+ raise APError("Review diff artifact path does not match canonical Git-local task state.")
11264
+ if _text(assignment.get("diff_artifact_format")) != _REVIEW_DIFF_ARTIFACT_FORMAT:
11265
+ raise APError("Review diff artifact format is unsupported.")
11266
+ return _read_verified_private_review_file(
11267
+ expected_path,
11268
+ _text(assignment.get("diff_artifact_sha256")),
11269
+ "diff artifact",
11270
+ )
11271
+
11272
+
10148
11273
  def _task_review_policy(cfg: dict, worktree: Path, manifest: dict) -> tuple[str, int]:
10149
11274
  changed_paths = _task_changed_paths_from_base(worktree, _text(manifest.get("base_sha")))
10150
11275
  plan = _resolve_execution_plan(
@@ -10187,12 +11312,12 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10187
11312
  worktree,
10188
11313
  _text(manifest.get("base_sha")),
10189
11314
  )
10190
- owned_paths = [
11315
+ changed_owned_paths = [
10191
11316
  path
10192
11317
  for path in changed_paths
10193
11318
  if _path_is_owned(path, list(manifest.get("owned_paths") or []))
10194
11319
  ]
10195
- if not owned_paths:
11320
+ if not changed_owned_paths:
10196
11321
  raise APError("Cannot issue a review assignment before the task has an owned diff.")
10197
11322
  reviewer = _text(args.reviewer)
10198
11323
  if not reviewer or any(char in reviewer for char in "\0\r\n"):
@@ -10201,7 +11326,19 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10201
11326
  owning_fixer = _text((manifest.get("writer_lease") or {}).get("holder")) or owner
10202
11327
  if reviewer in {owner, owning_fixer}:
10203
11328
  raise APError("Independent reviewer must differ from lifecycle owner and owning fixer.")
10204
- fingerprint = _task_review_fingerprint(worktree, manifest, worktree_cfg)
11329
+ snapshot = _task_review_snapshot(
11330
+ worktree,
11331
+ manifest,
11332
+ worktree_cfg,
11333
+ include_patch=True,
11334
+ )
11335
+ fingerprint = _text(snapshot.get("fingerprint"))
11336
+ patch = snapshot.get("patch")
11337
+ if not isinstance(patch, bytes) or not patch:
11338
+ raise APError("Cannot issue a review assignment for an empty immutable diff snapshot.")
11339
+ artifact_sha256 = _text(snapshot.get("patch_sha256"))
11340
+ artifact_path = _review_diff_artifact_path(control_repo, task_id, fingerprint)
11341
+ _persist_review_diff_artifact(artifact_path, patch, artifact_sha256)
10205
11342
  depth, review_timeout = _task_review_policy(worktree_cfg, worktree, manifest)
10206
11343
  issued = _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
10207
11344
  deadline = issued + _dt.timedelta(seconds=review_timeout)
@@ -10214,12 +11351,19 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10214
11351
  "scope": f"Review the task-owned diff for {task_id}",
10215
11352
  "depends_on": [owning_fixer],
10216
11353
  "acceptance": [
10217
- "Review only the assigned stable diff and supplied evidence.",
11354
+ "Verify diff_artifact_sha256 and review only the immutable diff artifact.",
10218
11355
  "Return the complete 16-field reviewer result bound to diff_fingerprint.",
10219
11356
  ],
11357
+ "execution_mode": _text(manifest.get("execution_mode")),
11358
+ "task_branch": _text(manifest.get("task_branch")),
11359
+ "worktree_path": str(worktree.resolve()),
11360
+ "owned_paths": list(manifest.get("owned_paths") or []),
10220
11361
  "diff_base": _text(manifest.get("base_sha")),
10221
11362
  "diff_head": _resolve_commit(worktree, "HEAD"),
10222
11363
  "diff_fingerprint": fingerprint,
11364
+ "diff_artifact_path": str(artifact_path.resolve()),
11365
+ "diff_artifact_sha256": artifact_sha256,
11366
+ "diff_artifact_format": _REVIEW_DIFF_ARTIFACT_FORMAT,
10223
11367
  "owning_fixer": owning_fixer,
10224
11368
  "review_depth": depth,
10225
11369
  "timeout_seconds": review_timeout,
@@ -10228,11 +11372,7 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10228
11372
  "scope_revision": int(manifest.get("scope_revision") or 1),
10229
11373
  }
10230
11374
  _validate_orchestration_contract("assignment", assignment)
10231
- assignment_path = (
10232
- _task_state_root(control_repo)
10233
- / "reviews"
10234
- / f"{task_id}-{fingerprint}.assignment.json"
10235
- )
11375
+ assignment_path = _review_assignment_path(control_repo, task_id, fingerprint)
10236
11376
  prior_review = manifest.get("review") or {}
10237
11377
  if (
10238
11378
  _text(prior_review.get("diff_fingerprint")) == fingerprint
@@ -10246,16 +11386,46 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10246
11386
  raise APError(
10247
11387
  "The single review attempt for this diff fingerprint is already complete or consumed."
10248
11388
  )
10249
- existing_assignment = _read_json_object(assignment_path)
11389
+ if assignment_path.exists() or assignment_path.is_symlink():
11390
+ if (
11391
+ _text(prior_review.get("diff_fingerprint")) == fingerprint
11392
+ and _text(prior_review.get("assignment_sha256"))
11393
+ ):
11394
+ existing_assignment = _load_bound_review_assignment(
11395
+ control_repo,
11396
+ manifest,
11397
+ assignment_path,
11398
+ )
11399
+ else:
11400
+ existing_assignment = _read_private_review_json(
11401
+ assignment_path,
11402
+ "assignment",
11403
+ )
11404
+ else:
11405
+ existing_assignment = None
10250
11406
  if existing_assignment:
10251
11407
  _validate_orchestration_contract("assignment", existing_assignment)
10252
11408
  expected_fields = {
11409
+ "contract_version": assignment["contract_version"],
10253
11410
  "task_id": task_id,
11411
+ "role": "reviewer",
10254
11412
  "base_sha": assignment["base_sha"],
11413
+ "scope": assignment["scope"],
11414
+ "depends_on": assignment["depends_on"],
11415
+ "acceptance": assignment["acceptance"],
11416
+ "execution_mode": assignment["execution_mode"],
11417
+ "task_branch": assignment["task_branch"],
11418
+ "worktree_path": assignment["worktree_path"],
11419
+ "owned_paths": assignment["owned_paths"],
10255
11420
  "diff_base": assignment["diff_base"],
10256
11421
  "diff_head": assignment["diff_head"],
10257
11422
  "diff_fingerprint": fingerprint,
11423
+ "diff_artifact_path": assignment["diff_artifact_path"],
11424
+ "diff_artifact_sha256": assignment["diff_artifact_sha256"],
11425
+ "diff_artifact_format": assignment["diff_artifact_format"],
10258
11426
  "owning_fixer": owning_fixer,
11427
+ "review_depth": assignment["review_depth"],
11428
+ "timeout_seconds": assignment["timeout_seconds"],
10259
11429
  "scope_revision": assignment["scope_revision"],
10260
11430
  }
10261
11431
  mismatched = [
@@ -10273,10 +11443,33 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10273
11443
  "This diff fingerprint already has a reviewer assignment; "
10274
11444
  "the single review attempt cannot be reassigned."
10275
11445
  )
11446
+ existing_issued = _parse_iso_timestamp(
11447
+ existing_assignment.get("issued_at"),
11448
+ "issued_at",
11449
+ )
11450
+ _validate_review_diff_artifact(control_repo, existing_assignment)
10276
11451
  existing_deadline = _parse_iso_timestamp(
10277
11452
  existing_assignment.get("deadline_at"),
10278
11453
  "deadline_at",
10279
11454
  )
11455
+ if int((existing_deadline - existing_issued).total_seconds()) != review_timeout:
11456
+ raise APError("Existing review assignment deadline does not match its fixed timeout.")
11457
+ if _text(prior_review.get("diff_fingerprint")) == fingerprint:
11458
+ expected_prior_fields = {
11459
+ "assignment_path": str(assignment_path),
11460
+ "issued_at": existing_assignment["issued_at"],
11461
+ "deadline_at": existing_assignment["deadline_at"],
11462
+ }
11463
+ prior_mismatches = [
11464
+ field
11465
+ for field, expected in expected_prior_fields.items()
11466
+ if prior_review.get(field) != expected
11467
+ ]
11468
+ if prior_mismatches:
11469
+ raise APError(
11470
+ "Existing review assignment does not match its manifest timing: "
11471
+ + ", ".join(prior_mismatches)
11472
+ )
10280
11473
  if _dt.datetime.now(_dt.timezone.utc) > existing_deadline:
10281
11474
  raise APError(
10282
11475
  "Review attempt timed out and is blocked for this diff fingerprint; "
@@ -10305,11 +11498,12 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10305
11498
  assignment["deadline_at"] = deadline.isoformat()
10306
11499
  assignment["timeout_seconds"] = int((deadline - issued).total_seconds())
10307
11500
  _validate_orchestration_contract("assignment", assignment)
10308
- _write_json_object(assignment_path, assignment)
11501
+ _write_private_json(assignment_path, assignment)
10309
11502
  depth = _text(assignment.get("review_depth"))
10310
11503
  review_timeout = int(assignment.get("timeout_seconds") or 0)
10311
11504
  else:
10312
- _write_json_object(assignment_path, assignment)
11505
+ _write_private_json(assignment_path, assignment)
11506
+ assignment_sha256 = _review_assignment_file_sha256(assignment_path)
10313
11507
  manifest["review_depth"] = depth
10314
11508
  manifest["review_timeout_seconds"] = review_timeout
10315
11509
  review_state = {
@@ -10321,6 +11515,10 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10321
11515
  "reviewed_at": "",
10322
11516
  "reason": "review assignment issued",
10323
11517
  "assignment_path": str(assignment_path),
11518
+ "assignment_sha256": assignment_sha256,
11519
+ "diff_artifact_path": assignment["diff_artifact_path"],
11520
+ "diff_artifact_sha256": assignment["diff_artifact_sha256"],
11521
+ "diff_artifact_format": assignment["diff_artifact_format"],
10324
11522
  "issued_at": assignment["issued_at"],
10325
11523
  "deadline_at": assignment["deadline_at"],
10326
11524
  }
@@ -10344,12 +11542,34 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10344
11542
  print(f"[review-assignment] assignment={assignment_path}")
10345
11543
 
10346
11544
 
11545
+ def cmd_review_artifact(args: argparse.Namespace) -> None:
11546
+ repo = Path(args.repo).resolve()
11547
+ ensure_git_repo(repo)
11548
+ assignment_path = Path(args.file).resolve()
11549
+ task_id = _validate_task_id(assignment_path.parent.name)
11550
+ manifest = _load_task_manifest(repo, task_id)
11551
+ assignment = _load_bound_review_assignment(repo, manifest, assignment_path)
11552
+ assigned_worktree = Path(_text(assignment.get("worktree_path"))).resolve()
11553
+ if assigned_worktree != repo:
11554
+ raise APError(
11555
+ f"Review artifact must be read from its assigned worktree: expected={assigned_worktree}, current={repo}."
11556
+ )
11557
+ if _dt.datetime.now(_dt.timezone.utc) >= _parse_iso_timestamp(
11558
+ assignment.get("deadline_at"),
11559
+ "deadline_at",
11560
+ ):
11561
+ raise APError("Review assignment deadline expired before diff artifact access.")
11562
+ payload = _validate_review_diff_artifact(repo, assignment)
11563
+ sys.stdout.flush()
11564
+ sys.stdout.buffer.write(payload)
11565
+ sys.stdout.buffer.flush()
11566
+
11567
+
10347
11568
  def _write_private_json(path: Path, payload: dict) -> None:
10348
- _write_json_object(path, payload)
10349
- try:
10350
- path.chmod(0o600)
10351
- except OSError as exc:
10352
- raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
11569
+ encoded = (
11570
+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
11571
+ ).encode("utf-8")
11572
+ _write_private_bytes(path, encoded)
10353
11573
 
10354
11574
 
10355
11575
  def _review_runtime_paths(
@@ -10357,9 +11577,155 @@ def _review_runtime_paths(
10357
11577
  task_id: str,
10358
11578
  fingerprint: str,
10359
11579
  ) -> tuple[Path, Path]:
10360
- root = _task_state_root(control_repo) / "reviews"
10361
- stem = f"{_validate_task_id(task_id)}-{fingerprint}"
10362
- return root / f"{stem}.result.json", root / f"{stem}.run.json"
11580
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11581
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11582
+ root = _task_review_dir(control_repo, task_id, create=True)
11583
+ return root / f"{fingerprint}.result.json", root / f"{fingerprint}.run.json"
11584
+
11585
+
11586
+ def _review_runtime_event_log_path(
11587
+ control_repo: Path,
11588
+ task_id: str,
11589
+ fingerprint: str,
11590
+ ) -> Path:
11591
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11592
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11593
+ root = _task_review_dir(control_repo, task_id, create=True)
11594
+ return root / f"{fingerprint}.events.jsonl"
11595
+
11596
+
11597
+ def _review_runtime_override_path(
11598
+ control_repo: Path,
11599
+ task_id: str,
11600
+ fingerprint: str,
11601
+ ) -> Path:
11602
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11603
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11604
+ root = _task_review_dir(control_repo, task_id, create=True)
11605
+ return root / f"{fingerprint}.override.json"
11606
+
11607
+
11608
+ def _open_private_review_event_log(path: Path):
11609
+ _guard_review_file_parent(path)
11610
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
11611
+ try:
11612
+ descriptor = os.open(path, flags, 0o600)
11613
+ if os.name == "posix":
11614
+ os.fchmod(descriptor, 0o600)
11615
+ return os.fdopen(descriptor, "w", encoding="utf-8", buffering=1)
11616
+ except OSError as exc:
11617
+ raise APError(f"Cannot create private Reviewer event log: {path}: {exc}") from exc
11618
+
11619
+
11620
+ def _private_review_file_sha256(path: Path, label: str) -> str:
11621
+ payload = _read_private_review_file(path, label)
11622
+ return hashlib.sha256(payload).hexdigest()
11623
+
11624
+
11625
+ def _reviewer_cli_version(command: list[str], runner_kind: str) -> str:
11626
+ if runner_kind != "codex" or not command:
11627
+ return "test-override"
11628
+ try:
11629
+ completed = subprocess.run(
11630
+ [command[0], "--version"],
11631
+ check=False,
11632
+ text=True,
11633
+ capture_output=True,
11634
+ timeout=5,
11635
+ )
11636
+ except (OSError, subprocess.TimeoutExpired):
11637
+ return "unavailable"
11638
+ return _text(completed.stdout) or _text(completed.stderr) or "unknown"
11639
+
11640
+
11641
+ def _reviewer_command_metadata(command: list[str], runner_kind: str) -> dict:
11642
+ model = "runtime-default"
11643
+ reasoning_effort = "unknown"
11644
+ for index, argument in enumerate(command):
11645
+ if argument in {"-m", "--model"} and index + 1 < len(command):
11646
+ model = command[index + 1]
11647
+ match = re.fullmatch(r'model_reasoning_effort="?([^"=]+)"?', argument)
11648
+ if match:
11649
+ reasoning_effort = match.group(1)
11650
+ return {
11651
+ "runner_kind": runner_kind,
11652
+ "cli_path": command[0] if command else "",
11653
+ "cli_version": _reviewer_cli_version(command, runner_kind),
11654
+ "model": model,
11655
+ "reasoning_effort": reasoning_effort,
11656
+ }
11657
+
11658
+
11659
+ def _safe_reviewer_attempt(diagnostics: dict, attempt: int, status: str) -> dict:
11660
+ return {
11661
+ "attempt": attempt,
11662
+ "status": status,
11663
+ "started_at": _text(diagnostics.get("started_at")),
11664
+ "finished_at": _text(diagnostics.get("finished_at")),
11665
+ "first_event_at": _text(diagnostics.get("first_event_at")),
11666
+ "last_event_at": _text(diagnostics.get("last_event_at")),
11667
+ "last_event_type": _text(diagnostics.get("last_event_type")),
11668
+ "event_count": int(diagnostics.get("event_count") or 0),
11669
+ "phase": _text(diagnostics.get("phase")) or "unknown",
11670
+ "exit_code": diagnostics.get("exit_code"),
11671
+ "stdout_bytes": int(diagnostics.get("stdout_bytes") or 0),
11672
+ "stderr_bytes": int(diagnostics.get("stderr_bytes") or 0),
11673
+ "stdout_sha256": _text(diagnostics.get("stdout_sha256")),
11674
+ "stderr_sha256": _text(diagnostics.get("stderr_sha256")),
11675
+ "diagnostic_categories": list(diagnostics.get("diagnostic_categories") or []),
11676
+ }
11677
+
11678
+
11679
+ def _validate_review_runtime_receipt(receipt: dict) -> dict:
11680
+ if int(receipt.get("schema") or 0) == 1:
11681
+ return receipt
11682
+ if int(receipt.get("schema") or 0) != 2:
11683
+ raise APError("Reviewer runtime receipt has an unsupported schema.")
11684
+ required_strings = (
11685
+ "task_id",
11686
+ "reviewer",
11687
+ "diff_fingerprint",
11688
+ "assignment_sha256",
11689
+ "diff_artifact_sha256",
11690
+ "command_sha256",
11691
+ "runner_kind",
11692
+ "cli_path",
11693
+ "cli_version",
11694
+ "model",
11695
+ "reasoning_effort",
11696
+ "event_log_path",
11697
+ "status",
11698
+ "started_at",
11699
+ )
11700
+ missing = [field for field in required_strings if not _text(receipt.get(field))]
11701
+ if missing:
11702
+ raise APError("Reviewer runtime receipt is missing: " + ", ".join(missing))
11703
+ attempts = receipt.get("attempts")
11704
+ if not isinstance(attempts, list) or len(attempts) > _REVIEW_RUNTIME_ATTEMPT_LIMIT:
11705
+ raise APError("Reviewer runtime receipt has an invalid attempts list.")
11706
+ allowed_statuses = {
11707
+ "starting",
11708
+ "retrying",
11709
+ "runtime-unavailable",
11710
+ "analysis-timed-out",
11711
+ "output-limit",
11712
+ "failed",
11713
+ "result-invalid",
11714
+ "blocked",
11715
+ "completed",
11716
+ }
11717
+ if _text(receipt.get("status")) not in allowed_statuses:
11718
+ raise APError("Reviewer runtime receipt has an invalid status.")
11719
+ for index, attempt in enumerate(attempts, start=1):
11720
+ if not isinstance(attempt, dict) or int(attempt.get("attempt") or 0) != index:
11721
+ raise APError("Reviewer runtime receipt attempts are not sequential.")
11722
+ if "stderr_tail" in attempt:
11723
+ raise APError("Reviewer runtime receipt cannot persist raw stderr text.")
11724
+ for field in ("stdout_bytes", "stderr_bytes", "event_count"):
11725
+ value = attempt.get(field)
11726
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
11727
+ raise APError(f"Reviewer runtime receipt attempt {field} is invalid.")
11728
+ return receipt
10363
11729
 
10364
11730
 
10365
11731
  def _review_command_sha256(command: list[str]) -> str:
@@ -10377,26 +11743,63 @@ def _bounded_reviewer_output(value: str, label: str) -> str:
10377
11743
  return value
10378
11744
 
10379
11745
 
10380
- def _read_bounded_reviewer_output(path: Path) -> str:
11746
+ def _read_bounded_reviewer_bytes(path: Path) -> bytes:
10381
11747
  try:
10382
- with path.open("rb") as handle:
11748
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
11749
+ metadata = os.fstat(descriptor)
11750
+ if not stat.S_ISREG(metadata.st_mode):
11751
+ os.close(descriptor)
11752
+ raise APError(f"Reviewer result must be a regular file: {path}")
11753
+ with os.fdopen(descriptor, "rb") as handle:
10383
11754
  payload = handle.read(_REVIEW_OUTPUT_MAX_BYTES + 1)
10384
11755
  except OSError as exc:
10385
11756
  raise APError(f"Cannot read Reviewer result: {path}: {exc}") from exc
10386
11757
  if len(payload) > _REVIEW_OUTPUT_MAX_BYTES:
10387
11758
  raise APError(f"Reviewer result exceeded {_REVIEW_OUTPUT_MAX_BYTES} bytes; refusing oversized output.")
10388
- return payload.decode("utf-8", errors="strict")
11759
+ return payload
11760
+
11761
+
11762
+ def _read_bounded_reviewer_output(path: Path) -> str:
11763
+ return _read_bounded_reviewer_bytes(path).decode("utf-8", errors="strict")
10389
11764
 
10390
11765
 
10391
11766
  def _review_result_file_sha256(path: Path) -> str:
11767
+ return hashlib.sha256(_read_bounded_reviewer_bytes(path)).hexdigest()
11768
+
11769
+
11770
+ def _substantive_reviewer_result(path: Path, assignment: dict) -> Optional[dict]:
11771
+ if path.is_symlink():
11772
+ raise APError("Refusing a symlinked Reviewer result.")
11773
+ if not path.exists():
11774
+ return None
10392
11775
  try:
10393
- with path.open("rb") as handle:
10394
- payload = handle.read(_REVIEW_OUTPUT_MAX_BYTES + 1)
10395
- except OSError as exc:
10396
- raise APError(f"Cannot hash Reviewer result: {path}: {exc}") from exc
10397
- if len(payload) > _REVIEW_OUTPUT_MAX_BYTES:
10398
- raise APError(f"Reviewer result exceeded {_REVIEW_OUTPUT_MAX_BYTES} bytes; refusing oversized output.")
10399
- return hashlib.sha256(payload).hexdigest()
11776
+ payload = json.loads(_read_bounded_reviewer_output(path))
11777
+ result = _normalize_reviewer_runtime_result(assignment, payload)
11778
+ except (APError, json.JSONDecodeError, UnicodeDecodeError):
11779
+ return None
11780
+ if _text(result.get("verdict")) in {"blocked", "changes-requested"}:
11781
+ return result
11782
+ return None
11783
+
11784
+
11785
+ def _substantive_reviewer_event_result(stdout: str, assignment: dict) -> Optional[dict]:
11786
+ substantive: Optional[dict] = None
11787
+ for line in stdout.splitlines():
11788
+ try:
11789
+ event = json.loads(line)
11790
+ item = event.get("item") if isinstance(event, dict) else None
11791
+ if not isinstance(item, dict) or _text(item.get("type")) != "agent_message":
11792
+ continue
11793
+ payload = json.loads(_text(item.get("text")))
11794
+ result = _normalize_reviewer_runtime_result(assignment, payload)
11795
+ except (APError, json.JSONDecodeError, TypeError):
11796
+ continue
11797
+ verdict = _text(result.get("verdict"))
11798
+ if verdict == "blocked":
11799
+ substantive = result
11800
+ elif verdict == "changes-requested" and substantive is None:
11801
+ substantive = result
11802
+ return substantive
10400
11803
 
10401
11804
 
10402
11805
  def _update_review_runtime(
@@ -10419,11 +11822,83 @@ def _update_review_runtime(
10419
11822
  manifest["review"] = review
10420
11823
  receipt = _read_json_object(receipt_path) or {}
10421
11824
  receipt.update(receipt_updates)
11825
+ _validate_review_runtime_receipt(receipt)
10422
11826
  _write_private_json(receipt_path, receipt)
11827
+ review["runtime_receipt_sha256"] = _private_review_file_sha256(
11828
+ receipt_path,
11829
+ "runtime receipt",
11830
+ )
11831
+ if _REVIEW_SHA256_RE.fullmatch(_text(receipt.get("event_log_sha256"))):
11832
+ review["runtime_event_log_sha256"] = _text(receipt.get("event_log_sha256"))
11833
+ if _REVIEW_SHA256_RE.fullmatch(_text(receipt.get("result_sha256"))):
11834
+ review["runtime_result_sha256"] = _text(receipt.get("result_sha256"))
10423
11835
  _save_task_manifest(control_repo, manifest)
10424
11836
  return manifest
10425
11837
 
10426
11838
 
11839
+ def _validate_bound_review_runtime_receipt(
11840
+ control_repo: Path,
11841
+ manifest: dict,
11842
+ assignment: dict,
11843
+ receipt_path: Path,
11844
+ expected_status: str,
11845
+ ) -> dict:
11846
+ review = manifest.get("review") or {}
11847
+ task_id = _text(manifest.get("task_id"))
11848
+ fingerprint = _text(review.get("diff_fingerprint"))
11849
+ expected_result_path, expected_receipt_path = _review_runtime_paths(
11850
+ control_repo,
11851
+ task_id,
11852
+ fingerprint,
11853
+ )
11854
+ if receipt_path.resolve() != expected_receipt_path.resolve():
11855
+ raise APError("Reviewer runtime receipt path is not canonical.")
11856
+ payload = _read_private_review_file(receipt_path, "runtime receipt")
11857
+ try:
11858
+ receipt = json.loads(payload.decode("utf-8"))
11859
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
11860
+ raise APError("Reviewer runtime receipt is invalid JSON.") from exc
11861
+ if not isinstance(receipt, dict):
11862
+ raise APError("Reviewer runtime receipt must contain one JSON object.")
11863
+ _validate_review_runtime_receipt(receipt)
11864
+ expected = {
11865
+ "task_id": task_id,
11866
+ "reviewer": _text(review.get("reviewer")),
11867
+ "diff_fingerprint": fingerprint,
11868
+ "assignment_path": _text(review.get("assignment_path")),
11869
+ "assignment_sha256": _text(review.get("assignment_sha256")),
11870
+ "diff_artifact_path": _text(assignment.get("diff_artifact_path")),
11871
+ "diff_artifact_sha256": _text(assignment.get("diff_artifact_sha256")),
11872
+ "result_path": str(expected_result_path),
11873
+ "command_sha256": _text(review.get("runtime_command_sha256")),
11874
+ "event_log_path": str(
11875
+ _review_runtime_event_log_path(control_repo, task_id, fingerprint)
11876
+ ),
11877
+ "status": expected_status,
11878
+ }
11879
+ mismatched = [field for field, value in expected.items() if receipt.get(field) != value]
11880
+ if mismatched:
11881
+ raise APError(
11882
+ "Reviewer runtime receipt does not match task state: " + ", ".join(mismatched)
11883
+ )
11884
+ receipt_sha256 = hashlib.sha256(payload).hexdigest()
11885
+ if receipt_sha256 != _text(review.get("runtime_receipt_sha256")):
11886
+ raise APError("Reviewer runtime receipt changed after failure finalization.")
11887
+ event_log_path = Path(_text(receipt.get("event_log_path"))).resolve()
11888
+ event_log_sha256 = _private_review_file_sha256(event_log_path, "event log")
11889
+ if event_log_sha256 != _text(receipt.get("event_log_sha256")) or event_log_sha256 != _text(
11890
+ review.get("runtime_event_log_sha256")
11891
+ ):
11892
+ raise APError("Reviewer runtime event log changed after failure finalization.")
11893
+ result_sha256 = _text(receipt.get("result_sha256"))
11894
+ if result_sha256 and (
11895
+ _review_result_file_sha256(expected_result_path) != result_sha256
11896
+ or result_sha256 != _text(review.get("runtime_result_sha256"))
11897
+ ):
11898
+ raise APError("Reviewer runtime result changed after failure finalization.")
11899
+ return receipt
11900
+
11901
+
10427
11902
  def _blocked_reviewer_runtime_result(
10428
11903
  assignment: dict,
10429
11904
  reason: str,
@@ -10455,15 +11930,25 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10455
11930
  manifest = _load_task_manifest(control_repo, task_id)
10456
11931
  review = manifest.get("review") or {}
10457
11932
  assignment_path = Path(_text(review.get("assignment_path"))).resolve()
10458
- assignment = _read_json_object(assignment_path)
10459
- if not assignment:
10460
- raise APError("Review assignment file is missing or invalid.")
10461
- _validate_orchestration_contract("assignment", assignment)
11933
+ assignment = _load_bound_review_assignment(
11934
+ control_repo,
11935
+ manifest,
11936
+ assignment_path,
11937
+ )
10462
11938
  fingerprint = _text(assignment.get("diff_fingerprint"))
11939
+ assignment_sha256 = _text((manifest.get("review") or {}).get("assignment_sha256"))
11940
+ _validate_review_diff_artifact(control_repo, assignment)
11941
+ if _task_review_fingerprint(worktree, manifest, _load_cfg(worktree)) != fingerprint:
11942
+ raise APError("Review assignment is stale; the task-owned working tree changed before Reviewer start.")
10463
11943
  result_path, receipt_path = _review_runtime_paths(control_repo, task_id, fingerprint)
10464
11944
 
10465
11945
  command_override = _text(getattr(args, "runner_command_json", ""))
10466
11946
  if command_override:
11947
+ if _text(os.environ.get("AUTOCODING_TEST_RUNNER_OVERRIDE")) != "1":
11948
+ raise APError(
11949
+ "--runner-command-json is test-only; set AUTOCODING_TEST_RUNNER_OVERRIDE=1 "
11950
+ "inside the isolated test harness."
11951
+ )
10467
11952
  try:
10468
11953
  command_value = json.loads(command_override)
10469
11954
  except json.JSONDecodeError as exc:
@@ -10473,18 +11958,35 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10473
11958
  ):
10474
11959
  raise APError("--runner-command-json must be a non-empty JSON array of argv strings.")
10475
11960
  command = command_value
11961
+ runner_kind = "test-override"
10476
11962
  else:
10477
- command = _codex_reviewer_command(worktree, assignment_path, result_path)
11963
+ command = _codex_reviewer_command(
11964
+ worktree,
11965
+ assignment_path,
11966
+ result_path,
11967
+ review_depth=_text(assignment.get("review_depth")) or "focused",
11968
+ )
11969
+ runner_kind = "codex"
10478
11970
  command_sha256 = _review_command_sha256(command)
11971
+ command_metadata = _reviewer_command_metadata(command, runner_kind)
10479
11972
  started_at = _now_iso()
11973
+ event_log_path = _review_runtime_event_log_path(control_repo, task_id, fingerprint)
10480
11974
  receipt = {
10481
- "schema": 1,
11975
+ "schema": 2,
10482
11976
  "task_id": task_id,
10483
11977
  "reviewer": reviewer,
10484
11978
  "diff_fingerprint": fingerprint,
10485
11979
  "assignment_path": str(assignment_path),
11980
+ "assignment_sha256": assignment_sha256,
11981
+ "diff_artifact_path": _text(assignment.get("diff_artifact_path")),
11982
+ "diff_artifact_sha256": _text(assignment.get("diff_artifact_sha256")),
10486
11983
  "result_path": str(result_path),
10487
11984
  "command_sha256": command_sha256,
11985
+ **command_metadata,
11986
+ "event_log_path": str(event_log_path),
11987
+ "event_log_sha256": "",
11988
+ "attempts": [],
11989
+ "failure_kind": "",
10488
11990
  "status": "starting",
10489
11991
  "started_at": started_at,
10490
11992
  "finished_at": "",
@@ -10496,6 +11998,14 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10496
11998
  current_review = dict(manifest.get("review") or {})
10497
11999
  if _text(current_review.get("diff_fingerprint")) != fingerprint:
10498
12000
  raise APError("Review assignment became stale before Reviewer runtime start.")
12001
+ assignment = _load_bound_review_assignment(
12002
+ control_repo,
12003
+ manifest,
12004
+ assignment_path,
12005
+ )
12006
+ _validate_review_diff_artifact(control_repo, assignment)
12007
+ if _task_review_fingerprint(worktree, manifest, _load_cfg(worktree)) != fingerprint:
12008
+ raise APError("Review assignment is stale; the task-owned working tree changed before Reviewer start.")
10499
12009
  if _text(current_review.get("runtime_state")) or receipt_path.exists():
10500
12010
  raise APError(
10501
12011
  "The supervised Reviewer runtime has already started for this diff fingerprint."
@@ -10503,7 +12013,18 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10503
12013
  deadline = _parse_iso_timestamp(assignment.get("deadline_at"), "deadline_at")
10504
12014
  if _dt.datetime.now(_dt.timezone.utc) >= deadline:
10505
12015
  raise APError("Review assignment deadline expired before Reviewer runtime start.")
10506
- _write_private_json(receipt_path, receipt)
12016
+ if result_path.exists() or result_path.is_symlink():
12017
+ raise APError("Reviewer runtime result already exists before the first attempt.")
12018
+ if event_log_path.exists() or event_log_path.is_symlink():
12019
+ raise APError("Reviewer runtime event log already exists for this diff fingerprint.")
12020
+ event_log = _open_private_review_event_log(event_log_path)
12021
+ try:
12022
+ _validate_review_runtime_receipt(receipt)
12023
+ _write_private_json(receipt_path, receipt)
12024
+ except Exception:
12025
+ event_log.close()
12026
+ event_log_path.unlink(missing_ok=True)
12027
+ raise
10507
12028
  current_review.update(
10508
12029
  {
10509
12030
  "runtime_state": "starting",
@@ -10513,6 +12034,9 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10513
12034
  "runtime_exit_code": None,
10514
12035
  "runtime_command_sha256": command_sha256,
10515
12036
  "runtime_receipt_path": str(receipt_path),
12037
+ "runtime_event_log_path": str(event_log_path),
12038
+ "runtime_attempt_count": 0,
12039
+ "runtime_failure_kind": "",
10516
12040
  }
10517
12041
  )
10518
12042
  manifest["review"] = current_review
@@ -10523,49 +12047,221 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10523
12047
  env.update(
10524
12048
  {
10525
12049
  "AUTOCODING_REVIEW_ASSIGNMENT": str(assignment_path),
12050
+ "AUTOCODING_REVIEW_ASSIGNMENT_SHA256": assignment_sha256,
12051
+ "AUTOCODING_REVIEW_DIFF_ARTIFACT": _text(assignment.get("diff_artifact_path")),
12052
+ "AUTOCODING_REVIEW_DIFF_ARTIFACT_SHA256": _text(assignment.get("diff_artifact_sha256")),
10526
12053
  "AUTOCODING_REVIEW_RESULT": str(result_path),
10527
12054
  "AUTOCODING_REVIEW_DEADLINE": _text(assignment.get("deadline_at")),
10528
12055
  "AUTOCODING_REVIEW_TIMEOUT_SECONDS": str(int(assignment.get("timeout_seconds") or 0)),
10529
12056
  }
10530
12057
  )
10531
12058
  deadline = _parse_iso_timestamp(assignment.get("deadline_at"), "deadline_at")
10532
- remaining = (deadline - _dt.datetime.now(_dt.timezone.utc)).total_seconds()
10533
- try:
10534
- completed = _run_supervised_reviewer_process(
10535
- command,
10536
- cwd=worktree,
10537
- env=env,
10538
- timeout_seconds=remaining,
10539
- )
10540
- except _ReviewerRuntimeTimeout as exc:
12059
+ attempts: list[dict] = []
12060
+ completed: Optional[subprocess.CompletedProcess[str]] = None
12061
+ runtime_failure: Optional[_ReviewerRuntimeFailure] = None
12062
+ failure_kind = ""
12063
+ substantive_result: Optional[dict] = None
12064
+
12065
+ def observed_substantive_result() -> bool:
12066
+ nonlocal substantive_result, runtime_failure, failure_kind
12067
+ try:
12068
+ substantive_result = _substantive_reviewer_result(result_path, assignment)
12069
+ if substantive_result is None and runtime_failure is not None:
12070
+ substantive_result = _substantive_reviewer_event_result(
12071
+ runtime_failure.stdout,
12072
+ assignment,
12073
+ )
12074
+ except APError:
12075
+ runtime_failure = _ReviewerRuntimeInternalError(
12076
+ {"phase": "result-inspection-failed"}
12077
+ )
12078
+ failure_kind = "supervision-error"
12079
+ return True
12080
+ return substantive_result is not None
12081
+
12082
+ for attempt_number in range(1, _REVIEW_RUNTIME_ATTEMPT_LIMIT + 1):
12083
+ remaining = (deadline - _dt.datetime.now(_dt.timezone.utc)).total_seconds()
12084
+ if remaining <= 0:
12085
+ runtime_failure = _ReviewerRuntimeTimeout()
12086
+ failure_kind = "analysis-timeout"
12087
+ break
12088
+ if attempt_number > 1:
12089
+ if result_path.is_symlink():
12090
+ event_log.close()
12091
+ raise APError("Refusing a symlinked Reviewer result before retry.")
12092
+ result_path.unlink(missing_ok=True)
12093
+ try:
12094
+ completed, diagnostics = _run_supervised_reviewer_process(
12095
+ command,
12096
+ cwd=worktree,
12097
+ env=env,
12098
+ timeout_seconds=remaining,
12099
+ startup_timeout_seconds=_review_startup_timeout_seconds(),
12100
+ event_writer=event_log,
12101
+ )
12102
+ attempts.append(
12103
+ _safe_reviewer_attempt(
12104
+ diagnostics,
12105
+ attempt_number,
12106
+ "completed" if completed.returncode == 0 else "failed",
12107
+ )
12108
+ )
12109
+ break
12110
+ except _ReviewerRuntimeUnavailable as exc:
12111
+ runtime_failure = exc
12112
+ failure_kind = "runtime-unavailable"
12113
+ attempts.append(
12114
+ _safe_reviewer_attempt(exc.diagnostics, attempt_number, failure_kind)
12115
+ )
12116
+ if observed_substantive_result():
12117
+ break
12118
+ if attempt_number < _REVIEW_RUNTIME_ATTEMPT_LIMIT:
12119
+ _update_review_runtime(
12120
+ control_repo,
12121
+ task_id,
12122
+ fingerprint,
12123
+ updates={
12124
+ "runtime_state": "retrying",
12125
+ "runtime_attempt_count": attempt_number,
12126
+ "runtime_failure_kind": failure_kind,
12127
+ },
12128
+ receipt_path=receipt_path,
12129
+ receipt_updates={
12130
+ "status": "retrying",
12131
+ "attempts": attempts,
12132
+ "failure_kind": failure_kind,
12133
+ },
12134
+ )
12135
+ continue
12136
+ break
12137
+ except _ReviewerRuntimeTimeout as exc:
12138
+ runtime_failure = exc
12139
+ failure_kind = "analysis-timeout"
12140
+ attempts.append(
12141
+ _safe_reviewer_attempt(exc.diagnostics, attempt_number, failure_kind)
12142
+ )
12143
+ observed_substantive_result()
12144
+ break
12145
+ except _ReviewerRuntimeOutputLimit as exc:
12146
+ runtime_failure = exc
12147
+ failure_kind = "output-limit"
12148
+ attempts.append(
12149
+ _safe_reviewer_attempt(exc.diagnostics, attempt_number, failure_kind)
12150
+ )
12151
+ observed_substantive_result()
12152
+ break
12153
+ except _ReviewerRuntimeInternalError as exc:
12154
+ runtime_failure = exc
12155
+ failure_kind = "supervision-error"
12156
+ attempts.append(
12157
+ _safe_reviewer_attempt(exc.diagnostics, attempt_number, failure_kind)
12158
+ )
12159
+ observed_substantive_result()
12160
+ break
12161
+
12162
+ event_log.close()
12163
+ event_log_sha256 = _private_review_file_sha256(event_log_path, "event log")
12164
+ if runtime_failure is not None:
10541
12165
  finished_at = _now_iso()
12166
+ if substantive_result is not None:
12167
+ _write_private_json(result_path, substantive_result)
12168
+ result_sha256 = _review_result_file_sha256(result_path)
12169
+ _update_review_runtime(
12170
+ control_repo,
12171
+ task_id,
12172
+ fingerprint,
12173
+ updates={
12174
+ "verdict": substantive_result["verdict"],
12175
+ "reason": "substantive Reviewer result observed before runtime failure",
12176
+ "runtime_state": "blocked",
12177
+ "runtime_finished_at": finished_at,
12178
+ "runtime_exit_code": None,
12179
+ "runtime_attempt_count": len(attempts),
12180
+ "runtime_failure_kind": failure_kind,
12181
+ },
12182
+ receipt_path=receipt_path,
12183
+ receipt_updates={
12184
+ "status": "blocked",
12185
+ "finished_at": finished_at,
12186
+ "exit_code": None,
12187
+ "verdict": substantive_result["verdict"],
12188
+ "result_sha256": result_sha256,
12189
+ "attempts": attempts,
12190
+ "failure_kind": failure_kind,
12191
+ "event_log_sha256": event_log_sha256,
12192
+ },
12193
+ )
12194
+ print(json.dumps(substantive_result, ensure_ascii=False, indent=2))
12195
+ raise APError(
12196
+ "Reviewer produced a substantive result before runtime failure; it cannot be bypassed."
12197
+ ) from runtime_failure
12198
+ runtime_state = (
12199
+ "runtime-unavailable"
12200
+ if failure_kind == "runtime-unavailable"
12201
+ else "analysis-timed-out"
12202
+ if failure_kind == "analysis-timeout"
12203
+ else "failed"
12204
+ )
10542
12205
  result = _blocked_reviewer_runtime_result(
10543
12206
  assignment,
10544
- "Reviewer runtime reached its fixed deadline and was terminated.",
10545
- ["runtime_timeout=true"],
12207
+ (
12208
+ "Reviewer runtime was unavailable before analysis started."
12209
+ if failure_kind == "runtime-unavailable"
12210
+ else "Reviewer analysis reached its fixed deadline and was terminated."
12211
+ if failure_kind == "analysis-timeout"
12212
+ else "Reviewer runtime exceeded its bounded output limit."
12213
+ if failure_kind == "output-limit"
12214
+ else "Reviewer runtime supervision failed safely."
12215
+ ),
12216
+ [
12217
+ f"runtime_failure_kind={failure_kind}",
12218
+ f"runtime_attempt_count={len(attempts)}",
12219
+ f"event_log_sha256={event_log_sha256}",
12220
+ ],
10546
12221
  )
10547
12222
  _write_private_json(result_path, result)
12223
+ result_sha256 = _review_result_file_sha256(result_path)
10548
12224
  _update_review_runtime(
10549
12225
  control_repo,
10550
12226
  task_id,
10551
12227
  fingerprint,
10552
12228
  updates={
10553
12229
  "verdict": "blocked",
10554
- "reason": "reviewer runtime timeout",
10555
- "runtime_state": "timed-out",
12230
+ "reason": f"reviewer {failure_kind}",
12231
+ "runtime_state": runtime_state,
10556
12232
  "runtime_finished_at": finished_at,
10557
12233
  "runtime_exit_code": None,
12234
+ "runtime_attempt_count": len(attempts),
12235
+ "runtime_failure_kind": failure_kind,
10558
12236
  },
10559
12237
  receipt_path=receipt_path,
10560
12238
  receipt_updates={
10561
- "status": "timed-out",
12239
+ "status": (
12240
+ "runtime-unavailable"
12241
+ if failure_kind == "runtime-unavailable"
12242
+ else "analysis-timed-out"
12243
+ if failure_kind == "analysis-timeout"
12244
+ else "output-limit"
12245
+ if failure_kind == "output-limit"
12246
+ else "failed"
12247
+ ),
10562
12248
  "finished_at": finished_at,
10563
12249
  "exit_code": None,
12250
+ "attempts": attempts,
12251
+ "failure_kind": failure_kind,
12252
+ "event_log_sha256": event_log_sha256,
12253
+ "result_sha256": result_sha256,
10564
12254
  },
10565
12255
  )
10566
12256
  print(json.dumps(result, ensure_ascii=False, indent=2))
10567
- raise APError("Reviewer runtime timed out and was terminated; review is blocked.") from exc
12257
+ if runtime_state in {"runtime-unavailable", "analysis-timed-out"}:
12258
+ raise APError(
12259
+ f"Reviewer {failure_kind}; review is blocked unless an explicit runtime override is recorded."
12260
+ ) from runtime_failure
12261
+ raise APError(f"Reviewer {failure_kind}; review is blocked.") from runtime_failure
10568
12262
 
12263
+ if completed is None:
12264
+ raise APError("Reviewer runtime ended without a process result.")
10569
12265
  finished_at = _now_iso()
10570
12266
  if completed.returncode != 0:
10571
12267
  result = _blocked_reviewer_runtime_result(
@@ -10574,6 +12270,7 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10574
12270
  [f"runner_exit_code={completed.returncode}"],
10575
12271
  )
10576
12272
  _write_private_json(result_path, result)
12273
+ result_sha256 = _review_result_file_sha256(result_path)
10577
12274
  _update_review_runtime(
10578
12275
  control_repo,
10579
12276
  task_id,
@@ -10584,12 +12281,18 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10584
12281
  "runtime_state": "failed",
10585
12282
  "runtime_finished_at": finished_at,
10586
12283
  "runtime_exit_code": completed.returncode,
12284
+ "runtime_attempt_count": len(attempts),
12285
+ "runtime_failure_kind": "process-exit",
10587
12286
  },
10588
12287
  receipt_path=receipt_path,
10589
12288
  receipt_updates={
10590
12289
  "status": "failed",
10591
12290
  "finished_at": finished_at,
10592
12291
  "exit_code": completed.returncode,
12292
+ "attempts": attempts,
12293
+ "failure_kind": "process-exit",
12294
+ "event_log_sha256": event_log_sha256,
12295
+ "result_sha256": result_sha256,
10593
12296
  },
10594
12297
  )
10595
12298
  print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -10610,6 +12313,7 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10610
12313
  ["result_contract_valid=false"],
10611
12314
  )
10612
12315
  _write_private_json(result_path, result)
12316
+ result_sha256 = _review_result_file_sha256(result_path)
10613
12317
  _update_review_runtime(
10614
12318
  control_repo,
10615
12319
  task_id,
@@ -10620,12 +12324,18 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10620
12324
  "runtime_state": "failed",
10621
12325
  "runtime_finished_at": finished_at,
10622
12326
  "runtime_exit_code": completed.returncode,
12327
+ "runtime_attempt_count": len(attempts),
12328
+ "runtime_failure_kind": "result-invalid",
10623
12329
  },
10624
12330
  receipt_path=receipt_path,
10625
12331
  receipt_updates={
10626
12332
  "status": "result-invalid",
10627
12333
  "finished_at": finished_at,
10628
12334
  "exit_code": completed.returncode,
12335
+ "attempts": attempts,
12336
+ "failure_kind": "result-invalid",
12337
+ "event_log_sha256": event_log_sha256,
12338
+ "result_sha256": result_sha256,
10629
12339
  },
10630
12340
  )
10631
12341
  print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -10644,6 +12354,8 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10644
12354
  "runtime_state": runtime_state,
10645
12355
  "runtime_finished_at": finished_at,
10646
12356
  "runtime_exit_code": completed.returncode,
12357
+ "runtime_attempt_count": len(attempts),
12358
+ "runtime_failure_kind": "",
10647
12359
  },
10648
12360
  receipt_path=receipt_path,
10649
12361
  receipt_updates={
@@ -10652,6 +12364,9 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10652
12364
  "exit_code": completed.returncode,
10653
12365
  "verdict": result["verdict"],
10654
12366
  "result_sha256": result_sha256,
12367
+ "attempts": attempts,
12368
+ "failure_kind": "",
12369
+ "event_log_sha256": event_log_sha256,
10655
12370
  },
10656
12371
  )
10657
12372
  if result["verdict"] == "blocked":
@@ -10671,6 +12386,130 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10671
12386
  print(json.dumps(result, ensure_ascii=False, indent=2))
10672
12387
 
10673
12388
 
12389
+ def cmd_review_runtime_override(args: argparse.Namespace) -> None:
12390
+ repo = Path(args.repo).resolve()
12391
+ ensure_git_repo(repo)
12392
+ cfg = _load_cfg(repo)
12393
+ task_id = _validate_task_id(args.task_id)
12394
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
12395
+ if not bool(getattr(args, "confirm_runtime_bypass", False)):
12396
+ raise APError("Runtime bypass requires --confirm-runtime-bypass.")
12397
+ authorized_by = _text(getattr(args, "authorized_by", ""))
12398
+ authorization_ref = _text(getattr(args, "authorization_ref", ""))
12399
+ reason = _text(getattr(args, "reason", ""))
12400
+ evidence = list(getattr(args, "evidence", None) or [])
12401
+ for label, value in (
12402
+ ("authorized-by", authorized_by),
12403
+ ("authorization-ref", authorization_ref),
12404
+ ("reason", reason),
12405
+ ):
12406
+ if not value or any(char in value for char in "\0\r\n"):
12407
+ raise APError(f"--{label} must be non-empty and single-line.")
12408
+ if len(reason) < 12:
12409
+ raise APError("--reason must explain the exceptional delivery decision.")
12410
+ if not evidence or not all(
12411
+ isinstance(item, str) and item and not any(char in item for char in "\0\r\n")
12412
+ for item in evidence
12413
+ ):
12414
+ raise APError("Runtime bypass requires at least one single-line --evidence value.")
12415
+
12416
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
12417
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
12418
+ manifest = _load_task_manifest(control_repo, task_id)
12419
+ lifecycle_actor = _text(os.environ.get("CODEX_THREAD_ID"))
12420
+ if not lifecycle_actor or lifecycle_actor != _text(manifest.get("owner")):
12421
+ raise APError("Only the task lifecycle owner may record a Reviewer runtime bypass.")
12422
+ if _text(manifest.get("state")) not in {"active", "pushed", "integration-raced"}:
12423
+ raise APError(f"Task {task_id} cannot accept a runtime bypass in state={manifest.get('state')}.")
12424
+ review = dict(manifest.get("review") or {})
12425
+ runtime_state = _text(review.get("runtime_state"))
12426
+ if runtime_state not in {"runtime-unavailable", "analysis-timed-out"}:
12427
+ raise APError(
12428
+ "Runtime bypass is allowed only after exhausted runtime-unavailable or analysis-timed-out state."
12429
+ )
12430
+ fingerprint = _task_review_fingerprint(worktree, manifest, _load_cfg(worktree))
12431
+ supplied = _text(args.diff_fingerprint)
12432
+ if supplied != fingerprint or _text(review.get("diff_fingerprint")) != fingerprint:
12433
+ raise APError(
12434
+ f"Runtime bypass fingerprint mismatch: supplied={supplied or '(missing)'}, current={fingerprint}."
12435
+ )
12436
+ assignment_path = Path(_text(review.get("assignment_path"))).resolve()
12437
+ assignment = _load_bound_review_assignment(control_repo, manifest, assignment_path)
12438
+ _validate_review_diff_artifact(control_repo, assignment)
12439
+ receipt_path = Path(_text(review.get("runtime_receipt_path"))).resolve()
12440
+ _, expected_receipt_path = _review_runtime_paths(
12441
+ control_repo,
12442
+ task_id,
12443
+ fingerprint,
12444
+ )
12445
+ if receipt_path != expected_receipt_path.resolve():
12446
+ raise APError("Reviewer runtime receipt path is not canonical.")
12447
+ receipt = _validate_bound_review_runtime_receipt(
12448
+ control_repo,
12449
+ manifest,
12450
+ assignment,
12451
+ receipt_path,
12452
+ runtime_state,
12453
+ )
12454
+ if int(receipt.get("schema") or 0) != 2:
12455
+ raise APError("Runtime bypass requires a schema-2 Reviewer receipt.")
12456
+ if runtime_state == "runtime-unavailable" and len(receipt.get("attempts") or []) != _REVIEW_RUNTIME_ATTEMPT_LIMIT:
12457
+ raise APError("Runtime-unavailable bypass requires exhausted startup attempts.")
12458
+ override_path = _review_runtime_override_path(control_repo, task_id, fingerprint)
12459
+ if override_path.exists() or override_path.is_symlink():
12460
+ raise APError("Reviewer runtime override already exists for this diff fingerprint.")
12461
+ payload = {
12462
+ "schema": 1,
12463
+ "task_id": task_id,
12464
+ "diff_fingerprint": fingerprint,
12465
+ "assignment_sha256": _text(review.get("assignment_sha256")),
12466
+ "diff_artifact_sha256": _text(review.get("diff_artifact_sha256")),
12467
+ "runtime_receipt_path": str(receipt_path),
12468
+ "runtime_receipt_sha256": _private_review_file_sha256(
12469
+ receipt_path,
12470
+ "runtime receipt",
12471
+ ),
12472
+ "runtime_failure_state": runtime_state,
12473
+ "user_authorized": True,
12474
+ "authorized_by": authorized_by,
12475
+ "authorization_ref": authorization_ref,
12476
+ "authorized_at": _now_iso(),
12477
+ "lifecycle_owner": lifecycle_actor,
12478
+ "reason": reason,
12479
+ "evidence": evidence,
12480
+ }
12481
+ _write_private_json(override_path, payload)
12482
+ override_sha256 = _private_review_file_sha256(override_path, "runtime override")
12483
+ review.update(
12484
+ {
12485
+ "verdict": "runtime-bypassed",
12486
+ "reason": reason,
12487
+ "reviewed_at": payload["authorized_at"],
12488
+ "runtime_state": "runtime-bypassed",
12489
+ "runtime_override_path": str(override_path),
12490
+ "runtime_override_sha256": override_sha256,
12491
+ }
12492
+ )
12493
+ manifest["review"] = review
12494
+ _save_task_manifest(control_repo, manifest)
12495
+ result = {
12496
+ "task_id": task_id,
12497
+ "verdict": "runtime-bypassed",
12498
+ "diff_fingerprint": fingerprint,
12499
+ "authorized_by": authorized_by,
12500
+ "authorization_ref": authorization_ref,
12501
+ "override_path": str(override_path),
12502
+ "override_sha256": override_sha256,
12503
+ }
12504
+ if bool(getattr(args, "json", False)):
12505
+ print(json.dumps(result, ensure_ascii=False, indent=2))
12506
+ else:
12507
+ print(
12508
+ f"[review-runtime-override] task={task_id} verdict=runtime-bypassed "
12509
+ f"fingerprint={fingerprint}"
12510
+ )
12511
+
12512
+
10674
12513
  def cmd_task_review(args: argparse.Namespace) -> None:
10675
12514
  repo = Path(args.repo).resolve()
10676
12515
  ensure_git_repo(repo)
@@ -10711,7 +12550,16 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10711
12550
  assigned_review = manifest.get("review") or {}
10712
12551
  if bool(manifest.get("review_required")) and not all(
10713
12552
  _text(assigned_review.get(field))
10714
- for field in ("assignment_path", "reviewer", "diff_fingerprint", "deadline_at")
12553
+ for field in (
12554
+ "assignment_path",
12555
+ "assignment_sha256",
12556
+ "reviewer",
12557
+ "diff_fingerprint",
12558
+ "diff_artifact_path",
12559
+ "diff_artifact_sha256",
12560
+ "diff_artifact_format",
12561
+ "deadline_at",
12562
+ )
10715
12563
  ):
10716
12564
  raise APError(
10717
12565
  "Review-required tasks must use review-assignment before task-review."
@@ -10731,23 +12579,29 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10731
12579
  assignment_path = _text(assigned_review.get("assignment_path"))
10732
12580
  assignment: Optional[dict] = None
10733
12581
  if assignment_path:
10734
- expected_assignment_path = (
10735
- _task_state_root(control_repo)
10736
- / "reviews"
10737
- / f"{task_id}-{fingerprint}.assignment.json"
12582
+ expected_assignment_path = _review_assignment_path(
12583
+ control_repo,
12584
+ task_id,
12585
+ fingerprint,
10738
12586
  ).resolve()
10739
12587
  if Path(assignment_path).resolve() != expected_assignment_path:
10740
12588
  raise APError("Review assignment path does not match Git-local task state.")
10741
- assignment = _read_json_object(expected_assignment_path)
10742
- if not assignment:
10743
- raise APError("Review assignment file is missing or invalid.")
10744
- _validate_orchestration_contract("assignment", assignment)
12589
+ assignment = _load_bound_review_assignment(
12590
+ control_repo,
12591
+ manifest,
12592
+ expected_assignment_path,
12593
+ )
10745
12594
  expected_assignment_fields = {
10746
12595
  "task_id": task_id,
10747
12596
  "base_sha": _text(manifest.get("base_sha")),
10748
12597
  "diff_base": _text(manifest.get("base_sha")),
10749
12598
  "diff_head": current_head,
10750
12599
  "diff_fingerprint": fingerprint,
12600
+ "diff_artifact_path": str(
12601
+ _review_diff_artifact_path(control_repo, task_id, fingerprint).resolve()
12602
+ ),
12603
+ "diff_artifact_sha256": _text(assigned_review.get("diff_artifact_sha256")),
12604
+ "diff_artifact_format": _REVIEW_DIFF_ARTIFACT_FORMAT,
10751
12605
  "node_id": reviewer,
10752
12606
  "owning_fixer": _text((manifest.get("writer_lease") or {}).get("holder")),
10753
12607
  "issued_at": _text(assigned_review.get("issued_at")),
@@ -10763,6 +12617,7 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10763
12617
  "Review assignment does not match the recorded task state: "
10764
12618
  + ", ".join(mismatched)
10765
12619
  )
12620
+ _validate_review_diff_artifact(control_repo, assignment)
10766
12621
  if int(assignment.get("scope_revision") or 0) != int(
10767
12622
  manifest.get("scope_revision") or 1
10768
12623
  ):
@@ -10802,13 +12657,34 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10802
12657
  raise APError(
10803
12658
  "Reviewer runtime verdict does not match the requested task-review verdict."
10804
12659
  )
10805
- receipt = _read_json_object(receipt_path)
10806
- if not receipt:
10807
- raise APError("Reviewer runtime receipt is missing or invalid.")
12660
+ receipt = _validate_bound_review_runtime_receipt(
12661
+ control_repo,
12662
+ manifest,
12663
+ assignment,
12664
+ receipt_path,
12665
+ "completed",
12666
+ )
12667
+ if int(receipt.get("schema") or 0) == 2:
12668
+ expected_event_log_path = _review_runtime_event_log_path(
12669
+ control_repo,
12670
+ task_id,
12671
+ fingerprint,
12672
+ ).resolve()
12673
+ if Path(_text(receipt.get("event_log_path"))).resolve() != expected_event_log_path:
12674
+ raise APError("Reviewer runtime event log path is not canonical.")
12675
+ if Path(_text(assigned_review.get("runtime_event_log_path"))).resolve() != expected_event_log_path:
12676
+ raise APError("Reviewer runtime event log manifest binding is invalid.")
12677
+ if _private_review_file_sha256(expected_event_log_path, "event log") != _text(
12678
+ receipt.get("event_log_sha256")
12679
+ ):
12680
+ raise APError("Reviewer runtime event log SHA-256 binding is invalid.")
10808
12681
  expected_receipt = {
10809
12682
  "task_id": task_id,
10810
12683
  "reviewer": reviewer,
10811
12684
  "diff_fingerprint": fingerprint,
12685
+ "assignment_sha256": _text(assigned_review.get("assignment_sha256")),
12686
+ "diff_artifact_path": _text(assignment.get("diff_artifact_path")),
12687
+ "diff_artifact_sha256": _text(assignment.get("diff_artifact_sha256")),
10812
12688
  "result_path": str(expected_result_path),
10813
12689
  "status": "completed",
10814
12690
  "verdict": _text(args.verdict),
@@ -10847,6 +12723,10 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10847
12723
  "reviewed_at": _now_iso(),
10848
12724
  "reason": "",
10849
12725
  "assignment_path": assignment_path,
12726
+ "assignment_sha256": _text(assigned_review.get("assignment_sha256")),
12727
+ "diff_artifact_path": _text(assigned_review.get("diff_artifact_path")),
12728
+ "diff_artifact_sha256": _text(assigned_review.get("diff_artifact_sha256")),
12729
+ "diff_artifact_format": _text(assigned_review.get("diff_artifact_format")),
10850
12730
  "issued_at": _text(assigned_review.get("issued_at")),
10851
12731
  "deadline_at": deadline_at,
10852
12732
  "review_depth": _text(manifest.get("review_depth")),
@@ -11327,6 +13207,22 @@ def _worktree_branches(repo: Path) -> set[str]:
11327
13207
  return branches
11328
13208
 
11329
13209
 
13210
+ def _worktree_task_ids(repo: Path) -> set[str]:
13211
+ task_ids: set[str] = set()
13212
+ for line in run(["git", "worktree", "list", "--porcelain"], cwd=repo).stdout.splitlines():
13213
+ if not line.startswith("worktree "):
13214
+ continue
13215
+ worktree = Path(line[len("worktree ") :].strip())
13216
+ payload = _active_task_manifest(worktree) if worktree.exists() else None
13217
+ if not payload:
13218
+ continue
13219
+ try:
13220
+ task_ids.add(_validate_task_id(_text(payload.get("task_id"))))
13221
+ except APError:
13222
+ continue
13223
+ return task_ids
13224
+
13225
+
11330
13226
  def cmd_task_prune(args: argparse.Namespace) -> None:
11331
13227
  repo = Path(args.repo).resolve()
11332
13228
  ensure_git_repo(repo)
@@ -11410,9 +13306,28 @@ def cmd_task_prune(args: argparse.Namespace) -> None:
11410
13306
  worktree = Path(_text(manifest.get("worktree_path")))
11411
13307
  if worktree.exists():
11412
13308
  continue
11413
- path.unlink(missing_ok=True)
13309
+ _delete_task_manifest(repo, manifest)
11414
13310
  run(["git", "worktree", "prune"], cwd=repo, check=False)
11415
13311
 
13312
+ active_worktree_tasks = _worktree_task_ids(repo)
13313
+ review_root = _task_review_root(repo)
13314
+ _cleanup_stale_review_snapshots(review_root, legacy_root=True)
13315
+ for review_dir in sorted(review_root.iterdir()) if review_root.exists() else []:
13316
+ if not review_dir.is_dir() or review_dir.is_symlink():
13317
+ continue
13318
+ try:
13319
+ orphan_task_id = _validate_task_id(review_dir.name)
13320
+ except APError:
13321
+ continue
13322
+ if _task_registry_path(repo, orphan_task_id).exists() or orphan_task_id in active_worktree_tasks:
13323
+ continue
13324
+ with _repo_lock(repo, f"task-{orphan_task_id}", timeout_s=timeout_s):
13325
+ if _task_registry_path(repo, orphan_task_id).exists():
13326
+ continue
13327
+ if orphan_task_id in _worktree_task_ids(repo):
13328
+ continue
13329
+ _delete_task_review_artifacts(repo, orphan_task_id)
13330
+
11416
13331
  if args.json:
11417
13332
  print(json.dumps({"removed": removed, "skipped": skipped}, ensure_ascii=False, indent=2))
11418
13333
  return
@@ -11525,7 +13440,7 @@ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") ->
11525
13440
  manifest["last_commit"] = commit_sha
11526
13441
  manifest["claimed_paths"] = _changed_files(repo, _text(manifest.get("base_sha")))
11527
13442
  review = manifest.get("review") or {}
11528
- if _text(review.get("verdict")) == "approved":
13443
+ if _text(review.get("verdict")) in {"approved", "runtime-bypassed"}:
11529
13444
  review["diff_head"] = commit_sha
11530
13445
  review["diff_fingerprint"] = _task_review_fingerprint(repo, manifest)
11531
13446
  manifest["review"] = review
@@ -11536,9 +13451,25 @@ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") ->
11536
13451
  def _clear_direct_task(repo: Path, manifest: dict) -> None:
11537
13452
  active_path = _worktree_manifest_path(repo)
11538
13453
  active = _read_json_object(active_path)
13454
+ removed_active = False
11539
13455
  if active and _text(active.get("task_uuid")) == _text(manifest.get("task_uuid")):
11540
- active_path.unlink(missing_ok=True)
11541
- _delete_task_manifest(repo, manifest)
13456
+ try:
13457
+ active_path.unlink(missing_ok=True)
13458
+ removed_active = True
13459
+ except OSError as exc:
13460
+ raise APError(f"Cannot remove direct task checkout state: {active_path}: {exc}") from exc
13461
+ try:
13462
+ _delete_task_manifest(repo, manifest)
13463
+ except APError as exc:
13464
+ if removed_active and active:
13465
+ try:
13466
+ _write_json_object(active_path, active)
13467
+ except (APError, OSError) as restore_exc:
13468
+ raise APError(
13469
+ f"Direct task cleanup failed ({exc}) and its checkout state could not be restored: "
13470
+ f"{restore_exc}"
13471
+ ) from restore_exc
13472
+ raise
11542
13473
 
11543
13474
 
11544
13475
  def _cmd_direct_commit_push_locked(
@@ -11626,6 +13557,7 @@ def _cmd_direct_commit_push_locked(
11626
13557
  unstaged = _unstaged_task_paths(repo)
11627
13558
  if unstaged:
11628
13559
  raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
13560
+ _require_staged_review_matches(repo, cfg, manifest)
11629
13561
  _extend_final_gate_receipt(
11630
13562
  repo,
11631
13563
  cfg,
@@ -11769,6 +13701,7 @@ def _cmd_commit_push_locked(
11769
13701
  raise APError(
11770
13702
  "Task-owned files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged)
11771
13703
  )
13704
+ _require_staged_review_matches(repo, cfg, manifest)
11772
13705
  manifest = _require_task_context(repo, cfg, args.task_id)
11773
13706
  _extend_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
11774
13707
 
@@ -12039,6 +13972,13 @@ def main(argv: Optional[List[str]] = None) -> int:
12039
13972
  s.add_argument("--json", action="store_true")
12040
13973
  s.set_defaults(func=cmd_review_assignment)
12041
13974
 
13975
+ s = sp.add_parser(
13976
+ "review-artifact",
13977
+ help="Verify and emit the immutable Git-local diff artifact for a reviewer assignment",
13978
+ )
13979
+ s.add_argument("--file", required=True)
13980
+ s.set_defaults(func=cmd_review_artifact)
13981
+
12042
13982
  s = sp.add_parser(
12043
13983
  "review-run",
12044
13984
  help="Run the independent Codex Reviewer under the assignment's fixed runtime deadline",
@@ -12049,6 +13989,20 @@ def main(argv: Optional[List[str]] = None) -> int:
12049
13989
  s.add_argument("--runner-command-json", help=argparse.SUPPRESS)
12050
13990
  s.set_defaults(func=cmd_review_run)
12051
13991
 
13992
+ s = sp.add_parser(
13993
+ "review-runtime-override",
13994
+ help="Record an explicit user-authorized bypass for an exhausted Reviewer runtime failure",
13995
+ )
13996
+ s.add_argument("task_id")
13997
+ s.add_argument("--diff-fingerprint", required=True)
13998
+ s.add_argument("--authorized-by", required=True)
13999
+ s.add_argument("--authorization-ref", required=True)
14000
+ s.add_argument("--reason", required=True)
14001
+ s.add_argument("--evidence", action="append", required=True)
14002
+ s.add_argument("--confirm-runtime-bypass", action="store_true")
14003
+ s.add_argument("--json", action="store_true")
14004
+ s.set_defaults(func=cmd_review_runtime_override)
14005
+
12052
14006
  s = sp.add_parser("task-submodule-sync")
12053
14007
  s.add_argument("task_id")
12054
14008
  s.set_defaults(func=cmd_task_submodule_sync)