@elvis1513/auto-coding-skill 4.0.0 → 4.1.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.
@@ -46,10 +46,12 @@ _GENERATED_NOISE_PATTERNS = [
46
46
  ]
47
47
  _AGENT_CONTRACT_VERSION = 1
48
48
  _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
49
+ _MAX_FINAL_COMMAND_SECONDS = 120.0
50
+ _MAX_FINAL_TOTAL_SECONDS = 180.0
49
51
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
50
52
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
51
53
  "schema_version": 1,
52
- "managed_versions": {"agents": "4.0.0", "engineering": "4.0.0"},
54
+ "managed_versions": {"agents": "4.1.1", "engineering": "4.1.1"},
53
55
  "known_official_engineering_body_sha256": [
54
56
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
55
57
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -223,7 +225,13 @@ def _record_gate_profile(
223
225
  print(f"[gate-profile] WARN: failed to write profile log: {exc}", file=sys.stderr)
224
226
 
225
227
 
226
- def _run_configured_command(repo: Path, cfg: dict, name: str) -> bool:
228
+ def _run_configured_command(
229
+ repo: Path,
230
+ cfg: dict,
231
+ name: str,
232
+ *,
233
+ timeout_s: Optional[float] = None,
234
+ ) -> bool:
227
235
  commands = (cfg.get("commands") or {})
228
236
  command = str(commands.get(name) or "").strip()
229
237
  if not command:
@@ -231,7 +239,7 @@ def _run_configured_command(repo: Path, cfg: dict, name: str) -> bool:
231
239
  print(f"[run] {name}: {command}")
232
240
  start = time.time()
233
241
  try:
234
- run_shell(command, cwd=repo)
242
+ run_shell(command, cwd=repo, timeout_s=timeout_s)
235
243
  except APError as exc:
236
244
  duration_s = time.time() - start
237
245
  _record_gate_profile(repo, cfg, name, "fail", duration_s, detail=str(exc))
@@ -575,10 +583,6 @@ def _copy_conflicts(src: Path, dst: Path) -> list[Path]:
575
583
  return conflicts
576
584
 
577
585
 
578
- _MANAGED_EXTRA_CLEANUP_DIRS = {
579
- Path("data/templates/bridges"),
580
- }
581
-
582
586
  _CORE_DOC_TEMPLATES: list[Path] = []
583
587
 
584
588
 
@@ -634,8 +638,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
634
638
  if _text(workflow_cfg.get("completion")).lower() != "push":
635
639
  workflow_cfg["completion"] = "push"
636
640
  changed.append("workflow.completion")
637
- if _text(workflow_cfg.get("skill_version")) != "4.0.0":
638
- workflow_cfg["skill_version"] = "4.0.0"
641
+ if _text(workflow_cfg.get("skill_version")) != "4.1.1":
642
+ workflow_cfg["skill_version"] = "4.1.1"
639
643
  changed.append("workflow.skill_version")
640
644
 
641
645
  commands_cfg = cfg.setdefault("commands", {})
@@ -684,6 +688,13 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
684
688
  if _text(validation_cfg.get("on_unmapped")).lower() != "error":
685
689
  validation_cfg["on_unmapped"] = "error"
686
690
  changed.append("validation.on_unmapped")
691
+ for key, default_value in [
692
+ ("max_command_seconds", int(_MAX_FINAL_COMMAND_SECONDS)),
693
+ ("max_total_seconds", int(_MAX_FINAL_TOTAL_SECONDS)),
694
+ ]:
695
+ if key not in validation_cfg:
696
+ validation_cfg[key] = default_value
697
+ changed.append(f"validation.{key}")
687
698
  validation_routes = validation_cfg.setdefault("routes", [])
688
699
  if not isinstance(validation_routes, list):
689
700
  validation_routes = []
@@ -716,17 +727,6 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
716
727
  gate_cfg["rules"] = []
717
728
  changed.append("gate.rules")
718
729
 
719
- if not validation_routes:
720
- validation_routes.append(
721
- {
722
- "name": "project-code",
723
- "paths": ["**"],
724
- "exclude": ["*.md", "docs/**"],
725
- "commands": ["project_fast"],
726
- }
727
- )
728
- changed.append("validation.routes[0]")
729
-
730
730
  concurrency_cfg = cfg.setdefault("concurrency", {})
731
731
  if not isinstance(concurrency_cfg, dict):
732
732
  concurrency_cfg = {}
@@ -822,8 +822,19 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
822
822
  source_root = _find_skill_asset_root(repo)
823
823
  templates = source_root / "data" / "templates"
824
824
  template_engineering = templates / "ENGINEERING.md"
825
+ template_agents = templates / "bridges" / "AGENTS.md"
825
826
  actions: list[dict] = []
826
827
 
828
+ registry = _task_state_root(repo) / "tasks"
829
+ active_manifests = sorted(registry.glob("*.json")) if registry.exists() else []
830
+ if active_manifests:
831
+ names = ", ".join(path.name for path in active_manifests)
832
+ raise APError(
833
+ "Upgrade refused because registered tasks are still active: "
834
+ f"{names}. Finish, integrate, or clean them with the installed runtime first; "
835
+ "workflow semantics must not change mid-task."
836
+ )
837
+
827
838
  def add_action(kind: str, path: Path, action: str, detail: str = "") -> None:
828
839
  actions.append({
829
840
  "kind": kind,
@@ -836,7 +847,15 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
836
847
  # are safe migration inputs; every remaining match is project-owned and must
837
848
  # be handled explicitly instead of being overwritten by a partial upgrade.
838
849
  workflow_plans = _workflow_policy_plans(repo)
839
- workflow_issues = [issue for plan in workflow_plans for issue in plan["issues"]]
850
+ # Root AGENTS.md is a whole-file managed bridge in 4.1. Unknown legacy text
851
+ # is archived and replaced, so only ENGINEERING policy conflicts block the
852
+ # upgrade preflight.
853
+ workflow_issues = [
854
+ issue
855
+ for plan in workflow_plans
856
+ if plan["path"] == "docs/ENGINEERING.md"
857
+ for issue in plan["issues"]
858
+ ]
840
859
  if workflow_issues:
841
860
  raise APError(
842
861
  "Upgrade preflight found unknown workflow policy conflicts; no files were written:\n- "
@@ -851,6 +870,35 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
851
870
  body_start = frontmatter[1] if frontmatter else 0
852
871
  engineering_plan["output"] = current[:body_start] + template_body
853
872
 
873
+ section_migrations = [
874
+ item
875
+ for item in engineering_plan.get("migrations") or []
876
+ if _text(item.get("id")).startswith("engineering-section-")
877
+ ]
878
+ if section_migrations and engineering_plan.get("original"):
879
+ version_match = re.search(
880
+ r"auto-coding-skill:managed-workflow:start\s+version=([0-9]+\.[0-9]+\.[0-9]+)",
881
+ template_engineering.read_text(encoding="utf-8"),
882
+ )
883
+ version = version_match.group(1) if version_match else "current"
884
+ archive_header = (
885
+ f"# Archived ENGINEERING.md before auto-coding-skill {version} docs convergence\n\n"
886
+ "This file is historical and non-authoritative. Known duplicate workflow sections\n"
887
+ "were removed from docs/ENGINEERING.md. Move any still-current project facts into\n"
888
+ "docs/ENGINEERING.md project-fact sections or docs/project/.\n\n---\n\n"
889
+ )
890
+ archive_content = archive_header + engineering_plan["original"]
891
+ archive_dir = repo / "docs" / "archive" / "workflow"
892
+ archive = archive_dir / f"ENGINEERING.pre-{version}.md"
893
+ if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
894
+ digest = hashlib.sha256(engineering_plan["original"].encode("utf-8")).hexdigest()[:12]
895
+ archive = archive_dir / f"ENGINEERING.pre-{version}-{digest}.md"
896
+ if not archive.exists():
897
+ add_action("policy", archive, "archive", "before duplicate workflow section cleanup")
898
+ if write:
899
+ archive.parent.mkdir(parents=True, exist_ok=True)
900
+ archive.write_text(archive_content, encoding="utf-8")
901
+
854
902
  tool_files = [
855
903
  (
856
904
  source_root / "data" / "templates" / "tools" / "ap.py",
@@ -889,26 +937,39 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
889
937
  for dst in _iter_files(project_skill):
890
938
  rel = dst.relative_to(project_skill)
891
939
  if not (source_root / rel).exists():
892
- if rel.parts[:3] == ("data", "templates", "docs"):
893
- continue
894
- if rel.parent in _MANAGED_EXTRA_CLEANUP_DIRS:
895
- add_action("skill", dst, "delete", "stale managed template")
896
- if write:
897
- dst.unlink()
898
- else:
899
- add_action("skill", dst, "extra", "present only in project copy")
940
+ add_action("skill", dst, "delete", "stale file in fully managed Skill copy")
941
+ if write:
942
+ dst.unlink()
900
943
  else:
901
944
  add_action("skill", project_skill, "create", "install runtime required by the project launcher")
902
945
  if write:
903
946
  copy_tree(source_root, project_skill)
904
947
 
905
- agents_plan = workflow_plan_by_path["AGENTS.md"]
906
948
  agents_path = repo / "AGENTS.md"
907
- if agents_plan["output"] != agents_plan["original"]:
908
- migrated = ", ".join(item["id"] for item in agents_plan["migrations"])
909
- add_action("policy", agents_path, "migrate", migrated)
949
+ canonical_agents = template_agents.read_text(encoding="utf-8") if template_agents.exists() else ""
950
+ current_agents = agents_path.read_text(encoding="utf-8") if agents_path.exists() else ""
951
+ if canonical_agents and current_agents != canonical_agents:
952
+ if current_agents:
953
+ archive_dir = repo / "docs" / "archive" / "workflow"
954
+ archive_header = (
955
+ "# Archived AGENTS.md before auto-coding-skill 4.1.1\n\n"
956
+ "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
957
+ "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
958
+ "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
959
+ )
960
+ archive_content = archive_header + current_agents
961
+ archive = archive_dir / "AGENTS.pre-4.1.1.md"
962
+ if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
963
+ digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
964
+ archive = archive_dir / f"AGENTS.pre-4.1.1-{digest}.md"
965
+ if not archive.exists():
966
+ add_action("policy", archive, "archive", "historical and non-authoritative")
967
+ if write:
968
+ archive.parent.mkdir(parents=True, exist_ok=True)
969
+ archive.write_text(archive_content, encoding="utf-8")
970
+ add_action("policy", agents_path, "replace", "fully managed canonical AGENTS.md")
910
971
  if write:
911
- agents_path.write_text(agents_plan["output"], encoding="utf-8")
972
+ agents_path.write_text(canonical_agents, encoding="utf-8")
912
973
 
913
974
  docs_template = templates / "docs"
914
975
  for rel in _CORE_DOC_TEMPLATES:
@@ -928,6 +989,10 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
928
989
  engineering = repo / "docs" / "ENGINEERING.md"
929
990
  if engineering.exists() and template_engineering.exists():
930
991
  planned_engineering = engineering_plan["output"] or engineering.read_text(encoding="utf-8")
992
+ planned_engineering = _sync_managed_workflow_text(
993
+ planned_engineering,
994
+ template_engineering.read_text(encoding="utf-8"),
995
+ )
931
996
  current_cfg, body = _parse_frontmatter_markdown_text(planned_engineering, engineering)
932
997
  template_cfg, _ = _read_frontmatter_markdown(template_engineering)
933
998
  merged_cfg = json.loads(json.dumps(current_cfg))
@@ -1223,7 +1288,7 @@ def _load_workflow_migration_policy(repo: Path) -> dict:
1223
1288
  for index, fragment in enumerate(policy["known_official_fragments"]):
1224
1289
  if not isinstance(fragment, dict):
1225
1290
  raise APError(f"Workflow migration policy fragment[{index}] must be an object")
1226
- if fragment.get("match") not in {"exact-line", "exact-block"}:
1291
+ if fragment.get("match") not in {"exact-line", "exact-block", "heading-section"}:
1227
1292
  raise APError(f"Workflow migration policy fragment[{index}] has invalid match mode")
1228
1293
  if not _text(fragment.get("id")) or not isinstance(fragment.get("paths"), list):
1229
1294
  raise APError(f"Workflow migration policy fragment[{index}] is incomplete")
@@ -1292,6 +1357,30 @@ def _managed_document_span(text: str, kind: str, rel: str) -> Optional[tuple[int
1292
1357
  return starts[0].start(), ends[0].end()
1293
1358
 
1294
1359
 
1360
+ def _sync_managed_workflow_text(current: str, template: str) -> str:
1361
+ """Install the canonical managed workflow while preserving project facts."""
1362
+ template_span = _managed_document_span(template, "workflow", "template ENGINEERING.md")
1363
+ if not template_span:
1364
+ raise APError("Packaged ENGINEERING template has no managed workflow block")
1365
+ block = template[template_span[0]:template_span[1]]
1366
+ current_span = _managed_document_span(current, "workflow", "docs/ENGINEERING.md")
1367
+ if current_span:
1368
+ return current[:current_span[0]] + block + current[current_span[1]:]
1369
+
1370
+ frontmatter = _frontmatter_span(current, "docs/ENGINEERING.md")
1371
+ body_start = frontmatter[1] if frontmatter else 0
1372
+ body = current[body_start:]
1373
+ heading = re.search(r"^# Engineering Workflow[^\n]*(?:\n|$)", body, flags=re.MULTILINE)
1374
+ insertion = body_start + (heading.end() if heading else 0)
1375
+ before = current[:insertion]
1376
+ after = current[insertion:]
1377
+ if before and not before.endswith("\n"):
1378
+ before += "\n"
1379
+ if after and not after.startswith("\n"):
1380
+ after = "\n" + after
1381
+ return before + block + after
1382
+
1383
+
1295
1384
  def _frontmatter_span(text: str, rel: str) -> Optional[tuple[int, int]]:
1296
1385
  if not text.startswith("---\n"):
1297
1386
  return None
@@ -1314,6 +1403,28 @@ def _known_fragment_spans(
1314
1403
  replacement = str(fragment.get("replacement") or "")
1315
1404
  match_mode = _text(fragment.get("match"))
1316
1405
  expected = str(fragment.get("text") or "").replace("\r\n", "\n")
1406
+ if fragment.get("match") == "heading-section":
1407
+ lines = visible.splitlines(keepends=True)
1408
+ offsets: list[int] = []
1409
+ cursor = 0
1410
+ for line in lines:
1411
+ offsets.append(cursor)
1412
+ cursor += len(line)
1413
+ for index, line in enumerate(lines):
1414
+ heading = re.match(r"^\s*(#{1,6})\s+(.+?)\s*#*\s*$", line.rstrip("\n"))
1415
+ if not heading or heading.group(2).strip() != expected.strip():
1416
+ continue
1417
+ level = len(heading.group(1))
1418
+ end_index = index + 1
1419
+ while end_index < len(lines):
1420
+ next_heading = re.match(r"^\s*(#{1,6})\s+", lines[end_index])
1421
+ if next_heading and len(next_heading.group(1)) <= level:
1422
+ break
1423
+ end_index += 1
1424
+ end = offsets[end_index] if end_index < len(offsets) else len(visible)
1425
+ start = offsets[index]
1426
+ found.append((start, end, fragment_id, visible.count("\n", 0, start) + 1, replacement, match_mode))
1427
+ continue
1317
1428
  if fragment.get("match") == "exact-line":
1318
1429
  cursor = 0
1319
1430
  for line in visible.splitlines(keepends=True):
@@ -1330,7 +1441,17 @@ def _known_fragment_spans(
1330
1441
  end = start + len(expected)
1331
1442
  found.append((start, end, fragment_id, visible.count("\n", 0, start) + 1, replacement, match_mode))
1332
1443
  cursor = end
1333
- return found
1444
+ section_spans = [
1445
+ (start, end)
1446
+ for start, end, _, _, _, match_mode in found
1447
+ if match_mode == "heading-section"
1448
+ ]
1449
+ return [
1450
+ item
1451
+ for item in found
1452
+ if item[5] == "heading-section"
1453
+ or not any(start <= item[0] and item[1] <= end for start, end in section_spans)
1454
+ ]
1334
1455
 
1335
1456
 
1336
1457
  def _workflow_document_plan(repo: Path, rel: str, policy: dict) -> dict:
@@ -1953,6 +2074,36 @@ def _path_is_owned(path: str, owned_paths: list[str]) -> bool:
1953
2074
  )
1954
2075
 
1955
2076
 
2077
+ def _owned_paths_overlap(left: list[str], right: list[str]) -> bool:
2078
+ for first in left:
2079
+ first = _normalize_owned_path(first)
2080
+ for second in right:
2081
+ second = _normalize_owned_path(second)
2082
+ if (
2083
+ first == "."
2084
+ or second == "."
2085
+ or first == second
2086
+ or first.startswith(second.rstrip("/") + "/")
2087
+ or second.startswith(first.rstrip("/") + "/")
2088
+ ):
2089
+ return True
2090
+ return False
2091
+
2092
+
2093
+ _TERMINAL_LEDGER_PATTERNS = [
2094
+ "docs/tasks/taskbook.md",
2095
+ "docs/tasks/closure-log.md",
2096
+ "docs/tasks/archive-index.md",
2097
+ "docs/tasks/archives/**",
2098
+ "docs/tasks/closures/**",
2099
+ "docs/archive/design/**",
2100
+ ]
2101
+
2102
+
2103
+ def _is_terminal_ledger_maintenance(paths: list[str]) -> bool:
2104
+ return bool(paths) and all(_path_matches(path, _TERMINAL_LEDGER_PATTERNS) for path in paths)
2105
+
2106
+
1956
2107
  def _task_managed_paths(cfg: dict, manifest: dict) -> list[str]:
1957
2108
  if int(manifest.get("schema") or 2) >= 3:
1958
2109
  return []
@@ -2362,6 +2513,45 @@ def _validation_cfg(cfg: dict) -> dict:
2362
2513
  return value if isinstance(value, dict) else {}
2363
2514
 
2364
2515
 
2516
+ def _positive_seconds(value: object, default: float, label: str) -> float:
2517
+ if value in {None, ""}:
2518
+ return default
2519
+ try:
2520
+ parsed = float(value)
2521
+ except (TypeError, ValueError) as exc:
2522
+ raise APError(f"{label} must be a positive number") from exc
2523
+ if parsed <= 0:
2524
+ raise APError(f"{label} must be a positive number")
2525
+ return parsed
2526
+
2527
+
2528
+ def _final_gate_budget(cfg: dict) -> dict[str, float]:
2529
+ validation_cfg = _validation_cfg(cfg)
2530
+ command_seconds = _positive_seconds(
2531
+ validation_cfg.get("max_command_seconds"),
2532
+ _MAX_FINAL_COMMAND_SECONDS,
2533
+ "validation.max_command_seconds",
2534
+ )
2535
+ total_seconds = _positive_seconds(
2536
+ validation_cfg.get("max_total_seconds"),
2537
+ _MAX_FINAL_TOTAL_SECONDS,
2538
+ "validation.max_total_seconds",
2539
+ )
2540
+ if command_seconds > _MAX_FINAL_COMMAND_SECONDS:
2541
+ raise APError(
2542
+ f"validation.max_command_seconds cannot exceed {_MAX_FINAL_COMMAND_SECONDS:.0f}; "
2543
+ "move slower checks to an explicit diagnostic command"
2544
+ )
2545
+ if total_seconds > _MAX_FINAL_TOTAL_SECONDS:
2546
+ raise APError(
2547
+ f"validation.max_total_seconds cannot exceed {_MAX_FINAL_TOTAL_SECONDS:.0f}; "
2548
+ "move slower checks to an explicit diagnostic command"
2549
+ )
2550
+ if command_seconds > total_seconds:
2551
+ raise APError("validation.max_command_seconds cannot exceed validation.max_total_seconds")
2552
+ return {"command_seconds": command_seconds, "total_seconds": total_seconds}
2553
+
2554
+
2365
2555
  def _as_list(value: object) -> list:
2366
2556
  if value is None:
2367
2557
  return []
@@ -2391,7 +2581,14 @@ def _run_first_configured_command(repo: Path, cfg: dict, names: list[str]) -> st
2391
2581
  return ""
2392
2582
 
2393
2583
 
2394
- def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str]:
2584
+ def _run_configured_command_list(
2585
+ repo: Path,
2586
+ cfg: dict,
2587
+ names: list,
2588
+ *,
2589
+ deadline: Optional[float] = None,
2590
+ command_timeout_s: Optional[float] = None,
2591
+ ) -> list[str]:
2395
2592
  executed: list[str] = []
2396
2593
  missing: list[str] = []
2397
2594
  for name_ref in names:
@@ -2399,7 +2596,16 @@ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str
2399
2596
  if not name:
2400
2597
  continue
2401
2598
  if _configured_command(cfg, name):
2402
- _run_configured_command(repo, cfg, name)
2599
+ timeout_s = command_timeout_s
2600
+ if deadline is not None:
2601
+ remaining = deadline - time.monotonic()
2602
+ if remaining <= 0:
2603
+ raise APError(
2604
+ "Final changed-scope gate exceeded its total time budget before "
2605
+ f"commands.{name}; narrow validation.routes"
2606
+ )
2607
+ timeout_s = min(timeout_s, remaining) if timeout_s is not None else remaining
2608
+ _run_configured_command(repo, cfg, name, timeout_s=timeout_s)
2403
2609
  executed.append(name)
2404
2610
  else:
2405
2611
  missing.append(name)
@@ -2732,7 +2938,14 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
2732
2938
  print("[impact] changed: (none)")
2733
2939
 
2734
2940
 
2735
- def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2941
+ def _run_changed_gate(
2942
+ repo: Path,
2943
+ cfg: dict,
2944
+ paths: list[str],
2945
+ *,
2946
+ deadline: Optional[float] = None,
2947
+ command_timeout_s: Optional[float] = None,
2948
+ ) -> list[str]:
2736
2949
  plan = _validation_plan(cfg, paths)
2737
2950
  _validate_validation_plan(cfg, plan)
2738
2951
  if not paths:
@@ -2746,7 +2959,13 @@ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2746
2959
  "[validation] WARN: using 3.x compatibility fallback; migrate to validation.routes",
2747
2960
  file=sys.stderr,
2748
2961
  )
2749
- executed = _run_configured_command_list(repo, cfg, plan["commands"])
2962
+ executed = _run_configured_command_list(
2963
+ repo,
2964
+ cfg,
2965
+ plan["commands"],
2966
+ deadline=deadline,
2967
+ command_timeout_s=command_timeout_s,
2968
+ )
2750
2969
  print(
2751
2970
  "[validation] routes="
2752
2971
  + (", ".join(plan["matched_routes"]) or "(none)")
@@ -4208,9 +4427,10 @@ def _classification_for_categories(categories: set[str], file_count: int) -> dic
4208
4427
  "needs_dd": bool(
4209
4428
  categories
4210
4429
  & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config", "release_or_tooling"}
4211
- )
4212
- or file_count > 12,
4213
- "needs_adr": bool(categories & {"structure", "release_or_tooling"}) and not categories <= {"docs"},
4430
+ ),
4431
+ # Path names and file counts do not justify a durable architecture
4432
+ # record. The model or an explicit project rule decides.
4433
+ "needs_adr": False,
4214
4434
  "needs_browser": "ui" in categories,
4215
4435
  "needs_jenkins": bool(
4216
4436
  categories & {"release_or_tooling", "db", "auth", "payment", "gateway", "prod_config"}
@@ -4354,13 +4574,10 @@ def _agent_execution_plan(
4354
4574
  review_required: bool = False,
4355
4575
  ) -> dict:
4356
4576
  assignment_contract, result_contract = _agent_contract_shape()
4577
+ # Classification reports useful capabilities but never auto-dispatches
4578
+ # discovery roles. The model chooses delegation only when expected benefit
4579
+ # exceeds coordination cost.
4357
4580
  discovery_roles: list[str] = []
4358
- if categories & {"api", "release_or_tooling"}:
4359
- discovery_roles.append("docs_researcher")
4360
- if classification.get("needs_browser"):
4361
- discovery_roles.append("browser_debugger")
4362
- if profile == "high-risk" and not discovery_roles:
4363
- discovery_roles.append("explorer")
4364
4581
 
4365
4582
  policies = {
4366
4583
  "one_writer_per_worktree": True,
@@ -4426,6 +4643,51 @@ def _agent_execution_plan(
4426
4643
  })
4427
4644
 
4428
4645
 
4646
+ def _mechanism_plan(
4647
+ *,
4648
+ has_task_signal: bool,
4649
+ terminal_maintenance: bool,
4650
+ execution_mode: str,
4651
+ review_required: bool,
4652
+ design_required: bool,
4653
+ parallel_writers: int,
4654
+ ) -> dict:
4655
+ code_delivery = has_task_signal and not terminal_maintenance
4656
+ required = ["analysis"] if has_task_signal else []
4657
+ if design_required:
4658
+ required.append("durable_design")
4659
+ if execution_mode == "isolated":
4660
+ required.extend(["task_lifecycle", "worktree"])
4661
+ elif review_required:
4662
+ required.append("task_lifecycle")
4663
+ if parallel_writers > 1:
4664
+ required.append("parallel_fixers")
4665
+ if review_required:
4666
+ required.append("independent_review")
4667
+ if code_delivery:
4668
+ required.extend(["final_changed_scope_gate", "commit_push"])
4669
+ ordered = list(dict.fromkeys(required))
4670
+ optional = [
4671
+ mechanism
4672
+ for mechanism in [
4673
+ "classify",
4674
+ "durable_design",
4675
+ "task_lifecycle",
4676
+ "worktree",
4677
+ "read_only_subagents",
4678
+ "parallel_fixers",
4679
+ "independent_review",
4680
+ ]
4681
+ if mechanism not in ordered
4682
+ ]
4683
+ return {
4684
+ "required": ordered,
4685
+ "not_required": optional,
4686
+ "lifecycle_required": "task_lifecycle" in ordered,
4687
+ "rule": "do not add a mechanism that is not required unless the user explicitly requests it",
4688
+ }
4689
+
4690
+
4429
4691
  def _resolve_execution_plan(
4430
4692
  cfg: dict,
4431
4693
  repo: Path,
@@ -4471,6 +4733,7 @@ def _resolve_execution_plan(
4471
4733
  (docs_only_paths and str(impact["selected_scope"]) != "full")
4472
4734
  or _tests_only(classification_inputs)
4473
4735
  )
4736
+ terminal_maintenance = _is_terminal_ledger_maintenance(classification_inputs)
4474
4737
  if docs_or_tests_only and str(impact["selected_scope"]) != "full":
4475
4738
  detected_profile = "micro"
4476
4739
  profile_reasons.append("only docs/test files changed")
@@ -4503,9 +4766,6 @@ def _resolve_execution_plan(
4503
4766
  high_signals.append("high-risk category: " + ", ".join(sorted(categories & high_categories)))
4504
4767
  if "high-risk" in rule_profiles:
4505
4768
  high_signals.append("matched gate rule with profile=high-risk")
4506
- if len(classification_inputs) > 12 and not docs_or_tests_only:
4507
- high_signals.append("change spans more than 12 files")
4508
-
4509
4769
  if high_signals:
4510
4770
  detected_profile = "high-risk"
4511
4771
  profile_reasons.extend(high_signals)
@@ -4552,12 +4812,22 @@ def _resolve_execution_plan(
4552
4812
  _text(rule.get("design")).lower() in {"required", "true", "yes"}
4553
4813
  for rule in matching_rules
4554
4814
  )
4555
- review_required = bool(effective_profile == "high-risk" or writer_count > 1 or cross_module or rule_review)
4556
- design_required = bool(rule_design or (effective_profile == "high-risk" and cross_module))
4815
+ cross_module_contract_risk = bool(
4816
+ cross_module
4817
+ and categories & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config"}
4818
+ )
4819
+ review_required = bool(
4820
+ not terminal_maintenance
4821
+ and (effective_profile == "high-risk" or writer_count > 1 or cross_module_contract_risk or rule_review)
4822
+ )
4823
+ design_required = bool(
4824
+ not terminal_maintenance
4825
+ and (rule_design or (effective_profile == "high-risk" and cross_module))
4826
+ )
4557
4827
  has_task_signal = bool(classification_inputs or _text(intent))
4558
4828
  workspace_dirty = bool(_working_tree_paths(repo))
4559
4829
  configured_isolation = _task_isolation(cfg)
4560
- if not has_task_signal:
4830
+ if terminal_maintenance or not has_task_signal:
4561
4831
  execution_mode = "none"
4562
4832
  elif configured_isolation == "worktree" or writer_count > 1 or workspace_dirty:
4563
4833
  execution_mode = "isolated"
@@ -4578,6 +4848,14 @@ def _resolve_execution_plan(
4578
4848
  parallel_writers=writer_count,
4579
4849
  review_required=review_required,
4580
4850
  )
4851
+ mechanism_plan = _mechanism_plan(
4852
+ has_task_signal=has_task_signal,
4853
+ terminal_maintenance=terminal_maintenance,
4854
+ execution_mode=execution_mode,
4855
+ review_required=review_required,
4856
+ design_required=design_required,
4857
+ parallel_writers=writer_count,
4858
+ )
4581
4859
  return {
4582
4860
  **impact,
4583
4861
  "contract_version": _AGENT_CONTRACT_VERSION,
@@ -4595,6 +4873,7 @@ def _resolve_execution_plan(
4595
4873
  "requested_mode": requested_mode_value or None,
4596
4874
  "effective_mode": effective_mode,
4597
4875
  "execution_mode": execution_mode,
4876
+ "terminal_maintenance": terminal_maintenance,
4598
4877
  "workspace_dirty": workspace_dirty,
4599
4878
  "parallel_writers": writer_count,
4600
4879
  "cross_module": cross_module,
@@ -4615,6 +4894,7 @@ def _resolve_execution_plan(
4615
4894
  review_required=review_required,
4616
4895
  ),
4617
4896
  "agent_plan": agent_plan,
4897
+ "mechanism_plan": mechanism_plan,
4618
4898
  }
4619
4899
 
4620
4900
 
@@ -4666,6 +4946,14 @@ def cmd_classify(args: argparse.Namespace) -> None:
4666
4946
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
4667
4947
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
4668
4948
  print(f"[classify] agent_strategy={result['agent_plan']['strategy']}")
4949
+ print(
4950
+ "[classify] required_mechanisms="
4951
+ + (", ".join(result["mechanism_plan"]["required"]) or "(none)")
4952
+ )
4953
+ print(
4954
+ "[classify] not_required="
4955
+ + (", ".join(result["mechanism_plan"]["not_required"]) or "(none)")
4956
+ )
4669
4957
  for stage in result["agent_plan"]["stages"]:
4670
4958
  print(
4671
4959
  "[classify] agent_stage="
@@ -4705,7 +4993,10 @@ def cmd_run(args: argparse.Namespace) -> None:
4705
4993
  def cmd_light_gate(args: argparse.Namespace) -> None:
4706
4994
  repo = Path(args.repo).resolve()
4707
4995
  light_gate_start = time.time()
4996
+ monotonic_start = time.monotonic()
4708
4997
  cfg = _load_cfg(repo)
4998
+ budget = _final_gate_budget(cfg)
4999
+ deadline = monotonic_start + budget["total_seconds"]
4709
5000
  requested_scope = _text(getattr(args, "scope", "")).lower()
4710
5001
  if requested_scope not in {"", "auto", "changed"}:
4711
5002
  raise APError(
@@ -4727,9 +5018,20 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
4727
5018
 
4728
5019
  selected_scope = "changed"
4729
5020
  paths = list(plan.get("changed_files") or [])
4730
- executed = _run_changed_gate(repo, cfg, paths)
5021
+ executed = _run_changed_gate(
5022
+ repo,
5023
+ cfg,
5024
+ paths,
5025
+ deadline=deadline,
5026
+ command_timeout_s=budget["command_seconds"],
5027
+ )
4731
5028
 
4732
5029
  _run_git_diff_check(repo, cfg)
5030
+ if time.monotonic() > deadline:
5031
+ raise APError(
5032
+ f"Final changed-scope gate exceeded {budget['total_seconds']:.0f}s; "
5033
+ "narrow validation.routes and keep slower checks explicit"
5034
+ )
4733
5035
  executed.append("diff_check")
4734
5036
  duration_s = time.time() - light_gate_start
4735
5037
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
@@ -4920,12 +5222,15 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4920
5222
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
4921
5223
  profile = str(workflow_cfg.get("profile") or "auto").strip().lower()
4922
5224
  completion = str(workflow_cfg.get("completion") or "").strip().lower()
5225
+ skill_version = _text(workflow_cfg.get("skill_version"))
4923
5226
  if mode != "dev":
4924
5227
  missing.append("workflow.mode (must be dev; external verification is owner-managed)")
4925
5228
  if profile not in _WORKFLOW_PROFILES:
4926
5229
  missing.append("workflow.profile (must be auto, micro, standard, or high-risk)")
4927
5230
  if completion != "push":
4928
5231
  missing.append("workflow.completion (must be push)")
5232
+ if skill_version.startswith("4.1") and _text(docs_cfg.get("framework")) != "engineering-centered":
5233
+ missing.append("docs.framework (must be engineering-centered for auto-coding-skill 4.1)")
4929
5234
  isolation = _text(concurrency_cfg.get("isolation")).lower() or "adaptive"
4930
5235
  if isolation not in {"adaptive", "worktree"}:
4931
5236
  validation_errors.append(
@@ -4997,6 +5302,10 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4997
5302
  on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
4998
5303
  if on_unmapped not in {"error", "fallback"}:
4999
5304
  validation_errors.append("validation.on_unmapped must be error or fallback")
5305
+ try:
5306
+ _final_gate_budget(cfg)
5307
+ except APError as exc:
5308
+ validation_errors.append(str(exc))
5000
5309
  routes = validation_cfg.get("routes") or []
5001
5310
  if not isinstance(routes, list):
5002
5311
  validation_errors.append("validation.routes must be a list")
@@ -5028,6 +5337,26 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5028
5337
  validation_errors.append(
5029
5338
  "validation.routes is empty and no 3.x commands.gate_changed compatibility fallback exists"
5030
5339
  )
5340
+ tracked_validation_paths = [
5341
+ path
5342
+ for path in _tracked_files(repo)
5343
+ if not _path_matches(
5344
+ path,
5345
+ [
5346
+ "*.md",
5347
+ "docs/**",
5348
+ ".agents/**",
5349
+ ".local/**",
5350
+ "AGENTS.md",
5351
+ ],
5352
+ )
5353
+ ]
5354
+ if tracked_validation_paths:
5355
+ try:
5356
+ tracked_plan = _validation_plan(cfg, tracked_validation_paths)
5357
+ _validate_validation_plan(cfg, tracked_plan)
5358
+ except APError as exc:
5359
+ validation_errors.append(f"tracked validation coverage: {exc}")
5031
5360
 
5032
5361
  repo_docs: dict[str, Path] = {}
5033
5362
  api_doc = Path(repo, str(docs_cfg.get("api_doc", "docs/interfaces/api.md")))
@@ -6300,6 +6629,30 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6300
6629
  owned_paths = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
6301
6630
  if not owned_paths:
6302
6631
  raise APError("task-start requires at least one --owned-path.")
6632
+ if _is_terminal_ledger_maintenance(owned_paths):
6633
+ raise APError(
6634
+ "Pure taskbook/closure/archive reconciliation is terminal maintenance and must not "
6635
+ "create another task lifecycle. Run the targeted document check, commit once, and push."
6636
+ )
6637
+ writer_count = max(1, int(getattr(args, "writers", 1) or 1))
6638
+ if writer_count != 1:
6639
+ raise APError(
6640
+ "task-start creates exactly one writer lease and one worktree. Start each parallel "
6641
+ "writer as its own task ID; use --writers only with classify for planning."
6642
+ )
6643
+ registry_dir = _task_state_root(repo) / "tasks"
6644
+ for manifest_path in sorted(registry_dir.glob("*.json")) if registry_dir.exists() else []:
6645
+ active_manifest = _read_json_object(manifest_path) or {}
6646
+ if _text(active_manifest.get("state")) in {"integrated", "cleanup-pending"}:
6647
+ continue
6648
+ active_owned = active_manifest.get("owned_paths") or []
6649
+ if isinstance(active_owned, list) and _owned_paths_overlap(owned_paths, active_owned):
6650
+ active_id = _text(active_manifest.get("task_id")) or manifest_path.stem
6651
+ raise APError(
6652
+ f"Owned paths overlap active task {active_id}: "
6653
+ + ", ".join(active_owned)
6654
+ + ". Split ownership into non-overlapping task units or finish the active writer first."
6655
+ )
6303
6656
  depends_on: list[str] = []
6304
6657
  prerequisite_shas: dict[str, str] = {}
6305
6658
  for raw_dependency in args.depends_on or []:
@@ -6321,13 +6674,23 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6321
6674
  if not owner:
6322
6675
  raise APError("task-start requires --owner or CODEX_THREAD_ID.")
6323
6676
  writer = _text(getattr(args, "writer", "")) or owner
6324
- writer_count = max(1, int(getattr(args, "writers", 1) or 1))
6325
6677
  plan = _resolve_execution_plan(
6326
6678
  cfg,
6327
6679
  repo,
6328
6680
  planned_paths=owned_paths,
6329
6681
  parallel_writers=writer_count,
6330
6682
  )
6683
+ explicit_lifecycle = bool(
6684
+ getattr(args, "isolated", False)
6685
+ or getattr(args, "review_required", False)
6686
+ or getattr(args, "force_lifecycle", False)
6687
+ )
6688
+ if not plan["mechanism_plan"]["lifecycle_required"] and not explicit_lifecycle:
6689
+ raise APError(
6690
+ "This clean serial task does not need a machine task lifecycle. Work directly on "
6691
+ "the current branch, run the routed final gate, commit, and push. Use task-start "
6692
+ "only when classify requires isolation/review or the user explicitly requests it."
6693
+ )
6331
6694
  review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
6332
6695
  registry_dir = _task_state_root(repo) / "tasks"
6333
6696
  other_active = any(
@@ -6352,6 +6715,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6352
6715
  direct_base = _resolve_commit(repo, "HEAD")
6353
6716
  manifest = {
6354
6717
  "schema": 3,
6718
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
6355
6719
  "execution_mode": "direct",
6356
6720
  "review_required": review_required,
6357
6721
  "task_id": task_id,
@@ -6431,6 +6795,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6431
6795
  )
6432
6796
  manifest = {
6433
6797
  "schema": 3,
6798
+ "skill_version": _text((cfg.get("workflow") or {}).get("skill_version")),
6434
6799
  "execution_mode": "isolated",
6435
6800
  "review_required": review_required,
6436
6801
  "task_id": task_id,
@@ -7668,6 +8033,11 @@ def main(argv: Optional[List[str]] = None) -> int:
7668
8033
  s.add_argument("--writers", type=int, default=1)
7669
8034
  s.add_argument("--isolated", action="store_true")
7670
8035
  s.add_argument("--review-required", action="store_true")
8036
+ s.add_argument(
8037
+ "--force-lifecycle",
8038
+ action="store_true",
8039
+ help="Use only when the user explicitly requests lifecycle tracking for clean serial work",
8040
+ )
7671
8041
  s.add_argument("--owned-path", action="append")
7672
8042
  s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
7673
8043
  s.add_argument("--no-fetch", action="store_true")