@elvis1513/auto-coding-skill 3.0.0 → 3.0.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.
@@ -34,7 +34,7 @@ from scaffold_templates import scaffold_groups, templates_for
34
34
 
35
35
 
36
36
  _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
37
- _INVALID_PLACEHOLDERS = {"N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME", "PLACEHOLDER", "XXX"}
37
+ _INVALID_PLACEHOLDERS = {"N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME", "PLACEHOLDER", "XXX", "NULL", "~"}
38
38
  _GENERATED_NOISE_PATTERNS = [
39
39
  ".local/auto-coding-skill/**",
40
40
  "__pycache__/**",
@@ -44,6 +44,8 @@ _GENERATED_NOISE_PATTERNS = [
44
44
  ".DS_Store",
45
45
  "**/.DS_Store",
46
46
  ]
47
+ _AGENT_CONTRACT_VERSION = 1
48
+ _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
47
49
  _DEFAULT_DISPOSABLE_IGNORED_PATTERNS = [
48
50
  ".local/auto-coding-skill",
49
51
  ".local/auto-coding-skill/**",
@@ -139,11 +141,7 @@ def _evidence_log_path(repo: Path, cfg: dict) -> Path:
139
141
  docs_cfg = cfg.get("docs") or {}
140
142
  task_dir = _text(docs_cfg.get("task_evidence_dir")) or "docs/tasks/evidence"
141
143
  return Path(repo, task_dir, f"{manifest['task_id']}.jsonl")
142
- if _task_isolation(cfg) == "worktree":
143
- return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
144
- docs_cfg = cfg.get("docs") or {}
145
- rel = _text(docs_cfg.get("evidence_log")) or "docs/tasks/evidence.jsonl"
146
- return Path(repo, rel)
144
+ return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
147
145
 
148
146
 
149
147
  def _gate_profile_path(repo: Path, cfg: dict) -> Path:
@@ -563,21 +561,9 @@ def _inferred_gate_commands(repo: Path) -> dict[str, str]:
563
561
  scripts = payload.get("scripts") or {}
564
562
  if not isinstance(scripts, dict):
565
563
  return {}
566
- inferred: dict[str, str] = {}
567
- if isinstance(scripts.get("test"), str) and scripts["test"].strip():
568
- inferred["gate_changed"] = (
569
- "npm run test:changed"
570
- if isinstance(scripts.get("test:changed"), str) and scripts["test:changed"].strip()
571
- else "npm test"
572
- )
573
- inferred["gate_standard"] = (
574
- "npm run test:standard"
575
- if isinstance(scripts.get("test:standard"), str) and scripts["test:standard"].strip()
576
- else "npm test"
577
- )
578
- if isinstance(scripts.get("test:full"), str) and scripts["test:full"].strip():
579
- inferred["gate_full"] = "npm run test:full"
580
- return inferred
564
+ if isinstance(scripts.get("test:changed"), str) and scripts["test:changed"].strip():
565
+ return {"gate_changed": "npm run test:changed"}
566
+ return {}
581
567
 
582
568
 
583
569
  def _initialize_engineering_defaults(path: Path, repo: Path) -> None:
@@ -590,15 +576,67 @@ def _initialize_engineering_defaults(path: Path, repo: Path) -> None:
590
576
  1,
591
577
  )
592
578
  for key, gate_command in _inferred_gate_commands(repo).items():
593
- updated = updated.replace(
594
- f' {key}: ""',
595
- f" {key}: {json.dumps(gate_command)}",
596
- 1,
597
- )
579
+ for default_value in ['""', '"git diff --check"']:
580
+ candidate = updated.replace(
581
+ f" {key}: {default_value}",
582
+ f" {key}: {json.dumps(gate_command)}",
583
+ 1,
584
+ )
585
+ if candidate != updated:
586
+ updated = candidate
587
+ break
598
588
  if updated != text:
599
589
  path.write_text(updated, encoding="utf-8")
600
590
 
601
591
 
592
+ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
593
+ changed: list[str] = []
594
+
595
+ workflow_cfg = cfg.setdefault("workflow", {})
596
+ if not isinstance(workflow_cfg, dict):
597
+ workflow_cfg = {}
598
+ cfg["workflow"] = workflow_cfg
599
+ if _text(workflow_cfg.get("mode")).lower() != "dev":
600
+ workflow_cfg["mode"] = "dev"
601
+ changed.append("workflow.mode")
602
+ if _text(workflow_cfg.get("completion")).lower() != "push":
603
+ workflow_cfg["completion"] = "push"
604
+ changed.append("workflow.completion")
605
+
606
+ commands_cfg = cfg.setdefault("commands", {})
607
+ if not isinstance(commands_cfg, dict):
608
+ commands_cfg = {}
609
+ cfg["commands"] = commands_cfg
610
+ current_changed_gate = _text(commands_cfg.get("gate_changed"))
611
+ if current_changed_gate in {"", "npm test"}:
612
+ replacement = _inferred_gate_commands(repo).get("gate_changed", "git diff --check")
613
+ if current_changed_gate != replacement:
614
+ commands_cfg["gate_changed"] = replacement
615
+ changed.append("commands.gate_changed")
616
+
617
+ gate_cfg = cfg.setdefault("gate", {})
618
+ if not isinstance(gate_cfg, dict):
619
+ gate_cfg = {}
620
+ cfg["gate"] = gate_cfg
621
+ for key in ["default_scope", "fallback_scope", "no_change_scope"]:
622
+ if _text(gate_cfg.get(key)).lower() != "changed":
623
+ gate_cfg[key] = "changed"
624
+ changed.append(f"gate.{key}")
625
+ if _bool_config(gate_cfg.get("full_on_unknown"), False):
626
+ gate_cfg["full_on_unknown"] = False
627
+ changed.append("gate.full_on_unknown")
628
+
629
+ concurrency_cfg = cfg.setdefault("concurrency", {})
630
+ if not isinstance(concurrency_cfg, dict):
631
+ concurrency_cfg = {}
632
+ cfg["concurrency"] = concurrency_cfg
633
+ if _text(concurrency_cfg.get("isolation")).lower() != "worktree":
634
+ concurrency_cfg["isolation"] = "worktree"
635
+ changed.append("concurrency.isolation")
636
+
637
+ return changed
638
+
639
+
602
640
  def cmd_scaffold(args: argparse.Namespace) -> None:
603
641
  repo = Path(args.repo).resolve()
604
642
  group = str(args.group or "").strip().lower()
@@ -671,8 +709,8 @@ def cmd_install(args: argparse.Namespace) -> None:
671
709
  layout = "full" if args.full else "minimal"
672
710
  print(f"[install] OK: {layout} scaffold installed into {repo}")
673
711
  print(
674
- "[install] Next: edit docs/ENGINEERING.md frontmatter, set verification.*_required, "
675
- "fill only enabled environment fields, and commit that file into Git."
712
+ "[install] Next: fill every access.* URL, username, and password in "
713
+ "docs/ENGINEERING.md, run doctor, and commit that file into Git."
676
714
  )
677
715
 
678
716
 
@@ -765,8 +803,14 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
765
803
  template_cfg, _ = _read_frontmatter_markdown(template_engineering)
766
804
  merged_cfg = json.loads(json.dumps(current_cfg))
767
805
  added_keys = _deep_merge_missing(merged_cfg, template_cfg)
768
- if added_keys:
769
- add_action("config", engineering, "merge", ", ".join(added_keys))
806
+ migrated_keys = _migrate_fast_development_defaults(merged_cfg, repo)
807
+ if added_keys or migrated_keys:
808
+ detail_parts = []
809
+ if added_keys:
810
+ detail_parts.append("add " + ", ".join(added_keys))
811
+ if migrated_keys:
812
+ detail_parts.append("migrate " + ", ".join(migrated_keys))
813
+ add_action("config", engineering, "merge", "; ".join(detail_parts))
770
814
  if write:
771
815
  _write_frontmatter_markdown(engineering, merged_cfg, body)
772
816
  else:
@@ -852,9 +896,9 @@ def cmd_gen_summary(args: argparse.Namespace) -> None:
852
896
 
853
897
  ---
854
898
 
855
- ## 1. 目标与验收结论
899
+ ## 1. 目标与开发闭环
856
900
  - 目标:TODO
857
- - 验收结论:PASS / FAIL — TODO
901
+ - 开发结论:DEV-CLOSED / BLOCKED — TODO
858
902
 
859
903
  ## 2. 变更概览
860
904
  ### Git change snapshot
@@ -871,14 +915,13 @@ def cmd_gen_summary(args: argparse.Namespace) -> None:
871
915
  - 变更记录位置:`{api_change_log}`
872
916
 
873
917
  ## 4. 质量证据
874
- - 本地轻量校验:light_gate or quick_test/test/build / api docs / CI/Jenkins / diff-check — TODO
875
- - 结构检查:structure-check — TODO
918
+ - 本地快速门禁:changed gate + diff-check — TODO
919
+ - 项目 Git hooks:commit/push 时执行
876
920
  - 结构化证据:docs/tasks/evidence.jsonl — TODO
877
921
  - 门禁画像:.local/auto-coding-skill/gate-profile.jsonl — TODO
878
- - CI/Jenkins Build:TODO
879
- - 目标环境验证:TODO
880
- - 闭环记录:TODO
881
- - 回归矩阵(如有):`{regression_matrix}`
922
+ - 目标分支推送:TODO
923
+ - Jenkins / 构建 / 部署 / 实际验收:项目负责人推送后处理
924
+ - 可选诊断(如明确要求):`{regression_matrix}`
882
925
 
883
926
  ## 5. 风险与回滚
884
927
  - 风险:TODO
@@ -1067,8 +1110,8 @@ def _workflow_mode(cfg: dict, args: Optional[argparse.Namespace] = None) -> str:
1067
1110
  explicit = str(getattr(args, "mode", "") or "").strip().lower() if args else ""
1068
1111
  configured = str(((cfg.get("workflow") or {}).get("mode")) or "dev").strip().lower()
1069
1112
  mode = explicit or configured or "dev"
1070
- if mode not in {"dev", "verify"}:
1071
- raise APError("workflow.mode must be 'dev' or 'verify'.")
1113
+ if mode != "dev":
1114
+ raise APError("workflow.mode must be 'dev'; external verification is owner-managed after push.")
1072
1115
  return mode
1073
1116
 
1074
1117
 
@@ -1086,8 +1129,10 @@ def _concurrency_cfg(cfg: dict) -> dict:
1086
1129
 
1087
1130
  def _task_isolation(cfg: dict) -> str:
1088
1131
  isolation = _text(_concurrency_cfg(cfg).get("isolation")).lower() or "worktree"
1089
- if isolation not in {"worktree", "legacy"}:
1090
- raise APError("concurrency.isolation must be worktree or legacy")
1132
+ if isolation != "worktree":
1133
+ raise APError(
1134
+ "concurrency.isolation must be worktree; shared-checkout/legacy writes are no longer supported"
1135
+ )
1091
1136
  return isolation
1092
1137
 
1093
1138
 
@@ -1180,6 +1225,16 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1180
1225
  raise APError(
1181
1226
  f"Task registry identity mismatch: expected={expected_task_id}, manifest={task_id}"
1182
1227
  )
1228
+ try:
1229
+ schema = int(manifest.get("schema") or 1)
1230
+ except (TypeError, ValueError) as exc:
1231
+ raise APError(f"Task {task_id} has an invalid manifest schema.") from exc
1232
+ if schema < 2:
1233
+ raise APError(
1234
+ f"Task {task_id} is a legacy schema-1 task. This runtime cannot safely infer or claim "
1235
+ "owned_paths for an in-flight task. Finish or clean it with the previously installed "
1236
+ "runtime before running autocoding sync, or restore the 3.0.0 runtime."
1237
+ )
1183
1238
  task_uuid = _text(manifest.get("task_uuid"))
1184
1239
  if not re.fullmatch(r"[0-9a-f]{32}", task_uuid):
1185
1240
  raise APError(f"Invalid task manifest UUID for {task_id}; refusing Git operations.")
@@ -1215,6 +1270,33 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1215
1270
  raise APError(
1216
1271
  f"Task worktree must be outside its control checkout for {task_id}: {worktree}"
1217
1272
  )
1273
+ owned_paths = manifest.get("owned_paths")
1274
+ if not isinstance(owned_paths, list) or not owned_paths or not all(
1275
+ isinstance(item, str) and item for item in owned_paths
1276
+ ):
1277
+ raise APError(f"Task {task_id} has no valid owned_paths; refusing lifecycle operations.")
1278
+ depends_on = manifest.get("depends_on")
1279
+ prerequisite_shas = manifest.get("prerequisite_shas")
1280
+ if not isinstance(depends_on, list) or not isinstance(prerequisite_shas, dict):
1281
+ raise APError(f"Task {task_id} has an invalid dependency contract.")
1282
+ if set(depends_on) != set(prerequisite_shas):
1283
+ raise APError(f"Task {task_id} dependency IDs and prerequisite SHAs do not match.")
1284
+ for dependency, sha in prerequisite_shas.items():
1285
+ _validate_task_id(str(dependency))
1286
+ if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", _text(sha)):
1287
+ raise APError(f"Task {task_id} has an invalid prerequisite SHA for {dependency}.")
1288
+ lease = manifest.get("writer_lease")
1289
+ if not isinstance(lease, dict) or not _text(lease.get("holder")):
1290
+ raise APError(f"Task {task_id} has an invalid writer lease.")
1291
+ if int(lease.get("generation") or 0) < 1 or _text(lease.get("state")) != "active":
1292
+ raise APError(f"Task {task_id} writer lease is not active.")
1293
+ review = manifest.get("review")
1294
+ if not isinstance(review, dict) or _text(review.get("verdict")) not in {
1295
+ "pending",
1296
+ "approved",
1297
+ "changes-requested",
1298
+ }:
1299
+ raise APError(f"Task {task_id} has an invalid review contract.")
1218
1300
  return manifest
1219
1301
 
1220
1302
 
@@ -1415,6 +1497,167 @@ def _task_commit_paths(repo: Path) -> list[str]:
1415
1497
  return [path for path in _working_tree_paths(repo) if not _is_generated_noise_path(path)]
1416
1498
 
1417
1499
 
1500
+ def _normalize_owned_path(value: object) -> str:
1501
+ raw = _text(value).replace("\\", "/")
1502
+ while raw.startswith("./"):
1503
+ raw = raw[2:]
1504
+ normalized = posixpath.normpath(raw)
1505
+ if (
1506
+ not raw
1507
+ or raw.startswith("/")
1508
+ or normalized == ".."
1509
+ or normalized.startswith("../")
1510
+ or normalized == ".git"
1511
+ or normalized.startswith(".git/")
1512
+ ):
1513
+ raise APError(f"Owned paths must be safe repository-relative paths: {value!r}")
1514
+ return normalized
1515
+
1516
+
1517
+ def _path_is_owned(path: str, owned_paths: list[str]) -> bool:
1518
+ normalized = _normalize_owned_path(path)
1519
+ return any(
1520
+ owner == "." or normalized == owner or normalized.startswith(owner.rstrip("/") + "/")
1521
+ for owner in owned_paths
1522
+ )
1523
+
1524
+
1525
+ def _task_managed_paths(cfg: dict, manifest: dict) -> list[str]:
1526
+ docs_cfg = cfg.get("docs") or {}
1527
+ task_id = _validate_task_id(_text(manifest.get("task_id")))
1528
+ return sorted(
1529
+ {
1530
+ f"{(_text(docs_cfg.get('active_task_dir')) or 'docs/tasks/active').rstrip('/')}/{task_id}.md",
1531
+ f"{(_text(docs_cfg.get('task_closure_dir')) or 'docs/tasks/closures').rstrip('/')}/{task_id}.md",
1532
+ f"{(_text(docs_cfg.get('task_evidence_dir')) or 'docs/tasks/evidence').rstrip('/')}/{task_id}.jsonl",
1533
+ }
1534
+ )
1535
+
1536
+
1537
+ def _task_changed_paths_from_base(repo: Path, base_sha: str) -> list[str]:
1538
+ paths = set(
1539
+ _checked_git_z_paths(
1540
+ repo,
1541
+ ["git", "diff", "--name-only", "-z", "--diff-filter=ACDMRTUXB", base_sha, "--"],
1542
+ "task diff paths",
1543
+ )
1544
+ )
1545
+ paths.update(
1546
+ _checked_git_z_paths(
1547
+ repo,
1548
+ ["git", "ls-files", "--others", "--exclude-standard", "-z"],
1549
+ "task untracked paths",
1550
+ )
1551
+ )
1552
+ return sorted(path.replace("\\", "/") for path in paths if not _is_generated_noise_path(path))
1553
+
1554
+
1555
+ def _task_unowned_paths(repo: Path, cfg: dict, manifest: dict) -> list[str]:
1556
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
1557
+ managed = set(_task_managed_paths(cfg, manifest))
1558
+ return [
1559
+ path
1560
+ for path in _task_changed_paths_from_base(repo, _text(manifest.get("base_sha")))
1561
+ if path not in managed and not _path_is_owned(path, owned)
1562
+ ]
1563
+
1564
+
1565
+ def _task_review_fingerprint(repo: Path, manifest: dict, cfg: Optional[dict] = None) -> str:
1566
+ base_sha = _text(manifest.get("base_sha"))
1567
+ owned = [_normalize_owned_path(item) for item in manifest.get("owned_paths") or []]
1568
+ managed = set(_task_managed_paths(cfg or _load_cfg(repo), manifest))
1569
+ paths = [
1570
+ path
1571
+ for path in _task_changed_paths_from_base(repo, base_sha)
1572
+ if path not in managed and _path_is_owned(path, owned)
1573
+ ]
1574
+ digest = hashlib.sha256()
1575
+ digest.update(f"contract:{_AGENT_CONTRACT_VERSION}\nbase:{base_sha}\n".encode("utf-8"))
1576
+ for rel in paths:
1577
+ digest.update(f"path:{rel}\0".encode("utf-8", errors="surrogateescape"))
1578
+ path = repo / rel
1579
+ try:
1580
+ mode = path.lstat().st_mode
1581
+ except OSError:
1582
+ digest.update(b"missing\0")
1583
+ continue
1584
+ digest.update(f"mode:{mode:o}\0".encode("ascii"))
1585
+ if path.is_symlink():
1586
+ digest.update(os.readlink(path).encode("utf-8", errors="surrogateescape"))
1587
+ elif path.is_file():
1588
+ digest.update(path.read_bytes())
1589
+ else:
1590
+ digest.update(b"non-file")
1591
+ digest.update(b"\0")
1592
+ return digest.hexdigest()
1593
+
1594
+
1595
+ def _invalidate_task_review(manifest: dict, reason: str) -> None:
1596
+ manifest["review"] = {
1597
+ "verdict": "pending",
1598
+ "diff_base": _text(manifest.get("base_sha")),
1599
+ "diff_head": "",
1600
+ "diff_fingerprint": "",
1601
+ "reviewer": "",
1602
+ "reviewed_at": "",
1603
+ "reason": reason,
1604
+ }
1605
+
1606
+
1607
+ def _actor_id(args: argparse.Namespace, field: str = "writer") -> str:
1608
+ explicit = _text(getattr(args, field, ""))
1609
+ runtime_actor = _text(os.environ.get("CODEX_THREAD_ID"))
1610
+ if explicit and runtime_actor and explicit != runtime_actor:
1611
+ raise APError(
1612
+ f"Explicit --{field.replace('_', '-')} does not match CODEX_THREAD_ID; "
1613
+ "actor identity cannot be overridden."
1614
+ )
1615
+ actor = runtime_actor or explicit
1616
+ if not actor:
1617
+ raise APError(f"A stable --{field.replace('_', '-')} or CODEX_THREAD_ID is required.")
1618
+ if any(char in actor for char in "\0\r\n"):
1619
+ raise APError("Actor identity contains invalid characters.")
1620
+ return actor
1621
+
1622
+
1623
+ def _require_current_writer(manifest: dict, args: argparse.Namespace) -> str:
1624
+ actor = _actor_id(args, "writer")
1625
+ lease = manifest.get("writer_lease") or {}
1626
+ if _text(lease.get("state")) != "active" or actor != _text(lease.get("holder")):
1627
+ raise APError(
1628
+ f"Writer lease mismatch: current={actor}, holder={_text(lease.get('holder')) or '(missing)'}."
1629
+ )
1630
+ return actor
1631
+
1632
+
1633
+ def _require_dependencies(repo: Path, manifest: dict, ancestor_ref: str) -> None:
1634
+ for dependency in manifest.get("depends_on") or []:
1635
+ sha = _text((manifest.get("prerequisite_shas") or {}).get(dependency))
1636
+ if run(
1637
+ ["git", "merge-base", "--is-ancestor", sha, ancestor_ref],
1638
+ cwd=repo,
1639
+ check=False,
1640
+ ).returncode != 0:
1641
+ raise APError(
1642
+ f"Prerequisite {dependency} at {sha} is not integrated into {ancestor_ref}."
1643
+ )
1644
+
1645
+
1646
+ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
1647
+ unowned = _task_unowned_paths(repo, cfg, manifest)
1648
+ if unowned:
1649
+ raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
1650
+ fingerprint = _task_review_fingerprint(repo, manifest)
1651
+ review = manifest.get("review") or {}
1652
+ if _text(review.get("verdict")) != "approved":
1653
+ raise APError("Task review must be approved before commit-push or integration.")
1654
+ if _text(review.get("diff_fingerprint")) != fingerprint:
1655
+ raise APError("Approved review fingerprint is stale for the current owned diff.")
1656
+ if _text(review.get("diff_base")) != _text(manifest.get("base_sha")):
1657
+ raise APError("Approved review base is stale for the current task base.")
1658
+ return fingerprint
1659
+
1660
+
1418
1661
  def _unstaged_task_paths(repo: Path) -> list[str]:
1419
1662
  paths = set(
1420
1663
  _checked_git_z_paths(
@@ -1433,16 +1676,15 @@ def _unstaged_task_paths(repo: Path) -> list[str]:
1433
1676
  return sorted(path for path in paths if not _is_generated_noise_path(path))
1434
1677
 
1435
1678
 
1436
- def _require_task_context(repo: Path, cfg: dict, task_id: str) -> Optional[dict]:
1679
+ def _require_task_context(repo: Path, cfg: dict, task_id: str) -> dict:
1680
+ _task_isolation(cfg)
1437
1681
  manifest = _active_task_manifest(repo)
1438
1682
  if not manifest:
1439
1683
  if _git_dir(repo) != _git_common_dir(repo):
1440
1684
  raise APError(
1441
- "This linked worktree has no registered task manifest. Refusing legacy fallback; "
1685
+ "This linked worktree has no registered task manifest. "
1442
1686
  "return to the primary checkout and create or recover the task with task-start."
1443
1687
  )
1444
- if _task_isolation(cfg) == "legacy":
1445
- return None
1446
1688
  raise APError(
1447
1689
  "This project requires an isolated task worktree. "
1448
1690
  f"Run `python3 docs/tools/autopipeline/ap.py task-start {task_id}` from the main checkout, "
@@ -1559,6 +1801,48 @@ def _require_explicit_field(missing: List[str], field: str, value: object) -> No
1559
1801
  missing.append(f"{field} (must be explicitly filled, not blank/TODO)")
1560
1802
 
1561
1803
 
1804
+ _REQUIRED_ACCESS_FIELDS = [
1805
+ "access.project.frontend.url",
1806
+ "access.project.frontend.username",
1807
+ "access.project.frontend.password",
1808
+ "access.project.backend.url",
1809
+ "access.project.backend.username",
1810
+ "access.project.backend.password",
1811
+ "access.jenkins.frontend.url",
1812
+ "access.jenkins.frontend.username",
1813
+ "access.jenkins.frontend.password",
1814
+ "access.jenkins.backend.url",
1815
+ "access.jenkins.backend.username",
1816
+ "access.jenkins.backend.password",
1817
+ "access.gitlab.url",
1818
+ "access.gitlab.username",
1819
+ "access.gitlab.password",
1820
+ "access.nexus.frontend.url",
1821
+ "access.nexus.frontend.username",
1822
+ "access.nexus.frontend.password",
1823
+ ]
1824
+
1825
+
1826
+ def _nested_config_value(cfg: dict, field: str) -> object:
1827
+ value: object = cfg
1828
+ for part in field.split("."):
1829
+ if not isinstance(value, dict):
1830
+ return None
1831
+ value = value.get(part)
1832
+ return value
1833
+
1834
+
1835
+ def _access_config_issues(cfg: dict) -> list[str]:
1836
+ issues: list[str] = []
1837
+ for field in _REQUIRED_ACCESS_FIELDS:
1838
+ value = _nested_config_value(cfg, field)
1839
+ if not isinstance(value, str) or not _is_explicit_fill(value):
1840
+ issues.append(f"{field} (must be an explicitly filled string, not blank/TODO)")
1841
+ for field in [name for name in _REQUIRED_ACCESS_FIELDS if name.endswith(".url")]:
1842
+ _validate_url_field(issues, field, _nested_config_value(cfg, field))
1843
+ return issues
1844
+
1845
+
1562
1846
  def _has_secret_reference(section_cfg: dict, field: str) -> bool:
1563
1847
  return _is_explicit_fill(section_cfg.get(field)) or _is_explicit_fill(section_cfg.get(f"{field}_env"))
1564
1848
 
@@ -1596,7 +1880,7 @@ def _resolve_secret(section_name: str, section_cfg: dict, field: str) -> str:
1596
1880
 
1597
1881
  _GATE_SCOPES = {"auto", "changed", "standard", "full"}
1598
1882
  _WORKFLOW_PROFILES = {"auto", "micro", "standard", "high-risk"}
1599
- _PROFILE_GATE_SCOPE = {"micro": "changed", "standard": "standard", "high-risk": "full"}
1883
+ _PROFILE_GATE_SCOPE = {"micro": "changed", "standard": "changed", "high-risk": "changed"}
1600
1884
  _PROFILE_RANK = {"micro": 0, "standard": 1, "high-risk": 2}
1601
1885
  _SCOPE_RANK = {"changed": 0, "standard": 1, "full": 2}
1602
1886
  _DOC_PATH_PATTERNS = ["*.md", "docs/**"]
@@ -1831,44 +2115,16 @@ def _has_changed_gate(cfg: dict, gate_cfg: dict, paths: list[str]) -> bool:
1831
2115
 
1832
2116
  def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tuple[str, list[str], list[dict]]:
1833
2117
  gate_cfg = _gate_cfg(cfg)
1834
- scope = (requested_scope or _text(gate_cfg.get("default_scope")) or "standard").lower()
2118
+ scope = (requested_scope or _text(gate_cfg.get("default_scope")) or "changed").lower()
1835
2119
  if scope not in _GATE_SCOPES:
1836
2120
  raise APError("gate scope must be one of: " + ", ".join(sorted(_GATE_SCOPES)))
1837
2121
 
1838
2122
  matching_rules = _matching_gate_rules(paths, gate_cfg)
1839
- reasons: list[str] = []
1840
-
1841
- rule_scopes = {_text(rule.get("scope")).lower() for rule in matching_rules if _text(rule.get("scope"))}
1842
- if "full" in rule_scopes:
1843
- return "full", ["matched gate rule with scope=full"], matching_rules
1844
- if any(_path_matches(path, _gate_full_patterns(gate_cfg)) for path in paths):
1845
- return "full", ["changed files match full-gate patterns"], matching_rules
1846
-
1847
- if scope != "auto":
1848
- return scope, [f"requested scope: {scope}"], matching_rules
1849
-
1850
- if not paths:
1851
- fallback = _text(gate_cfg.get("no_change_scope")) or "standard"
1852
- if fallback not in {"changed", "standard", "full"}:
1853
- fallback = "standard"
1854
- return fallback, ["no changed files detected"], matching_rules
1855
-
1856
- if "standard" in rule_scopes:
1857
- return "standard", ["matched gate rule with scope=standard"], matching_rules
1858
-
1859
- if _docs_only(paths):
1860
- return "changed", ["docs-only change"], matching_rules
1861
-
1862
- if _has_changed_gate(cfg, gate_cfg, paths):
1863
- return "changed", ["matched changed-gate command or rule"], matching_rules
1864
-
1865
- fallback = _text(gate_cfg.get("fallback_scope")) or "standard"
1866
- if fallback not in {"changed", "standard", "full"}:
1867
- fallback = "standard"
1868
- if fallback == "changed" and _text(gate_cfg.get("full_on_unknown")).lower() in {"1", "true", "yes", "on"}:
1869
- fallback = "full"
1870
- reasons.append("no changed-gate command/rule matched")
1871
- return fallback, reasons, matching_rules
2123
+ requested = "auto" if scope == "auto" else scope
2124
+ reason = "local development gate is fixed to changed/quick scope"
2125
+ if requested not in {"auto", "changed"}:
2126
+ reason += f"; ignored requested scope={requested}"
2127
+ return "changed", [reason], matching_rules
1872
2128
 
1873
2129
 
1874
2130
  def _impact_summary(
@@ -1922,12 +2178,13 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
1922
2178
  print("[impact] changed: (none)")
1923
2179
 
1924
2180
 
1925
- def _run_changed_gate(repo: Path, cfg: dict, paths: list[str], matching_rules: list[dict]) -> list[str]:
1926
- executed: list[str] = []
1927
- for rule in matching_rules:
1928
- executed.extend(_run_configured_command_list(repo, cfg, _as_list(rule.get("commands"))))
1929
- if executed:
1930
- return executed
2181
+ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2182
+ # The generic scaffold uses this command as its whole fast gate. The
2183
+ # built-in diff check below covers working tree, index, and task commits, so
2184
+ # do not execute the narrower configured spelling first as a duplicate.
2185
+ if _configured_command(cfg, "gate_changed").strip() == "git diff --check":
2186
+ print("[gate] gate_changed is handled by the built-in diff check")
2187
+ return []
1931
2188
 
1932
2189
  fallback_commands = ["gate_changed"]
1933
2190
  if _docs_only(paths):
@@ -1940,13 +2197,13 @@ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str], matching_rules: l
1940
2197
  print("[gate] docs-only change with no changed-gate command configured; running built-in post checks only.")
1941
2198
  return ["docs_only_builtin"]
1942
2199
 
1943
- fallback = _run_first_configured_command(repo, cfg, ["quick_test", "test", "build"])
2200
+ fallback = _run_first_configured_command(repo, cfg, ["quick_test"])
1944
2201
  if fallback:
1945
2202
  return [fallback]
1946
2203
 
1947
2204
  raise APError(
1948
- "Changed gate has no configured command. Add commands.gate_changed or matching gate.rules commands, "
1949
- "or run light-gate --scope standard/full."
2205
+ "Changed gate has no fast command. Add commands.gate_changed or commands.quick_test. "
2206
+ "gate.rules commands are never executed by the automatic development flow."
1950
2207
  )
1951
2208
 
1952
2209
 
@@ -1964,8 +2221,8 @@ def _run_full_gate(repo: Path, cfg: dict) -> list[str]:
1964
2221
  command = _run_first_configured_command(repo, cfg, ["gate_full", "full_gate"])
1965
2222
  if not command:
1966
2223
  raise APError(
1967
- "Full gate is under-configured. High-risk and verify work requires "
1968
- "commands.gate_full or commands.full_gate; light/standard fallbacks do not count."
2224
+ "Optional full diagnostic is under-configured. Add commands.gate_full or "
2225
+ "commands.full_gate when you explicitly want to run it."
1969
2226
  )
1970
2227
  return [command]
1971
2228
 
@@ -3365,13 +3622,17 @@ def _classify_paths(paths: list[str]) -> dict:
3365
3622
  categories.add("docs")
3366
3623
  if any(token in lower for token in ["domain", "service", "usecase", "repository", "infrastructure", "adapter", "shared", "utils"]):
3367
3624
  categories.add("structure")
3625
+ return _classification_for_categories(categories, len(paths))
3626
+
3627
+
3628
+ def _classification_for_categories(categories: set[str], file_count: int) -> dict:
3368
3629
  return {
3369
3630
  "categories": sorted(categories),
3370
3631
  "needs_dd": bool(
3371
3632
  categories
3372
3633
  & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config", "release_or_tooling"}
3373
3634
  )
3374
- or len(paths) > 12,
3635
+ or file_count > 12,
3375
3636
  "needs_adr": bool(categories & {"structure", "release_or_tooling"}) and not categories <= {"docs"},
3376
3637
  "needs_browser": "ui" in categories,
3377
3638
  "needs_jenkins": bool(
@@ -3383,6 +3644,29 @@ def _classify_paths(paths: list[str]) -> dict:
3383
3644
  }
3384
3645
 
3385
3646
 
3647
+ def _classify_intent(intent: str) -> list[str]:
3648
+ value = _text(intent).lower()
3649
+ keyword_categories = {
3650
+ "db": ["database", "migration", "schema", "sql", "数据库", "数据迁移", "表结构"],
3651
+ "api": ["api", "controller", "endpoint", "接口", "控制器"],
3652
+ "auth": ["auth", "permission", "security", "登录", "认证", "鉴权", "权限", "安全"],
3653
+ "payment": ["payment", "billing", "checkout", "支付", "账单", "结算"],
3654
+ "file_transfer": ["upload", "download", "上传", "下载", "附件"],
3655
+ "gateway": ["gateway", "ingress", "nginx", "网关", "反向代理"],
3656
+ "prod_config": ["production config", "prod config", "生产配置"],
3657
+ "release_or_tooling": ["release", "deploy", "jenkins", "nexus", "发布", "部署", "构建"],
3658
+ "ui": ["frontend", "page", "component", "ui", "前端", "页面", "组件", "界面"],
3659
+ "test": ["test", "spec", "测试"],
3660
+ "docs": ["documentation", "docs", "文档"],
3661
+ "structure": ["refactor", "architecture", "重构", "架构", "分层"],
3662
+ }
3663
+ return sorted(
3664
+ category
3665
+ for category, keywords in keyword_categories.items()
3666
+ if any(keyword in value for keyword in keywords)
3667
+ )
3668
+
3669
+
3386
3670
  def _normalize_workflow_profile(value: object, default: str = "auto") -> str:
3387
3671
  profile = _text(value).lower() or default
3388
3672
  if profile not in _WORKFLOW_PROFILES:
@@ -3395,17 +3679,197 @@ def _configured_workflow_profile(cfg: dict) -> str:
3395
3679
 
3396
3680
 
3397
3681
  def _recommended_agents(profile: str, categories: set[str], classification: dict) -> list[str]:
3682
+ roles: list[str] = []
3683
+ for stage in _agent_execution_plan(profile, categories, classification)["stages"]:
3684
+ for role in stage["roles"]:
3685
+ if role != "main" and role not in roles:
3686
+ roles.append(role)
3687
+ return roles
3688
+
3689
+
3690
+ def _agent_contract_shape() -> tuple[dict, list[str]]:
3691
+ return (
3692
+ {
3693
+ "common": [
3694
+ "contract_version",
3695
+ "node_id",
3696
+ "task_id",
3697
+ "role",
3698
+ "base_sha",
3699
+ "scope",
3700
+ "depends_on",
3701
+ "acceptance",
3702
+ ],
3703
+ "writer": ["task_branch", "worktree_path", "owned_paths"],
3704
+ "reviewer": [
3705
+ "task_id",
3706
+ "diff_base",
3707
+ "diff_head",
3708
+ "diff_fingerprint",
3709
+ "owning_fixer",
3710
+ ],
3711
+ },
3712
+ [
3713
+ "contract_version",
3714
+ "node_id",
3715
+ "role",
3716
+ "task_id",
3717
+ "base_sha",
3718
+ "status",
3719
+ "summary",
3720
+ "depends_on",
3721
+ "owned_paths",
3722
+ "changed_paths",
3723
+ "diff_fingerprint",
3724
+ "evidence",
3725
+ "findings",
3726
+ "verdict",
3727
+ "risks",
3728
+ "next_owner",
3729
+ ],
3730
+ )
3731
+
3732
+
3733
+ def _validate_agent_plan(plan: dict) -> dict:
3734
+ required = {
3735
+ "contract_version",
3736
+ "contract_schema",
3737
+ "strategy",
3738
+ "policies",
3739
+ "assignment_contract",
3740
+ "result_contract",
3741
+ "stages",
3742
+ "constraints",
3743
+ }
3744
+ missing = sorted(required - set(plan))
3745
+ if missing or plan.get("contract_version") != _AGENT_CONTRACT_VERSION:
3746
+ raise APError("Invalid agent plan contract: " + (", ".join(missing) or "version"))
3747
+ if plan.get("contract_schema") != _AGENT_CONTRACT_SCHEMA:
3748
+ raise APError("Invalid agent plan schema path.")
3749
+ if not all(
3750
+ isinstance(stage, dict)
3751
+ and {"id", "mode", "roles", "depends_on"} <= set(stage)
3752
+ for stage in plan.get("stages") or []
3753
+ ):
3754
+ raise APError("Invalid agent plan stage contract.")
3755
+ return plan
3756
+
3757
+
3758
+ def _agent_execution_plan(profile: str, categories: set[str], classification: dict) -> dict:
3759
+ assignment_contract, result_contract = _agent_contract_shape()
3398
3760
  if profile == "micro":
3399
- return []
3400
- roles = ["explorer"]
3761
+ return _validate_agent_plan({
3762
+ "contract_version": _AGENT_CONTRACT_VERSION,
3763
+ "contract_schema": _AGENT_CONTRACT_SCHEMA,
3764
+ "strategy": "main-only",
3765
+ "policies": {
3766
+ "one_writer_per_worktree": True,
3767
+ "path_ownership": "explicit-non-overlapping",
3768
+ "dependency_policy": "integrate-before-dependent-start",
3769
+ "review_feedback_owner": "main",
3770
+ "review_binding": "diff-fingerprint",
3771
+ "lifecycle_owner": "main",
3772
+ "gate_owner": "main",
3773
+ },
3774
+ "assignment_contract": assignment_contract,
3775
+ "result_contract": result_contract,
3776
+ "stages": [
3777
+ {
3778
+ "id": "delivery",
3779
+ "mode": "serial",
3780
+ "roles": ["main"],
3781
+ "depends_on": [],
3782
+ }
3783
+ ],
3784
+ "constraints": [
3785
+ "Do not create subagents when the task has no independent work worth delegating.",
3786
+ "The main agent owns the fast gate, Git integration, push, and cleanup.",
3787
+ ],
3788
+ })
3789
+
3790
+ discovery_roles = ["explorer"]
3401
3791
  if categories & {"api", "release_or_tooling"}:
3402
- roles.append("docs_researcher")
3403
- roles.append("fixer")
3792
+ discovery_roles.append("docs_researcher")
3404
3793
  if classification.get("needs_browser"):
3405
- roles.append("browser_debugger")
3406
- if profile == "high-risk":
3407
- roles.append("reviewer")
3408
- return roles
3794
+ discovery_roles.append("browser_debugger")
3795
+
3796
+ return _validate_agent_plan({
3797
+ "contract_version": _AGENT_CONTRACT_VERSION,
3798
+ "contract_schema": _AGENT_CONTRACT_SCHEMA,
3799
+ "strategy": "orchestrated-subagents",
3800
+ "policies": {
3801
+ "one_writer_per_worktree": True,
3802
+ "path_ownership": "explicit-non-overlapping",
3803
+ "dependency_policy": "integrate-before-dependent-start",
3804
+ "review_feedback_owner": "owning-fixer",
3805
+ "review_binding": "diff-fingerprint",
3806
+ "lifecycle_owner": "main",
3807
+ "gate_owner": "main",
3808
+ },
3809
+ "assignment_contract": assignment_contract,
3810
+ "result_contract": result_contract,
3811
+ "stages": [
3812
+ {
3813
+ "id": "decomposition",
3814
+ "mode": "serial",
3815
+ "roles": ["main"],
3816
+ "depends_on": [],
3817
+ },
3818
+ {
3819
+ "id": "discovery",
3820
+ "mode": "parallel",
3821
+ "roles": discovery_roles,
3822
+ "depends_on": ["decomposition"],
3823
+ },
3824
+ {
3825
+ "id": "design",
3826
+ "mode": "serial",
3827
+ "roles": ["main"],
3828
+ "depends_on": ["discovery"],
3829
+ },
3830
+ {
3831
+ "id": "delivery",
3832
+ "mode": "dependency-waves",
3833
+ "roles": ["fixer", "reviewer", "main"],
3834
+ "depends_on": ["design"],
3835
+ "scale": "one fixer per independent development unit in the current dependency layer",
3836
+ "wave_phases": [
3837
+ {
3838
+ "id": "implementation",
3839
+ "mode": "parallel-isolated",
3840
+ "roles": ["fixer"],
3841
+ },
3842
+ {
3843
+ "id": "review",
3844
+ "mode": "parallel-read-only",
3845
+ "roles": ["reviewer"],
3846
+ "feedback_to": "owning fixer",
3847
+ },
3848
+ {
3849
+ "id": "gate-integrate",
3850
+ "mode": "serial",
3851
+ "roles": ["main"],
3852
+ },
3853
+ ],
3854
+ "next_wave": "start only after every prerequisite in the next layer is integrated",
3855
+ },
3856
+ {
3857
+ "id": "closure",
3858
+ "mode": "serial",
3859
+ "roles": ["main"],
3860
+ "depends_on": ["delivery"],
3861
+ },
3862
+ ],
3863
+ "constraints": [
3864
+ "Delegate only independent bounded work and declare dependencies before dispatch.",
3865
+ "Every fixer owns exactly one registered task branch/worktree and an explicit path scope.",
3866
+ "Never run two writers in one worktree or let the main agent edit a fixer-owned worktree concurrently.",
3867
+ "Start a dependent write task only after its prerequisite has been integrated into the target branch.",
3868
+ "Subagents do not commit, push, integrate, or clean task branches.",
3869
+ "Reviewers inspect a stable diff; changes-requested returns to the owning fixer and any edit requires re-review.",
3870
+ "The main agent routes review feedback, runs the single fast gate for each write task, integrates in dependency order, pushes, and cleans branches.",
3871
+ ],
3872
+ })
3409
3873
 
3410
3874
 
3411
3875
  def _resolve_execution_plan(
@@ -3417,6 +3881,8 @@ def _resolve_execution_plan(
3417
3881
  requested_mode: str = "",
3418
3882
  base_ref: str = "",
3419
3883
  changed_paths: Optional[list[str]] = None,
3884
+ planned_paths: Optional[list[str]] = None,
3885
+ intent: str = "",
3420
3886
  ) -> dict:
3421
3887
  impact = _impact_summary(
3422
3888
  cfg,
@@ -3426,21 +3892,29 @@ def _resolve_execution_plan(
3426
3892
  changed_paths=changed_paths,
3427
3893
  )
3428
3894
  paths = list(impact.get("changed_files") or [])
3429
- classification = _classify_paths(paths)
3895
+ normalized_planned_paths = sorted(
3896
+ {_normalize_owned_path(item) for item in (planned_paths or []) if _text(item)}
3897
+ )
3898
+ classification_inputs = [*paths, *normalized_planned_paths]
3899
+ classification = _classify_paths(classification_inputs)
3900
+ intent_categories = _classify_intent(intent)
3901
+ merged_categories = set(classification["categories"]) | set(intent_categories)
3902
+ classification = _classification_for_categories(merged_categories, len(classification_inputs))
3430
3903
  categories = set(classification["categories"])
3431
- matching_rules = _matching_gate_rules(paths, _gate_cfg(cfg))
3904
+ matching_rules = _matching_gate_rules(classification_inputs, _gate_cfg(cfg))
3432
3905
  configured_profile = _configured_workflow_profile(cfg)
3433
3906
  requested_profile_value = _normalize_workflow_profile(requested_profile) if requested_profile else ""
3434
3907
  configured_mode = _workflow_mode(cfg)
3435
3908
  requested_mode_value = _text(requested_mode).lower()
3436
- if requested_mode_value and requested_mode_value not in {"dev", "verify"}:
3437
- raise APError("workflow.mode must be 'dev' or 'verify'.")
3909
+ if requested_mode_value and requested_mode_value != "dev":
3910
+ raise APError("workflow.mode must be 'dev'; use explicit diagnostic commands when requested.")
3438
3911
 
3439
3912
  detected_profile = "standard"
3440
3913
  profile_reasons: list[str] = []
3441
- docs_only_paths = _docs_only(paths)
3442
- docs_or_tests_only = bool(paths) and (
3443
- (docs_only_paths and str(impact["selected_scope"]) != "full") or _tests_only(paths)
3914
+ docs_only_paths = _docs_only(classification_inputs)
3915
+ docs_or_tests_only = bool(classification_inputs) and (
3916
+ (docs_only_paths and str(impact["selected_scope"]) != "full")
3917
+ or _tests_only(classification_inputs)
3444
3918
  )
3445
3919
  if docs_or_tests_only and str(impact["selected_scope"]) != "full":
3446
3920
  detected_profile = "micro"
@@ -3472,14 +3946,10 @@ def _resolve_execution_plan(
3472
3946
  high_signals: list[str] = []
3473
3947
  if categories & high_categories and not docs_or_tests_only:
3474
3948
  high_signals.append("high-risk category: " + ", ".join(sorted(categories & high_categories)))
3475
- if str(impact["selected_scope"]) == "full":
3476
- high_signals.append("impact requires full gate")
3477
3949
  if "high-risk" in rule_profiles:
3478
3950
  high_signals.append("matched gate rule with profile=high-risk")
3479
- if len(paths) > 12 and not docs_or_tests_only:
3951
+ if len(classification_inputs) > 12 and not docs_or_tests_only:
3480
3952
  high_signals.append("change spans more than 12 files")
3481
- if requested_scope == "full":
3482
- high_signals.append("full scope explicitly requested")
3483
3953
 
3484
3954
  if high_signals:
3485
3955
  detected_profile = "high-risk"
@@ -3501,34 +3971,27 @@ def _resolve_execution_plan(
3501
3971
  if detected_profile == "high-risk" and effective_profile != "high-risk":
3502
3972
  effective_profile = "high-risk"
3503
3973
  profile_reasons.append("high-risk signals cannot be downgraded")
3504
- effective_mode = requested_mode_value or configured_mode
3505
- if configured_mode == "verify":
3506
- effective_mode = "verify"
3507
- if effective_mode == "verify" and effective_profile != "high-risk":
3508
- effective_profile = "high-risk"
3509
- profile_reasons.append("verify mode requires high-risk execution")
3974
+ effective_mode = "dev"
3510
3975
  if not profile_reasons:
3511
3976
  profile_reasons.append(f"configured profile={configured_profile}")
3512
3977
 
3513
- selected_scope = _PROFILE_GATE_SCOPE[effective_profile]
3514
- explicit_scope = _text(requested_scope).lower()
3515
- if explicit_scope in _SCOPE_RANK and _SCOPE_RANK[explicit_scope] > _SCOPE_RANK[selected_scope]:
3516
- selected_scope = explicit_scope
3517
- if str(impact["selected_scope"]) == "full":
3518
- selected_scope = "full"
3519
- effective_mode = "verify" if effective_profile == "high-risk" else effective_mode
3978
+ selected_scope = "changed"
3520
3979
  execution_reasons = list(impact.get("reasons") or [])
3521
- if selected_scope != str(impact["selected_scope"]):
3522
- execution_reasons.append(f"profile={effective_profile} requires scope={selected_scope}")
3980
+ execution_reasons.append("Jenkins/build/deploy and owner acceptance happen after coding completion")
3523
3981
 
3524
- jenkins_required = _verification_required(cfg, "jenkins", default=True)
3525
- target_env_required = _verification_required(cfg, "target_env", default=True)
3526
- needs_jenkins = bool(classification["needs_jenkins"] and jenkins_required)
3527
- needs_target = bool(classification["needs_target"] and target_env_required)
3982
+ needs_jenkins = False
3983
+ needs_target = False
3528
3984
  needs_dd = bool(classification["needs_dd"] or effective_profile == "high-risk")
3529
3985
 
3986
+ agent_plan = _agent_execution_plan(effective_profile, categories, classification)
3530
3987
  return {
3531
3988
  **impact,
3989
+ "contract_version": _AGENT_CONTRACT_VERSION,
3990
+ "contract_schema": _AGENT_CONTRACT_SCHEMA,
3991
+ "planned_files": normalized_planned_paths,
3992
+ "classification_files": classification_inputs,
3993
+ "intent_provided": bool(_text(intent)),
3994
+ "intent_categories": intent_categories,
3532
3995
  "reasons": execution_reasons,
3533
3996
  "configured_profile": configured_profile,
3534
3997
  "requested_profile": requested_profile_value or None,
@@ -3545,12 +4008,25 @@ def _resolve_execution_plan(
3545
4008
  "needs_jenkins": needs_jenkins,
3546
4009
  "needs_target": needs_target,
3547
4010
  "recommended_agents": _recommended_agents(effective_profile, categories, classification),
4011
+ "agent_plan": agent_plan,
3548
4012
  }
3549
4013
 
3550
4014
 
3551
4015
  def cmd_classify(args: argparse.Namespace) -> None:
3552
4016
  repo = Path(args.repo).resolve()
3553
4017
  cfg = _load_cfg(repo)
4018
+ intent_parts = [_text(getattr(args, "intent", ""))]
4019
+ intent_file = _text(getattr(args, "intent_file", ""))
4020
+ if intent_file:
4021
+ path = Path(intent_file)
4022
+ if not path.is_absolute():
4023
+ path = repo / path
4024
+ try:
4025
+ if path.stat().st_size > 65536:
4026
+ raise APError("--intent-file is limited to 64 KiB.")
4027
+ intent_parts.append(path.read_text(encoding="utf-8"))
4028
+ except OSError as exc:
4029
+ raise APError(f"Cannot read --intent-file: {path}: {exc}") from exc
3554
4030
  plan = _resolve_execution_plan(
3555
4031
  cfg,
3556
4032
  repo,
@@ -3558,17 +4034,13 @@ def cmd_classify(args: argparse.Namespace) -> None:
3558
4034
  requested_profile=_text(getattr(args, "profile", "")).lower(),
3559
4035
  requested_mode=_text(getattr(args, "mode", "")).lower(),
3560
4036
  base_ref=_text(getattr(args, "base", "")),
4037
+ planned_paths=list(getattr(args, "planned_path", []) or []),
4038
+ intent="\n".join(part for part in intent_parts if part),
3561
4039
  )
3562
4040
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
3563
- commands = [
3564
- "python3 docs/tools/autopipeline/ap.py impact --scope auto",
3565
- "python3 docs/tools/autopipeline/ap.py structure-check --scope auto",
3566
- f"python3 docs/tools/autopipeline/ap.py light-gate --profile {plan['profile']} --explain",
3567
- ]
4041
+ commands: list[str] = []
3568
4042
  if plan["needs_dd"]:
3569
4043
  commands.append("python3 docs/tools/autopipeline/ap.py scaffold design --write")
3570
- if plan["needs_jenkins"]:
3571
- commands.append("python3 docs/tools/autopipeline/ap.py verify-jenkins")
3572
4044
  result = {
3573
4045
  **plan,
3574
4046
  "risk": risk,
@@ -3583,6 +4055,13 @@ def cmd_classify(args: argparse.Namespace) -> None:
3583
4055
  print(f"[classify] selected_scope={result['selected_scope']}")
3584
4056
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
3585
4057
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
4058
+ print(f"[classify] agent_strategy={result['agent_plan']['strategy']}")
4059
+ for stage in result["agent_plan"]["stages"]:
4060
+ print(
4061
+ "[classify] agent_stage="
4062
+ f"{stage['id']} mode={stage['mode']} roles={','.join(stage['roles'])} "
4063
+ f"depends_on={','.join(stage['depends_on']) or '-'}"
4064
+ )
3586
4065
  for key in ["needs_dd", "needs_adr", "needs_browser", "needs_jenkins", "needs_target"]:
3587
4066
  print(f"[classify] {key}={result[key]}")
3588
4067
  for command in commands:
@@ -3616,18 +4095,17 @@ def cmd_run(args: argparse.Namespace) -> None:
3616
4095
  def cmd_light_gate(args: argparse.Namespace) -> None:
3617
4096
  repo = Path(args.repo).resolve()
3618
4097
  light_gate_start = time.time()
3619
- cmd_doctor(
3620
- argparse.Namespace(
3621
- repo=str(repo),
3622
- profile=_text(getattr(args, "profile", "")).lower(),
3623
- mode=_text(getattr(args, "mode", "")).lower(),
3624
- )
3625
- )
3626
4098
  cfg = _load_cfg(repo)
4099
+ requested_scope = _text(getattr(args, "scope", "")).lower()
4100
+ if requested_scope not in {"", "auto", "changed"}:
4101
+ raise APError(
4102
+ "light-gate only runs the changed-scope fast gate. "
4103
+ "Use 'ap.py run gate_standard' or 'ap.py run gate_full' for an explicit diagnostic."
4104
+ )
3627
4105
  plan = _resolve_execution_plan(
3628
4106
  cfg,
3629
4107
  repo,
3630
- requested_scope=_text(getattr(args, "scope", "")).lower(),
4108
+ requested_scope=requested_scope,
3631
4109
  requested_profile=_text(getattr(args, "profile", "")).lower(),
3632
4110
  requested_mode=_text(getattr(args, "mode", "")).lower(),
3633
4111
  base_ref=_text(getattr(args, "base", "")),
@@ -3637,27 +4115,12 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
3637
4115
  for reason in plan["profile_reasons"]:
3638
4116
  print(f"[impact] profile_reason: {reason}")
3639
4117
 
3640
- selected_scope = str(plan["selected_scope"])
4118
+ selected_scope = "changed"
3641
4119
  paths = list(plan.get("changed_files") or [])
3642
- matching_rules = _matching_gate_rules(paths, _gate_cfg(cfg))
3643
- executed: list[str] = []
3644
- executed.extend(_run_structure_check_for_gate(repo, cfg, selected_scope, str(getattr(args, "base", "") or "")))
3645
-
3646
- if selected_scope == "changed":
3647
- executed.extend(_run_changed_gate(repo, cfg, paths, matching_rules))
3648
- elif selected_scope == "full":
3649
- executed.extend(_run_full_gate(repo, cfg))
3650
- else:
3651
- executed.extend(_run_standard_gate(repo, cfg))
4120
+ executed = _run_changed_gate(repo, cfg, paths)
3652
4121
 
3653
4122
  _run_git_diff_check(repo, cfg)
3654
- cmd_verify_api_docs(argparse.Namespace(repo=str(repo)))
3655
- executed.extend(["diff_check", "verify_api_docs"])
3656
- if _verification_required(cfg, "jenkins", default=True):
3657
- cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
3658
- executed.append("verify_jenkins")
3659
- else:
3660
- executed.append("verify_jenkins_skipped")
4123
+ executed.append("diff_check")
3661
4124
  duration_s = time.time() - light_gate_start
3662
4125
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
3663
4126
  _record_evidence(
@@ -3835,9 +4298,6 @@ def cmd_doctor(args: argparse.Namespace) -> None:
3835
4298
  cfg = _load_cfg(repo)
3836
4299
  workflow_cfg = (cfg.get("workflow") or {})
3837
4300
  project_cfg = (cfg.get("project") or {})
3838
- commands = (cfg.get("commands") or {})
3839
- target_cfg = (cfg.get("target_env") or {})
3840
- jenkins_cfg = (cfg.get("jenkins") or {})
3841
4301
  docs_cfg = (cfg.get("docs") or {})
3842
4302
  runtime_cfg = (cfg.get("runtime") or {})
3843
4303
  structure_cfg = _structure_cfg(cfg)
@@ -3848,15 +4308,18 @@ def cmd_doctor(args: argparse.Namespace) -> None:
3848
4308
 
3849
4309
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
3850
4310
  profile = str(workflow_cfg.get("profile") or "auto").strip().lower()
3851
- target_env_required = _verification_required(cfg, "target_env", default=True)
3852
- jenkins_required = _verification_required(cfg, "jenkins", default=True)
3853
- if mode not in {"dev", "verify"}:
3854
- missing.append("workflow.mode (must be dev or verify)")
4311
+ completion = str(workflow_cfg.get("completion") or "").strip().lower()
4312
+ if mode != "dev":
4313
+ missing.append("workflow.mode (must be dev; external verification is owner-managed)")
3855
4314
  if profile not in _WORKFLOW_PROFILES:
3856
4315
  missing.append("workflow.profile (must be auto, micro, standard, or high-risk)")
4316
+ if completion != "push":
4317
+ missing.append("workflow.completion (must be push)")
3857
4318
  isolation = _text(concurrency_cfg.get("isolation")).lower() or "worktree"
3858
- if isolation not in {"worktree", "legacy"}:
3859
- validation_errors.append("concurrency.isolation must be worktree or legacy")
4319
+ if isolation != "worktree":
4320
+ validation_errors.append(
4321
+ "concurrency.isolation must be worktree; shared-checkout/legacy writes are no longer supported"
4322
+ )
3860
4323
  branch_prefix = _text(concurrency_cfg.get("branch_prefix")) or "codex/"
3861
4324
  if not branch_prefix.endswith("/"):
3862
4325
  validation_errors.append("concurrency.branch_prefix must end with '/'")
@@ -3868,6 +4331,7 @@ def cmd_doctor(args: argparse.Namespace) -> None:
3868
4331
  validation_errors.append("concurrency.branch_prefix does not form a valid Git branch")
3869
4332
  if not str(project_cfg.get("name") or "").strip():
3870
4333
  missing.append("project.name")
4334
+ missing.extend(_access_config_issues(cfg))
3871
4335
  enforcement = _text(structure_cfg.get("enforcement")).lower()
3872
4336
  if enforcement and enforcement not in {"advisory", "blocking"}:
3873
4337
  validation_errors.append("structure.enforcement must be advisory or blocking")
@@ -3895,72 +4359,8 @@ def cmd_doctor(args: argparse.Namespace) -> None:
3895
4359
  f"gate.rules[{index}].scope must be changed, standard, or full"
3896
4360
  )
3897
4361
 
3898
- if mode in {"dev", "verify"} and profile in _WORKFLOW_PROFILES and rules_valid:
3899
- try:
3900
- plan = _resolve_execution_plan(
3901
- cfg,
3902
- repo,
3903
- requested_profile=_text(getattr(args, "profile", "")).lower(),
3904
- requested_mode=_text(getattr(args, "mode", "")).lower(),
3905
- )
3906
- except APError as exc:
3907
- validation_errors.append(str(exc))
3908
- else:
3909
- effective_profile = str(plan["profile"])
3910
- changed_files = list(plan.get("changed_files") or [])
3911
- matching_rules = _matching_gate_rules(changed_files, gate_cfg)
3912
- rule_changed_gate = any(
3913
- any(_configured_command(cfg, _command_name(ref)) for ref in _as_list(rule.get("commands")))
3914
- for rule in matching_rules
3915
- )
3916
- changed_gate = bool(
3917
- _configured_command(cfg, "gate_changed")
3918
- or _configured_command(cfg, "quick_test")
3919
- or _configured_command(cfg, "test")
3920
- or _configured_command(cfg, "build")
3921
- or rule_changed_gate
3922
- or _docs_only(changed_files)
3923
- )
3924
- standard_gate = bool(
3925
- _configured_command(cfg, "gate_standard")
3926
- or _configured_command(cfg, "light_gate")
3927
- or _configured_command(cfg, "quick_test")
3928
- or _configured_command(cfg, "test")
3929
- or _configured_command(cfg, "build")
3930
- )
3931
- full_gate = bool(
3932
- _configured_command(cfg, "gate_full")
3933
- or _configured_command(cfg, "full_gate")
3934
- )
3935
- if effective_profile == "micro" and not changed_gate:
3936
- missing.append(
3937
- "micro gate command: commands.gate_changed, quick_test, test, build, "
3938
- "or a matching gate rule command"
3939
- )
3940
- elif effective_profile == "standard" and not standard_gate:
3941
- missing.append(
3942
- "standard gate command: commands.gate_standard, light_gate, quick_test, test, or build"
3943
- )
3944
- elif effective_profile == "high-risk" and not full_gate:
3945
- missing.append(
3946
- "full gate command: commands.gate_full or commands.full_gate "
3947
- "(required for high-risk/verify execution)"
3948
- )
3949
- if target_env_required:
3950
- _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
3951
- _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
3952
-
3953
- if jenkins_required:
3954
- _require_explicit_field(missing, "jenkins.base_url", jenkins_cfg.get("base_url"))
3955
- _require_explicit_field(missing, "jenkins.ui_username", jenkins_cfg.get("ui_username"))
3956
- _require_secret_reference(missing, "jenkins", jenkins_cfg, "ui_password")
3957
- _require_explicit_field(missing, "jenkins.job_url", jenkins_cfg.get("job_url"))
3958
- _require_explicit_field(missing, "jenkins.trigger_branch", jenkins_cfg.get("trigger_branch"))
3959
- _require_explicit_field(missing, "jenkins.image_repository", jenkins_cfg.get("image_repository"))
3960
- _require_explicit_field(missing, "jenkins.image_tag_strategy", jenkins_cfg.get("image_tag_strategy"))
3961
- _require_explicit_field(missing, "jenkins.deploy_env", jenkins_cfg.get("deploy_env"))
3962
- _require_explicit_field(missing, "jenkins.api_user", jenkins_cfg.get("api_user"))
3963
- _require_secret_reference(missing, "jenkins", jenkins_cfg, "api_password")
4362
+ if not (_configured_command(cfg, "gate_changed") or _configured_command(cfg, "quick_test")):
4363
+ missing.append("fast gate command: commands.gate_changed or commands.quick_test")
3964
4364
 
3965
4365
  repo_docs = {
3966
4366
  "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
@@ -3980,33 +4380,10 @@ def cmd_doctor(args: argparse.Namespace) -> None:
3980
4380
  if not path.exists():
3981
4381
  validation_errors.append(f"{key} missing on disk: {path}")
3982
4382
 
3983
- _validate_url_field(validation_errors, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
3984
- _validate_url_field(validation_errors, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
3985
- _validate_url_field(validation_errors, "target_env.health_base_url", target_cfg.get("health_base_url"))
3986
- _validate_path_field(validation_errors, "target_env.health_path", target_cfg.get("health_path"))
3987
- _validate_url_field(validation_errors, "jenkins.base_url", jenkins_cfg.get("base_url"))
3988
- _validate_url_field(validation_errors, "jenkins.job_url", jenkins_cfg.get("job_url"))
3989
-
3990
4383
  runtime_enabled = any(str(runtime_cfg.get(key) or "").strip() for key in ["docker_compose_file", "docker_service", "health_base_url", "health_path"])
3991
4384
  if runtime_enabled and not str(runtime_cfg.get("docker_compose_file") or "").strip():
3992
4385
  validation_errors.append("runtime config is partially enabled but runtime.docker_compose_file is missing")
3993
4386
 
3994
- ledger_result = _docs_ledger_check_result(repo, cfg)
3995
- ledger_status = "skipped" if not ledger_result.get("enabled", True) else ("fail" if ledger_result.get("blocking") else "pass")
3996
- _record_evidence(repo, cfg, "docs_ledger_check", ledger_status, ledger_result)
3997
- for issue in ledger_result.get("blocking") or []:
3998
- validation_errors.append(f"docs-ledger: {issue}")
3999
- for warning in ledger_result.get("warnings") or []:
4000
- print(f"[doctor] WARN docs-ledger: {warning}")
4001
-
4002
- try:
4003
- timeout_s = int(jenkins_cfg.get("deploy_timeout_sec") or 0)
4004
- if (jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec"))) and timeout_s <= 0:
4005
- validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
4006
- except Exception:
4007
- if jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec")):
4008
- validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
4009
-
4010
4387
  missing.extend(validation_errors)
4011
4388
 
4012
4389
  if missing:
@@ -4018,7 +4395,7 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4018
4395
  cfg,
4019
4396
  "doctor",
4020
4397
  "pass",
4021
- {"mode": mode, "target_env_required": target_env_required, "jenkins_required": jenkins_required},
4398
+ {"mode": mode, "completion": completion, "access_fields": len(_REQUIRED_ACCESS_FIELDS)},
4022
4399
  )
4023
4400
  print("[doctor] OK")
4024
4401
 
@@ -4182,9 +4559,7 @@ def _validate_closure_result(effective_mode: str, result: str) -> None:
4182
4559
  mode = _text(effective_mode).lower()
4183
4560
  normalized_result = _text(result).upper()
4184
4561
  if mode == "dev" and normalized_result == "PASS":
4185
- raise APError("PASS requires verify mode; use DEV-CLOSED, PARTIAL, or FAIL for dev execution.")
4186
- if mode == "verify" and normalized_result == "DEV-CLOSED":
4187
- raise APError("DEV-CLOSED is only valid for dev mode; use PASS, PARTIAL, or FAIL for verify execution.")
4562
+ raise APError("Automatic coding closure uses DEV-CLOSED; owner acceptance is handled after push.")
4188
4563
 
4189
4564
 
4190
4565
  def _validate_closure_evidence(result: str, verification_items: list[str]) -> None:
@@ -4241,20 +4616,20 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
4241
4616
  title = str(args.title or "").strip() or _infer_title(taskbook, task_id)
4242
4617
  timestamp = _dt.datetime.now().strftime("%Y-%m-%d %H:%M")
4243
4618
  commit_value = _resolve_git_short_sha(repo, args.commit)
4244
- target_env = str(args.target_env or target_cfg.get("name") or "").strip() or "(not set)"
4245
- verification_text = "; ".join(verification_items) if verification_items else "TODO"
4619
+ target_env = str(args.target_env or target_cfg.get("name") or "").strip() or "owner-managed acceptance"
4620
+ verification_text = "; ".join(verification_items) if verification_items else "fast gate evidence not recorded"
4246
4621
  follow_up = str(args.follow_up or "").strip() or "none"
4247
- jenkins_build = str(args.jenkins or "").strip() or "TODO"
4248
- structure_check = str(getattr(args, "structure_check", "") or "").strip() or "TODO"
4622
+ jenkins_build = str(args.jenkins or "").strip() or "owner-managed after push"
4623
+ structure_check = str(getattr(args, "structure_check", "") or "").strip() or "not part of the fast local gate"
4249
4624
  lines = [
4250
4625
  f"## {task_id} — {title} — {timestamp}",
4251
4626
  f"- Task: {task_id}",
4252
4627
  f"- Commit: {commit_value}",
4253
- f"- CI/Jenkins Build: {jenkins_build}",
4254
- f"- Target Env: {target_env}",
4255
- f"- Verification: {verification_text}",
4628
+ f"- Fast Local Gate: {verification_text}",
4629
+ f"- External Build/Deploy: {jenkins_build}",
4630
+ f"- Owner Acceptance: {target_env}",
4256
4631
  f"- Effective Profile: {profile}",
4257
- f"- Structure Check: {structure_check}",
4632
+ f"- Optional Structure Diagnostic: {structure_check}",
4258
4633
  f"- Result: {args.result}",
4259
4634
  f"- Follow-up: {follow_up}",
4260
4635
  ]
@@ -5172,8 +5547,22 @@ def _create_active_task_doc(repo: Path, cfg: dict, manifest: dict) -> None:
5172
5547
  f"- Base: `{manifest['base_ref']}` (`{manifest['base_sha'][:12]}`)",
5173
5548
  f"- Target: `{manifest['remote']}/{manifest['target_branch']}`",
5174
5549
  f"- Branch: `{manifest['task_branch']}`",
5550
+ f"- Worktree: `{manifest['worktree_path']}`",
5551
+ f"- Orchestrator: {manifest.get('owner') or 'TODO'}",
5552
+ f"- Owning fixer: {(manifest.get('writer_lease') or {}).get('holder') or 'TODO'}",
5553
+ "- Owned paths: " + ", ".join(f"`{item}`" for item in manifest.get("owned_paths") or []),
5554
+ "- Depends on integrated tasks: "
5555
+ + (
5556
+ ", ".join(
5557
+ f"`{item}`@`{(manifest.get('prerequisite_shas') or {}).get(item, '')[:12]}`"
5558
+ for item in manifest.get("depends_on") or []
5559
+ )
5560
+ or "none"
5561
+ ),
5562
+ "- Reviewer / stable diff: TODO",
5563
+ "- Review verdict: pending",
5175
5564
  "- Scope: TODO",
5176
- "- Acceptance: TODO",
5565
+ "- Development acceptance: TODO",
5177
5566
  "",
5178
5567
  ]
5179
5568
  ),
@@ -5218,6 +5607,13 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5218
5607
  repo = Path(args.repo).resolve()
5219
5608
  ensure_git_repo(repo)
5220
5609
  cfg = _load_cfg(repo)
5610
+ _task_isolation(cfg)
5611
+ access_issues = _access_config_issues(cfg)
5612
+ if access_issues:
5613
+ raise APError(
5614
+ "Project initialization is incomplete; fill docs/ENGINEERING.md before starting work:\n- "
5615
+ + "\n- ".join(access_issues)
5616
+ )
5221
5617
  task_id = _validate_task_id(args.task_id)
5222
5618
  _require_control_checkout(repo)
5223
5619
  remote, target_branch, base_ref = _task_remote_and_target(cfg, args)
@@ -5238,6 +5634,30 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5238
5634
  if not getattr(args, "no_fetch", False) and base_ref.startswith(f"{remote}/"):
5239
5635
  _fetch_target(repo, remote, target_branch)
5240
5636
  base_sha = _resolve_commit(repo, base_ref)
5637
+ owned_paths = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
5638
+ if not owned_paths:
5639
+ raise APError("task-start requires at least one --owned-path.")
5640
+ depends_on: list[str] = []
5641
+ prerequisite_shas: dict[str, str] = {}
5642
+ for raw_dependency in args.depends_on or []:
5643
+ dependency, separator, sha = _text(raw_dependency).partition("=")
5644
+ dependency = _validate_task_id(dependency)
5645
+ if not separator or not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", sha):
5646
+ raise APError("--depends-on must use TASK_ID=full_commit_SHA.")
5647
+ if dependency in prerequisite_shas and prerequisite_shas[dependency] != sha:
5648
+ raise APError(f"Conflicting prerequisite SHAs for {dependency}.")
5649
+ depends_on.append(dependency)
5650
+ prerequisite_shas[dependency] = sha
5651
+ depends_on = sorted(set(depends_on))
5652
+ dependency_contract = {
5653
+ "depends_on": depends_on,
5654
+ "prerequisite_shas": prerequisite_shas,
5655
+ }
5656
+ _require_dependencies(repo, dependency_contract, base_sha)
5657
+ owner = _text(getattr(args, "owner", "")) or _text(os.environ.get("CODEX_THREAD_ID"))
5658
+ if not owner:
5659
+ raise APError("task-start requires --owner or CODEX_THREAD_ID.")
5660
+ writer = _text(getattr(args, "writer", "")) or owner
5241
5661
  prefix = _task_branch_prefix(cfg)
5242
5662
  task_branch = f"{prefix}{task_id}"
5243
5663
  check_ref = run(["git", "check-ref-format", "--branch", task_branch], cwd=repo, check=False)
@@ -5267,10 +5687,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5267
5687
  cwd=repo,
5268
5688
  )
5269
5689
  manifest = {
5270
- "schema": 1,
5690
+ "schema": 2,
5271
5691
  "task_id": task_id,
5272
5692
  "task_uuid": task_uuid,
5273
- "owner": _text(getattr(args, "owner", "")) or os.environ.get("CODEX_THREAD_ID", "") or f"{socket.gethostname()}:{os.getpid()}",
5693
+ "owner": owner,
5274
5694
  "base_ref": base_ref,
5275
5695
  "base_sha": base_sha,
5276
5696
  "remote": remote,
@@ -5282,6 +5702,24 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5282
5702
  "state": "active",
5283
5703
  "created_at": _now_iso(),
5284
5704
  "initial_untracked": [],
5705
+ "owned_paths": owned_paths,
5706
+ "depends_on": depends_on,
5707
+ "prerequisite_shas": prerequisite_shas,
5708
+ "writer_lease": {
5709
+ "holder": writer,
5710
+ "generation": 1,
5711
+ "state": "active",
5712
+ "acquired_at": _now_iso(),
5713
+ },
5714
+ "review": {
5715
+ "verdict": "pending",
5716
+ "diff_base": base_sha,
5717
+ "diff_head": "",
5718
+ "diff_fingerprint": "",
5719
+ "reviewer": "",
5720
+ "reviewed_at": "",
5721
+ "reason": "task started",
5722
+ },
5285
5723
  "claimed_paths": [],
5286
5724
  "remote_task_tip": "",
5287
5725
  "common_submodule_config": common_submodule_config,
@@ -5350,6 +5788,9 @@ def _task_status_payload(repo: Path, manifest: dict) -> dict:
5350
5788
  "local_branch_exists": bool(tip),
5351
5789
  "tip": tip,
5352
5790
  "merged_into_target": merged,
5791
+ "current_diff_fingerprint": _task_review_fingerprint(worktree, manifest)
5792
+ if worktree.exists()
5793
+ else "",
5353
5794
  }
5354
5795
 
5355
5796
 
@@ -5381,6 +5822,138 @@ def cmd_task_status(args: argparse.Namespace) -> None:
5381
5822
  )
5382
5823
 
5383
5824
 
5825
+ def _task_lifecycle_context(repo: Path, cfg: dict, task_id: str) -> tuple[Path, Path, dict]:
5826
+ active = _active_task_manifest(repo)
5827
+ if active:
5828
+ manifest = _require_task_context(repo, cfg, task_id)
5829
+ return Path(_text(manifest.get("control_worktree_path"))).resolve(), repo, manifest
5830
+ manifest = _load_task_manifest(repo, task_id)
5831
+ _require_control_checkout(repo, manifest)
5832
+ return repo, Path(_text(manifest.get("worktree_path"))).resolve(), manifest
5833
+
5834
+
5835
+ def cmd_task_review(args: argparse.Namespace) -> None:
5836
+ repo = Path(args.repo).resolve()
5837
+ ensure_git_repo(repo)
5838
+ cfg = _load_cfg(repo)
5839
+ task_id = _validate_task_id(args.task_id)
5840
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
5841
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
5842
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
5843
+ manifest = _load_task_manifest(control_repo, task_id)
5844
+ lifecycle_actor = _text(os.environ.get("CODEX_THREAD_ID"))
5845
+ if not lifecycle_actor or lifecycle_actor != _text(manifest.get("owner")):
5846
+ raise APError("Only the task lifecycle owner may record a review verdict.")
5847
+ if _text(manifest.get("state")) not in {"active", "pushed", "integration-raced"}:
5848
+ raise APError(f"Task {task_id} is not reviewable in state={manifest.get('state')}.")
5849
+ if not worktree.exists():
5850
+ raise APError(f"Task worktree is missing: {worktree}")
5851
+ worktree_cfg = _load_cfg(worktree)
5852
+ unowned = _task_unowned_paths(worktree, worktree_cfg, manifest)
5853
+ if unowned:
5854
+ raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
5855
+ fingerprint = _task_review_fingerprint(worktree, manifest)
5856
+ supplied = _text(args.diff_fingerprint)
5857
+ if supplied != fingerprint:
5858
+ raise APError(
5859
+ f"Review fingerprint mismatch: supplied={supplied or '(missing)'}, current={fingerprint}."
5860
+ )
5861
+ reviewer = _text(getattr(args, "reviewer", "")) or _text(os.environ.get("CODEX_THREAD_ID"))
5862
+ if not reviewer:
5863
+ raise APError("task-review requires --reviewer or CODEX_THREAD_ID.")
5864
+ manifest["review"] = {
5865
+ "verdict": args.verdict,
5866
+ "diff_base": _text(manifest.get("base_sha")),
5867
+ "diff_head": _resolve_commit(worktree, "HEAD"),
5868
+ "diff_fingerprint": fingerprint,
5869
+ "reviewer": reviewer,
5870
+ "reviewed_at": _now_iso(),
5871
+ "reason": "",
5872
+ }
5873
+ _save_task_manifest(control_repo, manifest)
5874
+ print(f"[task-review] task={task_id} verdict={args.verdict} fingerprint={fingerprint}")
5875
+
5876
+
5877
+ def cmd_task_handoff(args: argparse.Namespace) -> None:
5878
+ repo = Path(args.repo).resolve()
5879
+ ensure_git_repo(repo)
5880
+ cfg = _load_cfg(repo)
5881
+ task_id = _validate_task_id(args.task_id)
5882
+ control_repo, _, _ = _task_lifecycle_context(repo, cfg, task_id)
5883
+ actor = _text(os.environ.get("CODEX_THREAD_ID"))
5884
+ if not actor:
5885
+ raise APError("task-handoff requires CODEX_THREAD_ID for the current writer.")
5886
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
5887
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
5888
+ manifest = _load_task_manifest(control_repo, task_id)
5889
+ if _text(manifest.get("state")) in {"integrated", "cleanup-pending"}:
5890
+ raise APError(f"Task {task_id} no longer accepts writer handoff.")
5891
+ lease = manifest.get("writer_lease") or {}
5892
+ generation = int(lease.get("generation") or 0)
5893
+ if _text(lease.get("holder")) != args.from_writer:
5894
+ raise APError("--from must match the current writer lease holder.")
5895
+ if actor not in {args.from_writer, _text(manifest.get("owner"))}:
5896
+ raise APError("Only the current writer or task lifecycle owner may hand off the task.")
5897
+ if args.generation is not None and args.generation != generation:
5898
+ raise APError(f"Writer lease generation changed: expected={args.generation}, current={generation}.")
5899
+ lease.update(
5900
+ {
5901
+ "holder": args.to_writer,
5902
+ "generation": generation + 1,
5903
+ "state": "active",
5904
+ "acquired_at": _now_iso(),
5905
+ }
5906
+ )
5907
+ manifest["writer_lease"] = lease
5908
+ _save_task_manifest(control_repo, manifest)
5909
+ print(f"[task-handoff] task={task_id} writer={args.to_writer} generation={generation + 1}")
5910
+
5911
+
5912
+ def cmd_task_resume(args: argparse.Namespace) -> None:
5913
+ repo = Path(args.repo).resolve()
5914
+ ensure_git_repo(repo)
5915
+ cfg = _load_cfg(repo)
5916
+ task_id = _validate_task_id(args.task_id)
5917
+ manifest = _load_task_manifest(repo, task_id)
5918
+ _require_control_checkout(repo, manifest)
5919
+ _require_current_writer(manifest, args)
5920
+ worktree = Path(_text(manifest.get("worktree_path"))).resolve()
5921
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
5922
+ with (
5923
+ _repo_lock(repo, "integration", timeout_s=timeout_s),
5924
+ _repo_lock(repo, f"task-{task_id}", timeout_s=timeout_s),
5925
+ ):
5926
+ manifest = _load_task_manifest(repo, task_id)
5927
+ _require_current_writer(manifest, args)
5928
+ if _text(manifest.get("state")) != "conflicted":
5929
+ raise APError(f"Task {task_id} is not awaiting conflict resume.")
5930
+ for marker in ("rebase-merge", "rebase-apply"):
5931
+ path = Path(run(["git", "rev-parse", "--git-path", marker], cwd=worktree).stdout.strip())
5932
+ if not path.is_absolute():
5933
+ path = worktree / path
5934
+ if path.exists():
5935
+ raise APError("Rebase is still in progress; resolve conflicts and run git rebase --continue first.")
5936
+ if _git_status(worktree):
5937
+ raise APError("Task worktree must be clean before task-resume.")
5938
+ target_sha = _text(manifest.get("rebase_target_sha"))
5939
+ if not target_sha or run(
5940
+ ["git", "merge-base", "--is-ancestor", target_sha, "HEAD"],
5941
+ cwd=worktree,
5942
+ check=False,
5943
+ ).returncode != 0:
5944
+ raise APError("Resolved task HEAD does not contain the recorded rebase target.")
5945
+ manifest["base_sha"] = target_sha
5946
+ manifest["base_ref"] = target_sha
5947
+ unowned = _task_unowned_paths(worktree, _load_cfg(worktree), manifest)
5948
+ if unowned:
5949
+ raise APError("Resolved rebase changed paths outside owned_paths:\n- " + "\n- ".join(unowned))
5950
+ _invalidate_task_review(manifest, "rebase conflict resolved; review again")
5951
+ manifest["state"] = "active"
5952
+ _save_task_manifest(repo, manifest)
5953
+ _push_current_task(worktree, manifest)
5954
+ print(f"[task-resume] task={task_id} state=pushed review=pending")
5955
+
5956
+
5384
5957
  def cmd_task_submodule_sync(args: argparse.Namespace) -> None:
5385
5958
  repo = Path(args.repo).resolve()
5386
5959
  ensure_git_repo(repo)
@@ -5593,18 +6166,6 @@ def cmd_task_finish(args: argparse.Namespace) -> None:
5593
6166
  )
5594
6167
 
5595
6168
 
5596
- def _append_integration_closure(repo: Path, cfg: dict, manifest: dict, target_sha: str) -> None:
5597
- path = _task_doc_path(repo, cfg, manifest, "closure")
5598
- path.parent.mkdir(parents=True, exist_ok=True)
5599
- if not path.exists():
5600
- path.write_text(f"# Task Closure — {manifest['task_id']}\n", encoding="utf-8")
5601
- with path.open("a", encoding="utf-8") as handle:
5602
- handle.write("\n## Integration\n")
5603
- handle.write(f"- Target: `{manifest['remote']}/{manifest['target_branch']}`\n")
5604
- handle.write(f"- Base: `{target_sha}`\n")
5605
- handle.write("- Gate: passed after rebase\n")
5606
-
5607
-
5608
6169
  def cmd_task_integrate(args: argparse.Namespace) -> None:
5609
6170
  repo = Path(args.repo).resolve()
5610
6171
  ensure_git_repo(repo)
@@ -5612,6 +6173,7 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5612
6173
  task_id = _validate_task_id(args.task_id)
5613
6174
  manifest = _load_task_manifest(repo, task_id)
5614
6175
  _require_control_checkout(repo, manifest)
6176
+ _require_current_writer(manifest, args)
5615
6177
  worktree = Path(_text(manifest.get("worktree_path")))
5616
6178
  if repo.resolve() == worktree.resolve():
5617
6179
  raise APError("Run task-integrate from the primary/control checkout, not from the task worktree.")
@@ -5622,6 +6184,7 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5622
6184
  _repo_lock(repo, f"task-{task_id}", timeout_s=timeout_s),
5623
6185
  ):
5624
6186
  manifest = _load_task_manifest(repo, task_id)
6187
+ _require_current_writer(manifest, args)
5625
6188
  worktree = Path(_text(manifest.get("worktree_path")))
5626
6189
  if not worktree.exists():
5627
6190
  raise APError(f"Task worktree is missing: {worktree}")
@@ -5636,7 +6199,7 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5636
6199
  check_common=True,
5637
6200
  )
5638
6201
  _save_task_manifest(repo, manifest)
5639
- if _text(manifest.get("state")) not in {"pushed", "integration-raced", "gate-failed"}:
6202
+ if _text(manifest.get("state")) not in {"pushed", "integration-raced"}:
5640
6203
  raise APError(f"Task {task_id} must be committed and pushed before integration.")
5641
6204
  dirty = _git_status(worktree)
5642
6205
  if dirty:
@@ -5646,14 +6209,33 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5646
6209
  target = _text(manifest.get("target_branch"))
5647
6210
  task_cfg = _load_cfg(worktree)
5648
6211
  target_sha = _fetch_target(worktree, remote, target)
5649
- rebase = run(["git", "rebase", target_sha], cwd=worktree, check=False)
5650
- if rebase.returncode != 0:
6212
+ _require_dependencies(worktree, manifest, target_sha)
6213
+ _require_approved_review(worktree, task_cfg, manifest)
6214
+ if target_sha == _text(manifest.get("base_sha")):
6215
+ rebase = None
6216
+ else:
6217
+ rebase = run(["git", "rebase", target_sha], cwd=worktree, check=False)
6218
+ if rebase is not None and rebase.returncode != 0:
5651
6219
  manifest["state"] = "conflicted"
6220
+ manifest["rebase_target_sha"] = target_sha
6221
+ _invalidate_task_review(manifest, "integration rebase conflicted")
5652
6222
  _save_task_manifest(repo, manifest)
5653
6223
  raise APError(
5654
6224
  f"Task integration rebase conflicted for {task_id}; resolve it only in {worktree}.\n"
5655
6225
  f"{rebase.stdout}\n{rebase.stderr}"
5656
6226
  )
6227
+ if rebase is not None:
6228
+ manifest["base_sha"] = target_sha
6229
+ manifest["base_ref"] = target_sha
6230
+ manifest["rebase_target_sha"] = ""
6231
+ _invalidate_task_review(manifest, "target changed and task was rebased; review again")
6232
+ manifest["state"] = "active"
6233
+ _save_task_manifest(repo, manifest)
6234
+ _push_current_task(worktree, manifest)
6235
+ raise APError(
6236
+ f"Task {task_id} was rebased onto {target_sha}; the task backup branch was updated. "
6237
+ "Run task-review again before final integration."
6238
+ )
5657
6239
 
5658
6240
  _sync_task_submodule_config(
5659
6241
  repo,
@@ -5664,60 +6246,12 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5664
6246
  )
5665
6247
  _save_task_manifest(repo, manifest)
5666
6248
 
5667
- before_gate = _task_content_fingerprint(worktree, task_cfg, manifest)
5668
- try:
5669
- cmd_light_gate(
5670
- argparse.Namespace(
5671
- repo=str(worktree),
5672
- scope="auto",
5673
- profile="",
5674
- mode="",
5675
- base=target_sha,
5676
- explain=False,
5677
- )
5678
- )
5679
- except APError:
5680
- manifest["state"] = "gate-failed"
5681
- _save_task_manifest(repo, manifest)
5682
- raise
5683
- after_gate = _task_content_fingerprint(worktree, task_cfg, manifest)
5684
- if after_gate != before_gate:
5685
- manifest["state"] = "gate-mutated"
5686
- _save_task_manifest(repo, manifest)
5687
- raise APError(
5688
- "Integration gate changed task-owned files. Review those changes, run commit-push again, "
5689
- "then retry integration."
5690
- )
5691
6249
  manifest = _require_task_context(worktree, task_cfg, task_id) or manifest
5692
-
5693
- _append_integration_closure(worktree, task_cfg, manifest, target_sha)
5694
- _update_active_task_status(worktree, task_cfg, manifest, "Integrated")
5695
- protected = set(manifest.get("initial_untracked") or [])
5696
- _cleanup_generated_noise(worktree, protected_paths=protected)
5697
- integration_fingerprint = _task_content_fingerprint(worktree, task_cfg, manifest)
5698
- manifest = _require_task_context(worktree, task_cfg, task_id) or manifest
5699
- if _task_content_fingerprint(worktree, task_cfg, manifest) != integration_fingerprint:
5700
- raise APError("Task-owned files changed immediately before staging integration evidence.")
5701
- integration_paths = _task_commit_paths(worktree)
5702
- task_tip = ""
5703
- if integration_paths:
5704
- staged = _stage_exact_paths(worktree, integration_paths)
5705
- if staged:
5706
- unstaged = _unstaged_task_paths(worktree)
5707
- if unstaged:
5708
- raise APError(
5709
- "Task-owned files changed while staging integration evidence:\n- "
5710
- + "\n- ".join(unstaged)
5711
- )
5712
- manifest = _require_task_context(worktree, task_cfg, task_id) or manifest
5713
- task_tip = _commit_exact_index(
5714
- worktree,
5715
- f"{task_id}: record integration evidence [skip ci]",
5716
- )
5717
-
5718
- task_tip = task_tip or _resolve_commit(worktree, "HEAD")
6250
+ _require_current_writer(manifest, args)
6251
+ _require_approved_review(worktree, task_cfg, manifest)
6252
+ task_tip = _resolve_commit(worktree, "HEAD")
5719
6253
  if _resolve_commit(worktree, "HEAD") != task_tip:
5720
- raise APError("HEAD moved after the verified integration commit; refusing to push.")
6254
+ raise APError("HEAD moved before the target push; refusing to push.")
5721
6255
  if run(
5722
6256
  ["git", "merge-base", "--is-ancestor", target_sha, task_tip],
5723
6257
  cwd=worktree,
@@ -5740,8 +6274,8 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
5740
6274
  manifest["integration_tip"] = task_tip
5741
6275
  _save_task_manifest(repo, manifest)
5742
6276
  raise APError(
5743
- f"Target branch moved while integrating {task_id}. Re-run task-integrate to fetch, rebase, "
5744
- f"and gate the new target.\n{push.stdout}\n{push.stderr}"
6277
+ f"Target branch moved while integrating {task_id}. Re-run task-integrate to fetch and "
6278
+ f"rebase the new target.\n{push.stdout}\n{push.stderr}"
5745
6279
  )
5746
6280
 
5747
6281
  fresh_target = _fetch_target(worktree, remote, target)
@@ -5952,43 +6486,48 @@ def _commit_exact_index(repo: Path, message: str) -> str:
5952
6486
  return commit_sha
5953
6487
 
5954
6488
 
5955
- def _push_current_task(repo: Path, manifest: Optional[dict], expected_commit: str = "") -> str:
6489
+ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") -> str:
5956
6490
  commit_sha = expected_commit or _resolve_commit(repo, "HEAD")
5957
6491
  if _resolve_commit(repo, "HEAD") != commit_sha:
5958
6492
  raise APError("HEAD moved after the verified commit; refusing to push.")
5959
- if manifest:
5960
- remote = _text(manifest.get("remote")) or "origin"
5961
- task_branch = _text(manifest.get("task_branch"))
5962
- remote_tip = _remote_branch_tip(repo, remote, task_branch)
5963
- command = ["git", "push", "--set-upstream"]
5964
- if remote_tip and run(
5965
- ["git", "merge-base", "--is-ancestor", remote_tip, "HEAD"],
5966
- cwd=repo,
5967
- check=False,
5968
- ).returncode != 0:
5969
- expected_tip = _text(manifest.get("remote_task_tip"))
5970
- if not expected_tip or expected_tip != remote_tip:
5971
- raise APError(
5972
- f"Remote task branch moved unexpectedly: {remote}/{task_branch}. "
5973
- "No force push was attempted."
5974
- )
5975
- command.append(f"--force-with-lease=refs/heads/{task_branch}:{expected_tip}")
5976
- command.extend([remote, f"{commit_sha}:refs/heads/{task_branch}"])
5977
- run(command, cwd=repo)
5978
- if _resolve_commit(repo, "HEAD") != commit_sha:
5979
- raise APError("A push hook changed HEAD. The verified task commit was pushed, but local state needs review.")
5980
- pushed_tip = _remote_branch_tip(repo, remote, task_branch)
5981
- if pushed_tip != commit_sha:
6493
+ remote = _text(manifest.get("remote")) or "origin"
6494
+ task_branch = _text(manifest.get("task_branch"))
6495
+ remote_tip = _remote_branch_tip(repo, remote, task_branch)
6496
+ command = ["git", "push", "--set-upstream"]
6497
+ # This is an internal backup branch, not the final project push. The
6498
+ # configured pre-push hook runs once later for the target-branch push.
6499
+ command.append("--no-verify")
6500
+ if remote_tip and run(
6501
+ ["git", "merge-base", "--is-ancestor", remote_tip, "HEAD"],
6502
+ cwd=repo,
6503
+ check=False,
6504
+ ).returncode != 0:
6505
+ expected_tip = _text(manifest.get("remote_task_tip"))
6506
+ if not expected_tip or expected_tip != remote_tip:
5982
6507
  raise APError(
5983
- f"Remote task branch verification failed: expected {commit_sha}, got {pushed_tip or '(missing)'}."
6508
+ f"Remote task branch moved unexpectedly: {remote}/{task_branch}. "
6509
+ "No force push was attempted."
5984
6510
  )
5985
- manifest["state"] = "pushed"
5986
- manifest["remote_task_tip"] = commit_sha
5987
- manifest["last_commit"] = commit_sha
5988
- manifest["claimed_paths"] = _changed_files(repo, _text(manifest.get("base_sha")))
5989
- _save_task_manifest(repo, manifest)
5990
- else:
5991
- run(["git", "push"], cwd=repo)
6511
+ command.append(f"--force-with-lease=refs/heads/{task_branch}:{expected_tip}")
6512
+ command.extend([remote, f"{commit_sha}:refs/heads/{task_branch}"])
6513
+ run(command, cwd=repo)
6514
+ if _resolve_commit(repo, "HEAD") != commit_sha:
6515
+ raise APError("A push hook changed HEAD. The verified task commit was pushed, but local state needs review.")
6516
+ pushed_tip = _remote_branch_tip(repo, remote, task_branch)
6517
+ if pushed_tip != commit_sha:
6518
+ raise APError(
6519
+ f"Remote task branch verification failed: expected {commit_sha}, got {pushed_tip or '(missing)'}."
6520
+ )
6521
+ manifest["state"] = "pushed"
6522
+ manifest["remote_task_tip"] = commit_sha
6523
+ manifest["last_commit"] = commit_sha
6524
+ manifest["claimed_paths"] = _changed_files(repo, _text(manifest.get("base_sha")))
6525
+ review = manifest.get("review") or {}
6526
+ if _text(review.get("verdict")) == "approved":
6527
+ review["diff_head"] = commit_sha
6528
+ review["diff_fingerprint"] = _task_review_fingerprint(repo, manifest)
6529
+ manifest["review"] = review
6530
+ _save_task_manifest(repo, manifest)
5992
6531
  return commit_sha
5993
6532
 
5994
6533
 
@@ -5996,18 +6535,20 @@ def _cmd_commit_push_locked(
5996
6535
  args: argparse.Namespace,
5997
6536
  repo: Path,
5998
6537
  cfg: dict,
5999
- manifest: Optional[dict],
6538
+ manifest: dict,
6000
6539
  ) -> None:
6001
- if manifest:
6002
- control_repo = Path(_text(manifest.get("control_worktree_path"))).resolve()
6003
- _sync_task_submodule_config(
6004
- control_repo,
6005
- repo,
6006
- manifest,
6007
- initial=False,
6008
- check_common=False,
6009
- )
6010
- _save_task_manifest(repo, manifest)
6540
+ control_repo = Path(_text(manifest.get("control_worktree_path"))).resolve()
6541
+ _sync_task_submodule_config(
6542
+ control_repo,
6543
+ repo,
6544
+ manifest,
6545
+ initial=False,
6546
+ check_common=False,
6547
+ )
6548
+ _save_task_manifest(repo, manifest)
6549
+ _require_current_writer(manifest, args)
6550
+ _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
6551
+ _require_approved_review(repo, cfg, manifest)
6011
6552
  cmd_doctor(
6012
6553
  argparse.Namespace(
6013
6554
  repo=str(repo),
@@ -6015,7 +6556,7 @@ def _cmd_commit_push_locked(
6015
6556
  mode=_text(getattr(args, "mode", "")).lower(),
6016
6557
  )
6017
6558
  )
6018
- base_ref = _text(manifest.get("base_sha")) if manifest else ""
6559
+ base_ref = _text(manifest.get("base_sha"))
6019
6560
  plan = _resolve_execution_plan(
6020
6561
  cfg,
6021
6562
  repo,
@@ -6028,29 +6569,21 @@ def _cmd_commit_push_locked(
6028
6569
  args.effective_profile = str(plan["profile"])
6029
6570
  if args.result:
6030
6571
  _validate_closure_result(mode, str(args.result))
6031
- target_cfg = (cfg.get("target_env") or {})
6032
- target_env_required = _verification_required(cfg, "target_env", default=True)
6033
- jenkins_required = _verification_required(cfg, "jenkins", default=True)
6034
6572
 
6035
6573
  msg = args.msg
6036
- structure_check_status = "skipped"
6037
-
6038
- if args.require_runtime_health:
6039
- cmd_wait_health(argparse.Namespace(repo=str(repo), scope="runtime"))
6574
+ structure_check_status = "not part of the fast local gate"
6040
6575
 
6041
6576
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
6042
- if mode in {"dev", "verify"} or args.require_light_gate:
6043
- cmd_light_gate(
6044
- argparse.Namespace(
6045
- repo=str(repo),
6046
- scope=plan["selected_scope"],
6047
- profile=plan["profile"],
6048
- mode=mode,
6049
- base=base_ref,
6050
- explain=False,
6051
- )
6577
+ cmd_light_gate(
6578
+ argparse.Namespace(
6579
+ repo=str(repo),
6580
+ scope="changed",
6581
+ profile=plan["profile"],
6582
+ mode="dev",
6583
+ base=base_ref,
6584
+ explain=False,
6052
6585
  )
6053
- structure_check_status = "passed via light-gate" if _structure_gate_enabled(cfg) else "skipped (structure disabled)"
6586
+ )
6054
6587
 
6055
6588
  after_gate = _task_content_fingerprint(repo, cfg, manifest)
6056
6589
  if after_gate != before_gate:
@@ -6058,14 +6591,9 @@ def _cmd_commit_push_locked(
6058
6591
  "The gate changed task-owned files or another writer modified this worktree. "
6059
6592
  "Review the changes and rerun commit-push; no files were staged or restored."
6060
6593
  )
6061
- if manifest:
6062
- manifest = _require_task_context(repo, cfg, args.task_id)
6063
-
6064
- if args.require_jenkins:
6065
- cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
6066
-
6067
- if args.require_matrix and mode != "verify":
6068
- cmd_check_matrix(argparse.Namespace(repo=str(repo)))
6594
+ manifest = _require_task_context(repo, cfg, args.task_id)
6595
+ _require_current_writer(manifest, args)
6596
+ _require_approved_review(repo, cfg, manifest)
6069
6597
 
6070
6598
  if _task_content_fingerprint(repo, cfg, manifest) != after_gate:
6071
6599
  raise APError(
@@ -6073,30 +6601,28 @@ def _cmd_commit_push_locked(
6073
6601
  "no files were staged or restored."
6074
6602
  )
6075
6603
 
6076
- if mode == "dev":
6077
- dev_verification = args.verification or [
6078
- "light-gate only",
6079
- "configured CI/Jenkins not verified in dev mode",
6080
- "target environment not verified in dev mode",
6081
- ]
6082
- _record_commit_push_closure(
6083
- repo,
6084
- args,
6085
- commit="generated by this commit-push run",
6086
- jenkins=args.jenkins_build or "not verified in dev mode",
6087
- target_env=args.target_env or "not verified in dev mode",
6088
- verification=dev_verification,
6089
- result=args.result or "DEV-CLOSED",
6090
- follow_up=args.follow_up or "Run verify mode when configured CI/Jenkins and target-environment evidence is required.",
6091
- structure_check=args.structure_check or structure_check_status,
6092
- )
6604
+ dev_verification = args.verification or [
6605
+ "fast changed-scope gate passed",
6606
+ "project commit/push hooks remain enabled",
6607
+ ]
6608
+ _record_commit_push_closure(
6609
+ repo,
6610
+ args,
6611
+ commit="generated by this commit-push run",
6612
+ jenkins="owner-managed after push",
6613
+ target_env="owner-managed acceptance",
6614
+ verification=dev_verification,
6615
+ result=args.result or "DEV-CLOSED",
6616
+ follow_up=args.follow_up or "Complete the push stage with task-integrate; do not wait for Jenkins.",
6617
+ structure_check=args.structure_check or structure_check_status,
6618
+ )
6093
6619
 
6094
- protected = set(manifest.get("initial_untracked") or []) if manifest else set()
6095
- if manifest:
6096
- _cleanup_generated_noise(repo, protected_paths=protected)
6620
+ protected = set(manifest.get("initial_untracked") or [])
6621
+ _cleanup_generated_noise(repo, protected_paths=protected)
6097
6622
  pre_stage_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
6098
- if manifest:
6099
- manifest = _require_task_context(repo, cfg, args.task_id)
6623
+ manifest = _require_task_context(repo, cfg, args.task_id)
6624
+ _require_current_writer(manifest, args)
6625
+ _require_approved_review(repo, cfg, manifest)
6100
6626
  if _task_content_fingerprint(repo, cfg, manifest) != pre_stage_fingerprint:
6101
6627
  raise APError("Task-owned files changed immediately before staging; refusing to commit.")
6102
6628
  task_paths = _task_commit_paths(repo)
@@ -6108,107 +6634,10 @@ def _cmd_commit_push_locked(
6108
6634
  raise APError(
6109
6635
  "Task-owned files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged)
6110
6636
  )
6111
- if manifest:
6112
- manifest = _require_task_context(repo, cfg, args.task_id)
6637
+ manifest = _require_task_context(repo, cfg, args.task_id)
6113
6638
 
6114
6639
  committed_sha = _commit_exact_index(repo, msg)
6115
6640
  _push_current_task(repo, manifest, committed_sha)
6116
-
6117
- if mode == "verify":
6118
- verification_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
6119
- if jenkins_required:
6120
- jenkins_build = cmd_verify_jenkins_build(
6121
- argparse.Namespace(
6122
- repo=str(repo),
6123
- git_ref="HEAD",
6124
- job_name=args.job_name,
6125
- job_url=args.job_url,
6126
- multibranch_root_job=args.multibranch_root_job,
6127
- branch_name=args.branch_name,
6128
- build_number=args.build_number,
6129
- max_builds=args.max_builds,
6130
- timeout_sec=args.timeout_sec,
6131
- poll_sec=args.poll_sec,
6132
- allow_no_deploy=args.allow_no_deploy,
6133
- )
6134
- )
6135
- else:
6136
- jenkins_build = "skipped by verification.jenkins_required=false"
6137
-
6138
- if target_env_required:
6139
- target_summary = cmd_verify_target(
6140
- argparse.Namespace(
6141
- repo=str(repo),
6142
- backend_path=args.backend_path,
6143
- frontend_path=args.frontend_path,
6144
- backend_basic_auth=args.backend_basic_auth,
6145
- frontend_basic_auth=args.frontend_basic_auth,
6146
- )
6147
- )
6148
- else:
6149
- target_summary = "skipped by verification.target_env_required=false"
6150
- if args.require_matrix:
6151
- cmd_check_matrix(argparse.Namespace(repo=str(repo)))
6152
- verification = args.verification
6153
- if not verification:
6154
- verification = []
6155
- if jenkins_required:
6156
- verification.append(f"CI/Jenkins build verified: {jenkins_build or 'verified by git-ref HEAD'}")
6157
- else:
6158
- verification.append("CI/Jenkins verification skipped by verification.jenkins_required=false")
6159
- if target_env_required:
6160
- verification.append(f"Target verification: {target_summary}")
6161
- else:
6162
- verification.append("Target verification skipped by verification.target_env_required=false")
6163
- if _task_content_fingerprint(repo, cfg, manifest) != verification_fingerprint:
6164
- raise APError(
6165
- "Verification changed task-owned files. Review them and rerun commit-push before "
6166
- "recording the verification closure."
6167
- )
6168
- if manifest:
6169
- manifest = _require_task_context(repo, cfg, args.task_id)
6170
- _record_commit_push_closure(
6171
- repo,
6172
- args,
6173
- commit="HEAD",
6174
- jenkins=args.jenkins_build or jenkins_build or "verified by git-ref HEAD",
6175
- target_env=args.target_env
6176
- or (str(target_cfg.get("name") or "").strip() if target_env_required else "skipped by verification.target_env_required=false"),
6177
- verification=verification,
6178
- result=args.result or "PASS",
6179
- follow_up=args.follow_up or "none",
6180
- structure_check=args.structure_check or structure_check_status,
6181
- )
6182
- if manifest:
6183
- _cleanup_generated_noise(repo, protected_paths=protected)
6184
- closure_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
6185
- if manifest:
6186
- manifest = _require_task_context(repo, cfg, args.task_id)
6187
- if _task_content_fingerprint(repo, cfg, manifest) != closure_fingerprint:
6188
- raise APError("Task-owned files changed immediately before staging verification closure.")
6189
- closure_paths = _task_commit_paths(repo)
6190
- closure_staged = _stage_exact_paths(repo, closure_paths)
6191
- if closure_staged:
6192
- unstaged = _unstaged_task_paths(repo)
6193
- if unstaged:
6194
- raise APError(
6195
- "Task-owned files changed while staging verification closure:\n- "
6196
- + "\n- ".join(unstaged)
6197
- )
6198
- closure_sha = _commit_exact_index(repo, f"{args.task_id}: record verification closure [skip ci]")
6199
- _push_current_task(repo, manifest, closure_sha)
6200
- elif args.record_closure and mode != "dev":
6201
- _record_commit_push_closure(
6202
- repo,
6203
- args,
6204
- commit="HEAD",
6205
- jenkins=args.jenkins_build or "TODO",
6206
- target_env=args.target_env or str(target_cfg.get("name") or "").strip(),
6207
- verification=args.verification or [],
6208
- result=args.result or "PARTIAL",
6209
- follow_up=args.follow_up or "none",
6210
- structure_check=args.structure_check or structure_check_status,
6211
- )
6212
6641
  print(f"[commit-push] OK - profile={plan['profile']} mode={mode} scope={plan['selected_scope']}")
6213
6642
 
6214
6643
 
@@ -6217,7 +6646,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
6217
6646
  ensure_git_repo(repo)
6218
6647
  cfg = _load_cfg(repo)
6219
6648
  manifest = _require_task_context(repo, cfg, args.task_id)
6220
- lock_name = f"task-{_validate_task_id(args.task_id)}" if manifest else "legacy-commit"
6649
+ _require_current_writer(manifest, args)
6650
+ lock_name = f"task-{_validate_task_id(args.task_id)}"
6221
6651
  timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
6222
6652
  with _repo_lock(repo, lock_name, timeout_s=timeout_s):
6223
6653
  _cmd_commit_push_locked(args, repo, cfg, manifest)
@@ -6272,7 +6702,7 @@ def main(argv: Optional[List[str]] = None) -> int:
6272
6702
  s = sp.add_parser("impact")
6273
6703
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
6274
6704
  s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
6275
- s.add_argument("--mode", choices=["dev", "verify"], default="")
6705
+ s.add_argument("--mode", choices=["dev"], default="")
6276
6706
  s.add_argument("--base")
6277
6707
  s.add_argument("--json", action="store_true")
6278
6708
  s.set_defaults(func=cmd_impact)
@@ -6280,8 +6710,11 @@ def main(argv: Optional[List[str]] = None) -> int:
6280
6710
  s = sp.add_parser("classify")
6281
6711
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
6282
6712
  s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
6283
- s.add_argument("--mode", choices=["dev", "verify"], default="")
6713
+ s.add_argument("--mode", choices=["dev"], default="")
6284
6714
  s.add_argument("--base")
6715
+ s.add_argument("--planned-path", action="append")
6716
+ s.add_argument("--intent")
6717
+ s.add_argument("--intent-file")
6285
6718
  s.add_argument("--json", action="store_true")
6286
6719
  s.set_defaults(func=cmd_classify)
6287
6720
 
@@ -6309,9 +6742,9 @@ def main(argv: Optional[List[str]] = None) -> int:
6309
6742
  s.set_defaults(func=cmd_docs_ledger_archive)
6310
6743
 
6311
6744
  s = sp.add_parser("light-gate")
6312
- s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
6745
+ s.add_argument("--scope", choices=["auto", "changed"], default="")
6313
6746
  s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
6314
- s.add_argument("--mode", choices=["dev", "verify"], default="")
6747
+ s.add_argument("--mode", choices=["dev"], default="")
6315
6748
  s.add_argument("--base")
6316
6749
  s.add_argument("--explain", action="store_true")
6317
6750
  s.set_defaults(func=cmd_light_gate)
@@ -6378,6 +6811,9 @@ def main(argv: Optional[List[str]] = None) -> int:
6378
6811
  s.add_argument("--remote")
6379
6812
  s.add_argument("--worktree-root")
6380
6813
  s.add_argument("--owner")
6814
+ s.add_argument("--writer")
6815
+ s.add_argument("--owned-path", action="append")
6816
+ s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
6381
6817
  s.add_argument("--no-fetch", action="store_true")
6382
6818
  s.set_defaults(func=cmd_task_start)
6383
6819
 
@@ -6390,10 +6826,30 @@ def main(argv: Optional[List[str]] = None) -> int:
6390
6826
  s.add_argument("task_id")
6391
6827
  s.set_defaults(func=cmd_task_submodule_sync)
6392
6828
 
6829
+ s = sp.add_parser("task-review")
6830
+ s.add_argument("task_id")
6831
+ s.add_argument("--verdict", choices=["approved", "changes-requested"], required=True)
6832
+ s.add_argument("--diff-fingerprint", required=True)
6833
+ s.add_argument("--reviewer")
6834
+ s.set_defaults(func=cmd_task_review)
6835
+
6836
+ s = sp.add_parser("task-handoff")
6837
+ s.add_argument("task_id")
6838
+ s.add_argument("--from", dest="from_writer", required=True)
6839
+ s.add_argument("--to", dest="to_writer", required=True)
6840
+ s.add_argument("--generation", type=int)
6841
+ s.set_defaults(func=cmd_task_handoff)
6842
+
6843
+ s = sp.add_parser("task-resume")
6844
+ s.add_argument("task_id")
6845
+ s.add_argument("--writer")
6846
+ s.set_defaults(func=cmd_task_resume)
6847
+
6393
6848
  s = sp.add_parser("task-integrate")
6394
6849
  s.add_argument("task_id")
6395
6850
  s.add_argument("--keep-worktree", action="store_true")
6396
6851
  s.add_argument("--keep-remote", action="store_true")
6852
+ s.add_argument("--writer")
6397
6853
  s.set_defaults(func=cmd_task_integrate)
6398
6854
 
6399
6855
  s = sp.add_parser("task-finish")
@@ -6409,28 +6865,8 @@ def main(argv: Optional[List[str]] = None) -> int:
6409
6865
  s.add_argument("task_id")
6410
6866
  s.add_argument("--title")
6411
6867
  s.add_argument("--msg", required=True)
6412
- s.add_argument("--mode", choices=["dev", "verify"])
6868
+ s.add_argument("--mode", choices=["dev"])
6413
6869
  s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES))
6414
- s.add_argument("--require-light-gate", action="store_true")
6415
- s.add_argument("--require-runtime-health", action="store_true")
6416
- s.add_argument("--require-jenkins", action="store_true")
6417
- s.add_argument("--require-matrix", action="store_true")
6418
- s.add_argument("--record-closure", action="store_true")
6419
- s.add_argument("--job-name")
6420
- s.add_argument("--job-url")
6421
- s.add_argument("--multibranch-root-job")
6422
- s.add_argument("--branch-name")
6423
- s.add_argument("--build-number", type=int)
6424
- s.add_argument("--max-builds", type=int, default=20)
6425
- s.add_argument("--timeout-sec", type=int, default=300)
6426
- s.add_argument("--poll-sec", type=int, default=5)
6427
- s.add_argument("--allow-no-deploy", action="store_true")
6428
- s.add_argument("--backend-path", action="append")
6429
- s.add_argument("--frontend-path", action="append")
6430
- s.add_argument("--backend-basic-auth", action="store_true")
6431
- s.add_argument("--frontend-basic-auth", action="store_true")
6432
- s.add_argument("--ci-build", "--jenkins-build", dest="jenkins_build", metavar="CI_BUILD")
6433
- s.add_argument("--target-env")
6434
6870
  s.add_argument("--verification", action="append")
6435
6871
  s.add_argument("--structure-check")
6436
6872
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"])
@@ -6438,6 +6874,7 @@ def main(argv: Optional[List[str]] = None) -> int:
6438
6874
  s.add_argument("--initial-commit")
6439
6875
  s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
6440
6876
  s.add_argument("--fix-commit")
6877
+ s.add_argument("--writer")
6441
6878
  s.set_defaults(func=cmd_commit_push)
6442
6879
 
6443
6880
  try: