@elvis1513/auto-coding-skill 4.1.7 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -25,7 +25,8 @@ from pathlib import Path
25
25
  from typing import Iterator, Optional, List
26
26
 
27
27
  from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_config, run_shell, http_get_status, require_yaml
28
- from scaffold_templates import scaffold_groups, templates_for
28
+ from install_integrity import verify_managed_install
29
+ from scaffold_templates import MANAGED_FRAMEWORK_DOCS, scaffold_groups, templates_for
29
30
 
30
31
 
31
32
  _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
@@ -43,10 +44,12 @@ _AGENT_CONTRACT_VERSION = 1
43
44
  _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
44
45
  _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
45
46
  _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
47
+ _FINAL_GATE_CACHE_SCHEMA = 1
48
+ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
46
49
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
47
50
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
48
51
  "schema_version": 1,
49
- "managed_versions": {"agents": "4.1.7", "engineering": "4.1.7"},
52
+ "managed_versions": {"agents": "4.2.0", "engineering": "4.2.0"},
50
53
  "known_official_engineering_body_sha256": [
51
54
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
52
55
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -620,6 +623,332 @@ def _initialize_engineering_defaults(path: Path, repo: Path) -> None:
620
623
  path.write_text(updated, encoding="utf-8")
621
624
 
622
625
 
626
+ def _mapping(value: object) -> dict:
627
+ return value if isinstance(value, dict) else {}
628
+
629
+
630
+ def _string_list(value: object) -> list[str]:
631
+ if not isinstance(value, list):
632
+ return []
633
+ return [item.strip() for item in value if isinstance(item, str) and item.strip()]
634
+
635
+
636
+ def _copy_scalar_path(source: dict, target: dict, path: tuple[str, ...]) -> None:
637
+ current: object = source
638
+ for key in path:
639
+ if not isinstance(current, dict) or key not in current:
640
+ return
641
+ current = current[key]
642
+ destination = target
643
+ for key in path[:-1]:
644
+ destination = destination[key]
645
+ expected = destination[path[-1]]
646
+ compatible = (
647
+ (isinstance(expected, bool) and isinstance(current, bool))
648
+ or (isinstance(expected, str) and isinstance(current, str))
649
+ or (
650
+ isinstance(expected, (int, float))
651
+ and not isinstance(expected, bool)
652
+ and isinstance(current, (int, float))
653
+ and not isinstance(current, bool)
654
+ )
655
+ )
656
+ if compatible:
657
+ destination[path[-1]] = current
658
+
659
+
660
+ def _normalize_validation_routes(value: object) -> list[dict]:
661
+ routes: list[dict] = []
662
+ if not isinstance(value, list):
663
+ return routes
664
+ for raw in value:
665
+ if not isinstance(raw, dict):
666
+ continue
667
+ route: dict = {}
668
+ name = _text(raw.get("name"))
669
+ paths = _string_list(raw.get("paths"))
670
+ commands = [_command_name(item) for item in _string_list(raw.get("commands"))]
671
+ commands = [item for item in commands if item]
672
+ if name:
673
+ route["name"] = name
674
+ if paths:
675
+ route["paths"] = paths
676
+ exclude = _string_list(raw.get("exclude"))
677
+ if exclude:
678
+ route["exclude"] = exclude
679
+ if commands:
680
+ route["commands"] = commands
681
+ timeout = raw.get("timeout_seconds")
682
+ if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) and timeout > 0:
683
+ route["timeout_seconds"] = timeout
684
+ if paths and commands:
685
+ routes.append(route)
686
+ return routes
687
+
688
+
689
+ def _normalize_risk_rules(value: object) -> list[dict]:
690
+ rules: list[dict] = []
691
+ if not isinstance(value, list):
692
+ return rules
693
+ for raw in value:
694
+ if not isinstance(raw, dict):
695
+ continue
696
+ rule: dict = {}
697
+ name = _text(raw.get("name"))
698
+ paths = _string_list(raw.get("paths"))
699
+ if name:
700
+ rule["name"] = name
701
+ if paths:
702
+ rule["paths"] = paths
703
+ profile = _text(raw.get("profile")).lower()
704
+ if profile in _WORKFLOW_PROFILES - {"auto"}:
705
+ rule["profile"] = profile
706
+ for key in ["review", "design"]:
707
+ value_text = _text(raw.get(key)).lower()
708
+ if value_text in {"required", "true", "yes", "false", "no"}:
709
+ rule[key] = value_text
710
+ if paths:
711
+ rules.append(rule)
712
+ return rules
713
+
714
+
715
+ def _normalize_layer_rules(value: object) -> list[dict]:
716
+ rules: list[dict] = []
717
+ if not isinstance(value, list):
718
+ return rules
719
+ for raw in value:
720
+ if not isinstance(raw, dict):
721
+ continue
722
+ paths = _string_list(raw.get("paths"))
723
+ forbidden = _string_list(raw.get("forbidden_imports"))
724
+ if not paths or not forbidden:
725
+ continue
726
+ rule = {"paths": paths, "forbidden_imports": forbidden}
727
+ name = _text(raw.get("name"))
728
+ if name:
729
+ rule = {"name": name, **rule}
730
+ rules.append(rule)
731
+ return rules
732
+
733
+
734
+ def _converged_engineering_document(repo: Path, template_path: Path) -> str:
735
+ template_cfg, template_body = _read_frontmatter_markdown(template_path)
736
+ engineering = repo / "docs" / "ENGINEERING.md"
737
+ current_cfg: dict = {}
738
+ if engineering.exists():
739
+ try:
740
+ current_cfg, _ = _read_frontmatter_markdown(engineering)
741
+ except Exception:
742
+ # Initialization is an authoritative reset. Malformed legacy policy
743
+ # must not prevent the current schema from taking effect.
744
+ current_cfg = {}
745
+
746
+ converged = json.loads(json.dumps(template_cfg))
747
+ preserve_scalar_paths = [
748
+ ("project", "name"),
749
+ ("project", "repo_root"),
750
+ ("project", "stack"),
751
+ ("access", "project", "frontend", "url"),
752
+ ("access", "project", "frontend", "username"),
753
+ ("access", "project", "frontend", "password"),
754
+ ("access", "project", "backend", "url"),
755
+ ("access", "project", "backend", "username"),
756
+ ("access", "project", "backend", "password"),
757
+ ("access", "jenkins", "frontend", "url"),
758
+ ("access", "jenkins", "frontend", "username"),
759
+ ("access", "jenkins", "frontend", "password"),
760
+ ("access", "jenkins", "backend", "url"),
761
+ ("access", "jenkins", "backend", "username"),
762
+ ("access", "jenkins", "backend", "password"),
763
+ ("access", "gitlab", "url"),
764
+ ("access", "gitlab", "username"),
765
+ ("access", "gitlab", "password"),
766
+ ("access", "nexus", "frontend", "url"),
767
+ ("access", "nexus", "frontend", "username"),
768
+ ("access", "nexus", "frontend", "password"),
769
+ ("concurrency", "base_ref"),
770
+ ("concurrency", "target_branch"),
771
+ ("concurrency", "branch_prefix"),
772
+ ("concurrency", "worktree_root"),
773
+ ("concurrency", "cleanup_merged"),
774
+ ("concurrency", "delete_remote_branch"),
775
+ ("validation", "max_command_seconds"),
776
+ ("validation", "max_total_seconds"),
777
+ ("structure", "architecture_standard"),
778
+ ("docs", "api_docs_required"),
779
+ ]
780
+ for field_path in preserve_scalar_paths:
781
+ _copy_scalar_path(current_cfg, converged, field_path)
782
+
783
+ current_concurrency = _mapping(current_cfg.get("concurrency"))
784
+ isolation = _text(current_concurrency.get("isolation")).lower()
785
+ if isolation in {"adaptive", "worktree"}:
786
+ converged["concurrency"]["isolation"] = isolation
787
+ converged["concurrency"]["disposable_ignored"] = _string_list(
788
+ current_concurrency.get("disposable_ignored")
789
+ )
790
+
791
+ current_commands = _mapping(current_cfg.get("commands"))
792
+ current_validation = _mapping(current_cfg.get("validation"))
793
+ routes = _normalize_validation_routes(current_validation.get("routes"))
794
+ referenced_commands = {
795
+ command
796
+ for route in routes
797
+ for command in _string_list(route.get("commands"))
798
+ }
799
+ referenced_commands.add("project_fast")
800
+ commands = {
801
+ str(name): value.strip()
802
+ for name, value in current_commands.items()
803
+ if name in referenced_commands and isinstance(name, str) and isinstance(value, str) and value.strip()
804
+ }
805
+ inferred = _inferred_gate_commands(repo)
806
+ if not commands.get("project_fast") and inferred.get("project_fast"):
807
+ commands["project_fast"] = inferred["project_fast"]
808
+ converged["commands"].update(commands)
809
+
810
+ converged["validation"]["routes"] = routes
811
+ converged["risk"]["rules"] = _normalize_risk_rules(
812
+ _mapping(current_cfg.get("risk")).get("rules")
813
+ )
814
+ current_structure = _mapping(current_cfg.get("structure"))
815
+ converged["structure"]["accepted_debt_paths"] = _string_list(
816
+ current_structure.get("accepted_debt_paths")
817
+ )
818
+ current_layers = _mapping(current_structure.get("layer_rules"))
819
+ converged["structure"]["layer_rules"]["rules"] = _normalize_layer_rules(
820
+ current_layers.get("rules")
821
+ )
822
+
823
+ if not _text(_mapping(converged.get("project")).get("name")):
824
+ converged["project"]["name"] = repo.name
825
+ dumped = require_yaml().safe_dump(converged, allow_unicode=True, sort_keys=False).strip()
826
+ return f"---\n{dumped}\n---\n{template_body.lstrip()}"
827
+
828
+
829
+ _PROJECT_ARTIFACT_PATTERNS = (
830
+ "docs/architecture/*.md",
831
+ "docs/architecture/adr/*.md",
832
+ "docs/deployment/deploy-records/*.md",
833
+ "docs/design/*.md",
834
+ "docs/interfaces/*.md",
835
+ "docs/reviews/*.md",
836
+ )
837
+
838
+
839
+ def _is_allowed_project_doc(rel: Path) -> bool:
840
+ return any(rel.match(pattern) for pattern in _PROJECT_ARTIFACT_PATTERNS)
841
+
842
+
843
+ def cmd_project_converge(args: argparse.Namespace) -> None:
844
+ repo = Path(args.repo).resolve()
845
+ template = _skill_root() / "data" / "templates" / "ENGINEERING.md"
846
+ engineering = repo / "docs" / "ENGINEERING.md"
847
+ output = _converged_engineering_document(repo, template)
848
+ current = engineering.read_text(encoding="utf-8") if engineering.exists() else ""
849
+ changed = not bool(current)
850
+ if current:
851
+ try:
852
+ current_cfg, current_body = _parse_frontmatter_markdown_text(current, engineering)
853
+ output_cfg, output_body = _parse_frontmatter_markdown_text(output, engineering)
854
+ changed = current_cfg != output_cfg or current_body != output_body
855
+ except Exception:
856
+ changed = True
857
+ actions: list[dict] = []
858
+ version = _text(_mapping(_read_frontmatter_markdown(template)[0].get("workflow")).get("skill_version")) or "current"
859
+
860
+ def archive_previous(source_path: Path, content: str, label: str) -> None:
861
+ archive_root = repo / ".agents" / "archive" / "auto-coding-skill" / version
862
+ archive = archive_root / source_path.relative_to(repo)
863
+ if archive.exists() and archive.read_text(encoding="utf-8") != content:
864
+ digest = hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
865
+ archive = archive.with_name(f"{archive.stem}-{digest}{archive.suffix}")
866
+ if archive.exists():
867
+ return
868
+ actions.append({"action": "archive", "path": _repo_rel(repo, archive), "detail": label})
869
+ if args.write:
870
+ archive.parent.mkdir(parents=True, exist_ok=True)
871
+ archive.write_text(content, encoding="utf-8")
872
+
873
+ def archive_extra(source_path: Path, label: str) -> None:
874
+ content = source_path.read_bytes()
875
+ archive_root = repo / ".agents" / "archive" / "auto-coding-skill" / version
876
+ archive = archive_root / source_path.relative_to(repo)
877
+ if archive.exists() and archive.read_bytes() != content:
878
+ digest = hashlib.sha256(content).hexdigest()[:12]
879
+ archive = archive.with_name(f"{archive.stem}-{digest}{archive.suffix}")
880
+ if not archive.exists():
881
+ actions.append({"action": "archive", "path": _repo_rel(repo, archive), "detail": label})
882
+ if args.write:
883
+ archive.parent.mkdir(parents=True, exist_ok=True)
884
+ archive.write_bytes(content)
885
+
886
+ if changed and current:
887
+ archive_header = (
888
+ f"# Archived ENGINEERING.md before auto-coding-skill {version}\n\n"
889
+ "Historical and non-authoritative. Do not use this file as workflow policy.\n\n---\n\n"
890
+ )
891
+ archive_previous(engineering, archive_header + current, "previous project configuration")
892
+ if changed:
893
+ actions.append({
894
+ "action": "create" if not current else "replace",
895
+ "path": "docs/ENGINEERING.md",
896
+ })
897
+ if args.write:
898
+ engineering.parent.mkdir(parents=True, exist_ok=True)
899
+ engineering.write_text(output, encoding="utf-8")
900
+
901
+ for rel, canonical in sorted(templates_for("all").items()):
902
+ target = repo / rel
903
+ existing = target.read_text(encoding="utf-8") if target.exists() else ""
904
+ managed = rel in MANAGED_FRAMEWORK_DOCS
905
+ if existing and (not managed or existing == canonical):
906
+ continue
907
+ if existing:
908
+ archive_previous(target, existing, "previous managed documentation template")
909
+ actions.append({"action": "create" if not existing else "replace", "path": rel})
910
+ if args.write:
911
+ target.parent.mkdir(parents=True, exist_ok=True)
912
+ target.write_text(canonical, encoding="utf-8")
913
+
914
+ allowed_docs = {
915
+ Path("docs/ENGINEERING.md"),
916
+ Path("docs/tools/autopipeline/ap.py"),
917
+ *(Path(rel) for rel in templates_for("all")),
918
+ }
919
+ docs_root = repo / "docs"
920
+ if docs_root.exists():
921
+ for candidate in sorted(docs_root.rglob("*")):
922
+ if not candidate.is_file() and not candidate.is_symlink():
923
+ continue
924
+ rel = candidate.relative_to(repo)
925
+ if rel in allowed_docs or _is_allowed_project_doc(rel):
926
+ continue
927
+ archive_extra(candidate, "removed from the exact docs framework")
928
+ actions.append({"action": "delete", "path": rel.as_posix()})
929
+ if args.write:
930
+ candidate.unlink()
931
+ if args.write:
932
+ for directory in sorted(
933
+ (item for item in docs_root.rglob("*") if item.is_dir()),
934
+ key=lambda item: len(item.parts),
935
+ reverse=True,
936
+ ):
937
+ try:
938
+ directory.rmdir()
939
+ except OSError:
940
+ pass
941
+
942
+ result = {"changed": bool(actions), "mode": "write" if args.write else "plan", "actions": actions}
943
+ if args.json:
944
+ print(json.dumps(result, ensure_ascii=False, indent=2))
945
+ return
946
+ for action in actions:
947
+ print(f"[project-converge] {action['action']}: {action['path']}")
948
+ if not actions:
949
+ print("[project-converge] OK: already current")
950
+
951
+
623
952
  def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
624
953
  changed: list[str] = []
625
954
 
@@ -633,8 +962,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
633
962
  if _text(workflow_cfg.get("completion")).lower() != "push":
634
963
  workflow_cfg["completion"] = "push"
635
964
  changed.append("workflow.completion")
636
- if _text(workflow_cfg.get("skill_version")) != "4.1.7":
637
- workflow_cfg["skill_version"] = "4.1.7"
965
+ if _text(workflow_cfg.get("skill_version")) != "4.2.0":
966
+ workflow_cfg["skill_version"] = "4.2.0"
638
967
  changed.append("workflow.skill_version")
639
968
 
640
969
  commands_cfg = cfg.setdefault("commands", {})
@@ -947,16 +1276,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
947
1276
  if current_agents:
948
1277
  archive_dir = repo / "docs" / "archive" / "workflow"
949
1278
  archive_header = (
950
- "# Archived AGENTS.md before auto-coding-skill 4.1.7\n\n"
1279
+ "# Archived AGENTS.md before auto-coding-skill 4.2.0\n\n"
951
1280
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
952
1281
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
953
1282
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
954
1283
  )
955
1284
  archive_content = archive_header + current_agents
956
- archive = archive_dir / "AGENTS.pre-4.1.7.md"
1285
+ archive = archive_dir / "AGENTS.pre-4.2.0.md"
957
1286
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
958
1287
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
959
- archive = archive_dir / f"AGENTS.pre-4.1.7-{digest}.md"
1288
+ archive = archive_dir / f"AGENTS.pre-4.2.0-{digest}.md"
960
1289
  if not archive.exists():
961
1290
  add_action("policy", archive, "archive", "historical and non-authoritative")
962
1291
  if write:
@@ -1969,6 +2298,19 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1969
2298
  review_required = manifest.get("review_required", schema < 3)
1970
2299
  if not isinstance(review_required, bool):
1971
2300
  raise APError(f"Task {task_id} has an invalid review_required flag.")
2301
+ try:
2302
+ scope_revision = int(manifest.get("scope_revision") or 1)
2303
+ except (TypeError, ValueError) as exc:
2304
+ raise APError(f"Task {task_id} has an invalid scope_revision.") from exc
2305
+ if scope_revision < 1:
2306
+ raise APError(f"Task {task_id} has an invalid scope_revision.")
2307
+ effective_profile = _text(manifest.get("effective_profile"))
2308
+ if effective_profile and effective_profile not in (_WORKFLOW_PROFILES - {"auto"}):
2309
+ raise APError(f"Task {task_id} has an invalid effective_profile.")
2310
+ if "design_required" in manifest and not isinstance(manifest.get("design_required"), bool):
2311
+ raise APError(f"Task {task_id} has an invalid design_required flag.")
2312
+ if "scope_history" in manifest and not isinstance(manifest.get("scope_history"), list):
2313
+ raise APError(f"Task {task_id} has an invalid scope_history.")
1972
2314
  return manifest
1973
2315
 
1974
2316
 
@@ -1982,7 +2324,7 @@ def _load_task_manifest(repo: Path, task_id: str) -> dict:
1982
2324
  return _validate_task_manifest(repo, manifest, task_id)
1983
2325
 
1984
2326
 
1985
- def _save_task_manifest(repo: Path, manifest: dict) -> None:
2327
+ def _save_task_manifest(repo: Path, manifest: dict, *, strict_worktree: bool = False) -> None:
1986
2328
  _validate_task_manifest(repo, manifest)
1987
2329
  task_id = _validate_task_id(_text(manifest.get("task_id")))
1988
2330
  manifest["updated_at"] = _now_iso()
@@ -1994,11 +2336,15 @@ def _save_task_manifest(repo: Path, manifest: dict) -> None:
1994
2336
  try:
1995
2337
  _write_json_object(_worktree_manifest_path(worktree), manifest)
1996
2338
  except APError:
1997
- pass
2339
+ if strict_worktree:
2340
+ raise
1998
2341
 
1999
2342
 
2000
2343
  def _delete_task_manifest(repo: Path, manifest: dict) -> None:
2001
2344
  task_id = _validate_task_id(_text(manifest.get("task_id")))
2345
+ worktree_value = _text(manifest.get("worktree_path"))
2346
+ if worktree_value and Path(worktree_value).exists():
2347
+ _clear_final_gate_receipt(Path(worktree_value))
2002
2348
  _task_registry_path(repo, task_id).unlink(missing_ok=True)
2003
2349
 
2004
2350
 
@@ -2046,13 +2392,13 @@ def _working_tree_paths(repo: Path) -> list[str]:
2046
2392
  paths.update(
2047
2393
  _git_z_paths(
2048
2394
  repo,
2049
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2395
+ ["git", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2050
2396
  )
2051
2397
  )
2052
2398
  paths.update(
2053
2399
  _git_z_paths(
2054
2400
  repo,
2055
- ["git", "diff", "--cached", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2401
+ ["git", "diff", "--cached", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2056
2402
  )
2057
2403
  )
2058
2404
  paths.update(
@@ -2117,13 +2463,13 @@ def _task_content_fingerprint(repo: Path, cfg: dict, manifest: Optional[dict]) -
2117
2463
  if not batch:
2118
2464
  continue
2119
2465
  cached = run(
2120
- ["git", "diff", "--cached", "--binary", "--no-ext-diff", "--", *batch],
2466
+ ["git", "diff", "--cached", "--no-renames", "--binary", "--no-ext-diff", "--", *batch],
2121
2467
  cwd=repo,
2122
2468
  check=False,
2123
2469
  )
2124
2470
  digest.update(cached.stdout.encode("utf-8", errors="surrogateescape"))
2125
2471
  unstaged = run(
2126
- ["git", "diff", "--binary", "--no-ext-diff", "--", *batch],
2472
+ ["git", "diff", "--no-renames", "--binary", "--no-ext-diff", "--", *batch],
2127
2473
  cwd=repo,
2128
2474
  check=False,
2129
2475
  )
@@ -2137,11 +2483,140 @@ def _task_content_fingerprint(repo: Path, cfg: dict, manifest: Optional[dict]) -
2137
2483
  return digest.hexdigest()
2138
2484
 
2139
2485
 
2140
- def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2141
- expected = sorted(set(path for path in paths if path))
2142
- for start in range(0, len(expected), 100):
2143
- run(["git", "add", "-A", "--", *expected[start : start + 100]], cwd=repo)
2144
- staged = sorted(
2486
+ def _final_gate_receipt_path(repo: Path) -> Path:
2487
+ return _git_dir(repo) / "auto-coding-skill-final-gate.json"
2488
+
2489
+
2490
+ def _clear_final_gate_receipt(repo: Path) -> None:
2491
+ try:
2492
+ _final_gate_receipt_path(repo).unlink(missing_ok=True)
2493
+ except APError:
2494
+ return
2495
+
2496
+
2497
+ def _final_gate_identity(
2498
+ repo: Path,
2499
+ cfg: dict,
2500
+ manifest: dict,
2501
+ plan: dict,
2502
+ base_ref: str,
2503
+ ) -> tuple[dict, str]:
2504
+ paths = list(plan.get("changed_files") or [])
2505
+ validation_plan = _validation_plan(cfg, paths)
2506
+ _validate_validation_plan(cfg, validation_plan)
2507
+ command_hashes = {
2508
+ name: hashlib.sha256(_configured_command(cfg, name).encode("utf-8")).hexdigest()
2509
+ for name in validation_plan["commands"]
2510
+ }
2511
+ plan_payload = {
2512
+ "scope": plan.get("selected_scope"),
2513
+ "profile": plan.get("profile"),
2514
+ "effective_mode": plan.get("effective_mode"),
2515
+ "paths": validation_plan["paths"],
2516
+ "commands": validation_plan["commands"],
2517
+ "command_hashes": command_hashes,
2518
+ "command_timeouts": validation_plan["command_timeouts"],
2519
+ "matched_routes": validation_plan["matched_routes"],
2520
+ "coverage": validation_plan["coverage"],
2521
+ "unmapped": validation_plan["unmapped"],
2522
+ "docs_only": validation_plan["docs_only"],
2523
+ "compatibility_fallback": validation_plan["compatibility_fallback"],
2524
+ "on_unmapped": _text(_validation_cfg(cfg).get("on_unmapped")).lower() or "error",
2525
+ "budget": _final_gate_budget(cfg),
2526
+ "diff_check": "working-index-base-v1",
2527
+ }
2528
+ plan_sha256 = hashlib.sha256(
2529
+ json.dumps(plan_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
2530
+ ).hexdigest()
2531
+ resolved_base = _resolve_commit(repo, base_ref or _text(manifest.get("base_sha")) or "HEAD")
2532
+ identity = {
2533
+ "algorithm": _FINAL_GATE_CACHE_ALGORITHM,
2534
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
2535
+ "task_id": _text(manifest.get("task_id")),
2536
+ "task_uuid": _text(manifest.get("task_uuid")),
2537
+ "worktree_path": str(repo.resolve()),
2538
+ "branch": _current_branch(repo),
2539
+ "base_sha": resolved_base,
2540
+ "head_sha": _resolve_commit(repo, "HEAD"),
2541
+ "scope_revision": int(manifest.get("scope_revision") or 1),
2542
+ "owned_paths": sorted(manifest.get("owned_paths") or []),
2543
+ "writer_generation": int((manifest.get("writer_lease") or {}).get("generation") or 0),
2544
+ "plan_sha256": plan_sha256,
2545
+ }
2546
+ return identity, _task_content_fingerprint(repo, cfg, manifest)
2547
+
2548
+
2549
+ def _record_final_gate_receipt(
2550
+ repo: Path,
2551
+ cfg: dict,
2552
+ manifest: dict,
2553
+ plan: dict,
2554
+ base_ref: str,
2555
+ executed: list[str],
2556
+ ) -> None:
2557
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2558
+ _write_json_object(
2559
+ _final_gate_receipt_path(repo),
2560
+ {
2561
+ "schema": _FINAL_GATE_CACHE_SCHEMA,
2562
+ "kind": "final_changed_scope_gate",
2563
+ "status": "pass",
2564
+ "identity": identity,
2565
+ "content_fingerprints": [fingerprint],
2566
+ "executed": list(executed),
2567
+ "passed_at": _now_iso(),
2568
+ },
2569
+ )
2570
+
2571
+
2572
+ def _reuse_final_gate_receipt(
2573
+ repo: Path,
2574
+ cfg: dict,
2575
+ manifest: dict,
2576
+ plan: dict,
2577
+ base_ref: str,
2578
+ ) -> Optional[dict]:
2579
+ receipt = _read_json_object(_final_gate_receipt_path(repo)) or {}
2580
+ if (
2581
+ int(receipt.get("schema") or 0) != _FINAL_GATE_CACHE_SCHEMA
2582
+ or _text(receipt.get("kind")) != "final_changed_scope_gate"
2583
+ or _text(receipt.get("status")) != "pass"
2584
+ ):
2585
+ return None
2586
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2587
+ if receipt.get("identity") != identity:
2588
+ return None
2589
+ allowed = receipt.get("content_fingerprints") or []
2590
+ if not isinstance(allowed, list) or fingerprint not in allowed:
2591
+ return None
2592
+ return receipt
2593
+
2594
+
2595
+ def _extend_final_gate_receipt(
2596
+ repo: Path,
2597
+ cfg: dict,
2598
+ manifest: dict,
2599
+ plan: dict,
2600
+ base_ref: str,
2601
+ ) -> None:
2602
+ receipt = _read_json_object(_final_gate_receipt_path(repo)) or {}
2603
+ identity, fingerprint = _final_gate_identity(repo, cfg, manifest, plan, base_ref)
2604
+ if (
2605
+ int(receipt.get("schema") or 0) != _FINAL_GATE_CACHE_SCHEMA
2606
+ or _text(receipt.get("kind")) != "final_changed_scope_gate"
2607
+ or _text(receipt.get("status")) != "pass"
2608
+ or receipt.get("identity") != identity
2609
+ ):
2610
+ raise APError("The successful final-gate receipt no longer matches the staged task state.")
2611
+ allowed = list(receipt.get("content_fingerprints") or [])
2612
+ if fingerprint not in allowed:
2613
+ allowed.append(fingerprint)
2614
+ receipt["content_fingerprints"] = allowed
2615
+ _write_json_object(_final_gate_receipt_path(repo), receipt)
2616
+
2617
+
2618
+ def _staged_paths(repo: Path) -> list[str]:
2619
+ return sorted(
2145
2620
  set(
2146
2621
  _checked_git_z_paths(
2147
2622
  repo,
@@ -2149,6 +2624,7 @@ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2149
2624
  "git",
2150
2625
  "diff",
2151
2626
  "--cached",
2627
+ "--no-renames",
2152
2628
  "--name-only",
2153
2629
  "-z",
2154
2630
  "--diff-filter=ACDMRTUXB",
@@ -2157,6 +2633,36 @@ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2157
2633
  )
2158
2634
  )
2159
2635
  )
2636
+
2637
+
2638
+ def _exact_stage_plan(repo: Path, paths: list[str], *, dry_run: bool) -> tuple[list[str], list[str]]:
2639
+ expected = sorted(set(path for path in paths if path))
2640
+ expected_set = set(expected)
2641
+ staged = _staged_paths(repo)
2642
+ pending = _unstaged_task_paths(repo)
2643
+ unexpected = sorted((set(staged) | set(pending)) - expected_set)
2644
+ if unexpected:
2645
+ raise APError(
2646
+ "Refusing to commit paths outside the current task:\n- " + "\n- ".join(unexpected)
2647
+ )
2648
+ if dry_run:
2649
+ for start in range(0, len(pending), 100):
2650
+ run(
2651
+ ["git", "add", "--dry-run", "-A", "--", *pending[start : start + 100]],
2652
+ cwd=repo,
2653
+ )
2654
+ return expected, pending
2655
+
2656
+
2657
+ def _preflight_exact_paths(repo: Path, paths: list[str]) -> None:
2658
+ _exact_stage_plan(repo, paths, dry_run=True)
2659
+
2660
+
2661
+ def _stage_exact_paths(repo: Path, paths: list[str]) -> list[str]:
2662
+ expected, pending = _exact_stage_plan(repo, paths, dry_run=False)
2663
+ for start in range(0, len(pending), 100):
2664
+ run(["git", "add", "-A", "--", *pending[start : start + 100]], cwd=repo)
2665
+ staged = _staged_paths(repo)
2160
2666
  unexpected = sorted(set(staged) - set(expected))
2161
2667
  if unexpected:
2162
2668
  raise APError(
@@ -2242,7 +2748,16 @@ def _task_changed_paths_from_base(repo: Path, base_sha: str) -> list[str]:
2242
2748
  paths = set(
2243
2749
  _checked_git_z_paths(
2244
2750
  repo,
2245
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB", base_sha, "--"],
2751
+ [
2752
+ "git",
2753
+ "diff",
2754
+ "--no-renames",
2755
+ "--name-only",
2756
+ "-z",
2757
+ "--diff-filter=ACDMRTUXB",
2758
+ base_sha,
2759
+ "--",
2760
+ ],
2246
2761
  "task diff paths",
2247
2762
  )
2248
2763
  )
@@ -2266,6 +2781,20 @@ def _task_unowned_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
2266
2781
  ]
2267
2782
 
2268
2783
 
2784
+ def _task_staging_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
2785
+ paths = _task_commit_paths(repo)
2786
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
2787
+ managed = set(_task_managed_paths(cfg, manifest))
2788
+ unowned = [
2789
+ path
2790
+ for path in paths
2791
+ if path not in managed and not _path_is_owned(path, owned)
2792
+ ]
2793
+ if unowned:
2794
+ raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
2795
+ return paths
2796
+
2797
+
2269
2798
  def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
2270
2799
  base_sha = _text(manifest.get("base_sha"))
2271
2800
  owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
@@ -2276,7 +2805,14 @@ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = N
2276
2805
  if path not in managed and _path_is_owned(path, owned)
2277
2806
  ]
2278
2807
  digest = hashlib.sha256()
2279
- digest.update(f"contract:{_AGENT_CONTRACT_VERSION}\nbase:{base_sha}\n".encode("utf-8"))
2808
+ digest.update(
2809
+ (
2810
+ f"contract:{_AGENT_CONTRACT_VERSION}\nbase:{base_sha}\n"
2811
+ f"scope_revision:{int(manifest.get('scope_revision') or 1)}\n"
2812
+ ).encode("utf-8")
2813
+ )
2814
+ for owned_path in owned:
2815
+ digest.update(f"owned:{owned_path}\0".encode("utf-8", errors="surrogateescape"))
2280
2816
  for rel in paths:
2281
2817
  digest.update(f"path:{rel}\0".encode("utf-8", errors="surrogateescape"))
2282
2818
  path = repo / rel
@@ -2364,11 +2900,50 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
2364
2900
  return fingerprint
2365
2901
 
2366
2902
 
2903
+ def _reconcile_task_risk(repo: Path, cfg: dict, manifest: dict) -> None:
2904
+ changed_paths = _task_changed_paths_from_base(repo, _text(manifest.get("base_sha")))
2905
+ plan = _resolve_execution_plan(
2906
+ cfg,
2907
+ repo,
2908
+ changed_paths=changed_paths,
2909
+ planned_paths=list(manifest.get("owned_paths") or []),
2910
+ requested_task_kind="change",
2911
+ )
2912
+ old_profile = _text(manifest.get("effective_profile")) or (
2913
+ "high-risk" if bool(manifest.get("review_required")) else "standard"
2914
+ )
2915
+ planned_profile = _text(plan.get("profile")) or "standard"
2916
+ effective_profile = (
2917
+ planned_profile
2918
+ if _PROFILE_RANK[planned_profile] > _PROFILE_RANK[old_profile]
2919
+ else old_profile
2920
+ )
2921
+ review_required = bool(manifest.get("review_required") or plan.get("review_required"))
2922
+ design_required = bool(manifest.get("design_required") or plan.get("design_required"))
2923
+ escalated = (
2924
+ effective_profile != old_profile
2925
+ or review_required != bool(manifest.get("review_required"))
2926
+ or design_required != bool(manifest.get("design_required"))
2927
+ )
2928
+ if not escalated:
2929
+ return
2930
+ manifest["effective_profile"] = effective_profile
2931
+ manifest["review_required"] = review_required
2932
+ manifest["design_required"] = design_required
2933
+ _invalidate_task_review(manifest, "actual changed paths raised task risk; review again")
2934
+ _clear_final_gate_receipt(repo)
2935
+ _save_task_manifest(repo, manifest)
2936
+ raise APError(
2937
+ "Actual changed paths raised task risk. Complete any necessary design/review and retry "
2938
+ f"commit-push: profile={effective_profile}, review_required={str(review_required).lower()}."
2939
+ )
2940
+
2941
+
2367
2942
  def _unstaged_task_paths(repo: Path) -> list[str]:
2368
2943
  paths = set(
2369
2944
  _checked_git_z_paths(
2370
2945
  repo,
2371
- ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2946
+ ["git", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2372
2947
  "unstaged task paths",
2373
2948
  )
2374
2949
  )
@@ -2405,7 +2980,14 @@ def _require_task_context(repo: Path, cfg: dict, task_id: str) -> dict:
2405
2980
  registered = _read_json_object(_task_registry_path(repo, expected_task))
2406
2981
  if not registered:
2407
2982
  raise APError(f"Task registry entry is missing for {expected_task}; refusing to recreate it implicitly.")
2408
- for field in ("task_id", "task_uuid", "task_branch", "worktree_path", "base_sha"):
2983
+ for field in (
2984
+ "task_id",
2985
+ "task_uuid",
2986
+ "task_branch",
2987
+ "worktree_path",
2988
+ "base_sha",
2989
+ "scope_revision",
2990
+ ):
2409
2991
  if _text(registered.get(field)) != _text(manifest.get(field)):
2410
2992
  raise APError(f"Task manifest/registry mismatch for {expected_task}: {field}")
2411
2993
  manifest = registered
@@ -2717,7 +3299,7 @@ def _run_configured_command_list(
2717
3299
  remaining = deadline - time.monotonic()
2718
3300
  if remaining <= 0:
2719
3301
  raise APError(
2720
- "Final changed-scope gate exceeded its total time budget before "
3302
+ "Final changed-scope gate timed out: exceeded its total time budget before "
2721
3303
  f"commands.{name}; narrow validation.routes"
2722
3304
  )
2723
3305
  timeout_s = min(timeout_s, remaining) if timeout_s is not None else remaining
@@ -2781,9 +3363,9 @@ def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
2781
3363
  manifest = _active_task_manifest(repo)
2782
3364
  effective_base = base_ref or (_text(manifest.get("base_sha")) if manifest else "") or _default_base_ref(repo)
2783
3365
  if effective_base:
2784
- paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACDMRTUXB", f"{effective_base}...HEAD"]))
2785
- paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACDMRTUXB"]))
2786
- paths.extend(_git_lines(repo, ["git", "diff", "--cached", "--name-only", "--diff-filter=ACDMRTUXB"]))
3366
+ paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB", f"{effective_base}...HEAD"]))
3367
+ paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB"]))
3368
+ paths.extend(_git_lines(repo, ["git", "diff", "--cached", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB"]))
2787
3369
  paths.extend(_git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"]))
2788
3370
  return _unique_paths(paths)
2789
3371
 
@@ -2796,9 +3378,10 @@ def _commit_changed_files(repo: Path, ref: str) -> list[str]:
2796
3378
  "diff-tree",
2797
3379
  "--root",
2798
3380
  "--no-commit-id",
3381
+ "--no-renames",
2799
3382
  "--name-only",
2800
3383
  "-r",
2801
- "--diff-filter=ACMRTUXB",
3384
+ "--diff-filter=ACDMRTUXB",
2802
3385
  commit_ref,
2803
3386
  ],
2804
3387
  cwd=repo,
@@ -5572,6 +6155,11 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
5572
6155
  light_gate_start = time.time()
5573
6156
  monotonic_start = time.monotonic()
5574
6157
  cfg = _load_cfg(repo)
6158
+ manifest = _active_task_manifest(repo)
6159
+ if manifest:
6160
+ manifest = _require_task_context(repo, cfg, _text(manifest.get("task_id")))
6161
+ _clear_final_gate_receipt(repo)
6162
+ before_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
5575
6163
  budget = _final_gate_budget(cfg)
5576
6164
  deadline = monotonic_start + budget["total_seconds"]
5577
6165
  requested_scope = _text(getattr(args, "scope", "")).lower()
@@ -5606,10 +6194,23 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
5606
6194
  _run_git_diff_check(repo, cfg)
5607
6195
  if time.monotonic() > deadline:
5608
6196
  raise APError(
5609
- f"Final changed-scope gate exceeded {budget['total_seconds']:.0f}s; "
6197
+ f"Final changed-scope gate timed out after {budget['total_seconds']:.0f}s; "
5610
6198
  "narrow validation.routes and keep slower checks explicit"
5611
6199
  )
5612
6200
  executed.append("diff_check")
6201
+ after_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
6202
+ if after_fingerprint != before_fingerprint:
6203
+ _clear_final_gate_receipt(repo)
6204
+ raise APError("The final gate changed task content; inspect the diff before retrying.")
6205
+ if manifest:
6206
+ _record_final_gate_receipt(
6207
+ repo,
6208
+ cfg,
6209
+ manifest,
6210
+ plan,
6211
+ _text(getattr(args, "base", "")) or _text(manifest.get("base_sha")),
6212
+ executed,
6213
+ )
5613
6214
  duration_s = time.time() - light_gate_start
5614
6215
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
5615
6216
  _record_evidence(
@@ -5983,6 +6584,22 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5983
6584
  if runtime_enabled and not str(runtime_cfg.get("docker_compose_file") or "").strip():
5984
6585
  validation_errors.append("runtime config is partially enabled but runtime.docker_compose_file is missing")
5985
6586
 
6587
+ version_match = re.fullmatch(r"([0-9]+)\.([0-9]+)\.([0-9]+)", skill_version)
6588
+ integrity_required = bool(
6589
+ version_match
6590
+ and tuple(int(part) for part in version_match.groups()) >= (4, 1, 9)
6591
+ )
6592
+ manifest_exists = (repo / ".agents" / "managed-install.json").is_file()
6593
+ if integrity_required or manifest_exists:
6594
+ integrity = verify_managed_install(
6595
+ repo,
6596
+ mode="project",
6597
+ expected_version=skill_version or None,
6598
+ )
6599
+ validation_errors.extend(
6600
+ f"install integrity: {issue}" for issue in integrity["errors"]
6601
+ )
6602
+
5986
6603
  missing.extend(validation_errors)
5987
6604
 
5988
6605
  if missing:
@@ -7389,6 +8006,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7389
8006
  "created_at": _now_iso(),
7390
8007
  "initial_untracked": [],
7391
8008
  "owned_paths": owned_paths,
8009
+ "scope_revision": 1,
8010
+ "effective_profile": plan["profile"],
8011
+ "design_required": bool(plan["design_required"]),
8012
+ "scope_history": [],
7392
8013
  "depends_on": depends_on,
7393
8014
  "prerequisite_shas": prerequisite_shas,
7394
8015
  "writer_lease": {
@@ -7470,6 +8091,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7470
8091
  "created_at": _now_iso(),
7471
8092
  "initial_untracked": [],
7472
8093
  "owned_paths": owned_paths,
8094
+ "scope_revision": 1,
8095
+ "effective_profile": plan["profile"],
8096
+ "design_required": bool(plan["design_required"]),
8097
+ "scope_history": [],
7473
8098
  "depends_on": depends_on,
7474
8099
  "prerequisite_shas": prerequisite_shas,
7475
8100
  "writer_lease": {
@@ -7599,6 +8224,171 @@ def _task_lifecycle_context(repo: Path, cfg: dict, task_id: str) -> tuple[Path,
7599
8224
  return repo, Path(_text(manifest.get("worktree_path"))).resolve(), manifest
7600
8225
 
7601
8226
 
8227
+ def cmd_task_scope_add(args: argparse.Namespace) -> None:
8228
+ repo = Path(args.repo).resolve()
8229
+ ensure_git_repo(repo)
8230
+ cfg = _load_cfg(repo)
8231
+ task_id = _validate_task_id(args.task_id)
8232
+ additions = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
8233
+ if not additions:
8234
+ raise APError("task-scope-add requires at least one --owned-path.")
8235
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
8236
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
8237
+ result: dict = {}
8238
+ with (
8239
+ _repo_lock(control_repo, "integration", timeout_s=timeout_s),
8240
+ _repo_lock(control_repo, "task-registry", timeout_s=timeout_s),
8241
+ _repo_lock(control_repo, "direct-claim", timeout_s=timeout_s),
8242
+ _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s),
8243
+ ):
8244
+ manifest = _load_task_manifest(control_repo, task_id)
8245
+ _require_current_writer(manifest, args)
8246
+ if int(manifest.get("schema") or 0) < 3:
8247
+ raise APError("task-scope-add requires a schema-3 task created by the current workflow.")
8248
+ if _text(manifest.get("state")) != "active":
8249
+ raise APError(
8250
+ f"Task {task_id} cannot expand scope in state={manifest.get('state')}; start a new task."
8251
+ )
8252
+ lease_generation = int((manifest.get("writer_lease") or {}).get("generation") or 0)
8253
+ requested_generation = getattr(args, "lease_generation", None)
8254
+ if requested_generation is not None and requested_generation != lease_generation:
8255
+ raise APError(
8256
+ f"Writer lease generation changed: expected={requested_generation}, current={lease_generation}."
8257
+ )
8258
+ if not worktree.exists():
8259
+ raise APError(f"Task worktree is missing: {worktree}")
8260
+ if _resolve_commit(worktree, "HEAD") != _text(manifest.get("base_sha")):
8261
+ raise APError("task-scope-add is allowed only before the task creates a commit.")
8262
+ if _text(manifest.get("last_commit")) or _text(manifest.get("remote_task_tip")):
8263
+ raise APError("task-scope-add cannot extend a task that already committed or pushed work.")
8264
+
8265
+ current = sorted({_normalize_owned_path(item) for item in manifest.get("owned_paths") or []})
8266
+ new_paths = [path for path in additions if not _path_is_owned(path, current)]
8267
+ if not new_paths:
8268
+ result = {
8269
+ "task_id": task_id,
8270
+ "status": "noop",
8271
+ "scope_revision": int(manifest.get("scope_revision") or 1),
8272
+ "owned_paths": current,
8273
+ }
8274
+ else:
8275
+ proposed = sorted(set(current) | set(new_paths))
8276
+ for claim in _active_direct_claims(control_repo):
8277
+ claim_paths = list(claim.get("owned_paths") or [])
8278
+ if _owned_paths_overlap(proposed, claim_paths):
8279
+ raise APError(
8280
+ "Expanded scope overlaps active direct claim held by "
8281
+ f"{_text(claim.get('owner')) or '(unknown)'}: "
8282
+ + ", ".join(claim_paths)
8283
+ )
8284
+ registry_dir = _task_state_root(control_repo) / "tasks"
8285
+ for path in sorted(registry_dir.glob("*.json")) if registry_dir.exists() else []:
8286
+ other = _read_json_object(path) or {}
8287
+ if _text(other.get("task_id")) == task_id:
8288
+ continue
8289
+ if _text(other.get("state")) in {"", "integrated", "cleanup-pending"}:
8290
+ continue
8291
+ other_owned = other.get("owned_paths") or []
8292
+ if isinstance(other_owned, list) and _owned_paths_overlap(proposed, other_owned):
8293
+ raise APError(
8294
+ f"Expanded scope overlaps active task {_text(other.get('task_id')) or path.stem}: "
8295
+ + ", ".join(other_owned)
8296
+ )
8297
+
8298
+ worktree_cfg = _load_cfg(worktree)
8299
+ existing_unowned = _task_unowned_paths(worktree, worktree_cfg, manifest)
8300
+ implicit_adoptions = sorted(path for path in existing_unowned if path not in set(new_paths))
8301
+ if implicit_adoptions:
8302
+ raise APError(
8303
+ "Existing unowned changes must be added as exact --owned-path values before scope expansion:\n- "
8304
+ + "\n- ".join(implicit_adoptions)
8305
+ )
8306
+ changed_paths = _task_changed_paths_from_base(
8307
+ worktree,
8308
+ _text(manifest.get("base_sha")),
8309
+ )
8310
+ plan = _resolve_execution_plan(
8311
+ worktree_cfg,
8312
+ worktree,
8313
+ changed_paths=changed_paths,
8314
+ planned_paths=proposed,
8315
+ intent=_text(getattr(args, "intent", "")),
8316
+ requested_task_kind="change",
8317
+ )
8318
+ old_profile = _text(manifest.get("effective_profile")) or (
8319
+ "high-risk" if bool(manifest.get("review_required")) else "standard"
8320
+ )
8321
+ planned_profile = _text(plan.get("profile")) or "standard"
8322
+ effective_profile = (
8323
+ planned_profile
8324
+ if _PROFILE_RANK[planned_profile] > _PROFILE_RANK[old_profile]
8325
+ else old_profile
8326
+ )
8327
+ old_manifest = json.loads(json.dumps(manifest))
8328
+ revision = int(manifest.get("scope_revision") or 1) + 1
8329
+ manifest["owned_paths"] = proposed
8330
+ manifest["scope_revision"] = revision
8331
+ manifest["effective_profile"] = effective_profile
8332
+ manifest["review_required"] = bool(
8333
+ manifest.get("review_required")
8334
+ or plan.get("review_required")
8335
+ or bool(getattr(args, "review_required", False))
8336
+ )
8337
+ manifest["design_required"] = bool(
8338
+ manifest.get("design_required") or plan.get("design_required")
8339
+ )
8340
+ manifest["claimed_paths"] = []
8341
+ history = list(manifest.get("scope_history") or [])
8342
+ history.append(
8343
+ {
8344
+ "revision": revision,
8345
+ "added_paths": new_paths,
8346
+ "adopted_dirty_paths": existing_unowned,
8347
+ "actor": _text(getattr(args, "writer", ""))
8348
+ or _text(os.environ.get("CODEX_THREAD_ID")),
8349
+ "updated_at": _now_iso(),
8350
+ "previous_profile": old_profile,
8351
+ "effective_profile": effective_profile,
8352
+ }
8353
+ )
8354
+ manifest["scope_history"] = history
8355
+ _invalidate_task_review(manifest, "task scope expanded; review and final gate must run again")
8356
+ _clear_final_gate_receipt(worktree)
8357
+ try:
8358
+ _save_task_manifest(control_repo, manifest, strict_worktree=True)
8359
+ except Exception:
8360
+ _save_task_manifest(control_repo, old_manifest)
8361
+ raise
8362
+ registered = _load_task_manifest(control_repo, task_id)
8363
+ mirrored = _read_json_object(_worktree_manifest_path(worktree)) or {}
8364
+ for field in ("task_uuid", "scope_revision", "owned_paths", "review_required"):
8365
+ if registered.get(field) != mirrored.get(field):
8366
+ raise APError(f"Task scope manifest synchronization failed for field: {field}")
8367
+ result = {
8368
+ "task_id": task_id,
8369
+ "status": "expanded",
8370
+ "scope_revision": revision,
8371
+ "owned_paths": proposed,
8372
+ "added_paths": new_paths,
8373
+ "effective_profile": effective_profile,
8374
+ "review_required": manifest["review_required"],
8375
+ "design_required": manifest["design_required"],
8376
+ }
8377
+ if bool(getattr(args, "json", False)):
8378
+ print(json.dumps(result, ensure_ascii=False, indent=2))
8379
+ elif result["status"] == "noop":
8380
+ print(
8381
+ f"[task-scope-add] NOOP task={task_id} "
8382
+ f"scope_revision={result['scope_revision']}"
8383
+ )
8384
+ else:
8385
+ print(
8386
+ f"[task-scope-add] OK task={task_id} scope_revision={result['scope_revision']} "
8387
+ f"profile={result['effective_profile']} review_required="
8388
+ f"{str(result['review_required']).lower()} added={','.join(result['added_paths'])}"
8389
+ )
8390
+
8391
+
7602
8392
  def cmd_task_review(args: argparse.Namespace) -> None:
7603
8393
  repo = Path(args.repo).resolve()
7604
8394
  ensure_git_repo(repo)
@@ -7923,11 +8713,17 @@ def cmd_task_finish(args: argparse.Namespace) -> None:
7923
8713
  task_id = _validate_task_id(args.task_id)
7924
8714
  manifest = _load_task_manifest(repo, task_id)
7925
8715
  if _text(manifest.get("execution_mode")).lower() == "direct":
7926
- if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
7927
- raise APError("Run task-finish for a direct task from its current checkout.")
7928
- if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
7929
- raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
7930
- _clear_direct_task(repo, manifest)
8716
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
8717
+ with (
8718
+ _repo_lock(repo, "integration", timeout_s=timeout_s),
8719
+ _repo_lock(repo, f"task-{task_id}", timeout_s=timeout_s),
8720
+ ):
8721
+ manifest = _load_task_manifest(repo, task_id)
8722
+ if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
8723
+ raise APError("Run task-finish for a direct task from its current checkout.")
8724
+ if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
8725
+ raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
8726
+ _clear_direct_task(repo, manifest)
7931
8727
  print(f"[task-finish] OK task={task_id} execution_mode=direct no temporary branch existed")
7932
8728
  return
7933
8729
  _require_control_checkout(repo, manifest)
@@ -8332,6 +9128,7 @@ def _cmd_direct_commit_push_locked(
8332
9128
  ) -> None:
8333
9129
  _require_current_writer(manifest, args)
8334
9130
  _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
9131
+ _reconcile_task_risk(repo, cfg, manifest)
8335
9132
  _require_approved_review(repo, cfg, manifest)
8336
9133
  branch = _current_branch(repo)
8337
9134
  target = _text(manifest.get("target_branch"))
@@ -8353,6 +9150,8 @@ def _cmd_direct_commit_push_locked(
8353
9150
  commit_sha = pending_commit
8354
9151
  plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
8355
9152
  else:
9153
+ task_paths = _task_staging_paths(repo, cfg, manifest)
9154
+ _preflight_exact_paths(repo, task_paths)
8356
9155
  cmd_doctor(
8357
9156
  argparse.Namespace(
8358
9157
  repo=str(repo),
@@ -8368,23 +9167,36 @@ def _cmd_direct_commit_push_locked(
8368
9167
  base_ref=_text(manifest.get("base_sha")),
8369
9168
  )
8370
9169
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
8371
- cmd_light_gate(
8372
- argparse.Namespace(
8373
- repo=str(repo),
8374
- scope="changed",
8375
- profile=plan["profile"],
8376
- mode="dev",
8377
- base=_text(manifest.get("base_sha")),
8378
- explain=False,
8379
- )
9170
+ receipt = _reuse_final_gate_receipt(
9171
+ repo,
9172
+ cfg,
9173
+ manifest,
9174
+ plan,
9175
+ _text(manifest.get("base_sha")),
8380
9176
  )
9177
+ if receipt:
9178
+ print(
9179
+ "[light-gate] REUSED task="
9180
+ f"{manifest['task_id']} passed_at={receipt.get('passed_at')}"
9181
+ )
9182
+ else:
9183
+ cmd_light_gate(
9184
+ argparse.Namespace(
9185
+ repo=str(repo),
9186
+ scope="changed",
9187
+ profile=plan["profile"],
9188
+ mode="dev",
9189
+ base=_text(manifest.get("base_sha")),
9190
+ explain=False,
9191
+ )
9192
+ )
8381
9193
  after_gate = _task_content_fingerprint(repo, cfg, manifest)
8382
9194
  if after_gate != before_gate:
8383
9195
  raise APError("The final gate changed direct-task files; inspect them and retry commit-push.")
8384
9196
  manifest = _require_task_context(repo, cfg, args.task_id)
8385
9197
  _require_current_writer(manifest, args)
8386
9198
  _require_approved_review(repo, cfg, manifest)
8387
- task_paths = _task_commit_paths(repo)
9199
+ task_paths = _task_staging_paths(repo, cfg, manifest)
8388
9200
  staged = _stage_exact_paths(repo, task_paths)
8389
9201
  if not staged:
8390
9202
  _clear_direct_task(repo, manifest)
@@ -8393,6 +9205,13 @@ def _cmd_direct_commit_push_locked(
8393
9205
  unstaged = _unstaged_task_paths(repo)
8394
9206
  if unstaged:
8395
9207
  raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
9208
+ _extend_final_gate_receipt(
9209
+ repo,
9210
+ cfg,
9211
+ manifest,
9212
+ plan,
9213
+ _text(manifest.get("base_sha")),
9214
+ )
8396
9215
  commit_sha = _commit_exact_index(repo, args.msg)
8397
9216
  manifest["state"] = "push-pending"
8398
9217
  manifest["last_commit"] = commit_sha
@@ -8440,7 +9259,23 @@ def _cmd_commit_push_locked(
8440
9259
  _save_task_manifest(repo, manifest)
8441
9260
  _require_current_writer(manifest, args)
8442
9261
  _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
9262
+ _reconcile_task_risk(repo, cfg, manifest)
8443
9263
  _require_approved_review(repo, cfg, manifest)
9264
+ working_paths = _task_commit_paths(repo)
9265
+ head = _resolve_commit(repo, "HEAD")
9266
+ pending_commit = _text(manifest.get("last_commit"))
9267
+ if pending_commit and pending_commit == head and not working_paths:
9268
+ plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
9269
+ _push_current_task(repo, manifest, pending_commit)
9270
+ print(
9271
+ f"[commit-push] OK - profile={plan['profile']} mode={plan['effective_mode']} "
9272
+ f"scope={plan['selected_scope']} commit={pending_commit}"
9273
+ )
9274
+ return
9275
+ protected = set(manifest.get("initial_untracked") or [])
9276
+ _cleanup_generated_noise(repo, protected_paths=protected)
9277
+ task_paths = _task_staging_paths(repo, cfg, manifest)
9278
+ _preflight_exact_paths(repo, task_paths)
8444
9279
  cmd_doctor(
8445
9280
  argparse.Namespace(
8446
9281
  repo=str(repo),
@@ -8464,16 +9299,23 @@ def _cmd_commit_push_locked(
8464
9299
 
8465
9300
  msg = args.msg
8466
9301
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
8467
- cmd_light_gate(
8468
- argparse.Namespace(
8469
- repo=str(repo),
8470
- scope="changed",
8471
- profile=plan["profile"],
8472
- mode="dev",
8473
- base=base_ref,
8474
- explain=False,
9302
+ receipt = _reuse_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
9303
+ if receipt:
9304
+ print(
9305
+ "[light-gate] REUSED task="
9306
+ f"{manifest['task_id']} passed_at={receipt.get('passed_at')}"
9307
+ )
9308
+ else:
9309
+ cmd_light_gate(
9310
+ argparse.Namespace(
9311
+ repo=str(repo),
9312
+ scope="changed",
9313
+ profile=plan["profile"],
9314
+ mode="dev",
9315
+ base=base_ref,
9316
+ explain=False,
9317
+ )
8475
9318
  )
8476
- )
8477
9319
 
8478
9320
  after_gate = _task_content_fingerprint(repo, cfg, manifest)
8479
9321
  if after_gate != before_gate:
@@ -8491,15 +9333,13 @@ def _cmd_commit_push_locked(
8491
9333
  "no files were staged or restored."
8492
9334
  )
8493
9335
 
8494
- protected = set(manifest.get("initial_untracked") or [])
8495
- _cleanup_generated_noise(repo, protected_paths=protected)
8496
9336
  pre_stage_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
8497
9337
  manifest = _require_task_context(repo, cfg, args.task_id)
8498
9338
  _require_current_writer(manifest, args)
8499
9339
  _require_approved_review(repo, cfg, manifest)
8500
9340
  if _task_content_fingerprint(repo, cfg, manifest) != pre_stage_fingerprint:
8501
9341
  raise APError("Task-owned files changed immediately before staging; refusing to commit.")
8502
- task_paths = _task_commit_paths(repo)
9342
+ task_paths = _task_staging_paths(repo, cfg, manifest)
8503
9343
  staged = _stage_exact_paths(repo, task_paths)
8504
9344
  if not staged:
8505
9345
  raise APError("Nothing to commit.")
@@ -8509,8 +9349,12 @@ def _cmd_commit_push_locked(
8509
9349
  "Task-owned files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged)
8510
9350
  )
8511
9351
  manifest = _require_task_context(repo, cfg, args.task_id)
9352
+ _extend_final_gate_receipt(repo, cfg, manifest, plan, base_ref)
8512
9353
 
8513
9354
  committed_sha = _commit_exact_index(repo, msg)
9355
+ manifest["state"] = "push-pending"
9356
+ manifest["last_commit"] = committed_sha
9357
+ _save_task_manifest(repo, manifest)
8514
9358
  _push_current_task(repo, manifest, committed_sha)
8515
9359
  print(f"[commit-push] OK - profile={plan['profile']} mode={mode} scope={plan['selected_scope']}")
8516
9360
 
@@ -8525,6 +9369,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
8525
9369
  lock_name = f"task-{_validate_task_id(args.task_id)}"
8526
9370
  timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
8527
9371
  with _repo_lock(repo, lock_name, timeout_s=timeout_s):
9372
+ manifest = _require_task_context(repo, cfg, args.task_id)
9373
+ _require_current_writer(manifest, args)
8528
9374
  _cmd_commit_push_locked(args, repo, cfg, manifest)
8529
9375
 
8530
9376
 
@@ -8552,6 +9398,11 @@ def main(argv: Optional[List[str]] = None) -> int:
8552
9398
  s.add_argument("--json", action="store_true")
8553
9399
  s.set_defaults(func=cmd_upgrade)
8554
9400
 
9401
+ s = sp.add_parser("project-converge", help=argparse.SUPPRESS)
9402
+ s.add_argument("--write", action="store_true")
9403
+ s.add_argument("--json", action="store_true")
9404
+ s.set_defaults(func=cmd_project_converge)
9405
+
8555
9406
  s = sp.add_parser("baseline")
8556
9407
  baseline_sp = s.add_subparsers(dest="baseline_cmd", required=True)
8557
9408
  b = baseline_sp.add_parser("init")
@@ -8728,6 +9579,16 @@ def main(argv: Optional[List[str]] = None) -> int:
8728
9579
  s.add_argument("--json", action="store_true")
8729
9580
  s.set_defaults(func=cmd_task_status)
8730
9581
 
9582
+ s = sp.add_parser("task-scope-add")
9583
+ s.add_argument("task_id")
9584
+ s.add_argument("--owned-path", action="append", required=True)
9585
+ s.add_argument("--writer")
9586
+ s.add_argument("--lease-generation", type=int)
9587
+ s.add_argument("--intent")
9588
+ s.add_argument("--review-required", action="store_true")
9589
+ s.add_argument("--json", action="store_true")
9590
+ s.set_defaults(func=cmd_task_scope_add)
9591
+
8731
9592
  s = sp.add_parser("task-submodule-sync")
8732
9593
  s.add_argument("task_id")
8733
9594
  s.set_defaults(func=cmd_task_submodule_sync)