@elvis1513/auto-coding-skill 4.1.9 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -42,12 +42,25 @@ _GENERATED_NOISE_PATTERNS = [
42
42
  ]
43
43
  _AGENT_CONTRACT_VERSION = 1
44
44
  _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
45
+ _FOCUSED_REVIEW_TIMEOUT_SECONDS = 90
46
+ _DEEP_REVIEW_TIMEOUT_SECONDS = 300
47
+ _DEEP_REVIEW_CATEGORIES = {
48
+ "api",
49
+ "auth",
50
+ "db",
51
+ "file_transfer",
52
+ "gateway",
53
+ "payment",
54
+ "prod_config",
55
+ }
45
56
  _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
46
57
  _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
58
+ _FINAL_GATE_CACHE_SCHEMA = 1
59
+ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
47
60
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
48
61
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
49
62
  "schema_version": 1,
50
- "managed_versions": {"agents": "4.1.9", "engineering": "4.1.9"},
63
+ "managed_versions": {"agents": "4.2.1", "engineering": "4.2.1"},
51
64
  "known_official_engineering_body_sha256": [
52
65
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
53
66
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -960,8 +973,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
960
973
  if _text(workflow_cfg.get("completion")).lower() != "push":
961
974
  workflow_cfg["completion"] = "push"
962
975
  changed.append("workflow.completion")
963
- if _text(workflow_cfg.get("skill_version")) != "4.1.9":
964
- workflow_cfg["skill_version"] = "4.1.9"
976
+ if _text(workflow_cfg.get("skill_version")) != "4.2.1":
977
+ workflow_cfg["skill_version"] = "4.2.1"
965
978
  changed.append("workflow.skill_version")
966
979
 
967
980
  commands_cfg = cfg.setdefault("commands", {})
@@ -1274,16 +1287,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
1274
1287
  if current_agents:
1275
1288
  archive_dir = repo / "docs" / "archive" / "workflow"
1276
1289
  archive_header = (
1277
- "# Archived AGENTS.md before auto-coding-skill 4.1.9\n\n"
1290
+ "# Archived AGENTS.md before auto-coding-skill 4.2.1\n\n"
1278
1291
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
1279
1292
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
1280
1293
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
1281
1294
  )
1282
1295
  archive_content = archive_header + current_agents
1283
- archive = archive_dir / "AGENTS.pre-4.1.9.md"
1296
+ archive = archive_dir / "AGENTS.pre-4.2.1.md"
1284
1297
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
1285
1298
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
1286
- archive = archive_dir / f"AGENTS.pre-4.1.9-{digest}.md"
1299
+ archive = archive_dir / f"AGENTS.pre-4.2.1-{digest}.md"
1287
1300
  if not archive.exists():
1288
1301
  add_action("policy", archive, "archive", "historical and non-authoritative")
1289
1302
  if write:
@@ -2064,9 +2077,38 @@ def _active_direct_claims(repo: Path) -> list[dict]:
2064
2077
  return []
2065
2078
  active: list[dict] = []
2066
2079
  for path in sorted(root.glob("*.json")):
2067
- payload = _read_json_object(path) or {}
2068
- worktree = Path(_text(payload.get("worktree_path"))).resolve()
2069
- valid_checkout = worktree.exists() and _text(payload.get("worktree_path"))
2080
+ payload = _read_json_object(path)
2081
+ if payload is None:
2082
+ raise APError(
2083
+ f"Direct claim registry is unreadable or invalid JSON: {path}. "
2084
+ "Refusing to assume the checkout has no active writer."
2085
+ )
2086
+ try:
2087
+ schema = int(payload.get("schema") or 0)
2088
+ except (TypeError, ValueError) as exc:
2089
+ raise APError(f"Direct claim registry has an invalid schema: {path}") from exc
2090
+ claim_id = _text(payload.get("claim_id"))
2091
+ worktree_value = _text(payload.get("worktree_path"))
2092
+ owned_paths = payload.get("owned_paths")
2093
+ if (
2094
+ schema != 1
2095
+ or _text(payload.get("state")) != "active"
2096
+ or claim_id != path.stem
2097
+ or not _DIRECT_CLAIM_ID_RE.fullmatch(claim_id)
2098
+ or not _text(payload.get("owner"))
2099
+ or not _text(payload.get("base_sha"))
2100
+ or not _text(payload.get("branch"))
2101
+ or not worktree_value
2102
+ or not isinstance(owned_paths, list)
2103
+ or not owned_paths
2104
+ or not all(isinstance(item, str) and _text(item) for item in owned_paths)
2105
+ ):
2106
+ raise APError(
2107
+ f"Direct claim registry is malformed: {path}. "
2108
+ "Refusing to assume the checkout has no active writer."
2109
+ )
2110
+ worktree = Path(worktree_value).resolve()
2111
+ valid_checkout = worktree.exists()
2070
2112
  if valid_checkout:
2071
2113
  try:
2072
2114
  valid_checkout = bool(
@@ -2075,11 +2117,7 @@ def _active_direct_claims(repo: Path) -> list[dict]:
2075
2117
  )
2076
2118
  except APError:
2077
2119
  valid_checkout = False
2078
- if (
2079
- int(payload.get("schema") or 0) != 1
2080
- or _text(payload.get("state")) != "active"
2081
- or not valid_checkout
2082
- ):
2120
+ if not valid_checkout:
2083
2121
  path.unlink(missing_ok=True)
2084
2122
  continue
2085
2123
  active.append(payload)
@@ -2112,23 +2150,25 @@ def _create_direct_claim(repo: Path, cfg: dict, owned_paths: list[str], owner: s
2112
2150
  if _has_registered_active_task(repo):
2113
2151
  raise APError("A registered active task acquired repository writes.")
2114
2152
  existing = _active_direct_claims(repo)
2115
- other = [item for item in existing if _text(item.get("owner")) != _text(owner)]
2116
- if other:
2153
+ base_sha = _resolve_commit(repo, "HEAD")
2154
+ worktree_path = str(repo.resolve())
2155
+ if existing:
2117
2156
  raise APError(
2118
2157
  "Another direct writer already owns this checkout: "
2119
- + ", ".join(_text(item.get("owner")) for item in other)
2158
+ + ", ".join(
2159
+ f"{_text(item.get('owner'))}:{_text(item.get('claim_id'))}"
2160
+ for item in existing
2161
+ )
2120
2162
  )
2121
- for item in existing:
2122
- _direct_claim_path(repo, _text(item.get("claim_id"))).unlink(missing_ok=True)
2123
2163
  claim_id = uuid.uuid4().hex
2124
2164
  payload = {
2125
2165
  "schema": 1,
2126
2166
  "claim_id": claim_id,
2127
2167
  "state": "active",
2128
2168
  "owner": _text(owner),
2129
- "base_sha": _resolve_commit(repo, "HEAD"),
2169
+ "base_sha": base_sha,
2130
2170
  "branch": branch,
2131
- "worktree_path": str(repo.resolve()),
2171
+ "worktree_path": worktree_path,
2132
2172
  "owned_paths": normalized,
2133
2173
  "created_at": _now_iso(),
2134
2174
  }
@@ -2173,8 +2213,19 @@ def _has_registered_active_task(repo: Path) -> bool:
2173
2213
  if not registry.exists():
2174
2214
  return False
2175
2215
  for path in sorted(registry.glob("*.json")):
2176
- payload = _read_json_object(path) or {}
2177
- if _text(payload.get("state")) not in {"", "integrated", "cleanup-pending"}:
2216
+ payload = _read_json_object(path)
2217
+ if payload is None:
2218
+ raise APError(
2219
+ f"Task registry is unreadable or invalid JSON: {path}. "
2220
+ "Refusing to assume the checkout has no active writer."
2221
+ )
2222
+ state = _text(payload.get("state"))
2223
+ if not state:
2224
+ raise APError(
2225
+ f"Task registry has no state: {path}. "
2226
+ "Refusing to assume the checkout has no active writer."
2227
+ )
2228
+ if state not in {"integrated", "cleanup-pending"}:
2178
2229
  return True
2179
2230
  return False
2180
2231
 
@@ -2296,6 +2347,19 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
2296
2347
  review_required = manifest.get("review_required", schema < 3)
2297
2348
  if not isinstance(review_required, bool):
2298
2349
  raise APError(f"Task {task_id} has an invalid review_required flag.")
2350
+ try:
2351
+ scope_revision = int(manifest.get("scope_revision") or 1)
2352
+ except (TypeError, ValueError) as exc:
2353
+ raise APError(f"Task {task_id} has an invalid scope_revision.") from exc
2354
+ if scope_revision < 1:
2355
+ raise APError(f"Task {task_id} has an invalid scope_revision.")
2356
+ effective_profile = _text(manifest.get("effective_profile"))
2357
+ if effective_profile and effective_profile not in (_WORKFLOW_PROFILES - {"auto"}):
2358
+ raise APError(f"Task {task_id} has an invalid effective_profile.")
2359
+ if "design_required" in manifest and not isinstance(manifest.get("design_required"), bool):
2360
+ raise APError(f"Task {task_id} has an invalid design_required flag.")
2361
+ if "scope_history" in manifest and not isinstance(manifest.get("scope_history"), list):
2362
+ raise APError(f"Task {task_id} has an invalid scope_history.")
2299
2363
  return manifest
2300
2364
 
2301
2365
 
@@ -2309,7 +2373,7 @@ def _load_task_manifest(repo: Path, task_id: str) -> dict:
2309
2373
  return _validate_task_manifest(repo, manifest, task_id)
2310
2374
 
2311
2375
 
2312
- def _save_task_manifest(repo: Path, manifest: dict) -> None:
2376
+ def _save_task_manifest(repo: Path, manifest: dict, *, strict_worktree: bool = False) -> None:
2313
2377
  _validate_task_manifest(repo, manifest)
2314
2378
  task_id = _validate_task_id(_text(manifest.get("task_id")))
2315
2379
  manifest["updated_at"] = _now_iso()
@@ -2321,11 +2385,15 @@ def _save_task_manifest(repo: Path, manifest: dict) -> None:
2321
2385
  try:
2322
2386
  _write_json_object(_worktree_manifest_path(worktree), manifest)
2323
2387
  except APError:
2324
- pass
2388
+ if strict_worktree:
2389
+ raise
2325
2390
 
2326
2391
 
2327
2392
  def _delete_task_manifest(repo: Path, manifest: dict) -> None:
2328
2393
  task_id = _validate_task_id(_text(manifest.get("task_id")))
2394
+ worktree_value = _text(manifest.get("worktree_path"))
2395
+ if worktree_value and Path(worktree_value).exists():
2396
+ _clear_final_gate_receipt(Path(worktree_value))
2329
2397
  _task_registry_path(repo, task_id).unlink(missing_ok=True)
2330
2398
 
2331
2399
 
@@ -2369,22 +2437,57 @@ def _checked_git_z_paths(repo: Path, command: list[str], context: str) -> list[s
2369
2437
 
2370
2438
 
2371
2439
  def _working_tree_paths(repo: Path) -> list[str]:
2372
- paths: set[str] = set()
2373
- paths.update(
2374
- _git_z_paths(
2375
- repo,
2376
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2377
- )
2440
+ """Return one fail-closed Git status snapshot, including both rename endpoints."""
2441
+ result = run(
2442
+ [
2443
+ "git",
2444
+ "status",
2445
+ "--porcelain=v2",
2446
+ "-z",
2447
+ "--untracked-files=all",
2448
+ "--no-renames",
2449
+ ],
2450
+ cwd=repo,
2451
+ check=False,
2378
2452
  )
2379
- paths.update(
2380
- _git_z_paths(
2381
- repo,
2382
- ["git", "diff", "--cached", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2453
+ if result.returncode != 0:
2454
+ raise APError(
2455
+ "Cannot inspect working tree status; refusing a direct execution plan: "
2456
+ + (result.stderr.strip() or result.stdout.strip() or "git status failed")
2383
2457
  )
2384
- )
2385
- paths.update(
2386
- _git_z_paths(repo, ["git", "ls-files", "--others", "--exclude-standard", "-z"])
2387
- )
2458
+ paths: set[str] = set()
2459
+ entries = result.stdout.split("\0")
2460
+ index = 0
2461
+ while index < len(entries):
2462
+ entry = entries[index]
2463
+ index += 1
2464
+ if not entry:
2465
+ continue
2466
+ record_type = entry[:1]
2467
+ if record_type == "1":
2468
+ fields = entry.split(" ", 8)
2469
+ path = fields[8] if len(fields) == 9 else ""
2470
+ elif record_type == "2":
2471
+ fields = entry.split(" ", 9)
2472
+ path = fields[9] if len(fields) == 10 else ""
2473
+ if index >= len(entries) or not entries[index]:
2474
+ raise APError(
2475
+ "Cannot parse renamed Git path; refusing a direct execution plan."
2476
+ )
2477
+ paths.add(entries[index])
2478
+ index += 1
2479
+ elif record_type == "u":
2480
+ fields = entry.split(" ", 10)
2481
+ path = fields[10] if len(fields) == 11 else ""
2482
+ elif entry.startswith("? "):
2483
+ path = entry[2:]
2484
+ else:
2485
+ path = ""
2486
+ if not path:
2487
+ raise APError(
2488
+ "Cannot parse Git working tree status; refusing a direct execution plan."
2489
+ )
2490
+ paths.add(path)
2388
2491
  return sorted(path.replace("\\", "/") for path in paths if path)
2389
2492
 
2390
2493
 
@@ -2444,13 +2547,13 @@ def _task_content_fingerprint(repo: Path, cfg: dict, manifest: Optional[dict]) -
2444
2547
  if not batch:
2445
2548
  continue
2446
2549
  cached = run(
2447
- ["git", "diff", "--cached", "--binary", "--no-ext-diff", "--", *batch],
2550
+ ["git", "diff", "--cached", "--no-renames", "--binary", "--no-ext-diff", "--", *batch],
2448
2551
  cwd=repo,
2449
2552
  check=False,
2450
2553
  )
2451
2554
  digest.update(cached.stdout.encode("utf-8", errors="surrogateescape"))
2452
2555
  unstaged = run(
2453
- ["git", "diff", "--binary", "--no-ext-diff", "--", *batch],
2556
+ ["git", "diff", "--no-renames", "--binary", "--no-ext-diff", "--", *batch],
2454
2557
  cwd=repo,
2455
2558
  check=False,
2456
2559
  )
@@ -2464,11 +2567,140 @@ def _task_content_fingerprint(repo: Path, cfg: dict, manifest: Optional[dict]) -
2464
2567
  return digest.hexdigest()
2465
2568
 
2466
2569
 
2467
- def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2468
- expected = sorted(set(path for path in paths if path))
2469
- for start in range(0, len(expected), 100):
2470
- run(["git", "add", "-A", "--", *expected[start : start + 100]], cwd=repo)
2471
- staged = sorted(
2570
+ def _final_gate_receipt_path(repo: Path) -> Path:
2571
+ return _git_dir(repo) / "auto-coding-skill-final-gate.json"
2572
+
2573
+
2574
+ def _clear_final_gate_receipt(repo: Path) -> None:
2575
+ try:
2576
+ _final_gate_receipt_path(repo).unlink(missing_ok=True)
2577
+ except APError:
2578
+ return
2579
+
2580
+
2581
+ def _final_gate_identity(
2582
+ repo: Path,
2583
+ cfg: dict,
2584
+ manifest: dict,
2585
+ plan: dict,
2586
+ base_ref: str,
2587
+ ) -> tuple[dict, str]:
2588
+ paths = list(plan.get("changed_files") or [])
2589
+ validation_plan = _validation_plan(cfg, paths)
2590
+ _validate_validation_plan(cfg, validation_plan)
2591
+ command_hashes = {
2592
+ name: hashlib.sha256(_configured_command(cfg, name).encode("utf-8")).hexdigest()
2593
+ for name in validation_plan["commands"]
2594
+ }
2595
+ plan_payload = {
2596
+ "scope": plan.get("selected_scope"),
2597
+ "profile": plan.get("profile"),
2598
+ "effective_mode": plan.get("effective_mode"),
2599
+ "paths": validation_plan["paths"],
2600
+ "commands": validation_plan["commands"],
2601
+ "command_hashes": command_hashes,
2602
+ "command_timeouts": validation_plan["command_timeouts"],
2603
+ "matched_routes": validation_plan["matched_routes"],
2604
+ "coverage": validation_plan["coverage"],
2605
+ "unmapped": validation_plan["unmapped"],
2606
+ "docs_only": validation_plan["docs_only"],
2607
+ "compatibility_fallback": validation_plan["compatibility_fallback"],
2608
+ "on_unmapped": _text(_validation_cfg(cfg).get("on_unmapped")).lower() or "error",
2609
+ "budget": _final_gate_budget(cfg),
2610
+ "diff_check": "working-index-base-v1",
2611
+ }
2612
+ plan_sha256 = hashlib.sha256(
2613
+ json.dumps(plan_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
2614
+ ).hexdigest()
2615
+ resolved_base = _resolve_commit(repo, base_ref or _text(manifest.get("base_sha")) or "HEAD")
2616
+ identity = {
2617
+ "algorithm": _FINAL_GATE_CACHE_ALGORITHM,
2618
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
2619
+ "task_id": _text(manifest.get("task_id")),
2620
+ "task_uuid": _text(manifest.get("task_uuid")),
2621
+ "worktree_path": str(repo.resolve()),
2622
+ "branch": _current_branch(repo),
2623
+ "base_sha": resolved_base,
2624
+ "head_sha": _resolve_commit(repo, "HEAD"),
2625
+ "scope_revision": int(manifest.get("scope_revision") or 1),
2626
+ "owned_paths": sorted(manifest.get("owned_paths") or []),
2627
+ "writer_generation": int((manifest.get("writer_lease") or {}).get("generation") or 0),
2628
+ "plan_sha256": plan_sha256,
2629
+ }
2630
+ return identity, _task_content_fingerprint(repo, cfg, manifest)
2631
+
2632
+
2633
+ def _record_final_gate_receipt(
2634
+ repo: Path,
2635
+ cfg: dict,
2636
+ manifest: dict,
2637
+ plan: dict,
2638
+ base_ref: str,
2639
+ executed: list[str],
2640
+ ) -> None:
2641
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2642
+ _write_json_object(
2643
+ _final_gate_receipt_path(repo),
2644
+ {
2645
+ "schema": _FINAL_GATE_CACHE_SCHEMA,
2646
+ "kind": "final_changed_scope_gate",
2647
+ "status": "pass",
2648
+ "identity": identity,
2649
+ "content_fingerprints": [fingerprint],
2650
+ "executed": list(executed),
2651
+ "passed_at": _now_iso(),
2652
+ },
2653
+ )
2654
+
2655
+
2656
+ def _reuse_final_gate_receipt(
2657
+ repo: Path,
2658
+ cfg: dict,
2659
+ manifest: dict,
2660
+ plan: dict,
2661
+ base_ref: str,
2662
+ ) -> Optional[dict]:
2663
+ receipt = _read_json_object(_final_gate_receipt_path(repo)) or {}
2664
+ if (
2665
+ int(receipt.get("schema") or 0) != _FINAL_GATE_CACHE_SCHEMA
2666
+ or _text(receipt.get("kind")) != "final_changed_scope_gate"
2667
+ or _text(receipt.get("status")) != "pass"
2668
+ ):
2669
+ return None
2670
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2671
+ if receipt.get("identity") != identity:
2672
+ return None
2673
+ allowed = receipt.get("content_fingerprints") or []
2674
+ if not isinstance(allowed, list) or fingerprint not in allowed:
2675
+ return None
2676
+ return receipt
2677
+
2678
+
2679
+ def _extend_final_gate_receipt(
2680
+ repo: Path,
2681
+ cfg: dict,
2682
+ manifest: dict,
2683
+ plan: dict,
2684
+ base_ref: str,
2685
+ ) -> None:
2686
+ receipt = _read_json_object(_final_gate_receipt_path(repo)) or {}
2687
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2688
+ if (
2689
+ int(receipt.get("schema") or 0) != _FINAL_GATE_CACHE_SCHEMA
2690
+ or _text(receipt.get("kind")) != "final_changed_scope_gate"
2691
+ or _text(receipt.get("status")) != "pass"
2692
+ or receipt.get("identity") != identity
2693
+ ):
2694
+ raise APError("The successful final-gate receipt no longer matches the staged task state.")
2695
+ allowed = list(receipt.get("content_fingerprints") or [])
2696
+ if fingerprint not in allowed:
2697
+ allowed.append(fingerprint)
2698
+ receipt["content_fingerprints"] = allowed
2699
+ _write_json_object(_final_gate_receipt_path(repo), receipt)
2700
+
2701
+
2702
+ def _staged_paths(repo: Path) -> list[str]:
2703
+ return sorted(
2472
2704
  set(
2473
2705
  _checked_git_z_paths(
2474
2706
  repo,
@@ -2476,6 +2708,7 @@ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2476
2708
  "git",
2477
2709
  "diff",
2478
2710
  "--cached",
2711
+ "--no-renames",
2479
2712
  "--name-only",
2480
2713
  "-z",
2481
2714
  "--diff-filter=ACDMRTUXB",
@@ -2484,6 +2717,36 @@ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2484
2717
  )
2485
2718
  )
2486
2719
  )
2720
+
2721
+
2722
+ def _exact_stage_plan(repo: Path, paths: list[str], *, dry_run: bool) -> tuple[list[str], list[str]]:
2723
+ expected = sorted(set(path for path in paths if path))
2724
+ expected_set = set(expected)
2725
+ staged = _staged_paths(repo)
2726
+ pending = _unstaged_task_paths(repo)
2727
+ unexpected = sorted((set(staged) | set(pending)) - expected_set)
2728
+ if unexpected:
2729
+ raise APError(
2730
+ "Refusing to commit paths outside the current task:\n- " + "\n- ".join(unexpected)
2731
+ )
2732
+ if dry_run:
2733
+ for start in range(0, len(pending), 100):
2734
+ run(
2735
+ ["git", "add", "--dry-run", "-A", "--", *pending[start : start + 100]],
2736
+ cwd=repo,
2737
+ )
2738
+ return expected, pending
2739
+
2740
+
2741
+ def _preflight_exact_paths(repo: Path, paths: list[str]) -> None:
2742
+ _exact_stage_plan(repo, paths, dry_run=True)
2743
+
2744
+
2745
+ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2746
+ expected, pending = _exact_stage_plan(repo, paths, dry_run=False)
2747
+ for start in range(0, len(pending), 100):
2748
+ run(["git", "add", "-A", "--", *pending[start : start + 100]], cwd=repo)
2749
+ staged = _staged_paths(repo)
2487
2750
  unexpected = sorted(set(staged) - set(expected))
2488
2751
  if unexpected:
2489
2752
  raise APError(
@@ -2569,7 +2832,16 @@ def _task_changed_paths_from_base(repo: Path, base_sha: str) -> list[str]:
2569
2832
  paths = set(
2570
2833
  _checked_git_z_paths(
2571
2834
  repo,
2572
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB", base_sha, "--"],
2835
+ [
2836
+ "git",
2837
+ "diff",
2838
+ "--no-renames",
2839
+ "--name-only",
2840
+ "-z",
2841
+ "--diff-filter=ACDMRTUXB",
2842
+ base_sha,
2843
+ "--",
2844
+ ],
2573
2845
  "task diff paths",
2574
2846
  )
2575
2847
  )
@@ -2593,6 +2865,20 @@ def _task_unowned_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
2593
2865
  ]
2594
2866
 
2595
2867
 
2868
+ def _task_staging_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
2869
+ paths = _task_commit_paths(repo)
2870
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
2871
+ managed = set(_task_managed_paths(cfg, manifest))
2872
+ unowned = [
2873
+ path
2874
+ for path in paths
2875
+ if path not in managed and not _path_is_owned(path, owned)
2876
+ ]
2877
+ if unowned:
2878
+ raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
2879
+ return paths
2880
+
2881
+
2596
2882
  def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
2597
2883
  base_sha = _text(manifest.get("base_sha"))
2598
2884
  owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
@@ -2603,7 +2889,14 @@ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = N
2603
2889
  if path not in managed and _path_is_owned(path, owned)
2604
2890
  ]
2605
2891
  digest = hashlib.sha256()
2606
- digest.update(f"contract:{_AGENT_CONTRACT_VERSION}\nbase:{base_sha}\n".encode("utf-8"))
2892
+ digest.update(
2893
+ (
2894
+ f"contract:{_AGENT_CONTRACT_VERSION}\nbase:{base_sha}\n"
2895
+ f"scope_revision:{int(manifest.get('scope_revision') or 1)}\n"
2896
+ ).encode("utf-8")
2897
+ )
2898
+ for owned_path in owned:
2899
+ digest.update(f"owned:{owned_path}\0".encode("utf-8", errors="surrogateescape"))
2607
2900
  for rel in paths:
2608
2901
  digest.update(f"path:{rel}\0".encode("utf-8", errors="surrogateescape"))
2609
2902
  path = repo / rel
@@ -2691,11 +2984,50 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
2691
2984
  return fingerprint
2692
2985
 
2693
2986
 
2987
+ def _reconcile_task_risk(repo: Path, cfg: dict, manifest: dict) -> None:
2988
+ changed_paths = _task_changed_paths_from_base(repo, _text(manifest.get("base_sha")))
2989
+ plan = _resolve_execution_plan(
2990
+ cfg,
2991
+ repo,
2992
+ changed_paths=changed_paths,
2993
+ planned_paths=list(manifest.get("owned_paths") or []),
2994
+ requested_task_kind="change",
2995
+ )
2996
+ old_profile = _text(manifest.get("effective_profile")) or (
2997
+ "high-risk" if bool(manifest.get("review_required")) else "standard"
2998
+ )
2999
+ planned_profile = _text(plan.get("profile")) or "standard"
3000
+ effective_profile = (
3001
+ planned_profile
3002
+ if _PROFILE_RANK[planned_profile] > _PROFILE_RANK[old_profile]
3003
+ else old_profile
3004
+ )
3005
+ review_required = bool(manifest.get("review_required") or plan.get("review_required"))
3006
+ design_required = bool(manifest.get("design_required") or plan.get("design_required"))
3007
+ escalated = (
3008
+ effective_profile != old_profile
3009
+ or review_required != bool(manifest.get("review_required"))
3010
+ or design_required != bool(manifest.get("design_required"))
3011
+ )
3012
+ if not escalated:
3013
+ return
3014
+ manifest["effective_profile"] = effective_profile
3015
+ manifest["review_required"] = review_required
3016
+ manifest["design_required"] = design_required
3017
+ _invalidate_task_review(manifest, "actual changed paths raised task risk; review again")
3018
+ _clear_final_gate_receipt(repo)
3019
+ _save_task_manifest(repo, manifest)
3020
+ raise APError(
3021
+ "Actual changed paths raised task risk. Complete any necessary design/review and retry "
3022
+ f"commit-push: profile={effective_profile}, review_required={str(review_required).lower()}."
3023
+ )
3024
+
3025
+
2694
3026
  def _unstaged_task_paths(repo: Path) -> list[str]:
2695
3027
  paths = set(
2696
3028
  _checked_git_z_paths(
2697
3029
  repo,
2698
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
3030
+ ["git", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2699
3031
  "unstaged task paths",
2700
3032
  )
2701
3033
  )
@@ -2732,7 +3064,14 @@ def _require_task_context(repo: Path, cfg: dict, task_id: str) -> dict:
2732
3064
  registered = _read_json_object(_task_registry_path(repo, expected_task))
2733
3065
  if not registered:
2734
3066
  raise APError(f"Task registry entry is missing for {expected_task}; refusing to recreate it implicitly.")
2735
- for field in ("task_id", "task_uuid", "task_branch", "worktree_path", "base_sha"):
3067
+ for field in (
3068
+ "task_id",
3069
+ "task_uuid",
3070
+ "task_branch",
3071
+ "worktree_path",
3072
+ "base_sha",
3073
+ "scope_revision",
3074
+ ):
2736
3075
  if _text(registered.get(field)) != _text(manifest.get(field)):
2737
3076
  raise APError(f"Task manifest/registry mismatch for {expected_task}: {field}")
2738
3077
  manifest = registered
@@ -3044,7 +3383,7 @@ def _run_configured_command_list(
3044
3383
  remaining = deadline - time.monotonic()
3045
3384
  if remaining <= 0:
3046
3385
  raise APError(
3047
- "Final changed-scope gate exceeded its total time budget before "
3386
+ "Final changed-scope gate timed out: exceeded its total time budget before "
3048
3387
  f"commands.{name}; narrow validation.routes"
3049
3388
  )
3050
3389
  timeout_s = min(timeout_s, remaining) if timeout_s is not None else remaining
@@ -3103,14 +3442,18 @@ def _default_base_ref(repo: Path) -> str:
3103
3442
  return upstream[0] if upstream else ""
3104
3443
 
3105
3444
 
3445
+ def _effective_change_base(repo: Path, base_ref: str = "") -> str:
3446
+ manifest = _active_task_manifest(repo)
3447
+ return base_ref or (_text(manifest.get("base_sha")) if manifest else "") or _default_base_ref(repo)
3448
+
3449
+
3106
3450
  def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
3107
3451
  paths: list[str] = []
3108
- manifest = _active_task_manifest(repo)
3109
- effective_base = base_ref or (_text(manifest.get("base_sha")) if manifest else "") or _default_base_ref(repo)
3452
+ effective_base = _effective_change_base(repo, base_ref)
3110
3453
  if effective_base:
3111
- paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACDMRTUXB", f"{effective_base}...HEAD"]))
3112
- paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACDMRTUXB"]))
3113
- paths.extend(_git_lines(repo, ["git", "diff", "--cached", "--name-only", "--diff-filter=ACDMRTUXB"]))
3454
+ paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB", f"{effective_base}...HEAD"]))
3455
+ paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB"]))
3456
+ paths.extend(_git_lines(repo, ["git", "diff", "--cached", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB"]))
3114
3457
  paths.extend(_git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"]))
3115
3458
  return _unique_paths(paths)
3116
3459
 
@@ -3123,9 +3466,10 @@ def _commit_changed_files(repo: Path, ref: str) -> list[str]:
3123
3466
  "diff-tree",
3124
3467
  "--root",
3125
3468
  "--no-commit-id",
3469
+ "--no-renames",
3126
3470
  "--name-only",
3127
3471
  "-r",
3128
- "--diff-filter=ACMRTUXB",
3472
+ "--diff-filter=ACDMRTUXB",
3129
3473
  commit_ref,
3130
3474
  ],
3131
3475
  cwd=repo,
@@ -3500,6 +3844,9 @@ def _run_git_diff_check(repo: Path, cfg: dict) -> None:
3500
3844
 
3501
3845
  _DEFAULT_STRUCTURE_ALLOW_PATTERNS = [
3502
3846
  ".git/**",
3847
+ ".agents/archive/**",
3848
+ ".agents/agents/**",
3849
+ ".agents/managed-install.json",
3503
3850
  ".agents/skills/**",
3504
3851
  ".next/**",
3505
3852
  ".nuxt/**",
@@ -4876,7 +5223,7 @@ def _classify_paths(paths: list[str]) -> dict:
4876
5223
  categories.add("gateway")
4877
5224
  if "production" in words or "prod" in words and "config" in words or ".env.prod" in lower:
4878
5225
  categories.add("prod_config")
4879
- if any(token in lower for token in ["page", "component", "view", "frontend", "miniapp", ".tsx", ".jsx", ".vue", ".scss", ".css"]):
5226
+ if _is_ui_path(path):
4880
5227
  categories.add("ui")
4881
5228
  if any(token in lower for token in ["test", "spec", "__tests__"]):
4882
5229
  categories.add("test")
@@ -4887,6 +5234,17 @@ def _classify_paths(paths: list[str]) -> dict:
4887
5234
  return _classification_for_categories(categories, len(paths))
4888
5235
 
4889
5236
 
5237
+ _UI_PATH_SEGMENTS = {"frontend", "miniapp", "page", "pages", "component", "components", "view", "views"}
5238
+ _UI_FILE_SUFFIXES = {".css", ".jsx", ".scss", ".tsx", ".vue"}
5239
+
5240
+
5241
+ def _is_ui_path(path: str) -> bool:
5242
+ """Classify UI paths by exact directory semantics or UI-only extensions."""
5243
+ normalized = path.replace("\\", "/").strip("/").lower()
5244
+ directories = [part for part in normalized.split("/")[:-1] if part]
5245
+ return Path(normalized).suffix.lower() in _UI_FILE_SUFFIXES or any(part in _UI_PATH_SEGMENTS for part in directories)
5246
+
5247
+
4890
5248
  def _classification_for_categories(categories: set[str], file_count: int) -> dict:
4891
5249
  return {
4892
5250
  "categories": sorted(categories),
@@ -4967,6 +5325,79 @@ def _high_confidence_intent_categories(intent: str) -> set[str]:
4967
5325
  }
4968
5326
 
4969
5327
 
5328
+ _MECHANICAL_CHANGE_SIGNALS = (
5329
+ "mechanical", "rename only", "move only", "pure rename", "pure move", "no behavior change",
5330
+ "without behavior change", "behavior unchanged", "source of truth unchanged", "contract unchanged",
5331
+ "仅改名", "只改名", "仅移动", "只移动", "不改变行为", "行为不变", "机械同步", "机械变更", "契约不变", "事实源不变",
5332
+ )
5333
+ _SEMANTIC_CHANGE_SIGNALS = (
5334
+ "semantic change", "change behavior", "behavior change", "new behavior", "architecture change", "contract change", "schema change",
5335
+ "语义变更", "行为变更", "改变行为", "新增行为", "架构变更", "契约变更", "模式变更",
5336
+ )
5337
+
5338
+
5339
+ def _intent_change_nature(intent: str) -> str:
5340
+ value = _text(intent).lower()
5341
+ if not value:
5342
+ return "unknown"
5343
+ semantic_value = re.sub(r"\b(?:not\s+(?:a\s+)?|non[- ]?|isn't\s+)mechanical\b|(?:不是|并非|非)机械(?:变更|同步)?", " ", value)
5344
+ mechanical = [] if semantic_value != value else [signal for signal in _MECHANICAL_CHANGE_SIGNALS if signal in value]
5345
+ for signal in mechanical:
5346
+ semantic_value = semantic_value.replace(signal, " ")
5347
+ for pattern in [r"\bno\s+.{0,16}\bbehavior\s+change\b", r"不改变.{0,16}行为"]:
5348
+ if re.search(pattern, semantic_value):
5349
+ mechanical.append(pattern)
5350
+ semantic_value = re.sub(pattern, " ", semantic_value)
5351
+ if any(signal in semantic_value for signal in _SEMANTIC_CHANGE_SIGNALS) or re.search(
5352
+ r"\b(?:change|changes|changed|changing|modify|modifies|modified|modifying|alter|alters|altered|altering|update|updates|updated|updating)\b.{0,40}\b(?:behaviors?|semantics?|architecture|contracts?|schemas?)\b"
5353
+ r"|\b(?:behaviors?|semantics?|architecture|contracts?|schemas?)\b.{0,24}\b(?:change|changes|changed|changing)\b|(?:修改|调整|改变|新增|更新).{0,32}(?:行为|语义|架构|契约|模式)|(?:行为|语义|架构|契约|模式).{0,16}(?:变化|变更|调整)", semantic_value
5354
+ ):
5355
+ return "semantic"
5356
+ if mechanical:
5357
+ return "mechanical"
5358
+ return "unknown"
5359
+
5360
+
5361
+ def _pure_exact_git_rename(repo: Path, base_ref: str, changed_paths: list[str]) -> bool:
5362
+ common = ["--name-status", "-z", "-M100%", "--diff-filter=ACDMRTUXB"]
5363
+ commands = [["git", "diff", *common], ["git", "diff", "--cached", *common]]
5364
+ effective_base = _effective_change_base(repo, base_ref)
5365
+ if effective_base:
5366
+ commands.insert(0, ["git", "diff", *common, f"{effective_base}...HEAD"])
5367
+ entries: list[tuple[str, tuple[str, ...]]] = []
5368
+ for command in commands:
5369
+ result = run(command, cwd=repo, check=False)
5370
+ if result.returncode != 0:
5371
+ return False
5372
+ tokens = [token for token in result.stdout.split("\0") if token]
5373
+ index = 0
5374
+ while index < len(tokens):
5375
+ status = tokens[index]
5376
+ width = 2 if status[:1] in {"R", "C"} else 1
5377
+ paths = tokens[index + 1 : index + 1 + width]
5378
+ if len(paths) != width:
5379
+ return False
5380
+ entries.append((status, tuple(path.replace("\\", "/") for path in paths)))
5381
+ index += width + 1
5382
+ renamed = {path for status, paths in entries if status == "R100" for path in paths}
5383
+ changed = {path.replace("\\", "/") for path in changed_paths if _text(path)}
5384
+ return bool(entries) and all(status == "R100" for status, _ in entries) and renamed == changed
5385
+
5386
+
5387
+ def _classify_change_nature(
5388
+ repo: Path,
5389
+ *,
5390
+ base_ref: str,
5391
+ changed_paths: list[str],
5392
+ intent: str,
5393
+ inspect_git: bool,
5394
+ ) -> str:
5395
+ intent_nature = _intent_change_nature(intent)
5396
+ if intent_nature != "semantic" and inspect_git and changed_paths and _pure_exact_git_rename(repo, base_ref, changed_paths):
5397
+ return "mechanical"
5398
+ return intent_nature
5399
+
5400
+
4970
5401
  def _resolve_task_kind(
4971
5402
  requested: str,
4972
5403
  paths: list[str],
@@ -5067,6 +5498,7 @@ def _recommended_agents(
5067
5498
  *,
5068
5499
  parallel_writers: int = 1,
5069
5500
  review_required: bool = False,
5501
+ review_policy: Optional[dict] = None,
5070
5502
  ) -> list[str]:
5071
5503
  roles: list[str] = []
5072
5504
  for stage in _agent_execution_plan(
@@ -5075,6 +5507,7 @@ def _recommended_agents(
5075
5507
  classification,
5076
5508
  parallel_writers=parallel_writers,
5077
5509
  review_required=review_required,
5510
+ review_policy=review_policy,
5078
5511
  )["stages"]:
5079
5512
  for role in stage["roles"]:
5080
5513
  if role != "main" and role not in roles:
@@ -5174,9 +5607,19 @@ def _contract_equal(left: object, right: object) -> bool:
5174
5607
  return left == right
5175
5608
 
5176
5609
 
5177
- def _validate_contract_fragment(fragment: dict, value: object, root: dict, path: str) -> None:
5610
+ def _contract_validation_errors(
5611
+ fragment: dict,
5612
+ value: object,
5613
+ root: dict,
5614
+ path: str,
5615
+ ) -> list[str]:
5616
+ errors: list[str] = []
5178
5617
  if "$ref" in fragment:
5179
- _validate_contract_fragment(_contract_ref(root, _text(fragment["$ref"])), value, root, path)
5618
+ errors.extend(
5619
+ _contract_validation_errors(
5620
+ _contract_ref(root, _text(fragment["$ref"])), value, root, path
5621
+ )
5622
+ )
5180
5623
 
5181
5624
  expected_types = fragment.get("type")
5182
5625
  if expected_types is not None:
@@ -5184,60 +5627,61 @@ def _validate_contract_fragment(fragment: dict, value: object, root: dict, path:
5184
5627
  if not all(isinstance(item, str) for item in choices) or not any(
5185
5628
  _contract_type_matches(value, item) for item in choices
5186
5629
  ):
5187
- raise APError(f"Contract validation failed at {path}: expected type {choices}.")
5630
+ errors.append(f"{path}: expected type {choices}")
5631
+ return errors
5188
5632
 
5189
5633
  if "const" in fragment and not _contract_equal(value, fragment["const"]):
5190
- raise APError(f"Contract validation failed at {path}: expected constant {fragment['const']!r}.")
5191
- if "enum" in fragment and not any(_contract_equal(value, item) for item in fragment["enum"]):
5192
- raise APError(f"Contract validation failed at {path}: value is outside the allowed enum.")
5634
+ errors.append(f"{path}: expected constant {fragment['const']!r}")
5635
+ if "enum" in fragment and not any(
5636
+ _contract_equal(value, item) for item in fragment["enum"]
5637
+ ):
5638
+ errors.append(f"{path}: value is outside the allowed enum")
5193
5639
 
5194
5640
  if isinstance(value, str):
5195
5641
  if len(value) < int(fragment.get("minLength") or 0):
5196
- raise APError(f"Contract validation failed at {path}: string is too short.")
5642
+ errors.append(f"{path}: string is too short")
5197
5643
  pattern = fragment.get("pattern")
5198
5644
  if pattern and not re.search(str(pattern), value):
5199
- raise APError(f"Contract validation failed at {path}: string does not match {pattern!r}.")
5645
+ errors.append(f"{path}: string does not match {pattern!r}")
5200
5646
 
5201
5647
  if isinstance(value, list):
5202
5648
  if "maxItems" in fragment and len(value) > int(fragment["maxItems"]):
5203
- raise APError(f"Contract validation failed at {path}: too many array items.")
5649
+ errors.append(f"{path}: too many array items")
5204
5650
  item_schema = fragment.get("items")
5205
5651
  if isinstance(item_schema, dict):
5206
5652
  for index, item in enumerate(value):
5207
- _validate_contract_fragment(item_schema, item, root, f"{path}[{index}]")
5653
+ errors.extend(
5654
+ _contract_validation_errors(item_schema, item, root, f"{path}[{index}]")
5655
+ )
5208
5656
 
5209
5657
  if isinstance(value, dict):
5210
5658
  required = fragment.get("required") or []
5211
- missing = [item for item in required if item not in value]
5659
+ missing = sorted(item for item in required if item not in value)
5212
5660
  if missing:
5213
- raise APError(
5214
- f"Contract validation failed at {path}: missing " + ", ".join(sorted(missing)) + "."
5215
- )
5661
+ errors.append(f"{path}: missing " + ", ".join(missing))
5216
5662
  properties = fragment.get("properties") or {}
5217
5663
  if fragment.get("additionalProperties") is False:
5218
5664
  unexpected = sorted(set(value) - set(properties))
5219
5665
  if unexpected:
5220
- raise APError(
5221
- f"Contract validation failed at {path}: unexpected " + ", ".join(unexpected) + "."
5222
- )
5666
+ errors.append(f"{path}: unexpected " + ", ".join(unexpected))
5223
5667
  for key, child in properties.items():
5224
5668
  if key in value and isinstance(child, dict):
5225
- _validate_contract_fragment(child, value[key], root, f"{path}.{key}")
5669
+ errors.extend(
5670
+ _contract_validation_errors(child, value[key], root, f"{path}.{key}")
5671
+ )
5226
5672
 
5227
5673
  condition = fragment.get("if")
5228
- if isinstance(condition, dict):
5229
- try:
5230
- _validate_contract_fragment(condition, value, root, path)
5231
- except APError:
5232
- pass
5233
- else:
5234
- then = fragment.get("then")
5235
- if isinstance(then, dict):
5236
- _validate_contract_fragment(then, value, root, path)
5674
+ if isinstance(condition, dict) and not _contract_validation_errors(
5675
+ condition, value, root, path
5676
+ ):
5677
+ then = fragment.get("then")
5678
+ if isinstance(then, dict):
5679
+ errors.extend(_contract_validation_errors(then, value, root, path))
5237
5680
 
5238
5681
  for child in fragment.get("allOf") or []:
5239
5682
  if isinstance(child, dict):
5240
- _validate_contract_fragment(child, value, root, path)
5683
+ errors.extend(_contract_validation_errors(child, value, root, path))
5684
+ return errors
5241
5685
 
5242
5686
 
5243
5687
  def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
@@ -5251,28 +5695,85 @@ def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
5251
5695
  if not definition:
5252
5696
  raise APError(f"Unknown orchestration contract kind: {kind}")
5253
5697
  root = _orchestration_schema()
5254
- _validate_contract_fragment(root["$defs"][definition], payload, root, "$")
5698
+ errors = _contract_validation_errors(root["$defs"][definition], payload, root, "$")
5255
5699
 
5256
5700
  role = _text(payload.get("role"))
5257
5701
  if kind == "assignment" and role == "reviewer":
5258
5702
  if _text(payload.get("node_id")) == _text(payload.get("owning_fixer")):
5259
- raise APError("Reviewer assignment node_id must differ from owning_fixer.")
5703
+ errors.append("$.node_id: reviewer must differ from owning_fixer")
5260
5704
  if kind == "result":
5261
- if role == "fixer":
5705
+ owned_paths = payload.get("owned_paths")
5706
+ changed_paths = payload.get("changed_paths")
5707
+ if role == "fixer" and isinstance(owned_paths, list) and isinstance(changed_paths, list):
5262
5708
  owned = [_normalize_owned_path(item) for item in payload.get("owned_paths") or []]
5263
5709
  outside = [
5264
5710
  path
5265
5711
  for path in payload.get("changed_paths") or []
5712
+ if isinstance(path, str)
5266
5713
  if not _path_is_owned(path, owned)
5267
5714
  ]
5268
5715
  if outside:
5269
- raise APError("Fixer result changed_paths exceed owned_paths: " + ", ".join(outside))
5716
+ errors.append(
5717
+ "$.changed_paths: fixer paths exceed owned_paths: " + ", ".join(outside)
5718
+ )
5270
5719
  if role == "reviewer" and _text(payload.get("verdict")) in {"approved", "changes-requested"}:
5271
5720
  if not re.fullmatch(r"[0-9a-f]{64}", _text(payload.get("diff_fingerprint"))):
5272
- raise APError("Reviewer result must bind its verdict to a non-empty diff fingerprint.")
5721
+ errors.append(
5722
+ "$.diff_fingerprint: reviewer verdict must bind to a 64-character fingerprint"
5723
+ )
5724
+ errors = list(dict.fromkeys(errors))
5725
+ if errors:
5726
+ raise APError("Contract validation failed:\n- " + "\n- ".join(errors))
5273
5727
  return payload
5274
5728
 
5275
5729
 
5730
+ def _reviewer_result_template(assignment: dict, verdict: str) -> dict:
5731
+ """Build a complete Reviewer result without guessing review evidence or findings."""
5732
+ _validate_orchestration_contract("assignment", assignment)
5733
+ if _text(assignment.get("role")) != "reviewer":
5734
+ raise APError("Reviewer result templates require a reviewer assignment.")
5735
+ normalized_verdict = _text(verdict).lower()
5736
+ if normalized_verdict not in {"approved", "changes-requested", "blocked"}:
5737
+ raise APError(
5738
+ "Reviewer result verdict must be approved, changes-requested, or blocked."
5739
+ )
5740
+ fingerprint = _text(assignment.get("diff_fingerprint"))
5741
+ if not re.fullmatch(r"[0-9a-f]{64}", fingerprint):
5742
+ raise APError(
5743
+ "Reviewer result templates require a non-empty 64-character diff fingerprint."
5744
+ )
5745
+ status = "blocked" if normalized_verdict == "blocked" else "completed"
5746
+ next_owner = (
5747
+ _text(assignment.get("owning_fixer"))
5748
+ if normalized_verdict == "changes-requested"
5749
+ else "main"
5750
+ )
5751
+ summaries = {
5752
+ "approved": "Review completed with no blocking findings.",
5753
+ "changes-requested": "Review completed with changes requested.",
5754
+ "blocked": "Review could not be completed.",
5755
+ }
5756
+ result = {
5757
+ "contract_version": _AGENT_CONTRACT_VERSION,
5758
+ "node_id": _text(assignment.get("node_id")),
5759
+ "role": "reviewer",
5760
+ "task_id": _text(assignment.get("task_id")),
5761
+ "base_sha": _text(assignment.get("base_sha")),
5762
+ "status": status,
5763
+ "summary": summaries[normalized_verdict],
5764
+ "depends_on": list(assignment.get("depends_on") or []),
5765
+ "owned_paths": [],
5766
+ "changed_paths": [],
5767
+ "diff_fingerprint": fingerprint,
5768
+ "evidence": [],
5769
+ "findings": [],
5770
+ "verdict": normalized_verdict,
5771
+ "risks": [],
5772
+ "next_owner": next_owner,
5773
+ }
5774
+ return _validate_orchestration_contract("result", result)
5775
+
5776
+
5276
5777
  def _validate_agent_plan(plan: dict) -> dict:
5277
5778
  required = {
5278
5779
  "contract_version",
@@ -5292,6 +5793,35 @@ def _validate_agent_plan(plan: dict) -> dict:
5292
5793
  return plan
5293
5794
 
5294
5795
 
5796
+ def _review_execution_policy(
5797
+ *,
5798
+ review_required: bool,
5799
+ categories: set[str],
5800
+ cross_module: bool,
5801
+ parallel_writers: int,
5802
+ ) -> dict:
5803
+ if not review_required:
5804
+ return {
5805
+ "depth": "none",
5806
+ "agent": "",
5807
+ "timeout_seconds": 0,
5808
+ "analysis_attempt_limit": 0,
5809
+ }
5810
+ deep = bool(
5811
+ cross_module
5812
+ or parallel_writers > 1
5813
+ or categories & _DEEP_REVIEW_CATEGORIES
5814
+ )
5815
+ return {
5816
+ "depth": "deep" if deep else "focused",
5817
+ "agent": "reviewer",
5818
+ "timeout_seconds": (
5819
+ _DEEP_REVIEW_TIMEOUT_SECONDS if deep else _FOCUSED_REVIEW_TIMEOUT_SECONDS
5820
+ ),
5821
+ "analysis_attempt_limit": 1,
5822
+ }
5823
+
5824
+
5295
5825
  def _agent_execution_plan(
5296
5826
  profile: str,
5297
5827
  categories: set[str],
@@ -5299,10 +5829,12 @@ def _agent_execution_plan(
5299
5829
  *,
5300
5830
  parallel_writers: int = 1,
5301
5831
  review_required: bool = False,
5832
+ review_policy: Optional[dict] = None,
5302
5833
  optional_roles: Optional[list[str]] = None,
5303
5834
  ) -> dict:
5304
5835
  assignment_contract, result_contract = _agent_contract_shape()
5305
5836
  optional_roles = list(dict.fromkeys(optional_roles or []))
5837
+ review_policy = dict(review_policy or {})
5306
5838
  # Optional roles are candidates, never automatic stages. The model selects
5307
5839
  # them only when expected benefit exceeds coordination cost.
5308
5840
  discovery_roles: list[str] = []
@@ -5314,6 +5846,12 @@ def _agent_execution_plan(
5314
5846
  "dependency_policy": "integrate-before-dependent-start",
5315
5847
  "review_feedback_owner": "owning-fixer" if review_required else "main",
5316
5848
  "review_binding": "diff-fingerprint-when-required",
5849
+ "review_depth": _text(review_policy.get("depth")) or "none",
5850
+ "review_agent": _text(review_policy.get("agent")),
5851
+ "review_timeout_seconds": int(review_policy.get("timeout_seconds") or 0),
5852
+ "review_analysis_attempt_limit": int(
5853
+ review_policy.get("analysis_attempt_limit") or 0
5854
+ ),
5317
5855
  "lifecycle_owner": "main",
5318
5856
  "gate_owner": "main",
5319
5857
  }
@@ -5323,6 +5861,11 @@ def _agent_execution_plan(
5323
5861
  "Never run two writers in one worktree.",
5324
5862
  "The main agent runs one final changed-scope gate, pushes, and cleans only temporary branches actually created.",
5325
5863
  ]
5864
+ if review_required:
5865
+ constraints.append(
5866
+ "Run one bounded review analysis over the supplied diff and relevant evidence; "
5867
+ "a timeout is blocked, never approved, and JSON formatting repair must reuse the same analysis."
5868
+ )
5326
5869
 
5327
5870
  if parallel_writers <= 1 and not discovery_roles and not review_required:
5328
5871
  stages = [{"id": "delivery", "mode": "serial", "roles": ["main"], "depends_on": []}]
@@ -5348,7 +5891,7 @@ def _agent_execution_plan(
5348
5891
  delivery_roles = ["fixer", "main"]
5349
5892
  delivery_mode = "parallel-isolated"
5350
5893
  if review_required:
5351
- delivery_roles.append("reviewer")
5894
+ delivery_roles.append(_text(review_policy.get("agent")) or "reviewer")
5352
5895
  stages.append(
5353
5896
  {
5354
5897
  "id": "delivery",
@@ -5431,7 +5974,8 @@ def _mechanism_plan(
5431
5974
  "rule": (
5432
5975
  "run required mechanisms; select optional mechanisms only when expected value exceeds "
5433
5976
  "coordination cost; reclassify before changing writer count; do not run forbidden "
5434
- "mechanisms unless the user explicitly overrides"
5977
+ "mechanisms unless the user explicitly overrides; direct/worktree decisions apply only "
5978
+ "to the reported workspace snapshot and require reclassification if it changes"
5435
5979
  ),
5436
5980
  }
5437
5981
 
@@ -5465,6 +6009,13 @@ def _resolve_execution_plan(
5465
6009
  )
5466
6010
  classification_inputs = [*paths, *normalized_planned_paths]
5467
6011
  task_kind = _resolve_task_kind(requested_task_kind, classification_inputs, intent)
6012
+ change_nature = _classify_change_nature(
6013
+ repo,
6014
+ base_ref=base_ref,
6015
+ changed_paths=paths,
6016
+ intent=intent,
6017
+ inspect_git=changed_paths is None,
6018
+ )
5468
6019
  path_classification = _classify_paths(classification_inputs)
5469
6020
  path_categories = set(path_classification["categories"])
5470
6021
  intent_categories = _classify_intent(intent)
@@ -5605,7 +6156,14 @@ def _resolve_execution_plan(
5605
6156
  )
5606
6157
  design_required = bool(
5607
6158
  task_kind == "change"
5608
- and (rule_design or (effective_profile == "high-risk" and cross_module))
6159
+ and (
6160
+ rule_design
6161
+ or (
6162
+ effective_profile == "high-risk"
6163
+ and cross_module
6164
+ and change_nature != "mechanical"
6165
+ )
6166
+ )
5609
6167
  )
5610
6168
  dirty_paths = _working_tree_paths(repo)
5611
6169
  workspace_dirty = bool(dirty_paths)
@@ -5623,12 +6181,10 @@ def _resolve_execution_plan(
5623
6181
  if continue_direct
5624
6182
  else {}
5625
6183
  )
5626
- runtime_actor = _text(os.environ.get("CODEX_THREAD_ID"))
5627
6184
  other_direct_claims = [
5628
6185
  item
5629
6186
  for item in _active_direct_claims(repo)
5630
6187
  if _text(item.get("claim_id")) != _text(direct_claim_id)
5631
- and (not runtime_actor or _text(item.get("owner")) != runtime_actor)
5632
6188
  ]
5633
6189
  active_writer = bool(registered_active_writer or other_direct_claims)
5634
6190
  continued_direct = bool(
@@ -5666,12 +6222,19 @@ def _resolve_execution_plan(
5666
6222
  cross_module=cross_module,
5667
6223
  profile=effective_profile,
5668
6224
  )
6225
+ review_policy = _review_execution_policy(
6226
+ review_required=review_required,
6227
+ categories=categories,
6228
+ cross_module=cross_module,
6229
+ parallel_writers=writer_count,
6230
+ )
5669
6231
  agent_plan = _agent_execution_plan(
5670
6232
  effective_profile,
5671
6233
  categories,
5672
6234
  classification,
5673
6235
  parallel_writers=writer_count,
5674
6236
  review_required=review_required,
6237
+ review_policy=review_policy,
5675
6238
  optional_roles=optional_agents,
5676
6239
  )
5677
6240
  mechanism_plan = _mechanism_plan(
@@ -5688,6 +6251,7 @@ def _resolve_execution_plan(
5688
6251
  "planned_files": normalized_planned_paths,
5689
6252
  "classification_files": classification_inputs,
5690
6253
  "intent_provided": bool(_text(intent)),
6254
+ "change_nature": change_nature,
5691
6255
  "task_kind": task_kind,
5692
6256
  "intent_categories": intent_categories,
5693
6257
  "intent_risk_candidates": intent_risk_candidates,
@@ -5702,6 +6266,7 @@ def _resolve_execution_plan(
5702
6266
  "effective_mode": effective_mode,
5703
6267
  "execution_mode": execution_mode,
5704
6268
  "terminal_maintenance": terminal_maintenance,
6269
+ "repo": str(repo),
5705
6270
  "workspace_dirty": workspace_dirty,
5706
6271
  "dirty_paths": dirty_paths,
5707
6272
  "dirty_outside_plan": dirty_outside_plan,
@@ -5710,6 +6275,10 @@ def _resolve_execution_plan(
5710
6275
  "parallel_writers": writer_count,
5711
6276
  "cross_module": cross_module,
5712
6277
  "review_required": review_required,
6278
+ "review_depth": review_policy["depth"],
6279
+ "review_agent": review_policy["agent"],
6280
+ "review_timeout_seconds": review_policy["timeout_seconds"],
6281
+ "review_analysis_attempt_limit": review_policy["analysis_attempt_limit"],
5713
6282
  "design_required": design_required,
5714
6283
  "selected_scope": selected_scope,
5715
6284
  "categories": sorted(categories),
@@ -5724,6 +6293,7 @@ def _resolve_execution_plan(
5724
6293
  classification,
5725
6294
  parallel_writers=writer_count,
5726
6295
  review_required=review_required,
6296
+ review_policy=review_policy,
5727
6297
  ),
5728
6298
  "optional_agents": optional_agents,
5729
6299
  "agent_plan": agent_plan,
@@ -5800,9 +6370,24 @@ def cmd_classify(args: argparse.Namespace) -> None:
5800
6370
  print(f"[classify] task_kind={result['task_kind']}")
5801
6371
  print(f"[classify] profile={result['profile']}")
5802
6372
  print(f"[classify] effective_mode={result['effective_mode']}")
6373
+ print(f"[classify] repo={result['repo']}")
6374
+ print(f"[classify] workspace_dirty={str(result['workspace_dirty']).lower()}")
6375
+ print(
6376
+ "[classify] dirty_paths="
6377
+ + json.dumps(result["dirty_paths"], ensure_ascii=False, separators=(",", ":"))
6378
+ )
6379
+ print(f"[classify] active_writer={str(result['active_writer']).lower()}")
5803
6380
  print(f"[classify] execution_mode={result['execution_mode']}")
5804
6381
  print(f"[classify] review_required={str(result['review_required']).lower()}")
6382
+ print(f"[classify] review_depth={result['review_depth']}")
6383
+ print(f"[classify] review_agent={result['review_agent'] or '(none)'}")
6384
+ print(f"[classify] review_timeout_seconds={result['review_timeout_seconds']}")
6385
+ print(
6386
+ "[classify] review_analysis_attempt_limit="
6387
+ f"{result['review_analysis_attempt_limit']}"
6388
+ )
5805
6389
  print(f"[classify] design_required={str(result['design_required']).lower()}")
6390
+ print(f"[classify] change_nature={result['change_nature']}")
5806
6391
  print(f"[classify] selected_scope={result['selected_scope']}")
5807
6392
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
5808
6393
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
@@ -5838,8 +6423,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
5838
6423
  _record_evidence(repo, cfg, "classify", "pass", result)
5839
6424
 
5840
6425
 
5841
- def cmd_agent_contract_check(args: argparse.Namespace) -> None:
5842
- repo = Path(args.repo).resolve()
6426
+ def _agent_contract_payload(repo: Path, args: argparse.Namespace) -> dict:
5843
6427
  raw = _text(getattr(args, "payload", ""))
5844
6428
  source = _text(getattr(args, "file", ""))
5845
6429
  if source:
@@ -5863,6 +6447,12 @@ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
5863
6447
  raise APError(f"Agent contract payload is not valid JSON: {exc}") from exc
5864
6448
  if not isinstance(payload, dict):
5865
6449
  raise APError("Agent contract payload must be a JSON object.")
6450
+ return payload
6451
+
6452
+
6453
+ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
6454
+ repo = Path(args.repo).resolve()
6455
+ payload = _agent_contract_payload(repo, args)
5866
6456
  _validate_orchestration_contract(args.kind, payload)
5867
6457
  result = {"valid": True, "kind": args.kind}
5868
6458
  if args.json:
@@ -5871,6 +6461,13 @@ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
5871
6461
  print(f"[agent-contract-check] OK kind={args.kind}")
5872
6462
 
5873
6463
 
6464
+ def cmd_agent_result_template(args: argparse.Namespace) -> None:
6465
+ repo = Path(args.repo).resolve()
6466
+ assignment = _agent_contract_payload(repo, args)
6467
+ result = _reviewer_result_template(assignment, args.verdict)
6468
+ print(json.dumps(result, ensure_ascii=False, indent=2))
6469
+
6470
+
5874
6471
  def cmd_run(args: argparse.Namespace) -> None:
5875
6472
  """
5876
6473
  Run any configured gate command by name.
@@ -5899,6 +6496,11 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
5899
6496
  light_gate_start = time.time()
5900
6497
  monotonic_start = time.monotonic()
5901
6498
  cfg = _load_cfg(repo)
6499
+ manifest = _active_task_manifest(repo)
6500
+ if manifest:
6501
+ manifest = _require_task_context(repo, cfg, _text(manifest.get("task_id")))
6502
+ _clear_final_gate_receipt(repo)
6503
+ before_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
5902
6504
  budget = _final_gate_budget(cfg)
5903
6505
  deadline = monotonic_start + budget["total_seconds"]
5904
6506
  requested_scope = _text(getattr(args, "scope", "")).lower()
@@ -5933,10 +6535,23 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
5933
6535
  _run_git_diff_check(repo, cfg)
5934
6536
  if time.monotonic() > deadline:
5935
6537
  raise APError(
5936
- f"Final changed-scope gate exceeded {budget['total_seconds']:.0f}s; "
6538
+ f"Final changed-scope gate timed out after {budget['total_seconds']:.0f}s; "
5937
6539
  "narrow validation.routes and keep slower checks explicit"
5938
6540
  )
5939
6541
  executed.append("diff_check")
6542
+ after_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
6543
+ if after_fingerprint != before_fingerprint:
6544
+ _clear_final_gate_receipt(repo)
6545
+ raise APError("The final gate changed task content; inspect the diff before retrying.")
6546
+ if manifest:
6547
+ _record_final_gate_receipt(
6548
+ repo,
6549
+ cfg,
6550
+ manifest,
6551
+ plan,
6552
+ _text(getattr(args, "base", "")) or _text(manifest.get("base_sha")),
6553
+ executed,
6554
+ )
5940
6555
  duration_s = time.time() - light_gate_start
5941
6556
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
5942
6557
  _record_evidence(
@@ -7732,6 +8347,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7732
8347
  "created_at": _now_iso(),
7733
8348
  "initial_untracked": [],
7734
8349
  "owned_paths": owned_paths,
8350
+ "scope_revision": 1,
8351
+ "effective_profile": plan["profile"],
8352
+ "design_required": bool(plan["design_required"]),
8353
+ "scope_history": [],
7735
8354
  "depends_on": depends_on,
7736
8355
  "prerequisite_shas": prerequisite_shas,
7737
8356
  "writer_lease": {
@@ -7813,6 +8432,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7813
8432
  "created_at": _now_iso(),
7814
8433
  "initial_untracked": [],
7815
8434
  "owned_paths": owned_paths,
8435
+ "scope_revision": 1,
8436
+ "effective_profile": plan["profile"],
8437
+ "design_required": bool(plan["design_required"]),
8438
+ "scope_history": [],
7816
8439
  "depends_on": depends_on,
7817
8440
  "prerequisite_shas": prerequisite_shas,
7818
8441
  "writer_lease": {
@@ -7942,6 +8565,171 @@ def _task_lifecycle_context(repo: Path, cfg: dict, task_id: str) -> tuple[Path,
7942
8565
  return repo, Path(_text(manifest.get("worktree_path"))).resolve(), manifest
7943
8566
 
7944
8567
 
8568
+ def cmd_task_scope_add(args: argparse.Namespace) -> None:
8569
+ repo = Path(args.repo).resolve()
8570
+ ensure_git_repo(repo)
8571
+ cfg = _load_cfg(repo)
8572
+ task_id = _validate_task_id(args.task_id)
8573
+ additions = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
8574
+ if not additions:
8575
+ raise APError("task-scope-add requires at least one --owned-path.")
8576
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
8577
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
8578
+ result: dict = {}
8579
+ with (
8580
+ _repo_lock(control_repo, "integration", timeout_s=timeout_s),
8581
+ _repo_lock(control_repo, "task-registry", timeout_s=timeout_s),
8582
+ _repo_lock(control_repo, "direct-claim", timeout_s=timeout_s),
8583
+ _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s),
8584
+ ):
8585
+ manifest = _load_task_manifest(control_repo, task_id)
8586
+ _require_current_writer(manifest, args)
8587
+ if int(manifest.get("schema") or 0) < 3:
8588
+ raise APError("task-scope-add requires a schema-3 task created by the current workflow.")
8589
+ if _text(manifest.get("state")) != "active":
8590
+ raise APError(
8591
+ f"Task {task_id} cannot expand scope in state={manifest.get('state')}; start a new task."
8592
+ )
8593
+ lease_generation = int((manifest.get("writer_lease") or {}).get("generation") or 0)
8594
+ requested_generation = getattr(args, "lease_generation", None)
8595
+ if requested_generation is not None and requested_generation != lease_generation:
8596
+ raise APError(
8597
+ f"Writer lease generation changed: expected={requested_generation}, current={lease_generation}."
8598
+ )
8599
+ if not worktree.exists():
8600
+ raise APError(f"Task worktree is missing: {worktree}")
8601
+ if _resolve_commit(worktree, "HEAD") != _text(manifest.get("base_sha")):
8602
+ raise APError("task-scope-add is allowed only before the task creates a commit.")
8603
+ if _text(manifest.get("last_commit")) or _text(manifest.get("remote_task_tip")):
8604
+ raise APError("task-scope-add cannot extend a task that already committed or pushed work.")
8605
+
8606
+ current = sorted({_normalize_owned_path(item) for item in manifest.get("owned_paths") or []})
8607
+ new_paths = [path for path in additions if not _path_is_owned(path, current)]
8608
+ if not new_paths:
8609
+ result = {
8610
+ "task_id": task_id,
8611
+ "status": "noop",
8612
+ "scope_revision": int(manifest.get("scope_revision") or 1),
8613
+ "owned_paths": current,
8614
+ }
8615
+ else:
8616
+ proposed = sorted(set(current) | set(new_paths))
8617
+ for claim in _active_direct_claims(control_repo):
8618
+ claim_paths = list(claim.get("owned_paths") or [])
8619
+ if _owned_paths_overlap(proposed, claim_paths):
8620
+ raise APError(
8621
+ "Expanded scope overlaps active direct claim held by "
8622
+ f"{_text(claim.get('owner')) or '(unknown)'}: "
8623
+ + ", ".join(claim_paths)
8624
+ )
8625
+ registry_dir = _task_state_root(control_repo) / "tasks"
8626
+ for path in sorted(registry_dir.glob("*.json")) if registry_dir.exists() else []:
8627
+ other = _read_json_object(path) or {}
8628
+ if _text(other.get("task_id")) == task_id:
8629
+ continue
8630
+ if _text(other.get("state")) in {"", "integrated", "cleanup-pending"}:
8631
+ continue
8632
+ other_owned = other.get("owned_paths") or []
8633
+ if isinstance(other_owned, list) and _owned_paths_overlap(proposed, other_owned):
8634
+ raise APError(
8635
+ f"Expanded scope overlaps active task {_text(other.get('task_id')) or path.stem}: "
8636
+ + ", ".join(other_owned)
8637
+ )
8638
+
8639
+ worktree_cfg = _load_cfg(worktree)
8640
+ existing_unowned = _task_unowned_paths(worktree, worktree_cfg, manifest)
8641
+ implicit_adoptions = sorted(path for path in existing_unowned if path not in set(new_paths))
8642
+ if implicit_adoptions:
8643
+ raise APError(
8644
+ "Existing unowned changes must be added as exact --owned-path values before scope expansion:\n- "
8645
+ + "\n- ".join(implicit_adoptions)
8646
+ )
8647
+ changed_paths = _task_changed_paths_from_base(
8648
+ worktree,
8649
+ _text(manifest.get("base_sha")),
8650
+ )
8651
+ plan = _resolve_execution_plan(
8652
+ worktree_cfg,
8653
+ worktree,
8654
+ changed_paths=changed_paths,
8655
+ planned_paths=proposed,
8656
+ intent=_text(getattr(args, "intent", "")),
8657
+ requested_task_kind="change",
8658
+ )
8659
+ old_profile = _text(manifest.get("effective_profile")) or (
8660
+ "high-risk" if bool(manifest.get("review_required")) else "standard"
8661
+ )
8662
+ planned_profile = _text(plan.get("profile")) or "standard"
8663
+ effective_profile = (
8664
+ planned_profile
8665
+ if _PROFILE_RANK[planned_profile] > _PROFILE_RANK[old_profile]
8666
+ else old_profile
8667
+ )
8668
+ old_manifest = json.loads(json.dumps(manifest))
8669
+ revision = int(manifest.get("scope_revision") or 1) + 1
8670
+ manifest["owned_paths"] = proposed
8671
+ manifest["scope_revision"] = revision
8672
+ manifest["effective_profile"] = effective_profile
8673
+ manifest["review_required"] = bool(
8674
+ manifest.get("review_required")
8675
+ or plan.get("review_required")
8676
+ or bool(getattr(args, "review_required", False))
8677
+ )
8678
+ manifest["design_required"] = bool(
8679
+ manifest.get("design_required") or plan.get("design_required")
8680
+ )
8681
+ manifest["claimed_paths"] = []
8682
+ history = list(manifest.get("scope_history") or [])
8683
+ history.append(
8684
+ {
8685
+ "revision": revision,
8686
+ "added_paths": new_paths,
8687
+ "adopted_dirty_paths": existing_unowned,
8688
+ "actor": _text(getattr(args, "writer", ""))
8689
+ or _text(os.environ.get("CODEX_THREAD_ID")),
8690
+ "updated_at": _now_iso(),
8691
+ "previous_profile": old_profile,
8692
+ "effective_profile": effective_profile,
8693
+ }
8694
+ )
8695
+ manifest["scope_history"] = history
8696
+ _invalidate_task_review(manifest, "task scope expanded; review and final gate must run again")
8697
+ _clear_final_gate_receipt(worktree)
8698
+ try:
8699
+ _save_task_manifest(control_repo, manifest, strict_worktree=True)
8700
+ except Exception:
8701
+ _save_task_manifest(control_repo, old_manifest)
8702
+ raise
8703
+ registered = _load_task_manifest(control_repo, task_id)
8704
+ mirrored = _read_json_object(_worktree_manifest_path(worktree)) or {}
8705
+ for field in ("task_uuid", "scope_revision", "owned_paths", "review_required"):
8706
+ if registered.get(field) != mirrored.get(field):
8707
+ raise APError(f"Task scope manifest synchronization failed for field: {field}")
8708
+ result = {
8709
+ "task_id": task_id,
8710
+ "status": "expanded",
8711
+ "scope_revision": revision,
8712
+ "owned_paths": proposed,
8713
+ "added_paths": new_paths,
8714
+ "effective_profile": effective_profile,
8715
+ "review_required": manifest["review_required"],
8716
+ "design_required": manifest["design_required"],
8717
+ }
8718
+ if bool(getattr(args, "json", False)):
8719
+ print(json.dumps(result, ensure_ascii=False, indent=2))
8720
+ elif result["status"] == "noop":
8721
+ print(
8722
+ f"[task-scope-add] NOOP task={task_id} "
8723
+ f"scope_revision={result['scope_revision']}"
8724
+ )
8725
+ else:
8726
+ print(
8727
+ f"[task-scope-add] OK task={task_id} scope_revision={result['scope_revision']} "
8728
+ f"profile={result['effective_profile']} review_required="
8729
+ f"{str(result['review_required']).lower()} added={','.join(result['added_paths'])}"
8730
+ )
8731
+
8732
+
7945
8733
  def cmd_task_review(args: argparse.Namespace) -> None:
7946
8734
  repo = Path(args.repo).resolve()
7947
8735
  ensure_git_repo(repo)
@@ -8266,11 +9054,17 @@ def cmd_task_finish(args: argparse.Namespace) -> None:
8266
9054
  task_id = _validate_task_id(args.task_id)
8267
9055
  manifest = _load_task_manifest(repo, task_id)
8268
9056
  if _text(manifest.get("execution_mode")).lower() == "direct":
8269
- if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
8270
- raise APError("Run task-finish for a direct task from its current checkout.")
8271
- if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
8272
- raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
8273
- _clear_direct_task(repo, manifest)
9057
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
9058
+ with (
9059
+ _repo_lock(repo, "integration", timeout_s=timeout_s),
9060
+ _repo_lock(repo, f"task-{task_id}", timeout_s=timeout_s),
9061
+ ):
9062
+ manifest = _load_task_manifest(repo, task_id)
9063
+ if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
9064
+ raise APError("Run task-finish for a direct task from its current checkout.")
9065
+ if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
9066
+ raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
9067
+ _clear_direct_task(repo, manifest)
8274
9068
  print(f"[task-finish] OK task={task_id} execution_mode=direct no temporary branch existed")
8275
9069
  return
8276
9070
  _require_control_checkout(repo, manifest)
@@ -8675,6 +9469,7 @@ def _cmd_direct_commit_push_locked(
8675
9469
  ) -> None:
8676
9470
  _require_current_writer(manifest, args)
8677
9471
  _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
9472
+ _reconcile_task_risk(repo, cfg, manifest)
8678
9473
  _require_approved_review(repo, cfg, manifest)
8679
9474
  branch = _current_branch(repo)
8680
9475
  target = _text(manifest.get("target_branch"))
@@ -8696,6 +9491,8 @@ def _cmd_direct_commit_push_locked(
8696
9491
  commit_sha = pending_commit
8697
9492
  plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
8698
9493
  else:
9494
+ task_paths = _task_staging_paths(repo, cfg, manifest)
9495
+ _preflight_exact_paths(repo, task_paths)
8699
9496
  cmd_doctor(
8700
9497
  argparse.Namespace(
8701
9498
  repo=str(repo),
@@ -8711,23 +9508,36 @@ def _cmd_direct_commit_push_locked(
8711
9508
  base_ref=_text(manifest.get("base_sha")),
8712
9509
  )
8713
9510
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
8714
- cmd_light_gate(
8715
- argparse.Namespace(
8716
- repo=str(repo),
8717
- scope="changed",
8718
- profile=plan["profile"],
8719
- mode="dev",
8720
- base=_text(manifest.get("base_sha")),
8721
- explain=False,
8722
- )
9511
+ receipt = _reuse_final_gate_receipt(
9512
+ repo,
9513
+ cfg,
9514
+ manifest,
9515
+ plan,
9516
+ _text(manifest.get("base_sha")),
8723
9517
  )
9518
+ if receipt:
9519
+ print(
9520
+ "[light-gate] REUSED task="
9521
+ f"{manifest['task_id']} passed_at={receipt.get('passed_at')}"
9522
+ )
9523
+ else:
9524
+ cmd_light_gate(
9525
+ argparse.Namespace(
9526
+ repo=str(repo),
9527
+ scope="changed",
9528
+ profile=plan["profile"],
9529
+ mode="dev",
9530
+ base=_text(manifest.get("base_sha")),
9531
+ explain=False,
9532
+ )
9533
+ )
8724
9534
  after_gate = _task_content_fingerprint(repo, cfg, manifest)
8725
9535
  if after_gate != before_gate:
8726
9536
  raise APError("The final gate changed direct-task files; inspect them and retry commit-push.")
8727
9537
  manifest = _require_task_context(repo, cfg, args.task_id)
8728
9538
  _require_current_writer(manifest, args)
8729
9539
  _require_approved_review(repo, cfg, manifest)
8730
- task_paths = _task_commit_paths(repo)
9540
+ task_paths = _task_staging_paths(repo, cfg, manifest)
8731
9541
  staged = _stage_exact_paths(repo, task_paths)
8732
9542
  if not staged:
8733
9543
  _clear_direct_task(repo, manifest)
@@ -8736,6 +9546,13 @@ def _cmd_direct_commit_push_locked(
8736
9546
  unstaged = _unstaged_task_paths(repo)
8737
9547
  if unstaged:
8738
9548
  raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
9549
+ _extend_final_gate_receipt(
9550
+ repo,
9551
+ cfg,
9552
+ manifest,
9553
+ plan,
9554
+ _text(manifest.get("base_sha")),
9555
+ )
8739
9556
  commit_sha = _commit_exact_index(repo, args.msg)
8740
9557
  manifest["state"] = "push-pending"
8741
9558
  manifest["last_commit"] = commit_sha
@@ -8783,7 +9600,23 @@ def _cmd_commit_push_locked(
8783
9600
  _save_task_manifest(repo, manifest)
8784
9601
  _require_current_writer(manifest, args)
8785
9602
  _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
9603
+ _reconcile_task_risk(repo, cfg, manifest)
8786
9604
  _require_approved_review(repo, cfg, manifest)
9605
+ working_paths = _task_commit_paths(repo)
9606
+ head = _resolve_commit(repo, "HEAD")
9607
+ pending_commit = _text(manifest.get("last_commit"))
9608
+ if pending_commit and pending_commit == head and not working_paths:
9609
+ plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
9610
+ _push_current_task(repo, manifest, pending_commit)
9611
+ print(
9612
+ f"[commit-push] OK - profile={plan['profile']} mode={plan['effective_mode']} "
9613
+ f"scope={plan['selected_scope']} commit={pending_commit}"
9614
+ )
9615
+ return
9616
+ protected = set(manifest.get("initial_untracked") or [])
9617
+ _cleanup_generated_noise(repo, protected_paths=protected)
9618
+ task_paths = _task_staging_paths(repo, cfg, manifest)
9619
+ _preflight_exact_paths(repo, task_paths)
8787
9620
  cmd_doctor(
8788
9621
  argparse.Namespace(
8789
9622
  repo=str(repo),
@@ -8807,16 +9640,23 @@ def _cmd_commit_push_locked(
8807
9640
 
8808
9641
  msg = args.msg
8809
9642
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
8810
- cmd_light_gate(
8811
- argparse.Namespace(
8812
- repo=str(repo),
8813
- scope="changed",
8814
- profile=plan["profile"],
8815
- mode="dev",
8816
- base=base_ref,
8817
- explain=False,
9643
+ receipt = _reuse_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
9644
+ if receipt:
9645
+ print(
9646
+ "[light-gate] REUSED task="
9647
+ f"{manifest['task_id']} passed_at={receipt.get('passed_at')}"
9648
+ )
9649
+ else:
9650
+ cmd_light_gate(
9651
+ argparse.Namespace(
9652
+ repo=str(repo),
9653
+ scope="changed",
9654
+ profile=plan["profile"],
9655
+ mode="dev",
9656
+ base=base_ref,
9657
+ explain=False,
9658
+ )
8818
9659
  )
8819
- )
8820
9660
 
8821
9661
  after_gate = _task_content_fingerprint(repo, cfg, manifest)
8822
9662
  if after_gate != before_gate:
@@ -8834,15 +9674,13 @@ def _cmd_commit_push_locked(
8834
9674
  "no files were staged or restored."
8835
9675
  )
8836
9676
 
8837
- protected = set(manifest.get("initial_untracked") or [])
8838
- _cleanup_generated_noise(repo, protected_paths=protected)
8839
9677
  pre_stage_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
8840
9678
  manifest = _require_task_context(repo, cfg, args.task_id)
8841
9679
  _require_current_writer(manifest, args)
8842
9680
  _require_approved_review(repo, cfg, manifest)
8843
9681
  if _task_content_fingerprint(repo, cfg, manifest) != pre_stage_fingerprint:
8844
9682
  raise APError("Task-owned files changed immediately before staging; refusing to commit.")
8845
- task_paths = _task_commit_paths(repo)
9683
+ task_paths = _task_staging_paths(repo, cfg, manifest)
8846
9684
  staged = _stage_exact_paths(repo, task_paths)
8847
9685
  if not staged:
8848
9686
  raise APError("Nothing to commit.")
@@ -8852,8 +9690,12 @@ def _cmd_commit_push_locked(
8852
9690
  "Task-owned files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged)
8853
9691
  )
8854
9692
  manifest = _require_task_context(repo, cfg, args.task_id)
9693
+ _extend_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
8855
9694
 
8856
9695
  committed_sha = _commit_exact_index(repo, msg)
9696
+ manifest["state"] = "push-pending"
9697
+ manifest["last_commit"] = committed_sha
9698
+ _save_task_manifest(repo, manifest)
8857
9699
  _push_current_task(repo, manifest, committed_sha)
8858
9700
  print(f"[commit-push] OK - profile={plan['profile']} mode={mode} scope={plan['selected_scope']}")
8859
9701
 
@@ -8868,6 +9710,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
8868
9710
  lock_name = f"task-{_validate_task_id(args.task_id)}"
8869
9711
  timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
8870
9712
  with _repo_lock(repo, lock_name, timeout_s=timeout_s):
9713
+ manifest = _require_task_context(repo, cfg, args.task_id)
9714
+ _require_current_writer(manifest, args)
8871
9715
  _cmd_commit_push_locked(args, repo, cfg, manifest)
8872
9716
 
8873
9717
 
@@ -8955,6 +9799,20 @@ def main(argv: Optional[List[str]] = None) -> int:
8955
9799
  s.add_argument("--json", action="store_true")
8956
9800
  s.set_defaults(func=cmd_agent_contract_check)
8957
9801
 
9802
+ s = sp.add_parser(
9803
+ "agent-result-template",
9804
+ help="Generate a complete reviewer result from a validated assignment",
9805
+ )
9806
+ source = s.add_mutually_exclusive_group(required=True)
9807
+ source.add_argument("--file")
9808
+ source.add_argument("--payload")
9809
+ s.add_argument(
9810
+ "--verdict",
9811
+ choices=["approved", "changes-requested", "blocked"],
9812
+ required=True,
9813
+ )
9814
+ s.set_defaults(func=cmd_agent_result_template)
9815
+
8958
9816
  s = sp.add_parser("validation-map-check")
8959
9817
  s.add_argument("--base")
8960
9818
  s.add_argument("--path", action="append")
@@ -9076,6 +9934,16 @@ def main(argv: Optional[List[str]] = None) -> int:
9076
9934
  s.add_argument("--json", action="store_true")
9077
9935
  s.set_defaults(func=cmd_task_status)
9078
9936
 
9937
+ s = sp.add_parser("task-scope-add")
9938
+ s.add_argument("task_id")
9939
+ s.add_argument("--owned-path", action="append", required=True)
9940
+ s.add_argument("--writer")
9941
+ s.add_argument("--lease-generation", type=int)
9942
+ s.add_argument("--intent")
9943
+ s.add_argument("--review-required", action="store_true")
9944
+ s.add_argument("--json", action="store_true")
9945
+ s.set_defaults(func=cmd_task_scope_add)
9946
+
9079
9947
  s = sp.add_parser("task-submodule-sync")
9080
9948
  s.add_argument("task_id")
9081
9949
  s.set_defaults(func=cmd_task_submodule_sync)