@elvis1513/auto-coding-skill 4.1.0 → 4.1.2

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
+ _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
50
+ _RECOMMENDED_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.1.0", "engineering": "4.1.0"},
54
+ "managed_versions": {"agents": "4.1.2", "engineering": "4.1.2"},
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))
@@ -630,8 +638,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
630
638
  if _text(workflow_cfg.get("completion")).lower() != "push":
631
639
  workflow_cfg["completion"] = "push"
632
640
  changed.append("workflow.completion")
633
- if _text(workflow_cfg.get("skill_version")) != "4.1.0":
634
- workflow_cfg["skill_version"] = "4.1.0"
641
+ if _text(workflow_cfg.get("skill_version")) != "4.1.2":
642
+ workflow_cfg["skill_version"] = "4.1.2"
635
643
  changed.append("workflow.skill_version")
636
644
 
637
645
  commands_cfg = cfg.setdefault("commands", {})
@@ -680,6 +688,13 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
680
688
  if _text(validation_cfg.get("on_unmapped")).lower() != "error":
681
689
  validation_cfg["on_unmapped"] = "error"
682
690
  changed.append("validation.on_unmapped")
691
+ for key, default_value in [
692
+ ("max_command_seconds", int(_RECOMMENDED_FINAL_COMMAND_SECONDS)),
693
+ ("max_total_seconds", int(_RECOMMENDED_FINAL_TOTAL_SECONDS)),
694
+ ]:
695
+ if key not in validation_cfg:
696
+ validation_cfg[key] = default_value
697
+ changed.append(f"validation.{key}")
683
698
  validation_routes = validation_cfg.setdefault("routes", [])
684
699
  if not isinstance(validation_routes, list):
685
700
  validation_routes = []
@@ -937,16 +952,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
937
952
  if current_agents:
938
953
  archive_dir = repo / "docs" / "archive" / "workflow"
939
954
  archive_header = (
940
- "# Archived AGENTS.md before auto-coding-skill 4.1.0\n\n"
955
+ "# Archived AGENTS.md before auto-coding-skill 4.1.2\n\n"
941
956
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
942
957
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
943
958
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
944
959
  )
945
960
  archive_content = archive_header + current_agents
946
- archive = archive_dir / "AGENTS.pre-4.1.0.md"
961
+ archive = archive_dir / "AGENTS.pre-4.1.2.md"
947
962
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
948
963
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
949
- archive = archive_dir / f"AGENTS.pre-4.1.0-{digest}.md"
964
+ archive = archive_dir / f"AGENTS.pre-4.1.2-{digest}.md"
950
965
  if not archive.exists():
951
966
  add_action("policy", archive, "archive", "historical and non-authoritative")
952
967
  if write:
@@ -1717,6 +1732,17 @@ def _task_registry_path(repo: Path, task_id: str) -> Path:
1717
1732
  return _task_state_root(repo) / "tasks" / f"{_validate_task_id(task_id)}.json"
1718
1733
 
1719
1734
 
1735
+ def _has_registered_active_task(repo: Path) -> bool:
1736
+ registry = _task_state_root(repo) / "tasks"
1737
+ if not registry.exists():
1738
+ return False
1739
+ for path in sorted(registry.glob("*.json")):
1740
+ payload = _read_json_object(path) or {}
1741
+ if _text(payload.get("state")) not in {"", "integrated", "cleanup-pending"}:
1742
+ return True
1743
+ return False
1744
+
1745
+
1720
1746
  def _worktree_manifest_path(repo: Path) -> Path:
1721
1747
  return _git_dir(repo) / "auto-coding-skill-task.json"
1722
1748
 
@@ -2451,6 +2477,7 @@ def _resolve_secret(section_name: str, section_cfg: dict, field: str) -> str:
2451
2477
 
2452
2478
  _GATE_SCOPES = {"auto", "changed", "standard", "full"}
2453
2479
  _WORKFLOW_PROFILES = {"auto", "micro", "standard", "high-risk"}
2480
+ _TASK_KINDS = {"auto", "none", "read_only", "change", "terminal_maintenance"}
2454
2481
  _PROFILE_GATE_SCOPE = {"micro": "changed", "standard": "changed", "high-risk": "changed"}
2455
2482
  _PROFILE_RANK = {"micro": 0, "standard": 1, "high-risk": 2}
2456
2483
  _SCOPE_RANK = {"changed": 0, "standard": 1, "full": 2}
@@ -2498,6 +2525,35 @@ def _validation_cfg(cfg: dict) -> dict:
2498
2525
  return value if isinstance(value, dict) else {}
2499
2526
 
2500
2527
 
2528
+ def _positive_seconds(value: object, default: float, label: str) -> float:
2529
+ if value in {None, ""}:
2530
+ return default
2531
+ try:
2532
+ parsed = float(value)
2533
+ except (TypeError, ValueError) as exc:
2534
+ raise APError(f"{label} must be a positive number") from exc
2535
+ if parsed <= 0:
2536
+ raise APError(f"{label} must be a positive number")
2537
+ return parsed
2538
+
2539
+
2540
+ def _final_gate_budget(cfg: dict) -> dict[str, float]:
2541
+ validation_cfg = _validation_cfg(cfg)
2542
+ command_seconds = _positive_seconds(
2543
+ validation_cfg.get("max_command_seconds"),
2544
+ _RECOMMENDED_FINAL_COMMAND_SECONDS,
2545
+ "validation.max_command_seconds",
2546
+ )
2547
+ total_seconds = _positive_seconds(
2548
+ validation_cfg.get("max_total_seconds"),
2549
+ _RECOMMENDED_FINAL_TOTAL_SECONDS,
2550
+ "validation.max_total_seconds",
2551
+ )
2552
+ if command_seconds > total_seconds:
2553
+ raise APError("validation.max_command_seconds cannot exceed validation.max_total_seconds")
2554
+ return {"command_seconds": command_seconds, "total_seconds": total_seconds}
2555
+
2556
+
2501
2557
  def _as_list(value: object) -> list:
2502
2558
  if value is None:
2503
2559
  return []
@@ -2527,7 +2583,15 @@ def _run_first_configured_command(repo: Path, cfg: dict, names: list[str]) -> st
2527
2583
  return ""
2528
2584
 
2529
2585
 
2530
- def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str]:
2586
+ def _run_configured_command_list(
2587
+ repo: Path,
2588
+ cfg: dict,
2589
+ names: list,
2590
+ *,
2591
+ deadline: Optional[float] = None,
2592
+ command_timeout_s: Optional[float] = None,
2593
+ command_timeouts: Optional[dict[str, float]] = None,
2594
+ ) -> list[str]:
2531
2595
  executed: list[str] = []
2532
2596
  missing: list[str] = []
2533
2597
  for name_ref in names:
@@ -2535,7 +2599,19 @@ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str
2535
2599
  if not name:
2536
2600
  continue
2537
2601
  if _configured_command(cfg, name):
2538
- _run_configured_command(repo, cfg, name)
2602
+ timeout_s = command_timeout_s
2603
+ route_timeout = (command_timeouts or {}).get(name)
2604
+ if route_timeout is not None:
2605
+ timeout_s = min(timeout_s, route_timeout) if timeout_s is not None else route_timeout
2606
+ if deadline is not None:
2607
+ remaining = deadline - time.monotonic()
2608
+ if remaining <= 0:
2609
+ raise APError(
2610
+ "Final changed-scope gate exceeded its total time budget before "
2611
+ f"commands.{name}; narrow validation.routes"
2612
+ )
2613
+ timeout_s = min(timeout_s, remaining) if timeout_s is not None else remaining
2614
+ _run_configured_command(repo, cfg, name, timeout_s=timeout_s)
2539
2615
  executed.append(name)
2540
2616
  else:
2541
2617
  missing.append(name)
@@ -2714,6 +2790,7 @@ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2714
2790
  normalized = _unique_paths(paths)
2715
2791
  routes = _validation_routes(cfg)
2716
2792
  command_names: list[str] = []
2793
+ command_timeouts: dict[str, float] = {}
2717
2794
  matched_routes: list[str] = []
2718
2795
  coverage: dict[str, list[str]] = {}
2719
2796
  unmapped: list[str] = []
@@ -2724,6 +2801,13 @@ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2724
2801
  if not _validation_route_matches(path, route):
2725
2802
  continue
2726
2803
  route_name = _text(route.get("name")) or f"route-{index + 1}"
2804
+ route_timeout: Optional[float] = None
2805
+ if route.get("timeout_seconds") not in {None, ""}:
2806
+ route_timeout = _positive_seconds(
2807
+ route.get("timeout_seconds"),
2808
+ 1.0,
2809
+ f"validation.routes[{index}].timeout_seconds",
2810
+ )
2727
2811
  names.append(route_name)
2728
2812
  if route_name not in matched_routes:
2729
2813
  matched_routes.append(route_name)
@@ -2731,6 +2815,13 @@ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2731
2815
  command_name = _command_name(command_ref)
2732
2816
  if command_name and command_name not in command_names:
2733
2817
  command_names.append(command_name)
2818
+ if command_name and route_timeout is not None:
2819
+ current_timeout = command_timeouts.get(command_name)
2820
+ command_timeouts[command_name] = (
2821
+ min(current_timeout, route_timeout)
2822
+ if current_timeout is not None
2823
+ else route_timeout
2824
+ )
2734
2825
  coverage[path] = names
2735
2826
  if not names and not _path_matches(path, _DOC_PATH_PATTERNS):
2736
2827
  unmapped.append(path)
@@ -2759,6 +2850,7 @@ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2759
2850
  return {
2760
2851
  "paths": normalized,
2761
2852
  "commands": command_names,
2853
+ "command_timeouts": command_timeouts,
2762
2854
  "matched_routes": matched_routes,
2763
2855
  "coverage": coverage,
2764
2856
  "unmapped": unmapped,
@@ -2868,7 +2960,14 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
2868
2960
  print("[impact] changed: (none)")
2869
2961
 
2870
2962
 
2871
- def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2963
+ def _run_changed_gate(
2964
+ repo: Path,
2965
+ cfg: dict,
2966
+ paths: list[str],
2967
+ *,
2968
+ deadline: Optional[float] = None,
2969
+ command_timeout_s: Optional[float] = None,
2970
+ ) -> list[str]:
2872
2971
  plan = _validation_plan(cfg, paths)
2873
2972
  _validate_validation_plan(cfg, plan)
2874
2973
  if not paths:
@@ -2882,7 +2981,14 @@ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2882
2981
  "[validation] WARN: using 3.x compatibility fallback; migrate to validation.routes",
2883
2982
  file=sys.stderr,
2884
2983
  )
2885
- executed = _run_configured_command_list(repo, cfg, plan["commands"])
2984
+ executed = _run_configured_command_list(
2985
+ repo,
2986
+ cfg,
2987
+ plan["commands"],
2988
+ deadline=deadline,
2989
+ command_timeout_s=command_timeout_s,
2990
+ command_timeouts=plan["command_timeouts"],
2991
+ )
2886
2992
  print(
2887
2993
  "[validation] routes="
2888
2994
  + (", ".join(plan["matched_routes"]) or "(none)")
@@ -2907,6 +3013,7 @@ def cmd_validation_map_check(args: argparse.Namespace) -> None:
2907
3013
  result = {
2908
3014
  "paths": plan["paths"],
2909
3015
  "commands": plan["commands"],
3016
+ "command_timeouts": plan["command_timeouts"],
2910
3017
  "matched_routes": plan["matched_routes"],
2911
3018
  "coverage": plan["coverage"],
2912
3019
  "docs_only": plan["docs_only"],
@@ -4381,6 +4488,47 @@ def _classify_intent(intent: str) -> list[str]:
4381
4488
  )
4382
4489
 
4383
4490
 
4491
+ def _resolve_task_kind(
4492
+ requested: str,
4493
+ paths: list[str],
4494
+ intent: str,
4495
+ ) -> str:
4496
+ value = _text(requested).lower().replace("-", "_") or "auto"
4497
+ if value not in _TASK_KINDS:
4498
+ raise APError("task kind must be one of: " + ", ".join(sorted(_TASK_KINDS)))
4499
+ if value != "auto":
4500
+ return value
4501
+ if _is_terminal_ledger_maintenance(paths):
4502
+ return "terminal_maintenance"
4503
+ if paths:
4504
+ return "change"
4505
+ normalized_intent = _text(intent).lower()
4506
+ if not normalized_intent:
4507
+ return "none"
4508
+ terminal_action = bool(
4509
+ re.search(r"\b(archive|close|reconcile)\b", normalized_intent)
4510
+ or any(keyword in normalized_intent for keyword in ["归档", "对账", "收口"])
4511
+ )
4512
+ terminal_subject = bool(
4513
+ re.search(r"\b(closure|ledger|task\s+records?|taskbook)\b", normalized_intent)
4514
+ or any(keyword in normalized_intent for keyword in ["台账", "任务记录", "关闭记录"])
4515
+ )
4516
+ if terminal_action and terminal_subject:
4517
+ return "terminal_maintenance"
4518
+ english_change = re.search(
4519
+ r"\b(add|build|change|create|delete|deploy|develop|fix|implement|migrate|optimize|publish|refactor|release|remove|rename|resolve|update|upgrade)\b",
4520
+ normalized_intent,
4521
+ )
4522
+ chinese_change = any(
4523
+ keyword in normalized_intent
4524
+ for keyword in [
4525
+ "修改", "新增", "删除", "修复", "解决", "整改", "实现", "迁移", "发布",
4526
+ "重构", "改名", "升级", "优化", "完善", "补充", "清理", "落地", "提交", "推送",
4527
+ ]
4528
+ )
4529
+ return "change" if english_change or chinese_change else "read_only"
4530
+
4531
+
4384
4532
  def _normalize_workflow_profile(value: object, default: str = "auto") -> str:
4385
4533
  profile = _text(value).lower() or default
4386
4534
  if profile not in _WORKFLOW_PROFILES:
@@ -4560,6 +4708,71 @@ def _agent_execution_plan(
4560
4708
  })
4561
4709
 
4562
4710
 
4711
+ def _mechanism_plan(
4712
+ *,
4713
+ task_kind: str,
4714
+ execution_mode: str,
4715
+ review_required: bool,
4716
+ design_required: bool,
4717
+ parallel_writers: int,
4718
+ ) -> dict:
4719
+ universe = [
4720
+ "analysis",
4721
+ "targeted_consistency_check",
4722
+ "durable_design",
4723
+ "task_lifecycle",
4724
+ "worktree",
4725
+ "read_only_subagents",
4726
+ "parallel_fixers",
4727
+ "independent_review",
4728
+ "final_changed_scope_gate",
4729
+ "commit_push",
4730
+ ]
4731
+ required: list[str] = []
4732
+ optional: list[str] = []
4733
+ if task_kind == "read_only":
4734
+ required = ["analysis"]
4735
+ optional = ["read_only_subagents"]
4736
+ elif task_kind == "terminal_maintenance":
4737
+ required = ["analysis", "targeted_consistency_check", "commit_push"]
4738
+ elif task_kind == "change":
4739
+ required = ["analysis"]
4740
+ if design_required:
4741
+ required.append("durable_design")
4742
+ else:
4743
+ optional.append("durable_design")
4744
+ if execution_mode == "isolated":
4745
+ required.extend(["task_lifecycle", "worktree"])
4746
+ elif review_required:
4747
+ required.append("task_lifecycle")
4748
+ if parallel_writers > 1:
4749
+ required.append("parallel_fixers")
4750
+ else:
4751
+ optional.append("parallel_fixers")
4752
+ if review_required:
4753
+ required.append("independent_review")
4754
+ else:
4755
+ optional.append("independent_review")
4756
+ optional.append("read_only_subagents")
4757
+ required.extend(["final_changed_scope_gate", "commit_push"])
4758
+ ordered = list(dict.fromkeys(required))
4759
+ optional = [item for item in dict.fromkeys(optional) if item not in ordered]
4760
+ forbidden = [item for item in universe if item not in ordered and item not in optional]
4761
+ return {
4762
+ "required": ordered,
4763
+ "optional_when_beneficial": optional,
4764
+ "forbidden": forbidden,
4765
+ # 4.1 compatibility: old clients treat only truly forbidden mechanisms
4766
+ # as not required; model-selectable mechanisms remain available.
4767
+ "not_required": forbidden,
4768
+ "lifecycle_required": "task_lifecycle" in ordered,
4769
+ "rule": (
4770
+ "run required mechanisms; select optional mechanisms only when expected value exceeds "
4771
+ "coordination cost; do not run forbidden mechanisms unless the user explicitly overrides"
4772
+ ),
4773
+ }
4774
+
4775
+
4563
4776
  def _resolve_execution_plan(
4564
4777
  cfg: dict,
4565
4778
  repo: Path,
@@ -4572,6 +4785,7 @@ def _resolve_execution_plan(
4572
4785
  planned_paths: Optional[list[str]] = None,
4573
4786
  intent: str = "",
4574
4787
  parallel_writers: int = 1,
4788
+ requested_task_kind: str = "",
4575
4789
  ) -> dict:
4576
4790
  impact = _impact_summary(
4577
4791
  cfg,
@@ -4585,6 +4799,7 @@ def _resolve_execution_plan(
4585
4799
  {_normalize_owned_path(item) for item in (planned_paths or []) if _text(item)}
4586
4800
  )
4587
4801
  classification_inputs = [*paths, *normalized_planned_paths]
4802
+ task_kind = _resolve_task_kind(requested_task_kind, classification_inputs, intent)
4588
4803
  classification = _classify_paths(classification_inputs)
4589
4804
  intent_categories = _classify_intent(intent)
4590
4805
  merged_categories = set(classification["categories"]) | set(intent_categories)
@@ -4605,8 +4820,11 @@ def _resolve_execution_plan(
4605
4820
  (docs_only_paths and str(impact["selected_scope"]) != "full")
4606
4821
  or _tests_only(classification_inputs)
4607
4822
  )
4608
- terminal_maintenance = _is_terminal_ledger_maintenance(classification_inputs)
4609
- if docs_or_tests_only and str(impact["selected_scope"]) != "full":
4823
+ terminal_maintenance = task_kind == "terminal_maintenance"
4824
+ if task_kind in {"read_only", "terminal_maintenance", "none"}:
4825
+ detected_profile = "micro"
4826
+ profile_reasons.append(f"task kind: {task_kind}")
4827
+ elif docs_or_tests_only and str(impact["selected_scope"]) != "full":
4610
4828
  detected_profile = "micro"
4611
4829
  profile_reasons.append("only docs/test files changed")
4612
4830
 
@@ -4617,10 +4835,10 @@ def _resolve_execution_plan(
4617
4835
  "matched gate rule has invalid profile: " + ", ".join(sorted(invalid_rule_profiles))
4618
4836
  )
4619
4837
  rule_profiles = raw_rule_profiles
4620
- if "micro" in rule_profiles and detected_profile == "standard":
4838
+ if task_kind == "change" and "micro" in rule_profiles and detected_profile == "standard":
4621
4839
  detected_profile = "micro"
4622
4840
  profile_reasons.append("matched gate rule with profile=micro")
4623
- if "standard" in rule_profiles and detected_profile == "micro":
4841
+ if task_kind == "change" and "standard" in rule_profiles and detected_profile == "micro":
4624
4842
  detected_profile = "standard"
4625
4843
  profile_reasons.append("matched gate rule with profile=standard")
4626
4844
 
@@ -4634,9 +4852,9 @@ def _resolve_execution_plan(
4634
4852
  "release_or_tooling",
4635
4853
  }
4636
4854
  high_signals: list[str] = []
4637
- if categories & high_categories and not docs_or_tests_only:
4855
+ if task_kind == "change" and categories & high_categories and not docs_or_tests_only:
4638
4856
  high_signals.append("high-risk category: " + ", ".join(sorted(categories & high_categories)))
4639
- if "high-risk" in rule_profiles:
4857
+ if task_kind == "change" and "high-risk" in rule_profiles:
4640
4858
  high_signals.append("matched gate rule with profile=high-risk")
4641
4859
  if high_signals:
4642
4860
  detected_profile = "high-risk"
@@ -4689,19 +4907,19 @@ def _resolve_execution_plan(
4689
4907
  and categories & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config"}
4690
4908
  )
4691
4909
  review_required = bool(
4692
- not terminal_maintenance
4910
+ task_kind == "change"
4693
4911
  and (effective_profile == "high-risk" or writer_count > 1 or cross_module_contract_risk or rule_review)
4694
4912
  )
4695
4913
  design_required = bool(
4696
- not terminal_maintenance
4914
+ task_kind == "change"
4697
4915
  and (rule_design or (effective_profile == "high-risk" and cross_module))
4698
4916
  )
4699
- has_task_signal = bool(classification_inputs or _text(intent))
4700
4917
  workspace_dirty = bool(_working_tree_paths(repo))
4918
+ active_writer = _has_registered_active_task(repo)
4701
4919
  configured_isolation = _task_isolation(cfg)
4702
- if terminal_maintenance or not has_task_signal:
4920
+ if task_kind != "change":
4703
4921
  execution_mode = "none"
4704
- elif configured_isolation == "worktree" or writer_count > 1 or workspace_dirty:
4922
+ elif configured_isolation == "worktree" or writer_count > 1 or workspace_dirty or active_writer:
4705
4923
  execution_mode = "isolated"
4706
4924
  else:
4707
4925
  execution_mode = "direct"
@@ -4720,6 +4938,13 @@ def _resolve_execution_plan(
4720
4938
  parallel_writers=writer_count,
4721
4939
  review_required=review_required,
4722
4940
  )
4941
+ mechanism_plan = _mechanism_plan(
4942
+ task_kind=task_kind,
4943
+ execution_mode=execution_mode,
4944
+ review_required=review_required,
4945
+ design_required=design_required,
4946
+ parallel_writers=writer_count,
4947
+ )
4723
4948
  return {
4724
4949
  **impact,
4725
4950
  "contract_version": _AGENT_CONTRACT_VERSION,
@@ -4727,6 +4952,7 @@ def _resolve_execution_plan(
4727
4952
  "planned_files": normalized_planned_paths,
4728
4953
  "classification_files": classification_inputs,
4729
4954
  "intent_provided": bool(_text(intent)),
4955
+ "task_kind": task_kind,
4730
4956
  "intent_categories": intent_categories,
4731
4957
  "reasons": execution_reasons,
4732
4958
  "configured_profile": configured_profile,
@@ -4739,6 +4965,7 @@ def _resolve_execution_plan(
4739
4965
  "execution_mode": execution_mode,
4740
4966
  "terminal_maintenance": terminal_maintenance,
4741
4967
  "workspace_dirty": workspace_dirty,
4968
+ "active_writer": active_writer,
4742
4969
  "parallel_writers": writer_count,
4743
4970
  "cross_module": cross_module,
4744
4971
  "review_required": review_required,
@@ -4758,6 +4985,7 @@ def _resolve_execution_plan(
4758
4985
  review_required=review_required,
4759
4986
  ),
4760
4987
  "agent_plan": agent_plan,
4988
+ "mechanism_plan": mechanism_plan,
4761
4989
  }
4762
4990
 
4763
4991
 
@@ -4786,6 +5014,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
4786
5014
  planned_paths=list(getattr(args, "planned_path", []) or []),
4787
5015
  intent="\n".join(part for part in intent_parts if part),
4788
5016
  parallel_writers=int(getattr(args, "writers", 1) or 1),
5017
+ requested_task_kind=_text(getattr(args, "task_kind", "")),
4789
5018
  )
4790
5019
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
4791
5020
  commands: list[str] = []
@@ -4800,6 +5029,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
4800
5029
  print(json.dumps(result, ensure_ascii=False, indent=2))
4801
5030
  else:
4802
5031
  print(f"[classify] risk={risk}")
5032
+ print(f"[classify] task_kind={result['task_kind']}")
4803
5033
  print(f"[classify] profile={result['profile']}")
4804
5034
  print(f"[classify] effective_mode={result['effective_mode']}")
4805
5035
  print(f"[classify] execution_mode={result['execution_mode']}")
@@ -4809,6 +5039,18 @@ def cmd_classify(args: argparse.Namespace) -> None:
4809
5039
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
4810
5040
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
4811
5041
  print(f"[classify] agent_strategy={result['agent_plan']['strategy']}")
5042
+ print(
5043
+ "[classify] required_mechanisms="
5044
+ + (", ".join(result["mechanism_plan"]["required"]) or "(none)")
5045
+ )
5046
+ print(
5047
+ "[classify] optional_when_beneficial="
5048
+ + (", ".join(result["mechanism_plan"]["optional_when_beneficial"]) or "(none)")
5049
+ )
5050
+ print(
5051
+ "[classify] forbidden="
5052
+ + (", ".join(result["mechanism_plan"]["forbidden"]) or "(none)")
5053
+ )
4812
5054
  for stage in result["agent_plan"]["stages"]:
4813
5055
  print(
4814
5056
  "[classify] agent_stage="
@@ -4848,7 +5090,10 @@ def cmd_run(args: argparse.Namespace) -> None:
4848
5090
  def cmd_light_gate(args: argparse.Namespace) -> None:
4849
5091
  repo = Path(args.repo).resolve()
4850
5092
  light_gate_start = time.time()
5093
+ monotonic_start = time.monotonic()
4851
5094
  cfg = _load_cfg(repo)
5095
+ budget = _final_gate_budget(cfg)
5096
+ deadline = monotonic_start + budget["total_seconds"]
4852
5097
  requested_scope = _text(getattr(args, "scope", "")).lower()
4853
5098
  if requested_scope not in {"", "auto", "changed"}:
4854
5099
  raise APError(
@@ -4870,9 +5115,20 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
4870
5115
 
4871
5116
  selected_scope = "changed"
4872
5117
  paths = list(plan.get("changed_files") or [])
4873
- executed = _run_changed_gate(repo, cfg, paths)
5118
+ executed = _run_changed_gate(
5119
+ repo,
5120
+ cfg,
5121
+ paths,
5122
+ deadline=deadline,
5123
+ command_timeout_s=budget["command_seconds"],
5124
+ )
4874
5125
 
4875
5126
  _run_git_diff_check(repo, cfg)
5127
+ if time.monotonic() > deadline:
5128
+ raise APError(
5129
+ f"Final changed-scope gate exceeded {budget['total_seconds']:.0f}s; "
5130
+ "narrow validation.routes and keep slower checks explicit"
5131
+ )
4876
5132
  executed.append("diff_check")
4877
5133
  duration_s = time.time() - light_gate_start
4878
5134
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
@@ -5058,6 +5314,7 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5058
5314
 
5059
5315
  missing: List[str] = []
5060
5316
  validation_errors: List[str] = []
5317
+ advisories: List[str] = []
5061
5318
  validation_errors.extend(_workflow_policy_issues(repo, cfg))
5062
5319
 
5063
5320
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
@@ -5143,6 +5400,24 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5143
5400
  on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
5144
5401
  if on_unmapped not in {"error", "fallback"}:
5145
5402
  validation_errors.append("validation.on_unmapped must be error or fallback")
5403
+ try:
5404
+ final_budget = _final_gate_budget(cfg)
5405
+ if final_budget["command_seconds"] > _RECOMMENDED_FINAL_COMMAND_SECONDS:
5406
+ advisories.append(
5407
+ "validation.max_command_seconds exceeds the recommended 120s default; "
5408
+ "keep the affected-scope route targeted"
5409
+ )
5410
+ if final_budget["total_seconds"] > _RECOMMENDED_FINAL_TOTAL_SECONDS:
5411
+ advisories.append(
5412
+ "validation.max_total_seconds exceeds the recommended 180s default; "
5413
+ "keep the final gate bounded to affected scope"
5414
+ )
5415
+ except APError as exc:
5416
+ validation_errors.append(str(exc))
5417
+ final_budget = {
5418
+ "command_seconds": _RECOMMENDED_FINAL_COMMAND_SECONDS,
5419
+ "total_seconds": _RECOMMENDED_FINAL_TOTAL_SECONDS,
5420
+ }
5146
5421
  routes = validation_cfg.get("routes") or []
5147
5422
  if not isinstance(routes, list):
5148
5423
  validation_errors.append("validation.routes must be a list")
@@ -5161,6 +5436,20 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5161
5436
  validation_errors.append(
5162
5437
  f"validation.routes[{index}] references missing commands.{command_name}"
5163
5438
  )
5439
+ if "timeout_seconds" in route:
5440
+ try:
5441
+ route_timeout = _positive_seconds(
5442
+ route.get("timeout_seconds"),
5443
+ final_budget["command_seconds"],
5444
+ f"validation.routes[{index}].timeout_seconds",
5445
+ )
5446
+ if route_timeout > final_budget["command_seconds"]:
5447
+ advisories.append(
5448
+ f"validation.routes[{index}].timeout_seconds exceeds max_command_seconds "
5449
+ "and will be capped"
5450
+ )
5451
+ except APError as exc:
5452
+ validation_errors.append(str(exc))
5164
5453
  fallback_name = _command_name(validation_cfg.get("fallback_command"))
5165
5454
  if on_unmapped == "fallback" and not fallback_name:
5166
5455
  validation_errors.append(
@@ -5227,6 +5516,8 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5227
5516
  "pass",
5228
5517
  {"mode": mode, "completion": completion, "access_fields": len(_REQUIRED_ACCESS_FIELDS)},
5229
5518
  )
5519
+ for advisory in advisories:
5520
+ print(f"[doctor] WARN: {advisory}")
5230
5521
  print("[doctor] OK")
5231
5522
 
5232
5523
 
@@ -6437,6 +6728,41 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6437
6728
  repo = Path(args.repo).resolve()
6438
6729
  ensure_git_repo(repo)
6439
6730
  cfg = _load_cfg(repo)
6731
+ _require_control_checkout(repo)
6732
+ task_id = _validate_task_id(args.task_id)
6733
+ owned_paths = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
6734
+ if not owned_paths:
6735
+ raise APError("task-start requires at least one --owned-path.")
6736
+ if _is_terminal_ledger_maintenance(owned_paths):
6737
+ raise APError(
6738
+ "Pure taskbook/closure/archive reconciliation is terminal maintenance and must not "
6739
+ "create another task lifecycle. Run the targeted document check, commit once, and push."
6740
+ )
6741
+ writer_count = max(1, int(getattr(args, "writers", 1) or 1))
6742
+ if writer_count != 1:
6743
+ raise APError(
6744
+ "task-start creates exactly one writer lease and one worktree. Start each parallel "
6745
+ "writer as its own task ID; use --writers only with classify for planning."
6746
+ )
6747
+ explicit_lifecycle = bool(
6748
+ getattr(args, "isolated", False)
6749
+ or getattr(args, "review_required", False)
6750
+ or getattr(args, "force_lifecycle", False)
6751
+ )
6752
+ preflight_plan = _resolve_execution_plan(
6753
+ cfg,
6754
+ repo,
6755
+ planned_paths=owned_paths,
6756
+ parallel_writers=writer_count,
6757
+ requested_task_kind="change",
6758
+ )
6759
+ if not preflight_plan["mechanism_plan"]["lifecycle_required"] and not explicit_lifecycle:
6760
+ raise APError(
6761
+ "This clean serial task does not need a machine task lifecycle. Work directly on "
6762
+ "the current branch, run the routed final gate, commit, and push. Use task-start "
6763
+ "only when classify requires isolation/review or the user explicitly requests it."
6764
+ )
6765
+
6440
6766
  _require_workflow_policy_clean(repo, cfg)
6441
6767
  configured_isolation = _task_isolation(cfg)
6442
6768
  access_issues = _access_config_issues(cfg)
@@ -6445,8 +6771,6 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6445
6771
  "Project initialization is incomplete; fill docs/ENGINEERING.md before starting work:\n- "
6446
6772
  + "\n- ".join(access_issues)
6447
6773
  )
6448
- task_id = _validate_task_id(args.task_id)
6449
- _require_control_checkout(repo)
6450
6774
  remote, target_branch, base_ref = _task_remote_and_target(cfg, args)
6451
6775
  concurrency_cfg = _concurrency_cfg(cfg)
6452
6776
  timeout_s = float(concurrency_cfg.get("lock_timeout_sec") or 30)
@@ -6463,20 +6787,6 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6463
6787
  if not getattr(args, "no_fetch", False) and base_ref.startswith(f"{remote}/"):
6464
6788
  _fetch_target(repo, remote, target_branch)
6465
6789
  base_sha = _resolve_commit(repo, base_ref)
6466
- owned_paths = sorted({_normalize_owned_path(item) for item in (args.owned_path or [])})
6467
- if not owned_paths:
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
6790
  registry_dir = _task_state_root(repo) / "tasks"
6481
6791
  for manifest_path in sorted(registry_dir.glob("*.json")) if registry_dir.exists() else []:
6482
6792
  active_manifest = _read_json_object(manifest_path) or {}
@@ -6516,7 +6826,14 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6516
6826
  repo,
6517
6827
  planned_paths=owned_paths,
6518
6828
  parallel_writers=writer_count,
6829
+ requested_task_kind="change",
6519
6830
  )
6831
+ if not plan["mechanism_plan"]["lifecycle_required"] and not explicit_lifecycle:
6832
+ raise APError(
6833
+ "This clean serial task does not need a machine task lifecycle. Work directly on "
6834
+ "the current branch, run the routed final gate, commit, and push. Use task-start "
6835
+ "only when classify requires isolation/review or the user explicitly requests it."
6836
+ )
6520
6837
  review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
6521
6838
  registry_dir = _task_state_root(repo) / "tasks"
6522
6839
  other_active = any(
@@ -7751,6 +8068,7 @@ def main(argv: Optional[List[str]] = None) -> int:
7751
8068
  s.add_argument("--planned-path", action="append")
7752
8069
  s.add_argument("--intent")
7753
8070
  s.add_argument("--intent-file")
8071
+ s.add_argument("--task-kind", choices=sorted(_TASK_KINDS), default="auto")
7754
8072
  s.add_argument("--writers", type=int, default=1)
7755
8073
  s.add_argument("--json", action="store_true")
7756
8074
  s.set_defaults(func=cmd_classify)
@@ -7859,6 +8177,11 @@ def main(argv: Optional[List[str]] = None) -> int:
7859
8177
  s.add_argument("--writers", type=int, default=1)
7860
8178
  s.add_argument("--isolated", action="store_true")
7861
8179
  s.add_argument("--review-required", action="store_true")
8180
+ s.add_argument(
8181
+ "--force-lifecycle",
8182
+ action="store_true",
8183
+ help="Use only when the user explicitly requests lifecycle tracking for clean serial work",
8184
+ )
7862
8185
  s.add_argument("--owned-path", action="append")
7863
8186
  s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
7864
8187
  s.add_argument("--no-fetch", action="store_true")