@elvis1513/auto-coding-skill 3.0.4 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,7 +49,7 @@ _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
49
49
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
50
50
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
51
51
  "schema_version": 1,
52
- "managed_versions": {"agents": "3.0.3", "engineering": "3.0.3"},
52
+ "managed_versions": {"agents": "4.1.0", "engineering": "4.1.0"},
53
53
  "known_official_engineering_body_sha256": [
54
54
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
55
55
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -170,10 +170,12 @@ def _append_jsonl(path: Path, payload: dict) -> None:
170
170
 
171
171
  def _evidence_log_path(repo: Path, cfg: dict) -> Path:
172
172
  manifest = _active_task_manifest(repo)
173
- if manifest:
174
- docs_cfg = cfg.get("docs") or {}
173
+ docs_cfg = cfg.get("docs") or {}
174
+ if manifest and _bool_config(docs_cfg.get("track_task_evidence"), False):
175
175
  task_dir = _text(docs_cfg.get("task_evidence_dir")) or "docs/tasks/evidence"
176
176
  return Path(repo, task_dir, f"{manifest['task_id']}.jsonl")
177
+ if _bool_config(docs_cfg.get("track_evidence"), False) and _text(docs_cfg.get("evidence_log")):
178
+ return Path(repo, _text(docs_cfg.get("evidence_log")))
177
179
  return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
178
180
 
179
181
 
@@ -573,14 +575,7 @@ def _copy_conflicts(src: Path, dst: Path) -> list[Path]:
573
575
  return conflicts
574
576
 
575
577
 
576
- _MANAGED_EXTRA_CLEANUP_DIRS = {
577
- Path("data/templates/bridges"),
578
- }
579
-
580
- _CORE_DOC_TEMPLATES = [
581
- Path("tasks/taskbook.md"),
582
- Path("tasks/closure-log.md"),
583
- ]
578
+ _CORE_DOC_TEMPLATES: list[Path] = []
584
579
 
585
580
 
586
581
  def _inferred_gate_commands(repo: Path) -> dict[str, str]:
@@ -595,7 +590,7 @@ def _inferred_gate_commands(repo: Path) -> dict[str, str]:
595
590
  if not isinstance(scripts, dict):
596
591
  return {}
597
592
  if isinstance(scripts.get("test:changed"), str) and scripts["test:changed"].strip():
598
- return {"gate_changed": "npm run test:changed"}
593
+ return {"project_fast": "npm run test:changed"}
599
594
  return {}
600
595
 
601
596
 
@@ -635,17 +630,25 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
635
630
  if _text(workflow_cfg.get("completion")).lower() != "push":
636
631
  workflow_cfg["completion"] = "push"
637
632
  changed.append("workflow.completion")
633
+ if _text(workflow_cfg.get("skill_version")) != "4.1.0":
634
+ workflow_cfg["skill_version"] = "4.1.0"
635
+ changed.append("workflow.skill_version")
638
636
 
639
637
  commands_cfg = cfg.setdefault("commands", {})
640
638
  if not isinstance(commands_cfg, dict):
641
639
  commands_cfg = {}
642
640
  cfg["commands"] = commands_cfg
643
641
  current_changed_gate = _text(commands_cfg.get("gate_changed"))
644
- if current_changed_gate in {"", "npm test"}:
645
- replacement = _inferred_gate_commands(repo).get("gate_changed", "git diff --check")
646
- if current_changed_gate != replacement:
647
- commands_cfg["gate_changed"] = replacement
648
- changed.append("commands.gate_changed")
642
+ project_fast = _text(commands_cfg.get("project_fast"))
643
+ inferred_fast = _inferred_gate_commands(repo).get("project_fast", "")
644
+ if not project_fast:
645
+ replacement = (
646
+ current_changed_gate
647
+ if current_changed_gate and current_changed_gate not in {"git diff --check", "npm test"}
648
+ else inferred_fast
649
+ )
650
+ commands_cfg["project_fast"] = replacement
651
+ changed.append("commands.project_fast")
649
652
 
650
653
  gate_cfg = cfg.setdefault("gate", {})
651
654
  if not isinstance(gate_cfg, dict):
@@ -662,21 +665,52 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
662
665
  del gate_cfg["full_on"]
663
666
  changed.append("gate.full_on")
664
667
  raw_rules = gate_cfg.get("rules")
668
+ risk_cfg = cfg.setdefault("risk", {})
669
+ if not isinstance(risk_cfg, dict):
670
+ risk_cfg = {}
671
+ cfg["risk"] = risk_cfg
672
+ risk_rules = risk_cfg.setdefault("rules", [])
673
+ if not isinstance(risk_rules, list):
674
+ risk_rules = []
675
+ risk_cfg["rules"] = risk_rules
676
+ validation_cfg = cfg.setdefault("validation", {})
677
+ if not isinstance(validation_cfg, dict):
678
+ validation_cfg = {}
679
+ cfg["validation"] = validation_cfg
680
+ if _text(validation_cfg.get("on_unmapped")).lower() != "error":
681
+ validation_cfg["on_unmapped"] = "error"
682
+ changed.append("validation.on_unmapped")
683
+ validation_routes = validation_cfg.setdefault("routes", [])
684
+ if not isinstance(validation_routes, list):
685
+ validation_routes = []
686
+ validation_cfg["routes"] = validation_routes
665
687
  if isinstance(raw_rules, list):
666
688
  migrated_rules: list = []
667
689
  for index, rule in enumerate(raw_rules):
668
690
  if not isinstance(rule, dict):
669
691
  migrated_rules.append(rule)
670
692
  continue
671
- migrated_rule = dict(rule)
672
- for legacy_key in ["scope", "commands"]:
673
- if legacy_key in migrated_rule:
674
- del migrated_rule[legacy_key]
675
- changed.append(f"gate.rules[{index}].{legacy_key}")
676
- if migrated_rule:
677
- migrated_rules.append(migrated_rule)
693
+ migrated_rule = {
694
+ key: value
695
+ for key, value in rule.items()
696
+ if key in {"name", "paths", "profile", "review", "design"}
697
+ }
698
+ if migrated_rule and migrated_rule not in risk_rules:
699
+ risk_rules.append(migrated_rule)
700
+ changed.append(f"risk.rules[{len(risk_rules) - 1}]")
701
+ legacy_commands = _as_list(rule.get("commands"))
702
+ if legacy_commands and _as_list(rule.get("paths")):
703
+ route = {
704
+ "name": _text(rule.get("name")) or f"migrated-{index + 1}",
705
+ "paths": _as_list(rule.get("paths")),
706
+ "commands": [_command_name(item) for item in legacy_commands if _command_name(item)],
707
+ }
708
+ if route["commands"] and route not in validation_routes:
709
+ validation_routes.append(route)
710
+ changed.append(f"validation.routes[{len(validation_routes) - 1}]")
678
711
  if migrated_rules != raw_rules:
679
- gate_cfg["rules"] = migrated_rules
712
+ gate_cfg["rules"] = []
713
+ changed.append("gate.rules")
680
714
 
681
715
  concurrency_cfg = cfg.setdefault("concurrency", {})
682
716
  if not isinstance(concurrency_cfg, dict):
@@ -773,8 +807,19 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
773
807
  source_root = _find_skill_asset_root(repo)
774
808
  templates = source_root / "data" / "templates"
775
809
  template_engineering = templates / "ENGINEERING.md"
810
+ template_agents = templates / "bridges" / "AGENTS.md"
776
811
  actions: list[dict] = []
777
812
 
813
+ registry = _task_state_root(repo) / "tasks"
814
+ active_manifests = sorted(registry.glob("*.json")) if registry.exists() else []
815
+ if active_manifests:
816
+ names = ", ".join(path.name for path in active_manifests)
817
+ raise APError(
818
+ "Upgrade refused because registered tasks are still active: "
819
+ f"{names}. Finish, integrate, or clean them with the installed runtime first; "
820
+ "workflow semantics must not change mid-task."
821
+ )
822
+
778
823
  def add_action(kind: str, path: Path, action: str, detail: str = "") -> None:
779
824
  actions.append({
780
825
  "kind": kind,
@@ -787,7 +832,15 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
787
832
  # are safe migration inputs; every remaining match is project-owned and must
788
833
  # be handled explicitly instead of being overwritten by a partial upgrade.
789
834
  workflow_plans = _workflow_policy_plans(repo)
790
- workflow_issues = [issue for plan in workflow_plans for issue in plan["issues"]]
835
+ # Root AGENTS.md is a whole-file managed bridge in 4.1. Unknown legacy text
836
+ # is archived and replaced, so only ENGINEERING policy conflicts block the
837
+ # upgrade preflight.
838
+ workflow_issues = [
839
+ issue
840
+ for plan in workflow_plans
841
+ if plan["path"] == "docs/ENGINEERING.md"
842
+ for issue in plan["issues"]
843
+ ]
791
844
  if workflow_issues:
792
845
  raise APError(
793
846
  "Upgrade preflight found unknown workflow policy conflicts; no files were written:\n- "
@@ -802,6 +855,35 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
802
855
  body_start = frontmatter[1] if frontmatter else 0
803
856
  engineering_plan["output"] = current[:body_start] + template_body
804
857
 
858
+ section_migrations = [
859
+ item
860
+ for item in engineering_plan.get("migrations") or []
861
+ if _text(item.get("id")).startswith("engineering-section-")
862
+ ]
863
+ if section_migrations and engineering_plan.get("original"):
864
+ version_match = re.search(
865
+ r"auto-coding-skill:managed-workflow:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)",
866
+ template_engineering.read_text(encoding="utf-8"),
867
+ )
868
+ version = version_match.group(1) if version_match else "current"
869
+ archive_header = (
870
+ f"# Archived ENGINEERING.md before auto-coding-skill {version} docs convergence\n\n"
871
+ "This file is historical and non-authoritative. Known duplicate workflow sections\n"
872
+ "were removed from docs/ENGINEERING.md. Move any still-current project facts into\n"
873
+ "docs/ENGINEERING.md project-fact sections or docs/project/.\n\n---\n\n"
874
+ )
875
+ archive_content = archive_header + engineering_plan["original"]
876
+ archive_dir = repo / "docs" / "archive" / "workflow"
877
+ archive = archive_dir / f"ENGINEERING.pre-{version}.md"
878
+ if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
879
+ digest = hashlib.sha256(engineering_plan["original"].encode("utf-8")).hexdigest()[:12]
880
+ archive = archive_dir / f"ENGINEERING.pre-{version}-{digest}.md"
881
+ if not archive.exists():
882
+ add_action("policy", archive, "archive", "before duplicate workflow section cleanup")
883
+ if write:
884
+ archive.parent.mkdir(parents=True, exist_ok=True)
885
+ archive.write_text(archive_content, encoding="utf-8")
886
+
805
887
  tool_files = [
806
888
  (
807
889
  source_root / "data" / "templates" / "tools" / "ap.py",
@@ -840,26 +922,39 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
840
922
  for dst in _iter_files(project_skill):
841
923
  rel = dst.relative_to(project_skill)
842
924
  if not (source_root / rel).exists():
843
- if rel.parts[:3] == ("data", "templates", "docs"):
844
- continue
845
- if rel.parent in _MANAGED_EXTRA_CLEANUP_DIRS:
846
- add_action("skill", dst, "delete", "stale managed template")
847
- if write:
848
- dst.unlink()
849
- else:
850
- add_action("skill", dst, "extra", "present only in project copy")
925
+ add_action("skill", dst, "delete", "stale file in fully managed Skill copy")
926
+ if write:
927
+ dst.unlink()
851
928
  else:
852
929
  add_action("skill", project_skill, "create", "install runtime required by the project launcher")
853
930
  if write:
854
931
  copy_tree(source_root, project_skill)
855
932
 
856
- agents_plan = workflow_plan_by_path["AGENTS.md"]
857
933
  agents_path = repo / "AGENTS.md"
858
- if agents_plan["output"] != agents_plan["original"]:
859
- migrated = ", ".join(item["id"] for item in agents_plan["migrations"])
860
- add_action("policy", agents_path, "migrate", migrated)
934
+ canonical_agents = template_agents.read_text(encoding="utf-8") if template_agents.exists() else ""
935
+ current_agents = agents_path.read_text(encoding="utf-8") if agents_path.exists() else ""
936
+ if canonical_agents and current_agents != canonical_agents:
937
+ if current_agents:
938
+ archive_dir = repo / "docs" / "archive" / "workflow"
939
+ archive_header = (
940
+ "# Archived AGENTS.md before auto-coding-skill 4.1.0\n\n"
941
+ "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
942
+ "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
943
+ "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
944
+ )
945
+ archive_content = archive_header + current_agents
946
+ archive = archive_dir / "AGENTS.pre-4.1.0.md"
947
+ if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
948
+ digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
949
+ archive = archive_dir / f"AGENTS.pre-4.1.0-{digest}.md"
950
+ if not archive.exists():
951
+ add_action("policy", archive, "archive", "historical and non-authoritative")
952
+ if write:
953
+ archive.parent.mkdir(parents=True, exist_ok=True)
954
+ archive.write_text(archive_content, encoding="utf-8")
955
+ add_action("policy", agents_path, "replace", "fully managed canonical AGENTS.md")
861
956
  if write:
862
- agents_path.write_text(agents_plan["output"], encoding="utf-8")
957
+ agents_path.write_text(canonical_agents, encoding="utf-8")
863
958
 
864
959
  docs_template = templates / "docs"
865
960
  for rel in _CORE_DOC_TEMPLATES:
@@ -879,6 +974,10 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
879
974
  engineering = repo / "docs" / "ENGINEERING.md"
880
975
  if engineering.exists() and template_engineering.exists():
881
976
  planned_engineering = engineering_plan["output"] or engineering.read_text(encoding="utf-8")
977
+ planned_engineering = _sync_managed_workflow_text(
978
+ planned_engineering,
979
+ template_engineering.read_text(encoding="utf-8"),
980
+ )
882
981
  current_cfg, body = _parse_frontmatter_markdown_text(planned_engineering, engineering)
883
982
  template_cfg, _ = _read_frontmatter_markdown(template_engineering)
884
983
  merged_cfg = json.loads(json.dumps(current_cfg))
@@ -1174,7 +1273,7 @@ def _load_workflow_migration_policy(repo: Path) -> dict:
1174
1273
  for index, fragment in enumerate(policy["known_official_fragments"]):
1175
1274
  if not isinstance(fragment, dict):
1176
1275
  raise APError(f"Workflow migration policy fragment[{index}] must be an object")
1177
- if fragment.get("match") not in {"exact-line", "exact-block"}:
1276
+ if fragment.get("match") not in {"exact-line", "exact-block", "heading-section"}:
1178
1277
  raise APError(f"Workflow migration policy fragment[{index}] has invalid match mode")
1179
1278
  if not _text(fragment.get("id")) or not isinstance(fragment.get("paths"), list):
1180
1279
  raise APError(f"Workflow migration policy fragment[{index}] is incomplete")
@@ -1243,6 +1342,30 @@ def _managed_document_span(text: str, kind: str, rel: str) -> Optional[tuple[int
1243
1342
  return starts[0].start(), ends[0].end()
1244
1343
 
1245
1344
 
1345
+ def _sync_managed_workflow_text(current: str, template: str) -> str:
1346
+ """Install the canonical managed workflow while preserving project facts."""
1347
+ template_span = _managed_document_span(template, "workflow", "template ENGINEERING.md")
1348
+ if not template_span:
1349
+ raise APError("Packaged ENGINEERING template has no managed workflow block")
1350
+ block = template[template_span[0]:template_span[1]]
1351
+ current_span = _managed_document_span(current, "workflow", "docs/ENGINEERING.md")
1352
+ if current_span:
1353
+ return current[:current_span[0]] + block + current[current_span[1]:]
1354
+
1355
+ frontmatter = _frontmatter_span(current, "docs/ENGINEERING.md")
1356
+ body_start = frontmatter[1] if frontmatter else 0
1357
+ body = current[body_start:]
1358
+ heading = re.search(r"^# Engineering Workflow[^\n]*(?:\n|$)", body, flags=re.MULTILINE)
1359
+ insertion = body_start + (heading.end() if heading else 0)
1360
+ before = current[:insertion]
1361
+ after = current[insertion:]
1362
+ if before and not before.endswith("\n"):
1363
+ before += "\n"
1364
+ if after and not after.startswith("\n"):
1365
+ after = "\n" + after
1366
+ return before + block + after
1367
+
1368
+
1246
1369
  def _frontmatter_span(text: str, rel: str) -> Optional[tuple[int, int]]:
1247
1370
  if not text.startswith("---\n"):
1248
1371
  return None
@@ -1265,6 +1388,28 @@ def _known_fragment_spans(
1265
1388
  replacement = str(fragment.get("replacement") or "")
1266
1389
  match_mode = _text(fragment.get("match"))
1267
1390
  expected = str(fragment.get("text") or "").replace("\r\n", "\n")
1391
+ if fragment.get("match") == "heading-section":
1392
+ lines = visible.splitlines(keepends=True)
1393
+ offsets: list[int] = []
1394
+ cursor = 0
1395
+ for line in lines:
1396
+ offsets.append(cursor)
1397
+ cursor += len(line)
1398
+ for index, line in enumerate(lines):
1399
+ heading = re.match(r"^\s*(#{1,6})\s+(.+?)\s*#*\s*$", line.rstrip("\n"))
1400
+ if not heading or heading.group(2).strip() != expected.strip():
1401
+ continue
1402
+ level = len(heading.group(1))
1403
+ end_index = index + 1
1404
+ while end_index < len(lines):
1405
+ next_heading = re.match(r"^\s*(#{1,6})\s+", lines[end_index])
1406
+ if next_heading and len(next_heading.group(1)) <= level:
1407
+ break
1408
+ end_index += 1
1409
+ end = offsets[end_index] if end_index < len(offsets) else len(visible)
1410
+ start = offsets[index]
1411
+ found.append((start, end, fragment_id, visible.count("\n", 0, start) + 1, replacement, match_mode))
1412
+ continue
1268
1413
  if fragment.get("match") == "exact-line":
1269
1414
  cursor = 0
1270
1415
  for line in visible.splitlines(keepends=True):
@@ -1281,7 +1426,17 @@ def _known_fragment_spans(
1281
1426
  end = start + len(expected)
1282
1427
  found.append((start, end, fragment_id, visible.count("\n", 0, start) + 1, replacement, match_mode))
1283
1428
  cursor = end
1284
- return found
1429
+ section_spans = [
1430
+ (start, end)
1431
+ for start, end, _, _, _, match_mode in found
1432
+ if match_mode == "heading-section"
1433
+ ]
1434
+ return [
1435
+ item
1436
+ for item in found
1437
+ if item[5] == "heading-section"
1438
+ or not any(start <= item[0] and item[1] <= end for start, end in section_spans)
1439
+ ]
1285
1440
 
1286
1441
 
1287
1442
  def _workflow_document_plan(repo: Path, rel: str, policy: dict) -> dict:
@@ -1607,11 +1762,14 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1607
1762
  "owned_paths for an in-flight task. Finish or clean it with the previously installed "
1608
1763
  "runtime before running autocoding sync, or restore the 3.0.0 runtime."
1609
1764
  )
1765
+ execution_mode = _text(manifest.get("execution_mode")).lower() or "isolated"
1766
+ if execution_mode not in {"direct", "isolated"}:
1767
+ raise APError(f"Task {task_id} has an invalid execution_mode: {execution_mode!r}")
1610
1768
  task_uuid = _text(manifest.get("task_uuid"))
1611
1769
  if not re.fullmatch(r"[0-9a-f]{32}", task_uuid):
1612
1770
  raise APError(f"Invalid task manifest UUID for {task_id}; refusing Git operations.")
1613
1771
  task_branch = _text(manifest.get("task_branch"))
1614
- if not task_branch.endswith(f"/{task_id}") or run(
1772
+ if (execution_mode == "isolated" and not task_branch.endswith(f"/{task_id}")) or run(
1615
1773
  ["git", "check-ref-format", "--branch", task_branch],
1616
1774
  cwd=repo,
1617
1775
  check=False,
@@ -1638,7 +1796,11 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1638
1796
  raise APError(f"Task manifest paths must be absolute for {task_id}.")
1639
1797
  worktree = worktree.resolve()
1640
1798
  control = control.resolve()
1641
- if worktree == control or control in worktree.parents or worktree in control.parents:
1799
+ if execution_mode == "direct" and worktree != control:
1800
+ raise APError(f"Direct task {task_id} must use its control checkout.")
1801
+ if execution_mode == "isolated" and (
1802
+ worktree == control or control in worktree.parents or worktree in control.parents
1803
+ ):
1642
1804
  raise APError(
1643
1805
  f"Task worktree must be outside its control checkout for {task_id}: {worktree}"
1644
1806
  )
@@ -1669,6 +1831,9 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1669
1831
  "changes-requested",
1670
1832
  }:
1671
1833
  raise APError(f"Task {task_id} has an invalid review contract.")
1834
+ review_required = manifest.get("review_required", schema < 3)
1835
+ if not isinstance(review_required, bool):
1836
+ raise APError(f"Task {task_id} has an invalid review_required flag.")
1672
1837
  return manifest
1673
1838
 
1674
1839
 
@@ -1767,12 +1932,12 @@ def _task_runtime_paths(repo: Path, cfg: dict, manifest: Optional[dict]) -> set[
1767
1932
  paths = {
1768
1933
  _text(gate_cfg.get("profile_log")) or ".local/auto-coding-skill/gate-profile.jsonl",
1769
1934
  }
1770
- if manifest:
1935
+ if manifest and _bool_config(docs_cfg.get("track_task_evidence"), False):
1771
1936
  task_id = _validate_task_id(_text(manifest.get("task_id")))
1772
1937
  evidence_dir = _text(docs_cfg.get("task_evidence_dir")) or "docs/tasks/evidence"
1773
1938
  paths.add(f"{evidence_dir.rstrip('/')}/{task_id}.jsonl")
1774
1939
  else:
1775
- paths.add(_text(docs_cfg.get("evidence_log")) or "docs/tasks/evidence.jsonl")
1940
+ paths.add(".local/auto-coding-skill/evidence.jsonl")
1776
1941
  normalized: set[str] = set()
1777
1942
  for path in paths:
1778
1943
  value = path.replace("\\", "/")
@@ -1894,7 +2059,39 @@ def _path_is_owned(path: str, owned_paths: list[str]) -> bool:
1894
2059
  )
1895
2060
 
1896
2061
 
2062
+ def _owned_paths_overlap(left: list[str], right: list[str]) -> bool:
2063
+ for first in left:
2064
+ first = _normalize_owned_path(first)
2065
+ for second in right:
2066
+ second = _normalize_owned_path(second)
2067
+ if (
2068
+ first == "."
2069
+ or second == "."
2070
+ or first == second
2071
+ or first.startswith(second.rstrip("/") + "/")
2072
+ or second.startswith(first.rstrip("/") + "/")
2073
+ ):
2074
+ return True
2075
+ return False
2076
+
2077
+
2078
+ _TERMINAL_LEDGER_PATTERNS = [
2079
+ "docs/tasks/taskbook.md",
2080
+ "docs/tasks/closure-log.md",
2081
+ "docs/tasks/archive-index.md",
2082
+ "docs/tasks/archives/**",
2083
+ "docs/tasks/closures/**",
2084
+ "docs/archive/design/**",
2085
+ ]
2086
+
2087
+
2088
+ def _is_terminal_ledger_maintenance(paths: list[str]) -> bool:
2089
+ return bool(paths) and all(_path_matches(path, _TERMINAL_LEDGER_PATTERNS) for path in paths)
2090
+
2091
+
1897
2092
  def _task_managed_paths(cfg: dict, manifest: dict) -> list[str]:
2093
+ if int(manifest.get("schema") or 2) >= 3:
2094
+ return []
1898
2095
  docs_cfg = cfg.get("docs") or {}
1899
2096
  task_id = _validate_task_id(_text(manifest.get("task_id")))
1900
2097
  return sorted(
@@ -2020,6 +2217,8 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
2020
2217
  if unowned:
2021
2218
  raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
2022
2219
  fingerprint = _task_review_fingerprint(repo, manifest)
2220
+ if not bool(manifest.get("review_required", int(manifest.get("schema") or 2) < 3)):
2221
+ return fingerprint
2023
2222
  review = manifest.get("review") or {}
2024
2223
  if _text(review.get("verdict")) != "approved":
2025
2224
  raise APError("Task review must be approved before commit-push or integration.")
@@ -2058,9 +2257,9 @@ def _require_task_context(repo: Path, cfg: dict, task_id: str) -> dict:
2058
2257
  "return to the primary checkout and create or recover the task with task-start."
2059
2258
  )
2060
2259
  raise APError(
2061
- "This project requires an isolated task worktree. "
2260
+ "This checkout has no active task. "
2062
2261
  f"Run `python3 docs/tools/autopipeline/ap.py task-start {task_id}` from the main checkout, "
2063
- "then continue in the returned worktree."
2262
+ "then continue in the current checkout or returned worktree."
2064
2263
  )
2065
2264
  expected_task = _validate_task_id(task_id)
2066
2265
  actual_task = _text(manifest.get("task_id"))
@@ -2289,6 +2488,16 @@ def _gate_cfg(cfg: dict) -> dict:
2289
2488
  return gate_cfg if isinstance(gate_cfg, dict) else {}
2290
2489
 
2291
2490
 
2491
+ def _risk_cfg(cfg: dict) -> dict:
2492
+ value = cfg.get("risk") or {}
2493
+ return value if isinstance(value, dict) else {}
2494
+
2495
+
2496
+ def _validation_cfg(cfg: dict) -> dict:
2497
+ value = cfg.get("validation") or {}
2498
+ return value if isinstance(value, dict) else {}
2499
+
2500
+
2292
2501
  def _as_list(value: object) -> list:
2293
2502
  if value is None:
2294
2503
  return []
@@ -2330,8 +2539,8 @@ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str
2330
2539
  executed.append(name)
2331
2540
  else:
2332
2541
  missing.append(name)
2333
- if missing and not executed:
2334
- raise APError("Gate rule references missing commands: " + ", ".join(missing))
2542
+ if missing:
2543
+ raise APError("Validation route references missing commands: " + ", ".join(missing))
2335
2544
  return executed
2336
2545
 
2337
2546
 
@@ -2457,6 +2666,14 @@ def _gate_rules(gate_cfg: dict) -> list[dict]:
2457
2666
  return [rule for rule in rules if isinstance(rule, dict)]
2458
2667
 
2459
2668
 
2669
+ def _risk_rules(cfg: dict) -> list[dict]:
2670
+ rules = _risk_cfg(cfg).get("rules") or []
2671
+ current = [rule for rule in rules if isinstance(rule, dict)]
2672
+ # Keep reading 3.x gate.rules while projects migrate. They remain planning
2673
+ # metadata only and never execute validation commands.
2674
+ return current or _gate_rules(_gate_cfg(cfg))
2675
+
2676
+
2460
2677
  def _matching_gate_rules(paths: list[str], gate_cfg: dict) -> list[dict]:
2461
2678
  matches = []
2462
2679
  for rule in _gate_rules(gate_cfg):
@@ -2466,6 +2683,106 @@ def _matching_gate_rules(paths: list[str], gate_cfg: dict) -> list[dict]:
2466
2683
  return matches
2467
2684
 
2468
2685
 
2686
+ def _matching_risk_rules(paths: list[str], cfg: dict) -> list[dict]:
2687
+ matches: list[dict] = []
2688
+ for rule in _risk_rules(cfg):
2689
+ patterns = _as_list(rule.get("paths"))
2690
+ if patterns and any(_path_matches(path, patterns) for path in paths):
2691
+ matches.append(rule)
2692
+ return matches
2693
+
2694
+
2695
+ def _validation_routes(cfg: dict) -> list[dict]:
2696
+ routes = _validation_cfg(cfg).get("routes") or []
2697
+ return [route for route in routes if isinstance(route, dict)]
2698
+
2699
+
2700
+ def _validation_route_matches(path: str, route: dict) -> bool:
2701
+ patterns = _as_list(route.get("paths"))
2702
+ excludes = _as_list(route.get("exclude"))
2703
+ return bool(patterns) and _path_matches(path, patterns) and not _path_matches(path, excludes)
2704
+
2705
+
2706
+ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2707
+ """Resolve one deterministic changed-scope validation plan.
2708
+
2709
+ Risk rules deliberately live under ``risk.rules``. Validation routes are a
2710
+ separate execution surface so classification cannot silently turn into an
2711
+ expensive full gate and a documentation check cannot masquerade as code
2712
+ validation.
2713
+ """
2714
+ normalized = _unique_paths(paths)
2715
+ routes = _validation_routes(cfg)
2716
+ command_names: list[str] = []
2717
+ matched_routes: list[str] = []
2718
+ coverage: dict[str, list[str]] = {}
2719
+ unmapped: list[str] = []
2720
+
2721
+ for path in normalized:
2722
+ names: list[str] = []
2723
+ for index, route in enumerate(routes):
2724
+ if not _validation_route_matches(path, route):
2725
+ continue
2726
+ route_name = _text(route.get("name")) or f"route-{index + 1}"
2727
+ names.append(route_name)
2728
+ if route_name not in matched_routes:
2729
+ matched_routes.append(route_name)
2730
+ for command_ref in _as_list(route.get("commands")):
2731
+ command_name = _command_name(command_ref)
2732
+ if command_name and command_name not in command_names:
2733
+ command_names.append(command_name)
2734
+ coverage[path] = names
2735
+ if not names and not _path_matches(path, _DOC_PATH_PATTERNS):
2736
+ unmapped.append(path)
2737
+
2738
+ validation_cfg = _validation_cfg(cfg)
2739
+ compatibility_command = ""
2740
+ if not routes:
2741
+ compatibility_command = _command_name(validation_cfg.get("fallback_command"))
2742
+ if not compatibility_command and _configured_command(cfg, "gate_changed"):
2743
+ compatibility_command = "gate_changed"
2744
+ if compatibility_command:
2745
+ command_names.append(compatibility_command)
2746
+ matched_routes.append("3.x-compatibility-fallback")
2747
+ unmapped = []
2748
+
2749
+ on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
2750
+ if on_unmapped not in {"error", "fallback"}:
2751
+ raise APError("validation.on_unmapped must be error or fallback")
2752
+ if unmapped and on_unmapped == "fallback":
2753
+ fallback = _command_name(validation_cfg.get("fallback_command"))
2754
+ if fallback and fallback not in command_names:
2755
+ command_names.append(fallback)
2756
+ matched_routes.append("unmapped-fallback")
2757
+ unmapped = []
2758
+
2759
+ return {
2760
+ "paths": normalized,
2761
+ "commands": command_names,
2762
+ "matched_routes": matched_routes,
2763
+ "coverage": coverage,
2764
+ "unmapped": unmapped,
2765
+ "docs_only": _docs_only(normalized),
2766
+ "compatibility_fallback": compatibility_command,
2767
+ }
2768
+
2769
+
2770
+ def _validate_validation_plan(cfg: dict, plan: dict) -> None:
2771
+ missing = [name for name in plan["commands"] if not _configured_command(cfg, name)]
2772
+ if missing:
2773
+ raise APError("Validation route references missing commands: " + ", ".join(missing))
2774
+ if plan["unmapped"]:
2775
+ raise APError(
2776
+ "Changed code paths have no validation route:\n- "
2777
+ + "\n- ".join(plan["unmapped"])
2778
+ + "\nAdd validation.routes entries in docs/ENGINEERING.md."
2779
+ )
2780
+ if plan["paths"] and not plan["docs_only"] and not plan["commands"]:
2781
+ raise APError(
2782
+ "Changed code has no fast validation command. Add validation.routes with project-native commands."
2783
+ )
2784
+
2785
+
2469
2786
  def _gate_full_patterns(gate_cfg: dict) -> list:
2470
2787
  full_on = gate_cfg.get("full_on") or {}
2471
2788
  patterns = list(_DEFAULT_FULL_PATH_PATTERNS)
@@ -2518,7 +2835,8 @@ def _impact_summary(
2518
2835
  for path in ignored_runtime_paths
2519
2836
  }
2520
2837
  paths = [path for path in paths if path not in ignored_runtime_paths]
2521
- scope, reasons, matching_rules = _select_gate_scope(cfg, requested_scope, paths)
2838
+ scope, reasons, _ = _select_gate_scope(cfg, requested_scope, paths)
2839
+ matching_rules = _matching_risk_rules(paths, cfg)
2522
2840
  return {
2523
2841
  "requested_scope": requested_scope or _text(_gate_cfg(cfg).get("default_scope")) or "standard",
2524
2842
  "selected_scope": scope,
@@ -2551,31 +2869,54 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
2551
2869
 
2552
2870
 
2553
2871
  def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2554
- # The generic scaffold uses this command as its whole fast gate. The
2555
- # built-in diff check below covers working tree, index, and task commits, so
2556
- # do not execute the narrower configured spelling first as a duplicate.
2557
- if _configured_command(cfg, "gate_changed").strip() == "git diff --check":
2558
- print("[gate] gate_changed is handled by the built-in diff check")
2559
- return []
2560
-
2561
- fallback_commands = ["gate_changed"]
2562
- if _docs_only(paths):
2563
- fallback_commands.append("docs_check")
2564
- command = _run_first_configured_command(repo, cfg, fallback_commands)
2565
- if command:
2566
- return [command]
2567
-
2568
- if _docs_only(paths):
2569
- print("[gate] docs-only change with no changed-gate command configured; running built-in post checks only.")
2872
+ plan = _validation_plan(cfg, paths)
2873
+ _validate_validation_plan(cfg, plan)
2874
+ if not paths:
2875
+ print("[validation] no changed files; no project command needed")
2876
+ return ["no_changes"]
2877
+ if plan["docs_only"] and not plan["commands"]:
2878
+ print("[validation] docs-only change; built-in diff check is sufficient")
2570
2879
  return ["docs_only_builtin"]
2880
+ if plan["compatibility_fallback"]:
2881
+ print(
2882
+ "[validation] WARN: using 3.x compatibility fallback; migrate to validation.routes",
2883
+ file=sys.stderr,
2884
+ )
2885
+ executed = _run_configured_command_list(repo, cfg, plan["commands"])
2886
+ print(
2887
+ "[validation] routes="
2888
+ + (", ".join(plan["matched_routes"]) or "(none)")
2889
+ + " commands="
2890
+ + (", ".join(executed) or "(none)")
2891
+ )
2892
+ return executed
2571
2893
 
2572
- fallback = _run_first_configured_command(repo, cfg, ["quick_test"])
2573
- if fallback:
2574
- return [fallback]
2575
2894
 
2576
- raise APError(
2577
- "Changed gate has no fast command. Add commands.gate_changed or commands.quick_test. "
2578
- "gate.rules commands are never executed by the automatic development flow."
2895
+ def cmd_validation_map_check(args: argparse.Namespace) -> None:
2896
+ repo = Path(args.repo).resolve()
2897
+ cfg = _load_cfg(repo)
2898
+ explicit_paths = list(getattr(args, "path", []) or [])
2899
+ if explicit_paths:
2900
+ paths = _unique_paths(explicit_paths)
2901
+ elif bool(getattr(args, "tracked", False)):
2902
+ paths = _tracked_files(repo)
2903
+ else:
2904
+ paths = _changed_files(repo, _text(getattr(args, "base", "")))
2905
+ plan = _validation_plan(cfg, paths)
2906
+ _validate_validation_plan(cfg, plan)
2907
+ result = {
2908
+ "paths": plan["paths"],
2909
+ "commands": plan["commands"],
2910
+ "matched_routes": plan["matched_routes"],
2911
+ "coverage": plan["coverage"],
2912
+ "docs_only": plan["docs_only"],
2913
+ }
2914
+ if bool(getattr(args, "json", False)):
2915
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2916
+ return
2917
+ print(
2918
+ f"[validation-map] OK paths={len(plan['paths'])} "
2919
+ f"routes={len(plan['matched_routes'])} commands={len(plan['commands'])}"
2579
2920
  )
2580
2921
 
2581
2922
 
@@ -4003,9 +4344,10 @@ def _classification_for_categories(categories: set[str], file_count: int) -> dic
4003
4344
  "needs_dd": bool(
4004
4345
  categories
4005
4346
  & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config", "release_or_tooling"}
4006
- )
4007
- or file_count > 12,
4008
- "needs_adr": bool(categories & {"structure", "release_or_tooling"}) and not categories <= {"docs"},
4347
+ ),
4348
+ # Path names and file counts do not justify a durable architecture
4349
+ # record. The model or an explicit project rule decides.
4350
+ "needs_adr": False,
4009
4351
  "needs_browser": "ui" in categories,
4010
4352
  "needs_jenkins": bool(
4011
4353
  categories & {"release_or_tooling", "db", "auth", "payment", "gateway", "prod_config"}
@@ -4050,9 +4392,22 @@ def _configured_workflow_profile(cfg: dict) -> str:
4050
4392
  return _normalize_workflow_profile((cfg.get("workflow") or {}).get("profile"))
4051
4393
 
4052
4394
 
4053
- def _recommended_agents(profile: str, categories: set[str], classification: dict) -> list[str]:
4395
+ def _recommended_agents(
4396
+ profile: str,
4397
+ categories: set[str],
4398
+ classification: dict,
4399
+ *,
4400
+ parallel_writers: int = 1,
4401
+ review_required: bool = False,
4402
+ ) -> list[str]:
4054
4403
  roles: list[str] = []
4055
- for stage in _agent_execution_plan(profile, categories, classification)["stages"]:
4404
+ for stage in _agent_execution_plan(
4405
+ profile,
4406
+ categories,
4407
+ classification,
4408
+ parallel_writers=parallel_writers,
4409
+ review_required=review_required,
4410
+ )["stages"]:
4056
4411
  for role in stage["roles"]:
4057
4412
  if role != "main" and role not in roles:
4058
4413
  roles.append(role)
@@ -4127,122 +4482,81 @@ def _validate_agent_plan(plan: dict) -> dict:
4127
4482
  return plan
4128
4483
 
4129
4484
 
4130
- def _agent_execution_plan(profile: str, categories: set[str], classification: dict) -> dict:
4485
+ def _agent_execution_plan(
4486
+ profile: str,
4487
+ categories: set[str],
4488
+ classification: dict,
4489
+ *,
4490
+ parallel_writers: int = 1,
4491
+ review_required: bool = False,
4492
+ ) -> dict:
4131
4493
  assignment_contract, result_contract = _agent_contract_shape()
4132
- if profile == "micro":
4133
- return _validate_agent_plan({
4134
- "contract_version": _AGENT_CONTRACT_VERSION,
4135
- "contract_schema": _AGENT_CONTRACT_SCHEMA,
4136
- "strategy": "main-only",
4137
- "policies": {
4138
- "one_writer_per_worktree": True,
4139
- "workspace_isolation": "adaptive-clean-current-or-isolated",
4140
- "path_ownership": "explicit-non-overlapping",
4141
- "dependency_policy": "integrate-before-dependent-start",
4142
- "review_feedback_owner": "main",
4143
- "review_binding": "diff-fingerprint",
4144
- "lifecycle_owner": "main",
4145
- "gate_owner": "main",
4146
- },
4147
- "assignment_contract": assignment_contract,
4148
- "result_contract": result_contract,
4149
- "stages": [
4494
+ # Classification reports useful capabilities but never auto-dispatches
4495
+ # discovery roles. The model chooses delegation only when expected benefit
4496
+ # exceeds coordination cost.
4497
+ discovery_roles: list[str] = []
4498
+
4499
+ policies = {
4500
+ "one_writer_per_worktree": True,
4501
+ "workspace_isolation": "adaptive-clean-current-or-isolated",
4502
+ "path_ownership": "explicit-only-for-isolated-or-delegated-work",
4503
+ "dependency_policy": "integrate-before-dependent-start",
4504
+ "review_feedback_owner": "owning-fixer" if review_required else "main",
4505
+ "review_binding": "diff-fingerprint-when-required",
4506
+ "lifecycle_owner": "main",
4507
+ "gate_owner": "main",
4508
+ }
4509
+ constraints = [
4510
+ "Delegate only when independent work has a clear latency or expertise benefit.",
4511
+ "A clean single-writer checkout stays on its current branch; dirty or parallel work is isolated.",
4512
+ "Never run two writers in one worktree.",
4513
+ "The main agent runs one final changed-scope gate, pushes, and cleans only temporary branches actually created.",
4514
+ ]
4515
+
4516
+ if parallel_writers <= 1 and not discovery_roles and not review_required:
4517
+ stages = [{"id": "delivery", "mode": "serial", "roles": ["main"], "depends_on": []}]
4518
+ strategy = "main-only"
4519
+ else:
4520
+ stages = [
4521
+ {"id": "decomposition", "mode": "serial", "roles": ["main"], "depends_on": []}
4522
+ ]
4523
+ previous = "decomposition"
4524
+ if discovery_roles:
4525
+ stages.append(
4150
4526
  {
4151
- "id": "delivery",
4152
- "mode": "serial",
4153
- "roles": ["main"],
4154
- "depends_on": [],
4527
+ "id": "discovery",
4528
+ "mode": "parallel" if len(discovery_roles) > 1 else "serial",
4529
+ "roles": discovery_roles,
4530
+ "depends_on": [previous],
4155
4531
  }
4156
- ],
4157
- "constraints": [
4158
- "Do not create subagents when the task has no independent work worth delegating.",
4159
- "The main agent owns the fast gate, Git integration, push, and cleanup.",
4160
- ],
4161
- })
4162
-
4163
- discovery_roles = ["explorer"]
4164
- if categories & {"api", "release_or_tooling"}:
4165
- discovery_roles.append("docs_researcher")
4166
- if classification.get("needs_browser"):
4167
- discovery_roles.append("browser_debugger")
4532
+ )
4533
+ previous = "discovery"
4534
+ delivery_roles = ["main"]
4535
+ delivery_mode = "serial"
4536
+ if parallel_writers > 1:
4537
+ delivery_roles = ["fixer", "main"]
4538
+ delivery_mode = "parallel-isolated"
4539
+ if review_required:
4540
+ delivery_roles.append("reviewer")
4541
+ stages.append(
4542
+ {
4543
+ "id": "delivery",
4544
+ "mode": delivery_mode,
4545
+ "roles": delivery_roles,
4546
+ "depends_on": [previous],
4547
+ }
4548
+ )
4549
+ strategy = "parallel-writers" if parallel_writers > 1 else "risk-assisted"
4168
4550
 
4169
4551
  return _validate_agent_plan({
4170
4552
  "contract_version": _AGENT_CONTRACT_VERSION,
4171
4553
  "contract_schema": _AGENT_CONTRACT_SCHEMA,
4172
- "strategy": "orchestrated-subagents",
4173
- "policies": {
4174
- "one_writer_per_worktree": True,
4175
- "workspace_isolation": "adaptive-clean-current-or-isolated",
4176
- "path_ownership": "explicit-non-overlapping",
4177
- "dependency_policy": "integrate-before-dependent-start",
4178
- "review_feedback_owner": "owning-fixer",
4179
- "review_binding": "diff-fingerprint",
4180
- "lifecycle_owner": "main",
4181
- "gate_owner": "main",
4182
- },
4554
+ "strategy": strategy,
4555
+ "policies": policies,
4183
4556
  "assignment_contract": assignment_contract,
4184
4557
  "result_contract": result_contract,
4185
- "stages": [
4186
- {
4187
- "id": "decomposition",
4188
- "mode": "serial",
4189
- "roles": ["main"],
4190
- "depends_on": [],
4191
- },
4192
- {
4193
- "id": "discovery",
4194
- "mode": "parallel",
4195
- "roles": discovery_roles,
4196
- "depends_on": ["decomposition"],
4197
- },
4198
- {
4199
- "id": "design",
4200
- "mode": "serial",
4201
- "roles": ["main"],
4202
- "depends_on": ["discovery"],
4203
- },
4204
- {
4205
- "id": "delivery",
4206
- "mode": "dependency-waves",
4207
- "roles": ["fixer", "reviewer", "main"],
4208
- "depends_on": ["design"],
4209
- "scale": "one fixer per independent development unit in the current dependency layer",
4210
- "wave_phases": [
4211
- {
4212
- "id": "implementation",
4213
- "mode": "parallel-isolated",
4214
- "roles": ["fixer"],
4215
- },
4216
- {
4217
- "id": "review",
4218
- "mode": "parallel-read-only",
4219
- "roles": ["reviewer"],
4220
- "feedback_to": "owning fixer",
4221
- },
4222
- {
4223
- "id": "gate-integrate",
4224
- "mode": "serial",
4225
- "roles": ["main"],
4226
- },
4227
- ],
4228
- "next_wave": "start only after every prerequisite in the next layer is integrated",
4229
- },
4230
- {
4231
- "id": "closure",
4232
- "mode": "serial",
4233
- "roles": ["main"],
4234
- "depends_on": ["delivery"],
4235
- },
4236
- ],
4237
- "constraints": [
4238
- "Delegate only independent bounded work and declare dependencies before dispatch.",
4239
- "One serial fixer may use a clean current branch; dirty or parallel writers require registered task branches/worktrees.",
4240
- "Never run two writers in one worktree or let the main agent edit a fixer-owned worktree concurrently.",
4241
- "Start a dependent write task only after its prerequisite has been integrated into the target branch.",
4242
- "Subagents do not commit, push, integrate, or clean task branches.",
4243
- "Reviewers inspect a stable diff; changes-requested returns to the owning fixer and any edit requires re-review.",
4244
- "The main agent routes review feedback, runs one fast gate, pushes, and cleans only temporary branches/worktrees that were actually created.",
4245
- ],
4558
+ "stages": stages,
4559
+ "constraints": constraints,
4246
4560
  })
4247
4561
 
4248
4562
 
@@ -4257,6 +4571,7 @@ def _resolve_execution_plan(
4257
4571
  changed_paths: Optional[list[str]] = None,
4258
4572
  planned_paths: Optional[list[str]] = None,
4259
4573
  intent: str = "",
4574
+ parallel_writers: int = 1,
4260
4575
  ) -> dict:
4261
4576
  impact = _impact_summary(
4262
4577
  cfg,
@@ -4275,7 +4590,7 @@ def _resolve_execution_plan(
4275
4590
  merged_categories = set(classification["categories"]) | set(intent_categories)
4276
4591
  classification = _classification_for_categories(merged_categories, len(classification_inputs))
4277
4592
  categories = set(classification["categories"])
4278
- matching_rules = _matching_gate_rules(classification_inputs, _gate_cfg(cfg))
4593
+ matching_rules = _matching_risk_rules(classification_inputs, cfg)
4279
4594
  configured_profile = _configured_workflow_profile(cfg)
4280
4595
  requested_profile_value = _normalize_workflow_profile(requested_profile) if requested_profile else ""
4281
4596
  configured_mode = _workflow_mode(cfg)
@@ -4290,6 +4605,7 @@ def _resolve_execution_plan(
4290
4605
  (docs_only_paths and str(impact["selected_scope"]) != "full")
4291
4606
  or _tests_only(classification_inputs)
4292
4607
  )
4608
+ terminal_maintenance = _is_terminal_ledger_maintenance(classification_inputs)
4293
4609
  if docs_or_tests_only and str(impact["selected_scope"]) != "full":
4294
4610
  detected_profile = "micro"
4295
4611
  profile_reasons.append("only docs/test files changed")
@@ -4322,9 +4638,6 @@ def _resolve_execution_plan(
4322
4638
  high_signals.append("high-risk category: " + ", ".join(sorted(categories & high_categories)))
4323
4639
  if "high-risk" in rule_profiles:
4324
4640
  high_signals.append("matched gate rule with profile=high-risk")
4325
- if len(classification_inputs) > 12 and not docs_or_tests_only:
4326
- high_signals.append("change spans more than 12 files")
4327
-
4328
4641
  if high_signals:
4329
4642
  detected_profile = "high-risk"
4330
4643
  profile_reasons.extend(high_signals)
@@ -4353,11 +4666,60 @@ def _resolve_execution_plan(
4353
4666
  execution_reasons = list(impact.get("reasons") or [])
4354
4667
  execution_reasons.append("Jenkins/build/deploy and owner acceptance happen after coding completion")
4355
4668
 
4669
+ try:
4670
+ writer_count = max(1, int(parallel_writers or 1))
4671
+ except (TypeError, ValueError) as exc:
4672
+ raise APError("parallel writer count must be a positive integer") from exc
4673
+ module_roots = {
4674
+ path.split("/", 1)[0]
4675
+ for path in classification_inputs
4676
+ if path and not _path_matches(path, _DOC_PATH_PATTERNS)
4677
+ }
4678
+ cross_module = len(module_roots) > 1
4679
+ rule_review = any(
4680
+ _text(rule.get("review")).lower() in {"required", "true", "yes"}
4681
+ for rule in matching_rules
4682
+ )
4683
+ rule_design = any(
4684
+ _text(rule.get("design")).lower() in {"required", "true", "yes"}
4685
+ for rule in matching_rules
4686
+ )
4687
+ cross_module_contract_risk = bool(
4688
+ cross_module
4689
+ and categories & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config"}
4690
+ )
4691
+ review_required = bool(
4692
+ not terminal_maintenance
4693
+ and (effective_profile == "high-risk" or writer_count > 1 or cross_module_contract_risk or rule_review)
4694
+ )
4695
+ design_required = bool(
4696
+ not terminal_maintenance
4697
+ and (rule_design or (effective_profile == "high-risk" and cross_module))
4698
+ )
4699
+ has_task_signal = bool(classification_inputs or _text(intent))
4700
+ workspace_dirty = bool(_working_tree_paths(repo))
4701
+ configured_isolation = _task_isolation(cfg)
4702
+ if terminal_maintenance or not has_task_signal:
4703
+ execution_mode = "none"
4704
+ elif configured_isolation == "worktree" or writer_count > 1 or workspace_dirty:
4705
+ execution_mode = "isolated"
4706
+ else:
4707
+ execution_mode = "direct"
4708
+ execution_reasons.append(
4709
+ "execution mode is adaptive: clean single-writer work is direct; dirty or parallel work is isolated"
4710
+ )
4711
+
4356
4712
  needs_jenkins = False
4357
4713
  needs_target = False
4358
- needs_dd = bool(classification["needs_dd"] or effective_profile == "high-risk")
4359
-
4360
- agent_plan = _agent_execution_plan(effective_profile, categories, classification)
4714
+ needs_dd = design_required
4715
+
4716
+ agent_plan = _agent_execution_plan(
4717
+ effective_profile,
4718
+ categories,
4719
+ classification,
4720
+ parallel_writers=writer_count,
4721
+ review_required=review_required,
4722
+ )
4361
4723
  return {
4362
4724
  **impact,
4363
4725
  "contract_version": _AGENT_CONTRACT_VERSION,
@@ -4374,6 +4736,13 @@ def _resolve_execution_plan(
4374
4736
  "configured_mode": configured_mode,
4375
4737
  "requested_mode": requested_mode_value or None,
4376
4738
  "effective_mode": effective_mode,
4739
+ "execution_mode": execution_mode,
4740
+ "terminal_maintenance": terminal_maintenance,
4741
+ "workspace_dirty": workspace_dirty,
4742
+ "parallel_writers": writer_count,
4743
+ "cross_module": cross_module,
4744
+ "review_required": review_required,
4745
+ "design_required": design_required,
4377
4746
  "selected_scope": selected_scope,
4378
4747
  "categories": sorted(categories),
4379
4748
  "needs_dd": needs_dd,
@@ -4381,7 +4750,13 @@ def _resolve_execution_plan(
4381
4750
  "needs_browser": classification["needs_browser"],
4382
4751
  "needs_jenkins": needs_jenkins,
4383
4752
  "needs_target": needs_target,
4384
- "recommended_agents": _recommended_agents(effective_profile, categories, classification),
4753
+ "recommended_agents": _recommended_agents(
4754
+ effective_profile,
4755
+ categories,
4756
+ classification,
4757
+ parallel_writers=writer_count,
4758
+ review_required=review_required,
4759
+ ),
4385
4760
  "agent_plan": agent_plan,
4386
4761
  }
4387
4762
 
@@ -4410,6 +4785,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
4410
4785
  base_ref=_text(getattr(args, "base", "")),
4411
4786
  planned_paths=list(getattr(args, "planned_path", []) or []),
4412
4787
  intent="\n".join(part for part in intent_parts if part),
4788
+ parallel_writers=int(getattr(args, "writers", 1) or 1),
4413
4789
  )
4414
4790
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
4415
4791
  commands: list[str] = []
@@ -4426,6 +4802,9 @@ def cmd_classify(args: argparse.Namespace) -> None:
4426
4802
  print(f"[classify] risk={risk}")
4427
4803
  print(f"[classify] profile={result['profile']}")
4428
4804
  print(f"[classify] effective_mode={result['effective_mode']}")
4805
+ print(f"[classify] execution_mode={result['execution_mode']}")
4806
+ print(f"[classify] review_required={str(result['review_required']).lower()}")
4807
+ print(f"[classify] design_required={str(result['design_required']).lower()}")
4429
4808
  print(f"[classify] selected_scope={result['selected_scope']}")
4430
4809
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
4431
4810
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
@@ -4684,12 +5063,15 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4684
5063
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
4685
5064
  profile = str(workflow_cfg.get("profile") or "auto").strip().lower()
4686
5065
  completion = str(workflow_cfg.get("completion") or "").strip().lower()
5066
+ skill_version = _text(workflow_cfg.get("skill_version"))
4687
5067
  if mode != "dev":
4688
5068
  missing.append("workflow.mode (must be dev; external verification is owner-managed)")
4689
5069
  if profile not in _WORKFLOW_PROFILES:
4690
5070
  missing.append("workflow.profile (must be auto, micro, standard, or high-risk)")
4691
5071
  if completion != "push":
4692
5072
  missing.append("workflow.completion (must be push)")
5073
+ if skill_version.startswith("4.1") and _text(docs_cfg.get("framework")) != "engineering-centered":
5074
+ missing.append("docs.framework (must be engineering-centered for auto-coding-skill 4.1)")
4693
5075
  isolation = _text(concurrency_cfg.get("isolation")).lower() or "adaptive"
4694
5076
  if isolation not in {"adaptive", "worktree"}:
4695
5077
  validation_errors.append(
@@ -4741,13 +5123,79 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4741
5123
  f"gate.rules[{index}].commands is legacy automatic gate escalation; run ap.py upgrade"
4742
5124
  )
4743
5125
 
4744
- if not (_configured_command(cfg, "gate_changed") or _configured_command(cfg, "quick_test")):
4745
- missing.append("fast gate command: commands.gate_changed or commands.quick_test")
5126
+ risk_rules = _risk_cfg(cfg).get("rules") or []
5127
+ if not isinstance(risk_rules, list):
5128
+ validation_errors.append("risk.rules must be a list")
5129
+ risk_rules = []
5130
+ for index, rule in enumerate(risk_rules):
5131
+ if not isinstance(rule, dict):
5132
+ validation_errors.append(f"risk.rules[{index}] must be a mapping")
5133
+ continue
5134
+ if not _as_list(rule.get("paths")):
5135
+ validation_errors.append(f"risk.rules[{index}].paths must not be empty")
5136
+ rule_profile = _text(rule.get("profile")).lower()
5137
+ if rule_profile and rule_profile not in _WORKFLOW_PROFILES - {"auto"}:
5138
+ validation_errors.append(
5139
+ f"risk.rules[{index}].profile must be micro, standard, or high-risk"
5140
+ )
4746
5141
 
4747
- repo_docs = {
4748
- "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
4749
- "docs.closure_log": Path(repo, str(docs_cfg.get("closure_log", "docs/tasks/closure-log.md"))),
4750
- }
5142
+ validation_cfg = _validation_cfg(cfg)
5143
+ on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
5144
+ if on_unmapped not in {"error", "fallback"}:
5145
+ validation_errors.append("validation.on_unmapped must be error or fallback")
5146
+ routes = validation_cfg.get("routes") or []
5147
+ if not isinstance(routes, list):
5148
+ validation_errors.append("validation.routes must be a list")
5149
+ routes = []
5150
+ for index, route in enumerate(routes):
5151
+ if not isinstance(route, dict):
5152
+ validation_errors.append(f"validation.routes[{index}] must be a mapping")
5153
+ continue
5154
+ if not _as_list(route.get("paths")):
5155
+ validation_errors.append(f"validation.routes[{index}].paths must not be empty")
5156
+ commands = [_command_name(item) for item in _as_list(route.get("commands"))]
5157
+ if not commands:
5158
+ validation_errors.append(f"validation.routes[{index}].commands must not be empty")
5159
+ for command_name in commands:
5160
+ if command_name and not _configured_command(cfg, command_name):
5161
+ validation_errors.append(
5162
+ f"validation.routes[{index}] references missing commands.{command_name}"
5163
+ )
5164
+ fallback_name = _command_name(validation_cfg.get("fallback_command"))
5165
+ if on_unmapped == "fallback" and not fallback_name:
5166
+ validation_errors.append(
5167
+ "validation.fallback_command is required when validation.on_unmapped=fallback"
5168
+ )
5169
+ if fallback_name and not _configured_command(cfg, fallback_name):
5170
+ validation_errors.append(
5171
+ f"validation.fallback_command references missing commands.{fallback_name}"
5172
+ )
5173
+ if not routes and not (_configured_command(cfg, "gate_changed") or fallback_name):
5174
+ validation_errors.append(
5175
+ "validation.routes is empty and no 3.x commands.gate_changed compatibility fallback exists"
5176
+ )
5177
+ tracked_validation_paths = [
5178
+ path
5179
+ for path in _tracked_files(repo)
5180
+ if not _path_matches(
5181
+ path,
5182
+ [
5183
+ "*.md",
5184
+ "docs/**",
5185
+ ".agents/**",
5186
+ ".local/**",
5187
+ "AGENTS.md",
5188
+ ],
5189
+ )
5190
+ ]
5191
+ if tracked_validation_paths:
5192
+ try:
5193
+ tracked_plan = _validation_plan(cfg, tracked_validation_paths)
5194
+ _validate_validation_plan(cfg, tracked_plan)
5195
+ except APError as exc:
5196
+ validation_errors.append(f"tracked validation coverage: {exc}")
5197
+
5198
+ repo_docs: dict[str, Path] = {}
4751
5199
  api_doc = Path(repo, str(docs_cfg.get("api_doc", "docs/interfaces/api.md")))
4752
5200
  api_change_log = Path(repo, str(docs_cfg.get("api_change_log", "docs/interfaces/api-change-log.md")))
4753
5201
  api_docs_enabled = (
@@ -5990,7 +6438,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5990
6438
  ensure_git_repo(repo)
5991
6439
  cfg = _load_cfg(repo)
5992
6440
  _require_workflow_policy_clean(repo, cfg)
5993
- _task_isolation(cfg)
6441
+ configured_isolation = _task_isolation(cfg)
5994
6442
  access_issues = _access_config_issues(cfg)
5995
6443
  if access_issues:
5996
6444
  raise APError(
@@ -6010,8 +6458,6 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6010
6458
  if _read_json_object(_task_registry_path(repo, task_id)):
6011
6459
  raise APError(f"Task is already registered: {task_id}")
6012
6460
 
6013
- common_submodule_config = _common_submodule_config(repo)
6014
- _seed_control_submodule_config(repo)
6015
6461
  task_uuid = uuid.uuid4().hex
6016
6462
 
6017
6463
  if not getattr(args, "no_fetch", False) and base_ref.startswith(f"{remote}/"):
@@ -6020,6 +6466,30 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6020
6466
  owned_paths = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
6021
6467
  if not owned_paths:
6022
6468
  raise APError("task-start requires at least one --owned-path.")
6469
+ if _is_terminal_ledger_maintenance(owned_paths):
6470
+ raise APError(
6471
+ "Pure taskbook/closure/archive reconciliation is terminal maintenance and must not "
6472
+ "create another task lifecycle. Run the targeted document check, commit once, and push."
6473
+ )
6474
+ writer_count = max(1, int(getattr(args, "writers", 1) or 1))
6475
+ if writer_count != 1:
6476
+ raise APError(
6477
+ "task-start creates exactly one writer lease and one worktree. Start each parallel "
6478
+ "writer as its own task ID; use --writers only with classify for planning."
6479
+ )
6480
+ registry_dir = _task_state_root(repo) / "tasks"
6481
+ for manifest_path in sorted(registry_dir.glob("*.json")) if registry_dir.exists() else []:
6482
+ active_manifest = _read_json_object(manifest_path) or {}
6483
+ if _text(active_manifest.get("state")) in {"integrated", "cleanup-pending"}:
6484
+ continue
6485
+ active_owned = active_manifest.get("owned_paths") or []
6486
+ if isinstance(active_owned, list) and _owned_paths_overlap(owned_paths, active_owned):
6487
+ active_id = _text(active_manifest.get("task_id")) or manifest_path.stem
6488
+ raise APError(
6489
+ f"Owned paths overlap active task {active_id}: "
6490
+ + ", ".join(active_owned)
6491
+ + ". Split ownership into non-overlapping task units or finish the active writer first."
6492
+ )
6023
6493
  depends_on: list[str] = []
6024
6494
  prerequisite_shas: dict[str, str] = {}
6025
6495
  for raw_dependency in args.depends_on or []:
@@ -6041,6 +6511,86 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6041
6511
  if not owner:
6042
6512
  raise APError("task-start requires --owner or CODEX_THREAD_ID.")
6043
6513
  writer = _text(getattr(args, "writer", "")) or owner
6514
+ plan = _resolve_execution_plan(
6515
+ cfg,
6516
+ repo,
6517
+ planned_paths=owned_paths,
6518
+ parallel_writers=writer_count,
6519
+ )
6520
+ review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
6521
+ registry_dir = _task_state_root(repo) / "tasks"
6522
+ other_active = any(
6523
+ _text((payload or {}).get("state"))
6524
+ not in {"", "integrated", "cleanup-pending"}
6525
+ for payload in (
6526
+ _read_json_object(path)
6527
+ for path in sorted(registry_dir.glob("*.json"))
6528
+ )
6529
+ ) if registry_dir.exists() else False
6530
+ current_branch = _current_branch(repo)
6531
+ direct = bool(
6532
+ configured_isolation == "adaptive"
6533
+ and not bool(getattr(args, "isolated", False))
6534
+ and writer_count == 1
6535
+ and not other_active
6536
+ and not _task_commit_paths(repo)
6537
+ and current_branch
6538
+ and current_branch == target_branch
6539
+ )
6540
+ if direct:
6541
+ direct_base = _resolve_commit(repo, "HEAD")
6542
+ manifest = {
6543
+ "schema": 3,
6544
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
6545
+ "execution_mode": "direct",
6546
+ "review_required": review_required,
6547
+ "task_id": task_id,
6548
+ "task_uuid": task_uuid,
6549
+ "owner": owner,
6550
+ "base_ref": "HEAD",
6551
+ "base_sha": direct_base,
6552
+ "remote": remote,
6553
+ "target_branch": current_branch,
6554
+ "task_branch": current_branch,
6555
+ "worktree_path": str(repo.resolve()),
6556
+ "control_worktree_path": str(repo.resolve()),
6557
+ "cleanup_policy": _cleanup_policy(cfg),
6558
+ "state": "active",
6559
+ "created_at": _now_iso(),
6560
+ "initial_untracked": [],
6561
+ "owned_paths": owned_paths,
6562
+ "depends_on": depends_on,
6563
+ "prerequisite_shas": prerequisite_shas,
6564
+ "writer_lease": {
6565
+ "holder": writer,
6566
+ "generation": 1,
6567
+ "state": "active",
6568
+ "acquired_at": _now_iso(),
6569
+ },
6570
+ "review": {
6571
+ "verdict": "pending",
6572
+ "diff_base": direct_base,
6573
+ "diff_head": "",
6574
+ "diff_fingerprint": "",
6575
+ "reviewer": "",
6576
+ "reviewed_at": "",
6577
+ "reason": "review required" if review_required else "review not required",
6578
+ },
6579
+ "claimed_paths": [],
6580
+ "remote_task_tip": "",
6581
+ "common_submodule_config": {},
6582
+ }
6583
+ _save_task_manifest(repo, manifest)
6584
+ print(f"[task-start] task={task_id}")
6585
+ print("[task-start] execution_mode=direct")
6586
+ print(f"[task-start] branch={current_branch}")
6587
+ print(f"[task-start] base=HEAD@{direct_base}")
6588
+ print(f"[task-start] worktree={repo}")
6589
+ print("[task-start] no temporary branch or worktree created")
6590
+ return
6591
+
6592
+ common_submodule_config = _common_submodule_config(repo)
6593
+ _seed_control_submodule_config(repo)
6044
6594
  prefix = _task_branch_prefix(cfg)
6045
6595
  task_branch = f"{prefix}{task_id}"
6046
6596
  check_ref = run(["git", "check-ref-format", "--branch", task_branch], cwd=repo, check=False)
@@ -6070,7 +6620,10 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6070
6620
  cwd=repo,
6071
6621
  )
6072
6622
  manifest = {
6073
- "schema": 2,
6623
+ "schema": 3,
6624
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
6625
+ "execution_mode": "isolated",
6626
+ "review_required": review_required,
6074
6627
  "task_id": task_id,
6075
6628
  "task_uuid": task_uuid,
6076
6629
  "owner": owner,
@@ -6142,9 +6695,9 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6142
6695
  f"branch={initial_branch or '(detached)'} head={initial_head}\n{initial_status}"
6143
6696
  )
6144
6697
  _save_task_manifest(repo, manifest)
6145
- _create_active_task_doc(worktree, cfg, manifest)
6146
6698
 
6147
6699
  print(f"[task-start] task={task_id}")
6700
+ print("[task-start] execution_mode=isolated")
6148
6701
  print(f"[task-start] branch={task_branch}")
6149
6702
  print(f"[task-start] base={base_ref}@{base_sha}")
6150
6703
  print(f"[task-start] worktree={worktree}")
@@ -6530,6 +7083,14 @@ def cmd_task_finish(args: argparse.Namespace) -> None:
6530
7083
  cfg = _load_cfg(repo)
6531
7084
  task_id = _validate_task_id(args.task_id)
6532
7085
  manifest = _load_task_manifest(repo, task_id)
7086
+ if _text(manifest.get("execution_mode")).lower() == "direct":
7087
+ if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
7088
+ raise APError("Run task-finish for a direct task from its current checkout.")
7089
+ if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
7090
+ raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
7091
+ _clear_direct_task(repo, manifest)
7092
+ print(f"[task-finish] OK task={task_id} execution_mode=direct no temporary branch existed")
7093
+ return
6533
7094
  _require_control_checkout(repo, manifest)
6534
7095
  timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
6535
7096
  with (
@@ -6555,6 +7116,8 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
6555
7116
  cfg = _load_cfg(repo)
6556
7117
  task_id = _validate_task_id(args.task_id)
6557
7118
  manifest = _load_task_manifest(repo, task_id)
7119
+ if _text(manifest.get("execution_mode")).lower() == "direct":
7120
+ raise APError("Direct tasks push their current target branch in commit-push and do not use task-integrate.")
6558
7121
  _require_control_checkout(repo, manifest)
6559
7122
  _require_current_writer(manifest, args)
6560
7123
  worktree = Path(_text(manifest.get("worktree_path")))
@@ -6914,12 +7477,119 @@ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") ->
6914
7477
  return commit_sha
6915
7478
 
6916
7479
 
7480
+ def _clear_direct_task(repo: Path, manifest: dict) -> None:
7481
+ active_path = _worktree_manifest_path(repo)
7482
+ active = _read_json_object(active_path)
7483
+ if active and _text(active.get("task_uuid")) == _text(manifest.get("task_uuid")):
7484
+ active_path.unlink(missing_ok=True)
7485
+ _delete_task_manifest(repo, manifest)
7486
+
7487
+
7488
+ def _cmd_direct_commit_push_locked(
7489
+ args: argparse.Namespace,
7490
+ repo: Path,
7491
+ cfg: dict,
7492
+ manifest: dict,
7493
+ ) -> None:
7494
+ _require_current_writer(manifest, args)
7495
+ _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
7496
+ _require_approved_review(repo, cfg, manifest)
7497
+ branch = _current_branch(repo)
7498
+ target = _text(manifest.get("target_branch"))
7499
+ if branch != target:
7500
+ raise APError(f"Direct task branch changed: current={branch or '(detached)'}, expected={target}.")
7501
+ working_paths = _task_commit_paths(repo)
7502
+ head = _resolve_commit(repo, "HEAD")
7503
+ pending_commit = _text(manifest.get("last_commit"))
7504
+ if not working_paths and not (pending_commit and pending_commit == head):
7505
+ if head != _text(manifest.get("base_sha")):
7506
+ raise APError(
7507
+ "Direct task HEAD moved without a recorded commit-push result; refusing to guess ownership."
7508
+ )
7509
+ _clear_direct_task(repo, manifest)
7510
+ print(f"[commit-push] NOOP task={manifest['task_id']} execution_mode=direct; no changes")
7511
+ return
7512
+
7513
+ if pending_commit and pending_commit == head and not working_paths:
7514
+ commit_sha = pending_commit
7515
+ plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
7516
+ else:
7517
+ cmd_doctor(
7518
+ argparse.Namespace(
7519
+ repo=str(repo),
7520
+ profile=_text(getattr(args, "profile", "")).lower(),
7521
+ mode=_text(getattr(args, "mode", "")).lower(),
7522
+ )
7523
+ )
7524
+ plan = _resolve_execution_plan(
7525
+ cfg,
7526
+ repo,
7527
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
7528
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
7529
+ base_ref=_text(manifest.get("base_sha")),
7530
+ )
7531
+ before_gate = _task_content_fingerprint(repo, cfg, manifest)
7532
+ cmd_light_gate(
7533
+ argparse.Namespace(
7534
+ repo=str(repo),
7535
+ scope="changed",
7536
+ profile=plan["profile"],
7537
+ mode="dev",
7538
+ base=_text(manifest.get("base_sha")),
7539
+ explain=False,
7540
+ )
7541
+ )
7542
+ after_gate = _task_content_fingerprint(repo, cfg, manifest)
7543
+ if after_gate != before_gate:
7544
+ raise APError("The final gate changed direct-task files; inspect them and retry commit-push.")
7545
+ manifest = _require_task_context(repo, cfg, args.task_id)
7546
+ _require_current_writer(manifest, args)
7547
+ _require_approved_review(repo, cfg, manifest)
7548
+ task_paths = _task_commit_paths(repo)
7549
+ staged = _stage_exact_paths(repo, task_paths)
7550
+ if not staged:
7551
+ _clear_direct_task(repo, manifest)
7552
+ print(f"[commit-push] NOOP task={manifest['task_id']} execution_mode=direct; no changes")
7553
+ return
7554
+ unstaged = _unstaged_task_paths(repo)
7555
+ if unstaged:
7556
+ raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
7557
+ commit_sha = _commit_exact_index(repo, args.msg)
7558
+ manifest["state"] = "push-pending"
7559
+ manifest["last_commit"] = commit_sha
7560
+ _save_task_manifest(repo, manifest)
7561
+ remote = _text(manifest.get("remote")) or "origin"
7562
+ push = run(
7563
+ ["git", "push", "--set-upstream", remote, f"{commit_sha}:refs/heads/{target}"],
7564
+ cwd=repo,
7565
+ check=False,
7566
+ )
7567
+ if push.returncode != 0:
7568
+ raise APError(
7569
+ f"Direct target push failed; the local commit is preserved on {branch}.\n"
7570
+ f"{push.stdout}\n{push.stderr}"
7571
+ )
7572
+ remote_tip = _remote_branch_tip(repo, remote, target)
7573
+ if remote_tip != commit_sha:
7574
+ raise APError(
7575
+ f"Direct target verification failed: expected {commit_sha}, got {remote_tip or '(missing)'}"
7576
+ )
7577
+ _clear_direct_task(repo, manifest)
7578
+ print(
7579
+ f"[commit-push] OK task={manifest['task_id']} execution_mode=direct "
7580
+ f"profile={plan['profile']} scope=changed commit={commit_sha}"
7581
+ )
7582
+
7583
+
6917
7584
  def _cmd_commit_push_locked(
6918
7585
  args: argparse.Namespace,
6919
7586
  repo: Path,
6920
7587
  cfg: dict,
6921
7588
  manifest: dict,
6922
7589
  ) -> None:
7590
+ if _text(manifest.get("execution_mode")).lower() == "direct":
7591
+ _cmd_direct_commit_push_locked(args, repo, cfg, manifest)
7592
+ return
6923
7593
  control_repo = Path(_text(manifest.get("control_worktree_path"))).resolve()
6924
7594
  _sync_task_submodule_config(
6925
7595
  control_repo,
@@ -6954,8 +7624,6 @@ def _cmd_commit_push_locked(
6954
7624
  _validate_closure_result(mode, str(args.result))
6955
7625
 
6956
7626
  msg = args.msg
6957
- structure_check_status = "not part of the fast local gate"
6958
-
6959
7627
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
6960
7628
  cmd_light_gate(
6961
7629
  argparse.Namespace(
@@ -6984,22 +7652,6 @@ def _cmd_commit_push_locked(
6984
7652
  "no files were staged or restored."
6985
7653
  )
6986
7654
 
6987
- dev_verification = args.verification or [
6988
- "fast changed-scope gate passed",
6989
- "project commit/push hooks remain enabled",
6990
- ]
6991
- _record_commit_push_closure(
6992
- repo,
6993
- args,
6994
- commit="generated by this commit-push run",
6995
- jenkins="owner-managed after push",
6996
- target_env="owner-managed acceptance",
6997
- verification=dev_verification,
6998
- result=args.result or "DEV-CLOSED",
6999
- follow_up=args.follow_up or "Complete the push stage with task-integrate; do not wait for Jenkins.",
7000
- structure_check=args.structure_check or structure_check_status,
7001
- )
7002
-
7003
7655
  protected = set(manifest.get("initial_untracked") or [])
7004
7656
  _cleanup_generated_noise(repo, protected_paths=protected)
7005
7657
  pre_stage_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
@@ -7099,9 +7751,17 @@ def main(argv: Optional[List[str]] = None) -> int:
7099
7751
  s.add_argument("--planned-path", action="append")
7100
7752
  s.add_argument("--intent")
7101
7753
  s.add_argument("--intent-file")
7754
+ s.add_argument("--writers", type=int, default=1)
7102
7755
  s.add_argument("--json", action="store_true")
7103
7756
  s.set_defaults(func=cmd_classify)
7104
7757
 
7758
+ s = sp.add_parser("validation-map-check")
7759
+ s.add_argument("--base")
7760
+ s.add_argument("--path", action="append")
7761
+ s.add_argument("--tracked", action="store_true")
7762
+ s.add_argument("--json", action="store_true")
7763
+ s.set_defaults(func=cmd_validation_map_check)
7764
+
7105
7765
  s = sp.add_parser("structure-check")
7106
7766
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
7107
7767
  s.add_argument("--base")
@@ -7196,6 +7856,9 @@ def main(argv: Optional[List[str]] = None) -> int:
7196
7856
  s.add_argument("--worktree-root")
7197
7857
  s.add_argument("--owner")
7198
7858
  s.add_argument("--writer")
7859
+ s.add_argument("--writers", type=int, default=1)
7860
+ s.add_argument("--isolated", action="store_true")
7861
+ s.add_argument("--review-required", action="store_true")
7199
7862
  s.add_argument("--owned-path", action="append")
7200
7863
  s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
7201
7864
  s.add_argument("--no-fetch", action="store_true")