@elvis1513/auto-coding-skill 4.2.5 → 4.2.7

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.
@@ -16,11 +16,14 @@ import json
16
16
  import os
17
17
  import posixpath
18
18
  import re
19
+ import shlex
19
20
  import shutil
20
21
  import signal
21
22
  import socket
23
+ import stat
22
24
  import subprocess
23
25
  import sys
26
+ import tempfile
24
27
  import time
25
28
  import tomllib
26
29
  import urllib.parse
@@ -60,6 +63,9 @@ _REVIEW_RUNTIME_FIELDS = (
60
63
  "runtime_receipt_path",
61
64
  )
62
65
  _REVIEW_OUTPUT_MAX_BYTES = 1024 * 1024
66
+ _REVIEW_DIFF_ARTIFACT_FORMAT = "git-binary-patch-v1"
67
+ _REVIEW_DIFF_ARTIFACT_MAX_BYTES = 64 * 1024 * 1024
68
+ _REVIEW_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
63
69
  _DEEP_REVIEW_CATEGORIES = {
64
70
  "api",
65
71
  "auth",
@@ -78,6 +84,19 @@ class _ReviewerRuntimeTimeout(RuntimeError):
78
84
  super().__init__("Reviewer runtime exceeded its assignment deadline.")
79
85
  self.stdout = stdout
80
86
  self.stderr = stderr
87
+
88
+
89
+ def _review_diff_artifact_limit() -> int:
90
+ raw = _text(os.environ.get("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES"))
91
+ if not raw:
92
+ return _REVIEW_DIFF_ARTIFACT_MAX_BYTES
93
+ try:
94
+ requested = int(raw)
95
+ except ValueError as exc:
96
+ raise APError("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES must be a positive integer.") from exc
97
+ if requested < 1:
98
+ raise APError("AUTOCODING_REVIEW_ARTIFACT_MAX_BYTES must be a positive integer.")
99
+ return min(requested, _REVIEW_DIFF_ARTIFACT_MAX_BYTES)
81
100
  _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
82
101
  _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
83
102
  _FINAL_GATE_CACHE_SCHEMA = 1
@@ -85,7 +104,7 @@ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
85
104
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
86
105
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
87
106
  "schema_version": 1,
88
- "managed_versions": {"agents": "4.2.5", "engineering": "4.2.5"},
107
+ "managed_versions": {"agents": "4.2.7", "engineering": "4.2.7"},
89
108
  "known_official_engineering_body_sha256": [
90
109
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
91
110
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -1148,8 +1167,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
1148
1167
  if _text(workflow_cfg.get("completion")).lower() != "push":
1149
1168
  workflow_cfg["completion"] = "push"
1150
1169
  changed.append("workflow.completion")
1151
- if _text(workflow_cfg.get("skill_version")) != "4.2.5":
1152
- workflow_cfg["skill_version"] = "4.2.5"
1170
+ if _text(workflow_cfg.get("skill_version")) != "4.2.7":
1171
+ workflow_cfg["skill_version"] = "4.2.7"
1153
1172
  changed.append("workflow.skill_version")
1154
1173
 
1155
1174
  commands_cfg = cfg.setdefault("commands", {})
@@ -1462,16 +1481,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
1462
1481
  if current_agents:
1463
1482
  archive_dir = repo / "docs" / "archive" / "workflow"
1464
1483
  archive_header = (
1465
- "# Archived AGENTS.md before auto-coding-skill 4.2.5\n\n"
1484
+ "# Archived AGENTS.md before auto-coding-skill 4.2.7\n\n"
1466
1485
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
1467
1486
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
1468
1487
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
1469
1488
  )
1470
1489
  archive_content = archive_header + current_agents
1471
- archive = archive_dir / "AGENTS.pre-4.2.5.md"
1490
+ archive = archive_dir / "AGENTS.pre-4.2.7.md"
1472
1491
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
1473
1492
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
1474
- archive = archive_dir / f"AGENTS.pre-4.2.5-{digest}.md"
1493
+ archive = archive_dir / f"AGENTS.pre-4.2.7-{digest}.md"
1475
1494
  if not archive.exists():
1476
1495
  add_action("policy", archive, "archive", "historical and non-authoritative")
1477
1496
  if write:
@@ -2572,12 +2591,125 @@ def _save_task_manifest(repo: Path, manifest: dict, *, strict_worktree: bool = F
2572
2591
  raise
2573
2592
 
2574
2593
 
2594
+ def _guard_review_directory(path: Path, common_dir: Path, *, create: bool) -> None:
2595
+ if path.is_symlink():
2596
+ raise APError(f"Refusing symlinked Git-local review storage: {path}")
2597
+ if path.exists():
2598
+ try:
2599
+ metadata = path.lstat()
2600
+ except OSError as exc:
2601
+ raise APError(f"Cannot inspect Git-local review storage: {path}: {exc}") from exc
2602
+ if not stat.S_ISDIR(metadata.st_mode):
2603
+ raise APError(f"Git-local review storage must be a directory: {path}")
2604
+ elif create:
2605
+ try:
2606
+ path.mkdir(mode=0o700)
2607
+ except FileExistsError:
2608
+ _guard_review_directory(path, common_dir, create=False)
2609
+ except OSError as exc:
2610
+ raise APError(f"Cannot create Git-local review storage: {path}: {exc}") from exc
2611
+ try:
2612
+ resolved = path.resolve()
2613
+ resolved.relative_to(common_dir)
2614
+ except (OSError, ValueError) as exc:
2615
+ raise APError(f"Git-local review storage escapes the Git common directory: {path}") from exc
2616
+ if os.name == "posix" and path.exists():
2617
+ try:
2618
+ path.chmod(0o700)
2619
+ except OSError as exc:
2620
+ raise APError(f"Cannot protect Git-local review storage: {path}: {exc}") from exc
2621
+
2622
+
2623
+ def _task_review_root(repo: Path, *, create: bool = False) -> Path:
2624
+ common_dir = _git_common_dir(repo).resolve()
2625
+ state_root = common_dir / "auto-coding-skill"
2626
+ review_root = state_root / "reviews"
2627
+ _guard_review_directory(state_root, common_dir, create=create)
2628
+ if state_root.exists():
2629
+ _guard_review_directory(review_root, common_dir, create=create)
2630
+ return review_root
2631
+
2632
+
2633
+ def _task_review_dir(repo: Path, task_id: str, *, create: bool = False) -> Path:
2634
+ common_dir = _git_common_dir(repo).resolve()
2635
+ review_root = _task_review_root(repo, create=create)
2636
+ review_dir = review_root / _validate_task_id(task_id)
2637
+ if review_root.exists():
2638
+ _guard_review_directory(review_dir, common_dir, create=create)
2639
+ return review_dir
2640
+
2641
+
2642
+ def _process_is_running(pid: int) -> bool:
2643
+ if pid <= 0:
2644
+ return False
2645
+ try:
2646
+ os.kill(pid, 0)
2647
+ except ProcessLookupError:
2648
+ return False
2649
+ except PermissionError:
2650
+ return True
2651
+ except OSError:
2652
+ return False
2653
+ return True
2654
+
2655
+
2656
+ def _cleanup_stale_review_snapshots(root: Path, *, legacy_root: bool = False) -> None:
2657
+ if not root.exists() or root.is_symlink():
2658
+ return
2659
+ now = time.time()
2660
+ for candidate in sorted(root.glob(".snapshot-*")):
2661
+ if not candidate.is_dir() or candidate.is_symlink():
2662
+ continue
2663
+ match = re.fullmatch(r"\.snapshot-(\d+)-[A-Za-z0-9_-]+", candidate.name)
2664
+ if match and _process_is_running(int(match.group(1))):
2665
+ continue
2666
+ if not match:
2667
+ try:
2668
+ age_seconds = now - candidate.stat().st_mtime
2669
+ except OSError:
2670
+ continue
2671
+ if not legacy_root or age_seconds < 3600:
2672
+ continue
2673
+ try:
2674
+ shutil.rmtree(candidate)
2675
+ except OSError as exc:
2676
+ raise APError(f"Cannot remove stale Git-local review snapshot: {candidate}: {exc}") from exc
2677
+
2678
+
2679
+ def _delete_task_review_artifacts(repo: Path, task_id: str) -> None:
2680
+ review_dir = _task_review_dir(repo, task_id)
2681
+ if review_dir.is_symlink():
2682
+ raise APError(f"Refusing to remove symlinked Git-local review state: {review_dir}")
2683
+ if not review_dir.exists():
2684
+ return
2685
+ try:
2686
+ shutil.rmtree(review_dir)
2687
+ except OSError as exc:
2688
+ raise APError(f"Cannot remove Git-local review state: {review_dir}: {exc}") from exc
2689
+
2690
+
2575
2691
  def _delete_task_manifest(repo: Path, manifest: dict) -> None:
2576
2692
  task_id = _validate_task_id(_text(manifest.get("task_id")))
2693
+ registry_path = _task_registry_path(repo, task_id)
2694
+ try:
2695
+ registry_path.unlink(missing_ok=True)
2696
+ except OSError as exc:
2697
+ raise APError(f"Cannot remove task registry state: {registry_path}: {exc}") from exc
2698
+
2699
+ # Registry deletion is the authoritative lifecycle transition. Review
2700
+ # evidence is deliberately removed afterwards so a registry failure never
2701
+ # leaves a live task without the immutable artifact that justified it. If
2702
+ # artifact cleanup fails, task-prune can safely retry it as orphaned state.
2577
2703
  worktree_value = _text(manifest.get("worktree_path"))
2578
2704
  if worktree_value and Path(worktree_value).exists():
2579
2705
  _clear_final_gate_receipt(Path(worktree_value))
2580
- _task_registry_path(repo, task_id).unlink(missing_ok=True)
2706
+ try:
2707
+ _delete_task_review_artifacts(repo, task_id)
2708
+ except APError as exc:
2709
+ print(
2710
+ f"[task-cleanup] warning: registry removed but Git-local review state remains for task-prune: {exc}",
2711
+ file=sys.stderr,
2712
+ )
2581
2713
 
2582
2714
 
2583
2715
  def _current_branch(repo: Path) -> str:
@@ -3062,15 +3194,41 @@ def _task_staging_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
3062
3194
  return paths
3063
3195
 
3064
3196
 
3065
- def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3197
+ def _review_snapshot_git(
3198
+ repo: Path,
3199
+ arguments: list[str],
3200
+ env: dict[str, str],
3201
+ ) -> str:
3202
+ completed = subprocess.run(
3203
+ ["git", *arguments],
3204
+ cwd=str(repo),
3205
+ env=env,
3206
+ text=True,
3207
+ capture_output=True,
3208
+ check=False,
3209
+ )
3210
+ if completed.returncode != 0:
3211
+ raise APError(
3212
+ f"Cannot capture immutable task review snapshot ({completed.returncode}): "
3213
+ f"git {' '.join(arguments)}\nSTDOUT:\n{completed.stdout}\nSTDERR:\n{completed.stderr}"
3214
+ )
3215
+ return completed.stdout
3216
+
3217
+
3218
+ def _task_review_paths(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> list[str]:
3066
3219
  base_sha = _text(manifest.get("base_sha"))
3067
3220
  owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
3068
3221
  managed = set(_task_managed_paths(cfg or _load_cfg(repo), manifest))
3069
- paths = [
3222
+ return [
3070
3223
  path
3071
3224
  for path in _task_changed_paths_from_base(repo, base_sha)
3072
3225
  if path not in managed and _path_is_owned(path, owned)
3073
3226
  ]
3227
+
3228
+
3229
+ def _task_review_fingerprint_for_tree(manifest: dict, paths: list[str], tree_sha: str) -> str:
3230
+ base_sha = _text(manifest.get("base_sha"))
3231
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
3074
3232
  digest = hashlib.sha256()
3075
3233
  digest.update(
3076
3234
  (
@@ -3082,21 +3240,188 @@ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = N
3082
3240
  digest.update(f"owned:{owned_path}\0".encode("utf-8", errors="surrogateescape"))
3083
3241
  for rel in paths:
3084
3242
  digest.update(f"path:{rel}\0".encode("utf-8", errors="surrogateescape"))
3243
+ digest.update(f"tree:{tree_sha}\0".encode("ascii"))
3244
+ return digest.hexdigest()
3245
+
3246
+
3247
+ def _require_bounded_review_snapshot_input(repo: Path, paths: list[str]) -> None:
3248
+ limit = _review_diff_artifact_limit()
3249
+ total = 0
3250
+ for rel in paths:
3085
3251
  path = repo / rel
3086
3252
  try:
3087
- mode = path.lstat().st_mode
3088
- except OSError:
3089
- digest.update(b"missing\0")
3253
+ metadata = path.lstat()
3254
+ except FileNotFoundError:
3090
3255
  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()
3256
+ except OSError as exc:
3257
+ raise APError(f"Cannot size review snapshot input {rel}: {exc}") from exc
3258
+ if stat.S_ISREG(metadata.st_mode):
3259
+ total += metadata.st_size
3260
+ elif stat.S_ISLNK(metadata.st_mode):
3261
+ try:
3262
+ total += len(os.readlink(path).encode("utf-8", errors="surrogateescape"))
3263
+ except OSError as exc:
3264
+ raise APError(f"Cannot size review snapshot symlink {rel}: {exc}") from exc
3265
+ if total > limit:
3266
+ raise APError(
3267
+ "Task-owned review snapshot input exceeds the 64 MiB safety limit; "
3268
+ "narrow the task-owned scope or use a project-specific large-artifact review path."
3269
+ )
3270
+
3271
+
3272
+ def _task_review_snapshot(
3273
+ repo: Path,
3274
+ manifest: dict,
3275
+ cfg: Optional[dict] = None,
3276
+ *,
3277
+ include_patch: bool = False,
3278
+ ) -> dict:
3279
+ base_sha = _text(manifest.get("base_sha"))
3280
+ paths = _task_review_paths(repo, manifest, cfg)
3281
+ _require_bounded_review_snapshot_input(repo, paths)
3282
+ task_id = _validate_task_id(_text(manifest.get("task_id")))
3283
+ review_root = _task_review_dir(repo, task_id, create=True)
3284
+ _cleanup_stale_review_snapshots(review_root)
3285
+ snapshot_root = Path(
3286
+ tempfile.mkdtemp(prefix=f".snapshot-{os.getpid()}-", dir=review_root)
3287
+ )
3288
+ if os.name == "posix":
3289
+ snapshot_root.chmod(0o700)
3290
+ index_path = snapshot_root / "index"
3291
+ object_dir = snapshot_root / "objects"
3292
+ object_dir.mkdir(mode=0o700)
3293
+ env = os.environ.copy()
3294
+ inherited_alternates = _text(env.get("GIT_ALTERNATE_OBJECT_DIRECTORIES"))
3295
+ alternates = [str((_git_common_dir(repo) / "objects").resolve())]
3296
+ if inherited_alternates:
3297
+ alternates.append(inherited_alternates)
3298
+ env.update(
3299
+ {
3300
+ "GIT_INDEX_FILE": str(index_path),
3301
+ "GIT_OBJECT_DIRECTORY": str(object_dir),
3302
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": os.pathsep.join(alternates),
3303
+ "GIT_PAGER": "cat",
3304
+ }
3305
+ )
3306
+ try:
3307
+ _review_snapshot_git(repo, ["read-tree", base_sha], env)
3308
+ for start in range(0, len(paths), 100):
3309
+ _review_snapshot_git(
3310
+ repo,
3311
+ ["add", "-A", "--", *paths[start : start + 100]],
3312
+ env,
3313
+ )
3314
+ tree_sha = _text(_review_snapshot_git(repo, ["write-tree"], env))
3315
+ if not tree_sha:
3316
+ raise APError("Cannot capture immutable task review snapshot tree.")
3317
+ patch = b""
3318
+ if include_patch:
3319
+ patch_path = snapshot_root / "review.patch"
3320
+ patch_arguments = [
3321
+ "git",
3322
+ "diff",
3323
+ "--binary",
3324
+ "--full-index",
3325
+ "--no-renames",
3326
+ "--no-ext-diff",
3327
+ "--no-textconv",
3328
+ "--no-color",
3329
+ "--diff-algorithm=myers",
3330
+ "--no-indent-heuristic",
3331
+ "--src-prefix=a/",
3332
+ "--dst-prefix=b/",
3333
+ base_sha,
3334
+ tree_sha,
3335
+ "--",
3336
+ ]
3337
+ patch_limit = _review_diff_artifact_limit()
3338
+ stderr_path = snapshot_root / "review.stderr"
3339
+ process: Optional[subprocess.Popen[bytes]] = None
3340
+ try:
3341
+ with patch_path.open("wb") as handle, stderr_path.open("wb") as stderr_handle:
3342
+ process = subprocess.Popen(
3343
+ patch_arguments,
3344
+ cwd=str(repo),
3345
+ env=env,
3346
+ stdout=subprocess.PIPE,
3347
+ stderr=stderr_handle,
3348
+ )
3349
+ if process.stdout is None:
3350
+ raise APError("Cannot capture immutable task review patch output.")
3351
+ patch_size = 0
3352
+ while True:
3353
+ chunk = process.stdout.read(64 * 1024)
3354
+ if not chunk:
3355
+ break
3356
+ patch_size += len(chunk)
3357
+ if patch_size > patch_limit:
3358
+ if process.poll() is None:
3359
+ process.terminate()
3360
+ try:
3361
+ process.wait(timeout=2)
3362
+ except subprocess.TimeoutExpired:
3363
+ process.kill()
3364
+ process.wait(timeout=2)
3365
+ raise APError(
3366
+ "Immutable task review patch exceeds the 64 MiB safety limit; "
3367
+ "narrow the task-owned scope or review the large artifact through a project-specific path."
3368
+ )
3369
+ handle.write(chunk)
3370
+ handle.flush()
3371
+ os.fsync(handle.fileno())
3372
+ returncode = process.wait()
3373
+ except OSError as exc:
3374
+ if process is not None and process.poll() is None:
3375
+ process.kill()
3376
+ process.wait()
3377
+ raise APError(f"Cannot render immutable task review patch: {exc}") from exc
3378
+ if returncode != 0:
3379
+ raise APError(
3380
+ "Cannot render immutable task review patch "
3381
+ f"({returncode}): {stderr_path.read_text(encoding='utf-8', errors='replace')}"
3382
+ )
3383
+ patch = patch_path.read_bytes()
3384
+ finally:
3385
+ try:
3386
+ shutil.rmtree(snapshot_root)
3387
+ except OSError as exc:
3388
+ raise APError(
3389
+ f"Cannot remove temporary Git-local review snapshot state: {snapshot_root}: {exc}"
3390
+ ) from exc
3391
+
3392
+ return {
3393
+ "fingerprint": _task_review_fingerprint_for_tree(manifest, paths, tree_sha),
3394
+ "tree_sha": tree_sha,
3395
+ "paths": paths,
3396
+ "patch": patch,
3397
+ "patch_sha256": hashlib.sha256(patch).hexdigest() if include_patch else "",
3398
+ }
3399
+
3400
+
3401
+ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3402
+ return _text(_task_review_snapshot(repo, manifest, cfg).get("fingerprint"))
3403
+
3404
+
3405
+ def _staged_task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
3406
+ tree_sha = _text(run(["git", "write-tree"], cwd=repo).stdout)
3407
+ if not tree_sha:
3408
+ raise APError("Cannot bind the staged task tree to its approved review.")
3409
+ return _task_review_fingerprint_for_tree(
3410
+ manifest,
3411
+ _task_review_paths(repo, manifest, cfg),
3412
+ tree_sha,
3413
+ )
3414
+
3415
+
3416
+ def _require_staged_review_matches(repo: Path, cfg: dict, manifest: dict) -> None:
3417
+ if not bool(manifest.get("review_required", int(manifest.get("schema") or 2) < 3)):
3418
+ return
3419
+ approved = _text((manifest.get("review") or {}).get("diff_fingerprint"))
3420
+ staged = _staged_task_review_fingerprint(repo, manifest, cfg)
3421
+ if staged != approved:
3422
+ raise APError(
3423
+ "The exact staged tree does not match the immutable Reviewer snapshot; refusing to commit."
3424
+ )
3100
3425
 
3101
3426
 
3102
3427
  def _invalidate_task_review(manifest: dict, reason: str) -> None:
@@ -3164,6 +3489,25 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
3164
3489
  raise APError("Approved review fingerprint is stale for the current owned diff.")
3165
3490
  if _text(review.get("diff_base")) != _text(manifest.get("base_sha")):
3166
3491
  raise APError("Approved review base is stale for the current task base.")
3492
+ assignment_path = _text(review.get("assignment_path"))
3493
+ if not assignment_path:
3494
+ raise APError("Approved review has no immutable diff assignment.")
3495
+ expected_assignment_path = _review_assignment_path(
3496
+ repo,
3497
+ _text(manifest.get("task_id")),
3498
+ fingerprint,
3499
+ ).resolve()
3500
+ if Path(assignment_path).resolve() != expected_assignment_path:
3501
+ raise APError("Approved review assignment path does not match Git-local task state.")
3502
+ assignment = _load_bound_review_assignment(
3503
+ repo,
3504
+ manifest,
3505
+ expected_assignment_path,
3506
+ )
3507
+ for field in ("diff_artifact_path", "diff_artifact_sha256", "diff_artifact_format"):
3508
+ if assignment.get(field) != review.get(field):
3509
+ raise APError(f"Approved review {field} binding does not match its assignment.")
3510
+ _validate_review_diff_artifact(repo, assignment)
3167
3511
  return fingerprint
3168
3512
 
3169
3513
 
@@ -6566,6 +6910,9 @@ def _agent_contract_shape() -> tuple[dict, list[str]]:
6566
6910
  "diff_base",
6567
6911
  "diff_head",
6568
6912
  "diff_fingerprint",
6913
+ "diff_artifact_path",
6914
+ "diff_artifact_sha256",
6915
+ "diff_artifact_format",
6569
6916
  "owning_fixer",
6570
6917
  "review_depth",
6571
6918
  "timeout_seconds",
@@ -6918,9 +7265,21 @@ def _codex_reviewer_command(
6918
7265
  "Install Codex or run review-assignment and use another deadline-capable host."
6919
7266
  )
6920
7267
  instructions = _reviewer_agent_instructions(worktree)
7268
+ artifact_command = shlex.join(
7269
+ [
7270
+ "python3",
7271
+ "docs/tools/autopipeline/ap.py",
7272
+ "review-artifact",
7273
+ "--file",
7274
+ str(assignment_path),
7275
+ ]
7276
+ )
6921
7277
  prompt = (
6922
7278
  f"Review the exact assignment at {assignment_path}. "
6923
- "Stay inside its diff, identity, and deadline. Use "
7279
+ f"Before analysis, run `{artifact_command}`; it verifies diff_artifact_path, "
7280
+ "mode 0600, and diff_artifact_sha256, then emits the immutable patch. "
7281
+ "Review that emitted patch and never substitute a live git diff or diff_base..diff_head. "
7282
+ "Stay inside its identity and deadline. Use "
6924
7283
  "`python3 docs/tools/autopipeline/ap.py agent-result-template --file "
6925
7284
  f"{assignment_path} --verdict <approved|changes-requested|blocked>` when useful. "
6926
7285
  "Return only one JSON object as the final response; do not modify files."
@@ -10145,6 +10504,220 @@ def _parse_iso_timestamp(value: object, field: str) -> _dt.datetime:
10145
10504
  return parsed.astimezone(_dt.timezone.utc)
10146
10505
 
10147
10506
 
10507
+ def _review_assignment_path(control_repo: Path, task_id: str, fingerprint: str) -> Path:
10508
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
10509
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
10510
+ return _task_review_dir(control_repo, task_id) / f"{fingerprint}.assignment.json"
10511
+
10512
+
10513
+ def _review_diff_artifact_path(control_repo: Path, task_id: str, fingerprint: str) -> Path:
10514
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
10515
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
10516
+ return _task_review_dir(control_repo, task_id) / f"{fingerprint}.patch"
10517
+
10518
+
10519
+ def _guard_review_file_parent(path: Path) -> None:
10520
+ task_dir = path.parent
10521
+ review_root = task_dir.parent
10522
+ state_root = review_root.parent
10523
+ common_dir = state_root.parent.resolve()
10524
+ if review_root.name != "reviews" or state_root.name != "auto-coding-skill":
10525
+ raise APError(f"Review file path is outside canonical Git-local storage: {path}")
10526
+ for directory in (state_root, review_root, task_dir):
10527
+ _guard_review_directory(directory, common_dir, create=False)
10528
+ try:
10529
+ task_dir.resolve().relative_to(common_dir)
10530
+ except (OSError, ValueError) as exc:
10531
+ raise APError(f"Review file path escapes the Git common directory: {path}") from exc
10532
+ if path.is_symlink():
10533
+ raise APError(f"Refusing symlinked Git-local review file: {path}")
10534
+
10535
+
10536
+ def _write_private_bytes(path: Path, payload: bytes) -> None:
10537
+ _guard_review_file_parent(path)
10538
+ temporary_name = f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
10539
+ if os.name == "posix":
10540
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
10541
+ directory_fd = -1
10542
+ try:
10543
+ directory_fd = os.open(path.parent, directory_flags)
10544
+ descriptor = os.open(
10545
+ temporary_name,
10546
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0),
10547
+ 0o600,
10548
+ dir_fd=directory_fd,
10549
+ )
10550
+ with os.fdopen(descriptor, "wb") as handle:
10551
+ handle.write(payload)
10552
+ handle.flush()
10553
+ os.fsync(handle.fileno())
10554
+ os.replace(
10555
+ temporary_name,
10556
+ path.name,
10557
+ src_dir_fd=directory_fd,
10558
+ dst_dir_fd=directory_fd,
10559
+ )
10560
+ os.fsync(directory_fd)
10561
+ except OSError as exc:
10562
+ if directory_fd >= 0:
10563
+ try:
10564
+ os.unlink(temporary_name, dir_fd=directory_fd)
10565
+ except OSError:
10566
+ pass
10567
+ raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
10568
+ finally:
10569
+ if directory_fd >= 0:
10570
+ os.close(directory_fd)
10571
+ return
10572
+
10573
+ temporary = path.with_name(temporary_name)
10574
+ try:
10575
+ descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
10576
+ with os.fdopen(descriptor, "wb") as handle:
10577
+ handle.write(payload)
10578
+ handle.flush()
10579
+ os.fsync(handle.fileno())
10580
+ os.replace(temporary, path)
10581
+ except OSError as exc:
10582
+ temporary.unlink(missing_ok=True)
10583
+ raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
10584
+
10585
+
10586
+ def _read_private_review_file(path: Path, label: str) -> bytes:
10587
+ _guard_review_file_parent(path)
10588
+ if os.name == "posix":
10589
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
10590
+ directory_fd = -1
10591
+ file_fd = -1
10592
+ try:
10593
+ directory_fd = os.open(path.parent, directory_flags)
10594
+ file_fd = os.open(
10595
+ path.name,
10596
+ os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0),
10597
+ dir_fd=directory_fd,
10598
+ )
10599
+ metadata = os.fstat(file_fd)
10600
+ if not stat.S_ISREG(metadata.st_mode):
10601
+ raise APError(f"Review {label} must be a regular Git-local file: {path}")
10602
+ if stat.S_IMODE(metadata.st_mode) != 0o600:
10603
+ raise APError(f"Review {label} must use mode 0600: {path}")
10604
+ with os.fdopen(file_fd, "rb") as handle:
10605
+ file_fd = -1
10606
+ return handle.read()
10607
+ except APError:
10608
+ raise
10609
+ except OSError as exc:
10610
+ raise APError(f"Cannot read review {label}: {path}: {exc}") from exc
10611
+ finally:
10612
+ if file_fd >= 0:
10613
+ os.close(file_fd)
10614
+ if directory_fd >= 0:
10615
+ os.close(directory_fd)
10616
+
10617
+ try:
10618
+ metadata = path.lstat()
10619
+ if not stat.S_ISREG(metadata.st_mode) or path.is_symlink():
10620
+ raise APError(f"Review {label} must be a regular Git-local file: {path}")
10621
+ return path.read_bytes()
10622
+ except APError:
10623
+ raise
10624
+ except OSError as exc:
10625
+ raise APError(f"Cannot read review {label}: {path}: {exc}") from exc
10626
+
10627
+
10628
+ def _read_verified_private_review_file(path: Path, expected_sha256: str, label: str) -> bytes:
10629
+ if not _REVIEW_SHA256_RE.fullmatch(_text(expected_sha256)):
10630
+ raise APError(f"Review {label} has an invalid SHA-256 binding.")
10631
+ payload = _read_private_review_file(path, label)
10632
+ actual_sha256 = hashlib.sha256(payload).hexdigest()
10633
+ if actual_sha256 != expected_sha256:
10634
+ raise APError(
10635
+ f"Review {label} SHA-256 mismatch: expected={expected_sha256}, actual={actual_sha256}."
10636
+ )
10637
+ return payload
10638
+
10639
+
10640
+ def _review_assignment_file_sha256(path: Path) -> str:
10641
+ return hashlib.sha256(_read_private_review_file(path, "assignment")).hexdigest()
10642
+
10643
+
10644
+ def _read_private_review_json(path: Path, label: str) -> Optional[dict]:
10645
+ try:
10646
+ payload = json.loads(_read_private_review_file(path, label).decode("utf-8"))
10647
+ except (json.JSONDecodeError, UnicodeDecodeError):
10648
+ return None
10649
+ return payload if isinstance(payload, dict) else None
10650
+
10651
+
10652
+ def _load_bound_review_assignment(
10653
+ control_repo: Path,
10654
+ manifest: dict,
10655
+ assignment_path: Path,
10656
+ ) -> dict:
10657
+ review = manifest.get("review") or {}
10658
+ fingerprint = _text(review.get("diff_fingerprint"))
10659
+ expected_path = _review_assignment_path(
10660
+ control_repo,
10661
+ _text(manifest.get("task_id")),
10662
+ fingerprint,
10663
+ ).resolve()
10664
+ if assignment_path.resolve() != expected_path:
10665
+ raise APError("Review assignment path does not match canonical Git-local task state.")
10666
+ if _text(review.get("assignment_path")) and Path(_text(review.get("assignment_path"))).resolve() != expected_path:
10667
+ raise APError("Review assignment manifest path does not match canonical Git-local task state.")
10668
+ expected_sha256 = _text(review.get("assignment_sha256"))
10669
+ if not _REVIEW_SHA256_RE.fullmatch(expected_sha256):
10670
+ raise APError("Review assignment has no valid manifest SHA-256 binding.")
10671
+ payload = _read_private_review_file(expected_path, "assignment")
10672
+ if len(payload) > 1024 * 1024:
10673
+ raise APError("Review assignment exceeds the 1 MiB contract limit.")
10674
+ actual_sha256 = hashlib.sha256(payload).hexdigest()
10675
+ if actual_sha256 != expected_sha256:
10676
+ raise APError(
10677
+ f"Review assignment SHA-256 mismatch: expected={expected_sha256}, actual={actual_sha256}."
10678
+ )
10679
+ try:
10680
+ assignment = json.loads(payload.decode("utf-8"))
10681
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
10682
+ raise APError("Review assignment file is invalid JSON.") from exc
10683
+ if not isinstance(assignment, dict):
10684
+ raise APError("Review assignment file must contain one JSON object.")
10685
+ _validate_orchestration_contract("assignment", assignment)
10686
+ if _text(assignment.get("task_id")) != _text(manifest.get("task_id")):
10687
+ raise APError("Review assignment task identity does not match its manifest.")
10688
+ if _text(assignment.get("diff_fingerprint")) != fingerprint:
10689
+ raise APError("Review assignment fingerprint does not match its manifest.")
10690
+ return assignment
10691
+
10692
+
10693
+ def _persist_review_diff_artifact(path: Path, payload: bytes, expected_sha256: str) -> None:
10694
+ if hashlib.sha256(payload).hexdigest() != expected_sha256:
10695
+ raise APError("Generated review diff artifact SHA-256 is inconsistent.")
10696
+ if path.exists() or path.is_symlink():
10697
+ existing = _read_verified_private_review_file(path, expected_sha256, "diff artifact")
10698
+ if existing != payload:
10699
+ raise APError("Existing immutable review diff artifact does not match the current snapshot.")
10700
+ return
10701
+ _write_private_bytes(path, payload)
10702
+ _read_verified_private_review_file(path, expected_sha256, "diff artifact")
10703
+
10704
+
10705
+ def _validate_review_diff_artifact(control_repo: Path, assignment: dict) -> bytes:
10706
+ task_id = _validate_task_id(_text(assignment.get("task_id")))
10707
+ fingerprint = _text(assignment.get("diff_fingerprint"))
10708
+ expected_path = _review_diff_artifact_path(control_repo, task_id, fingerprint).resolve()
10709
+ supplied_path = Path(_text(assignment.get("diff_artifact_path"))).resolve()
10710
+ if supplied_path != expected_path:
10711
+ raise APError("Review diff artifact path does not match canonical Git-local task state.")
10712
+ if _text(assignment.get("diff_artifact_format")) != _REVIEW_DIFF_ARTIFACT_FORMAT:
10713
+ raise APError("Review diff artifact format is unsupported.")
10714
+ return _read_verified_private_review_file(
10715
+ expected_path,
10716
+ _text(assignment.get("diff_artifact_sha256")),
10717
+ "diff artifact",
10718
+ )
10719
+
10720
+
10148
10721
  def _task_review_policy(cfg: dict, worktree: Path, manifest: dict) -> tuple[str, int]:
10149
10722
  changed_paths = _task_changed_paths_from_base(worktree, _text(manifest.get("base_sha")))
10150
10723
  plan = _resolve_execution_plan(
@@ -10187,12 +10760,12 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10187
10760
  worktree,
10188
10761
  _text(manifest.get("base_sha")),
10189
10762
  )
10190
- owned_paths = [
10763
+ changed_owned_paths = [
10191
10764
  path
10192
10765
  for path in changed_paths
10193
10766
  if _path_is_owned(path, list(manifest.get("owned_paths") or []))
10194
10767
  ]
10195
- if not owned_paths:
10768
+ if not changed_owned_paths:
10196
10769
  raise APError("Cannot issue a review assignment before the task has an owned diff.")
10197
10770
  reviewer = _text(args.reviewer)
10198
10771
  if not reviewer or any(char in reviewer for char in "\0\r\n"):
@@ -10201,7 +10774,19 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10201
10774
  owning_fixer = _text((manifest.get("writer_lease") or {}).get("holder")) or owner
10202
10775
  if reviewer in {owner, owning_fixer}:
10203
10776
  raise APError("Independent reviewer must differ from lifecycle owner and owning fixer.")
10204
- fingerprint = _task_review_fingerprint(worktree, manifest, worktree_cfg)
10777
+ snapshot = _task_review_snapshot(
10778
+ worktree,
10779
+ manifest,
10780
+ worktree_cfg,
10781
+ include_patch=True,
10782
+ )
10783
+ fingerprint = _text(snapshot.get("fingerprint"))
10784
+ patch = snapshot.get("patch")
10785
+ if not isinstance(patch, bytes) or not patch:
10786
+ raise APError("Cannot issue a review assignment for an empty immutable diff snapshot.")
10787
+ artifact_sha256 = _text(snapshot.get("patch_sha256"))
10788
+ artifact_path = _review_diff_artifact_path(control_repo, task_id, fingerprint)
10789
+ _persist_review_diff_artifact(artifact_path, patch, artifact_sha256)
10205
10790
  depth, review_timeout = _task_review_policy(worktree_cfg, worktree, manifest)
10206
10791
  issued = _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
10207
10792
  deadline = issued + _dt.timedelta(seconds=review_timeout)
@@ -10214,12 +10799,19 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10214
10799
  "scope": f"Review the task-owned diff for {task_id}",
10215
10800
  "depends_on": [owning_fixer],
10216
10801
  "acceptance": [
10217
- "Review only the assigned stable diff and supplied evidence.",
10802
+ "Verify diff_artifact_sha256 and review only the immutable diff artifact.",
10218
10803
  "Return the complete 16-field reviewer result bound to diff_fingerprint.",
10219
10804
  ],
10805
+ "execution_mode": _text(manifest.get("execution_mode")),
10806
+ "task_branch": _text(manifest.get("task_branch")),
10807
+ "worktree_path": str(worktree.resolve()),
10808
+ "owned_paths": list(manifest.get("owned_paths") or []),
10220
10809
  "diff_base": _text(manifest.get("base_sha")),
10221
10810
  "diff_head": _resolve_commit(worktree, "HEAD"),
10222
10811
  "diff_fingerprint": fingerprint,
10812
+ "diff_artifact_path": str(artifact_path.resolve()),
10813
+ "diff_artifact_sha256": artifact_sha256,
10814
+ "diff_artifact_format": _REVIEW_DIFF_ARTIFACT_FORMAT,
10223
10815
  "owning_fixer": owning_fixer,
10224
10816
  "review_depth": depth,
10225
10817
  "timeout_seconds": review_timeout,
@@ -10228,11 +10820,7 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10228
10820
  "scope_revision": int(manifest.get("scope_revision") or 1),
10229
10821
  }
10230
10822
  _validate_orchestration_contract("assignment", assignment)
10231
- assignment_path = (
10232
- _task_state_root(control_repo)
10233
- / "reviews"
10234
- / f"{task_id}-{fingerprint}.assignment.json"
10235
- )
10823
+ assignment_path = _review_assignment_path(control_repo, task_id, fingerprint)
10236
10824
  prior_review = manifest.get("review") or {}
10237
10825
  if (
10238
10826
  _text(prior_review.get("diff_fingerprint")) == fingerprint
@@ -10246,16 +10834,46 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10246
10834
  raise APError(
10247
10835
  "The single review attempt for this diff fingerprint is already complete or consumed."
10248
10836
  )
10249
- existing_assignment = _read_json_object(assignment_path)
10837
+ if assignment_path.exists() or assignment_path.is_symlink():
10838
+ if (
10839
+ _text(prior_review.get("diff_fingerprint")) == fingerprint
10840
+ and _text(prior_review.get("assignment_sha256"))
10841
+ ):
10842
+ existing_assignment = _load_bound_review_assignment(
10843
+ control_repo,
10844
+ manifest,
10845
+ assignment_path,
10846
+ )
10847
+ else:
10848
+ existing_assignment = _read_private_review_json(
10849
+ assignment_path,
10850
+ "assignment",
10851
+ )
10852
+ else:
10853
+ existing_assignment = None
10250
10854
  if existing_assignment:
10251
10855
  _validate_orchestration_contract("assignment", existing_assignment)
10252
10856
  expected_fields = {
10857
+ "contract_version": assignment["contract_version"],
10253
10858
  "task_id": task_id,
10859
+ "role": "reviewer",
10254
10860
  "base_sha": assignment["base_sha"],
10861
+ "scope": assignment["scope"],
10862
+ "depends_on": assignment["depends_on"],
10863
+ "acceptance": assignment["acceptance"],
10864
+ "execution_mode": assignment["execution_mode"],
10865
+ "task_branch": assignment["task_branch"],
10866
+ "worktree_path": assignment["worktree_path"],
10867
+ "owned_paths": assignment["owned_paths"],
10255
10868
  "diff_base": assignment["diff_base"],
10256
10869
  "diff_head": assignment["diff_head"],
10257
10870
  "diff_fingerprint": fingerprint,
10871
+ "diff_artifact_path": assignment["diff_artifact_path"],
10872
+ "diff_artifact_sha256": assignment["diff_artifact_sha256"],
10873
+ "diff_artifact_format": assignment["diff_artifact_format"],
10258
10874
  "owning_fixer": owning_fixer,
10875
+ "review_depth": assignment["review_depth"],
10876
+ "timeout_seconds": assignment["timeout_seconds"],
10259
10877
  "scope_revision": assignment["scope_revision"],
10260
10878
  }
10261
10879
  mismatched = [
@@ -10273,10 +10891,33 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10273
10891
  "This diff fingerprint already has a reviewer assignment; "
10274
10892
  "the single review attempt cannot be reassigned."
10275
10893
  )
10894
+ existing_issued = _parse_iso_timestamp(
10895
+ existing_assignment.get("issued_at"),
10896
+ "issued_at",
10897
+ )
10898
+ _validate_review_diff_artifact(control_repo, existing_assignment)
10276
10899
  existing_deadline = _parse_iso_timestamp(
10277
10900
  existing_assignment.get("deadline_at"),
10278
10901
  "deadline_at",
10279
10902
  )
10903
+ if int((existing_deadline - existing_issued).total_seconds()) != review_timeout:
10904
+ raise APError("Existing review assignment deadline does not match its fixed timeout.")
10905
+ if _text(prior_review.get("diff_fingerprint")) == fingerprint:
10906
+ expected_prior_fields = {
10907
+ "assignment_path": str(assignment_path),
10908
+ "issued_at": existing_assignment["issued_at"],
10909
+ "deadline_at": existing_assignment["deadline_at"],
10910
+ }
10911
+ prior_mismatches = [
10912
+ field
10913
+ for field, expected in expected_prior_fields.items()
10914
+ if prior_review.get(field) != expected
10915
+ ]
10916
+ if prior_mismatches:
10917
+ raise APError(
10918
+ "Existing review assignment does not match its manifest timing: "
10919
+ + ", ".join(prior_mismatches)
10920
+ )
10280
10921
  if _dt.datetime.now(_dt.timezone.utc) > existing_deadline:
10281
10922
  raise APError(
10282
10923
  "Review attempt timed out and is blocked for this diff fingerprint; "
@@ -10305,11 +10946,12 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10305
10946
  assignment["deadline_at"] = deadline.isoformat()
10306
10947
  assignment["timeout_seconds"] = int((deadline - issued).total_seconds())
10307
10948
  _validate_orchestration_contract("assignment", assignment)
10308
- _write_json_object(assignment_path, assignment)
10949
+ _write_private_json(assignment_path, assignment)
10309
10950
  depth = _text(assignment.get("review_depth"))
10310
10951
  review_timeout = int(assignment.get("timeout_seconds") or 0)
10311
10952
  else:
10312
- _write_json_object(assignment_path, assignment)
10953
+ _write_private_json(assignment_path, assignment)
10954
+ assignment_sha256 = _review_assignment_file_sha256(assignment_path)
10313
10955
  manifest["review_depth"] = depth
10314
10956
  manifest["review_timeout_seconds"] = review_timeout
10315
10957
  review_state = {
@@ -10321,6 +10963,10 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10321
10963
  "reviewed_at": "",
10322
10964
  "reason": "review assignment issued",
10323
10965
  "assignment_path": str(assignment_path),
10966
+ "assignment_sha256": assignment_sha256,
10967
+ "diff_artifact_path": assignment["diff_artifact_path"],
10968
+ "diff_artifact_sha256": assignment["diff_artifact_sha256"],
10969
+ "diff_artifact_format": assignment["diff_artifact_format"],
10324
10970
  "issued_at": assignment["issued_at"],
10325
10971
  "deadline_at": assignment["deadline_at"],
10326
10972
  }
@@ -10344,12 +10990,34 @@ def cmd_review_assignment(args: argparse.Namespace) -> None:
10344
10990
  print(f"[review-assignment] assignment={assignment_path}")
10345
10991
 
10346
10992
 
10993
+ def cmd_review_artifact(args: argparse.Namespace) -> None:
10994
+ repo = Path(args.repo).resolve()
10995
+ ensure_git_repo(repo)
10996
+ assignment_path = Path(args.file).resolve()
10997
+ task_id = _validate_task_id(assignment_path.parent.name)
10998
+ manifest = _load_task_manifest(repo, task_id)
10999
+ assignment = _load_bound_review_assignment(repo, manifest, assignment_path)
11000
+ assigned_worktree = Path(_text(assignment.get("worktree_path"))).resolve()
11001
+ if assigned_worktree != repo:
11002
+ raise APError(
11003
+ f"Review artifact must be read from its assigned worktree: expected={assigned_worktree}, current={repo}."
11004
+ )
11005
+ if _dt.datetime.now(_dt.timezone.utc) >= _parse_iso_timestamp(
11006
+ assignment.get("deadline_at"),
11007
+ "deadline_at",
11008
+ ):
11009
+ raise APError("Review assignment deadline expired before diff artifact access.")
11010
+ payload = _validate_review_diff_artifact(repo, assignment)
11011
+ sys.stdout.flush()
11012
+ sys.stdout.buffer.write(payload)
11013
+ sys.stdout.buffer.flush()
11014
+
11015
+
10347
11016
  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
11017
+ encoded = (
11018
+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
11019
+ ).encode("utf-8")
11020
+ _write_private_bytes(path, encoded)
10353
11021
 
10354
11022
 
10355
11023
  def _review_runtime_paths(
@@ -10357,9 +11025,10 @@ def _review_runtime_paths(
10357
11025
  task_id: str,
10358
11026
  fingerprint: str,
10359
11027
  ) -> 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"
11028
+ if not _REVIEW_SHA256_RE.fullmatch(_text(fingerprint)):
11029
+ raise APError("Review fingerprint must be a lowercase SHA-256 value.")
11030
+ root = _task_review_dir(control_repo, task_id, create=True)
11031
+ return root / f"{fingerprint}.result.json", root / f"{fingerprint}.run.json"
10363
11032
 
10364
11033
 
10365
11034
  def _review_command_sha256(command: list[str]) -> str:
@@ -10455,11 +11124,16 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10455
11124
  manifest = _load_task_manifest(control_repo, task_id)
10456
11125
  review = manifest.get("review") or {}
10457
11126
  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)
11127
+ assignment = _load_bound_review_assignment(
11128
+ control_repo,
11129
+ manifest,
11130
+ assignment_path,
11131
+ )
10462
11132
  fingerprint = _text(assignment.get("diff_fingerprint"))
11133
+ assignment_sha256 = _text((manifest.get("review") or {}).get("assignment_sha256"))
11134
+ _validate_review_diff_artifact(control_repo, assignment)
11135
+ if _task_review_fingerprint(worktree, manifest, _load_cfg(worktree)) != fingerprint:
11136
+ raise APError("Review assignment is stale; the task-owned working tree changed before Reviewer start.")
10463
11137
  result_path, receipt_path = _review_runtime_paths(control_repo, task_id, fingerprint)
10464
11138
 
10465
11139
  command_override = _text(getattr(args, "runner_command_json", ""))
@@ -10483,6 +11157,9 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10483
11157
  "reviewer": reviewer,
10484
11158
  "diff_fingerprint": fingerprint,
10485
11159
  "assignment_path": str(assignment_path),
11160
+ "assignment_sha256": assignment_sha256,
11161
+ "diff_artifact_path": _text(assignment.get("diff_artifact_path")),
11162
+ "diff_artifact_sha256": _text(assignment.get("diff_artifact_sha256")),
10486
11163
  "result_path": str(result_path),
10487
11164
  "command_sha256": command_sha256,
10488
11165
  "status": "starting",
@@ -10496,6 +11173,14 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10496
11173
  current_review = dict(manifest.get("review") or {})
10497
11174
  if _text(current_review.get("diff_fingerprint")) != fingerprint:
10498
11175
  raise APError("Review assignment became stale before Reviewer runtime start.")
11176
+ assignment = _load_bound_review_assignment(
11177
+ control_repo,
11178
+ manifest,
11179
+ assignment_path,
11180
+ )
11181
+ _validate_review_diff_artifact(control_repo, assignment)
11182
+ if _task_review_fingerprint(worktree, manifest, _load_cfg(worktree)) != fingerprint:
11183
+ raise APError("Review assignment is stale; the task-owned working tree changed before Reviewer start.")
10499
11184
  if _text(current_review.get("runtime_state")) or receipt_path.exists():
10500
11185
  raise APError(
10501
11186
  "The supervised Reviewer runtime has already started for this diff fingerprint."
@@ -10523,6 +11208,9 @@ def cmd_review_run(args: argparse.Namespace) -> None:
10523
11208
  env.update(
10524
11209
  {
10525
11210
  "AUTOCODING_REVIEW_ASSIGNMENT": str(assignment_path),
11211
+ "AUTOCODING_REVIEW_ASSIGNMENT_SHA256": assignment_sha256,
11212
+ "AUTOCODING_REVIEW_DIFF_ARTIFACT": _text(assignment.get("diff_artifact_path")),
11213
+ "AUTOCODING_REVIEW_DIFF_ARTIFACT_SHA256": _text(assignment.get("diff_artifact_sha256")),
10526
11214
  "AUTOCODING_REVIEW_RESULT": str(result_path),
10527
11215
  "AUTOCODING_REVIEW_DEADLINE": _text(assignment.get("deadline_at")),
10528
11216
  "AUTOCODING_REVIEW_TIMEOUT_SECONDS": str(int(assignment.get("timeout_seconds") or 0)),
@@ -10711,7 +11399,16 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10711
11399
  assigned_review = manifest.get("review") or {}
10712
11400
  if bool(manifest.get("review_required")) and not all(
10713
11401
  _text(assigned_review.get(field))
10714
- for field in ("assignment_path", "reviewer", "diff_fingerprint", "deadline_at")
11402
+ for field in (
11403
+ "assignment_path",
11404
+ "assignment_sha256",
11405
+ "reviewer",
11406
+ "diff_fingerprint",
11407
+ "diff_artifact_path",
11408
+ "diff_artifact_sha256",
11409
+ "diff_artifact_format",
11410
+ "deadline_at",
11411
+ )
10715
11412
  ):
10716
11413
  raise APError(
10717
11414
  "Review-required tasks must use review-assignment before task-review."
@@ -10731,23 +11428,29 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10731
11428
  assignment_path = _text(assigned_review.get("assignment_path"))
10732
11429
  assignment: Optional[dict] = None
10733
11430
  if assignment_path:
10734
- expected_assignment_path = (
10735
- _task_state_root(control_repo)
10736
- / "reviews"
10737
- / f"{task_id}-{fingerprint}.assignment.json"
11431
+ expected_assignment_path = _review_assignment_path(
11432
+ control_repo,
11433
+ task_id,
11434
+ fingerprint,
10738
11435
  ).resolve()
10739
11436
  if Path(assignment_path).resolve() != expected_assignment_path:
10740
11437
  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)
11438
+ assignment = _load_bound_review_assignment(
11439
+ control_repo,
11440
+ manifest,
11441
+ expected_assignment_path,
11442
+ )
10745
11443
  expected_assignment_fields = {
10746
11444
  "task_id": task_id,
10747
11445
  "base_sha": _text(manifest.get("base_sha")),
10748
11446
  "diff_base": _text(manifest.get("base_sha")),
10749
11447
  "diff_head": current_head,
10750
11448
  "diff_fingerprint": fingerprint,
11449
+ "diff_artifact_path": str(
11450
+ _review_diff_artifact_path(control_repo, task_id, fingerprint).resolve()
11451
+ ),
11452
+ "diff_artifact_sha256": _text(assigned_review.get("diff_artifact_sha256")),
11453
+ "diff_artifact_format": _REVIEW_DIFF_ARTIFACT_FORMAT,
10751
11454
  "node_id": reviewer,
10752
11455
  "owning_fixer": _text((manifest.get("writer_lease") or {}).get("holder")),
10753
11456
  "issued_at": _text(assigned_review.get("issued_at")),
@@ -10763,6 +11466,7 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10763
11466
  "Review assignment does not match the recorded task state: "
10764
11467
  + ", ".join(mismatched)
10765
11468
  )
11469
+ _validate_review_diff_artifact(control_repo, assignment)
10766
11470
  if int(assignment.get("scope_revision") or 0) != int(
10767
11471
  manifest.get("scope_revision") or 1
10768
11472
  ):
@@ -10809,6 +11513,9 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10809
11513
  "task_id": task_id,
10810
11514
  "reviewer": reviewer,
10811
11515
  "diff_fingerprint": fingerprint,
11516
+ "assignment_sha256": _text(assigned_review.get("assignment_sha256")),
11517
+ "diff_artifact_path": _text(assignment.get("diff_artifact_path")),
11518
+ "diff_artifact_sha256": _text(assignment.get("diff_artifact_sha256")),
10812
11519
  "result_path": str(expected_result_path),
10813
11520
  "status": "completed",
10814
11521
  "verdict": _text(args.verdict),
@@ -10847,6 +11554,10 @@ def cmd_task_review(args: argparse.Namespace) -> None:
10847
11554
  "reviewed_at": _now_iso(),
10848
11555
  "reason": "",
10849
11556
  "assignment_path": assignment_path,
11557
+ "assignment_sha256": _text(assigned_review.get("assignment_sha256")),
11558
+ "diff_artifact_path": _text(assigned_review.get("diff_artifact_path")),
11559
+ "diff_artifact_sha256": _text(assigned_review.get("diff_artifact_sha256")),
11560
+ "diff_artifact_format": _text(assigned_review.get("diff_artifact_format")),
10850
11561
  "issued_at": _text(assigned_review.get("issued_at")),
10851
11562
  "deadline_at": deadline_at,
10852
11563
  "review_depth": _text(manifest.get("review_depth")),
@@ -11327,6 +12038,22 @@ def _worktree_branches(repo: Path) -> set[str]:
11327
12038
  return branches
11328
12039
 
11329
12040
 
12041
+ def _worktree_task_ids(repo: Path) -> set[str]:
12042
+ task_ids: set[str] = set()
12043
+ for line in run(["git", "worktree", "list", "--porcelain"], cwd=repo).stdout.splitlines():
12044
+ if not line.startswith("worktree "):
12045
+ continue
12046
+ worktree = Path(line[len("worktree ") :].strip())
12047
+ payload = _active_task_manifest(worktree) if worktree.exists() else None
12048
+ if not payload:
12049
+ continue
12050
+ try:
12051
+ task_ids.add(_validate_task_id(_text(payload.get("task_id"))))
12052
+ except APError:
12053
+ continue
12054
+ return task_ids
12055
+
12056
+
11330
12057
  def cmd_task_prune(args: argparse.Namespace) -> None:
11331
12058
  repo = Path(args.repo).resolve()
11332
12059
  ensure_git_repo(repo)
@@ -11410,9 +12137,28 @@ def cmd_task_prune(args: argparse.Namespace) -> None:
11410
12137
  worktree = Path(_text(manifest.get("worktree_path")))
11411
12138
  if worktree.exists():
11412
12139
  continue
11413
- path.unlink(missing_ok=True)
12140
+ _delete_task_manifest(repo, manifest)
11414
12141
  run(["git", "worktree", "prune"], cwd=repo, check=False)
11415
12142
 
12143
+ active_worktree_tasks = _worktree_task_ids(repo)
12144
+ review_root = _task_review_root(repo)
12145
+ _cleanup_stale_review_snapshots(review_root, legacy_root=True)
12146
+ for review_dir in sorted(review_root.iterdir()) if review_root.exists() else []:
12147
+ if not review_dir.is_dir() or review_dir.is_symlink():
12148
+ continue
12149
+ try:
12150
+ orphan_task_id = _validate_task_id(review_dir.name)
12151
+ except APError:
12152
+ continue
12153
+ if _task_registry_path(repo, orphan_task_id).exists() or orphan_task_id in active_worktree_tasks:
12154
+ continue
12155
+ with _repo_lock(repo, f"task-{orphan_task_id}", timeout_s=timeout_s):
12156
+ if _task_registry_path(repo, orphan_task_id).exists():
12157
+ continue
12158
+ if orphan_task_id in _worktree_task_ids(repo):
12159
+ continue
12160
+ _delete_task_review_artifacts(repo, orphan_task_id)
12161
+
11416
12162
  if args.json:
11417
12163
  print(json.dumps({"removed": removed, "skipped": skipped}, ensure_ascii=False, indent=2))
11418
12164
  return
@@ -11536,9 +12282,25 @@ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") ->
11536
12282
  def _clear_direct_task(repo: Path, manifest: dict) -> None:
11537
12283
  active_path = _worktree_manifest_path(repo)
11538
12284
  active = _read_json_object(active_path)
12285
+ removed_active = False
11539
12286
  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)
12287
+ try:
12288
+ active_path.unlink(missing_ok=True)
12289
+ removed_active = True
12290
+ except OSError as exc:
12291
+ raise APError(f"Cannot remove direct task checkout state: {active_path}: {exc}") from exc
12292
+ try:
12293
+ _delete_task_manifest(repo, manifest)
12294
+ except APError as exc:
12295
+ if removed_active and active:
12296
+ try:
12297
+ _write_json_object(active_path, active)
12298
+ except (APError, OSError) as restore_exc:
12299
+ raise APError(
12300
+ f"Direct task cleanup failed ({exc}) and its checkout state could not be restored: "
12301
+ f"{restore_exc}"
12302
+ ) from restore_exc
12303
+ raise
11542
12304
 
11543
12305
 
11544
12306
  def _cmd_direct_commit_push_locked(
@@ -11626,6 +12388,7 @@ def _cmd_direct_commit_push_locked(
11626
12388
  unstaged = _unstaged_task_paths(repo)
11627
12389
  if unstaged:
11628
12390
  raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
12391
+ _require_staged_review_matches(repo, cfg, manifest)
11629
12392
  _extend_final_gate_receipt(
11630
12393
  repo,
11631
12394
  cfg,
@@ -11769,6 +12532,7 @@ def _cmd_commit_push_locked(
11769
12532
  raise APError(
11770
12533
  "Task-owned files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged)
11771
12534
  )
12535
+ _require_staged_review_matches(repo, cfg, manifest)
11772
12536
  manifest = _require_task_context(repo, cfg, args.task_id)
11773
12537
  _extend_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
11774
12538
 
@@ -12039,6 +12803,13 @@ def main(argv: Optional[List[str]] = None) -> int:
12039
12803
  s.add_argument("--json", action="store_true")
12040
12804
  s.set_defaults(func=cmd_review_assignment)
12041
12805
 
12806
+ s = sp.add_parser(
12807
+ "review-artifact",
12808
+ help="Verify and emit the immutable Git-local diff artifact for a reviewer assignment",
12809
+ )
12810
+ s.add_argument("--file", required=True)
12811
+ s.set_defaults(func=cmd_review_artifact)
12812
+
12042
12813
  s = sp.add_parser(
12043
12814
  "review-run",
12044
12815
  help="Run the independent Codex Reviewer under the assignment's fixed runtime deadline",