@elvis1513/auto-coding-skill 4.1.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.
@@ -1,135 +1,119 @@
1
- <!-- auto-coding-skill:managed-agents:start version=4.1.0 -->
2
-
3
- # Repository Delivery Rules
1
+ <!-- auto-coding-skill:managed-agents:start version=4.1.1 -->
2
+ # Shared Engineering Protocol
4
3
 
5
4
  This file is fully managed by `auto-coding-skill`. Keep project-specific facts,
6
- commands, access values, path mappings, architecture boundaries, and runtime
7
- notes in `docs/ENGINEERING.md` or its linked project documents. Do not add local
8
- workflow rules here; the next Skill sync replaces this file as a whole.
5
+ access values, risk rules, and validation routes in `docs/ENGINEERING.md`.
6
+
7
+ ## Authority
9
8
 
10
- ## Required sources
9
+ Use this order when sources disagree:
11
10
 
12
- Before changing a repository, read:
11
+ 1. The current user request.
12
+ 2. Code, tests, schemas, migrations, and runtime configuration for behavior that
13
+ exists now.
14
+ 3. `docs/ENGINEERING.md` for project facts and workflow configuration.
15
+ 4. Current interface documentation for intended contracts.
16
+ 5. Accepted DD/ADR for lasting decisions.
17
+ 6. Taskbooks, closures, reviews, and deployment records as history only.
13
18
 
14
- 1. the current user request;
15
- 2. this file;
16
- 3. `docs/ENGINEERING.md` frontmatter and project-specific sections;
17
- 4. only the source, tests, contracts, migrations, runtime configuration, or
18
- decision records relevant to the requested scope.
19
+ Update authoritative documentation when a change intentionally changes its
20
+ contract. Never let stale history override current implementation.
19
21
 
20
- Use this authority order when sources disagree:
22
+ ## Minimum mechanism budget
21
23
 
22
- 1. the current user request;
23
- 2. executable code, tests, schemas, migrations, and runtime configuration for
24
- behavior that exists now;
25
- 3. `docs/ENGINEERING.md` for project boundaries, access, risk, and validation;
26
- 4. interface documentation for intended external contracts;
27
- 5. accepted DD/ADR documents for lasting decisions;
28
- 6. taskbooks, closure logs, summaries, reviews, and deployment records as
29
- historical evidence only.
24
+ Use only mechanisms that improve expected delivery speed or defect prevention.
25
+ The default budget is:
30
26
 
31
- Do not let stale historical documents override current implementation. If a
32
- requested change intentionally changes a contract or decision, update the
33
- authoritative documentation in the same change.
27
+ | Situation | Required mechanisms |
28
+ | --- | --- |
29
+ | Read-only question | none |
30
+ | Obvious clean serial edit | analysis, affected gate, commit/push |
31
+ | Terminal ledger/archive maintenance | targeted consistency check, one commit |
32
+ | Dirty checkout or concurrent writer | registered lifecycle and isolated worktree |
33
+ | High-risk or contract-crossing change | necessary design and independent review |
34
+ | Multiple independent writers | one task/worktree/lease per writer, ordered integration |
34
35
 
35
- ## Delivery flow
36
+ Do not add classify, task lifecycle, durable design, subagents, reviewer, or a
37
+ worktree outside this budget merely because the tool exists. If impact is unclear,
38
+ run `classify` and follow `mechanism_plan.required`; items in
39
+ `mechanism_plan.not_required` stay off unless the user explicitly requests them.
36
40
 
37
- This Skill is a selectable guardrail, not a mandatory ceremony. The model first
38
- decides which mechanisms have positive net value for the current task. Read-only
39
- work, an obvious clean-checkout edit, or terminal ledger reconciliation normally
40
- needs no classify command, task lifecycle, design record, reviewer, or subagent.
41
- Use the smallest safe path for repository changes:
41
+ Normal delivery is:
42
42
 
43
- `analysis → decomposition → necessary design → development → one final
43
+ `analysis → decomposition → necessary design → development → one bounded final
44
44
  changed-scope gate → commit/push`.
45
45
 
46
- - Analyze impact and reuse points before writing.
47
- - Split only genuinely independent work; keep dependencies and file ownership
48
- explicit.
46
+ Push to the target branch ends normal coding. Do not poll Jenkins, deploy, or run
47
+ owner acceptance automatically. A user-requested diagnosis of the just-pushed
48
+ failure may continue in the same conversation/task without a second lifecycle.
49
+
50
+ ## Git and parallel work
51
+
52
+ - One writer in a clean checkout works directly on the current branch without a
53
+ task lifecycle.
54
+ - Existing unrelated changes, another writer, or configured mandatory isolation
55
+ requires a registered task branch/worktree.
56
+ - Every writing agent owns a distinct task ID, worktree, writer lease,
57
+ non-overlapping `owned_paths`, and prerequisite commit SHAs.
58
+ - Never let multiple writing agents share a checkout. Never restore, reset, stash,
59
+ clean, overwrite, or commit unknown changes.
60
+ - No diff means no commit, push, or temporary branch.
61
+ - The main agent integrates in dependency order and removes only clean, safely
62
+ merged temporary worktrees and branches.
63
+ - Do not sync or upgrade while any registered task is active.
64
+
65
+ ## Design, agents, and review
66
+
67
+ - Micro and standard tasks stay main-agent-only unless independent delegation has
68
+ a concrete latency or expertise benefit.
49
69
  - Create DD/ADR only for lasting cross-module, API, data, security, deployment,
50
70
  or key user-flow decisions.
51
- - Focused tests may run and rerun during implementation. Run the configured final
52
- routed gate once after the diff is stable.
53
- - Commit and push all intended changes. A successful target-branch push ends
54
- normal coding work.
55
- - Do not poll Jenkins, deploy, or perform target acceptance automatically. If the
56
- user explicitly asks to diagnose a failure caused by the pushed change, keep
57
- that diagnosis and fix in the same conversation and task scope without
58
- creating an artificial new ledger task.
59
-
60
- ## Git safety and parallel work
61
-
62
- Inspect the checkout before writing.
63
-
64
- - One writer in a clean checkout works on the current branch.
65
- - Pre-existing unrelated changes, an already active writer, or two or more
66
- writers require isolated task branches/worktrees.
67
- - Each parallel writer gets one registered worktree, non-overlapping
68
- `owned_paths`, dependency commit SHAs, a distinct task ID, and a writer lease.
69
- - Never let multiple writing agents share a checkout.
70
- - Never restore, reset, stash, clean, overwrite, or commit unknown changes.
71
- - If a task produces no diff, create no commit or push. Direct work creates no
72
- temporary branch.
73
- - The main agent alone integrates by dependency order, pushes the target branch,
74
- and removes only clean, safely merged temporary worktrees and branches.
75
-
76
- Do not upgrade or sync the Skill while any registered task is active. Finish,
77
- integrate, or clean it with the installed runtime first so lifecycle semantics do
78
- not change mid-task.
79
-
80
- ## Risk, agents, and review
81
-
82
- - Micro and standard tasks default to the main agent. Do not require design,
83
- fan-out, a task ledger, or a reviewer merely because a change is non-trivial.
84
- - Use read-only explorer, documentation researcher, or browser roles only for
85
- independent questions whose expected value exceeds coordination cost.
86
- - Use parallel fixers only for bounded, dependency-aware units with separate
87
- worktrees and non-overlapping paths.
88
- - Require independent review for high-risk, cross-module, parallel integration,
71
+ - Use read-only explorer/docs/browser agents only for independent questions.
72
+ - Use parallel fixers only for bounded, dependency-free, non-overlapping units.
73
+ - Require fingerprinted review only for high-risk, contract-crossing, parallel,
89
74
  or explicitly configured work.
90
- - Review blocks only defects introduced or worsened inside the promised task
91
- scope. Record adjacent pre-existing issues as non-blocking follow-ups.
92
- - Any semantic code/config change invalidates review approval and requires a new
93
- diff fingerprint. A mechanical documentation-only correction may receive a
94
- targeted recheck by the same reviewer against the new fingerprint.
95
- - Historical debt does not block ordinary delivery. Block only new or worsened
96
- P0/P1 issues; handle broad cleanup through an explicit governance task.
97
-
98
- ## Validation
99
-
100
- `risk.rules` controls reasoning and review depth. `validation.routes` controls
101
- executable checks. Keep them separate.
102
-
103
- - Every changed code/config path must match one or more explicit validation
104
- routes in `docs/ENGINEERING.md`.
105
- - Run every matched command once in stable configuration order and de-duplicate
106
- repeated command references.
107
- - Unmapped code or a missing/blank command fails before staging.
108
- - Documentation-only work may use the built-in diff/format check.
109
- - `git diff --check` is additional hygiene and never business-code validation.
110
- - Use project-native fast checks. Do not automatically run a full repository
111
- build, Docker, Jenkins, deployment, live-device writes, or target validation.
112
- - Do not install dependencies proactively. Only after the selected final route
113
- fails because a repository-locked dependency is absent may it be restored once;
114
- then retry only that affected route.
115
- - External-system or real-device writes require the project's explicit safety
116
- rule or user confirmation; prefer fixtures/simulators for repeatable local
117
- coverage where the project supplies them.
75
+ - Review blocks only defects introduced or worsened in the promised scope.
76
+ Adjacent existing issues are non-blocking follow-ups.
77
+ - Semantic changes invalidate approval. Mechanical documentation-only corrections
78
+ may receive a targeted recheck by the same reviewer.
79
+ - Historical debt does not block ordinary delivery; block only new or worsened
80
+ P0/P1 issues.
81
+
82
+ ## Bounded real validation
83
+
84
+ - `risk.rules` controls reasoning/review depth. `validation.routes` alone selects
85
+ executable closure checks.
86
+ - Every changed code/config path must match one or more explicit routes. Run every
87
+ matched command once in stable order and de-duplicate references.
88
+ - Unmapped code or blank commands fail before staging. Documentation-only work may
89
+ use the built-in diff/format check. `git diff --check` is hygiene, not business
90
+ validation.
91
+ - Focused tests may run and rerun during development. Run one final routed gate
92
+ after the diff is stable.
93
+ - The final gate has hard project-configurable ceilings of 120 seconds per command
94
+ and 180 seconds total. A timeout must narrow the route; never expand or retry it
95
+ as a full gate.
96
+ - Do not proactively install dependencies. Only after the selected route fails
97
+ because a repository-locked dependency is absent may it be restored once and
98
+ only that route retried.
99
+ - Full regression, repository-wide scans, builds, Docker, Jenkins, deployment,
100
+ live-device writes, browser/API acceptance, and target checks are explicit
101
+ diagnostics, not normal closure.
102
+ - External-system writes require the project safety rule or user confirmation;
103
+ use fixtures/simulators when the project supplies them.
118
104
 
119
105
  ## Documentation and access
120
106
 
121
- - `docs/ENGINEERING.md` is the single project workflow configuration source. Its
122
- managed block explains the shared protocol; content outside that block contains
123
- project facts, not competing workflow instructions.
124
- - Put durable product/domain facts, repository maps, and runtime/deployment facts
125
- in `docs/project/` when they are too large for `ENGINEERING.md`.
126
- - Ordinary work does not create taskbook, closure Markdown, evidence JSONL,
127
- active-task documents, or design files. Pure ledger/archive reconciliation is
128
- a terminal maintenance action and must not create another task lifecycle.
129
- - Generated task state, leases, fingerprints, and gate evidence stay in Git
130
- common/local state so recording them cannot change the reviewed diff.
131
- - Fill the configured project/Jenkins/GitLab/Nexus access fields during project
132
- initialization. Plaintext values are allowed by the generic workflow; do not
133
- invent or echo credentials unnecessarily.
107
+ - This AGENTS file is the single behavioral protocol. The installed `SKILL.md`
108
+ contains invocation guidance. `docs/ENGINEERING.md` is the single project
109
+ configuration and facts source. Do not repeat the protocol elsewhere.
110
+ - Put larger product, repository, and runtime facts under `docs/project/` and link
111
+ them from ENGINEERING.
112
+ - Ordinary work creates no taskbook, closure Markdown, evidence JSONL, active-task
113
+ document, or design file. Machine coordination/evidence stays in Git
114
+ common/local state and cannot change the reviewed diff.
115
+ - Pure ledger/archive reconciliation is terminal: validate, commit once, and stop.
116
+ - Fill configured project/Jenkins/GitLab/Nexus access fields during initialization.
117
+ Plaintext values are allowed; do not invent or unnecessarily echo credentials.
134
118
 
135
119
  <!-- auto-coding-skill:managed-agents:end -->
@@ -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.1.0", "engineering": "4.1.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))
@@ -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.1":
642
+ workflow_cfg["skill_version"] = "4.1.1"
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(_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}")
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.1\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.1.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.1-{digest}.md"
950
965
  if not archive.exists():
951
966
  add_action("policy", archive, "archive", "historical and non-authoritative")
952
967
  if write:
@@ -2498,6 +2513,45 @@ def _validation_cfg(cfg: dict) -> dict:
2498
2513
  return value if isinstance(value, dict) else {}
2499
2514
 
2500
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
+
2501
2555
  def _as_list(value: object) -> list:
2502
2556
  if value is None:
2503
2557
  return []
@@ -2527,7 +2581,14 @@ def _run_first_configured_command(repo: Path, cfg: dict, names: list[str]) -> st
2527
2581
  return ""
2528
2582
 
2529
2583
 
2530
- 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]:
2531
2592
  executed: list[str] = []
2532
2593
  missing: list[str] = []
2533
2594
  for name_ref in names:
@@ -2535,7 +2596,16 @@ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str
2535
2596
  if not name:
2536
2597
  continue
2537
2598
  if _configured_command(cfg, name):
2538
- _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)
2539
2609
  executed.append(name)
2540
2610
  else:
2541
2611
  missing.append(name)
@@ -2868,7 +2938,14 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
2868
2938
  print("[impact] changed: (none)")
2869
2939
 
2870
2940
 
2871
- 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]:
2872
2949
  plan = _validation_plan(cfg, paths)
2873
2950
  _validate_validation_plan(cfg, plan)
2874
2951
  if not paths:
@@ -2882,7 +2959,13 @@ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2882
2959
  "[validation] WARN: using 3.x compatibility fallback; migrate to validation.routes",
2883
2960
  file=sys.stderr,
2884
2961
  )
2885
- 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
+ )
2886
2969
  print(
2887
2970
  "[validation] routes="
2888
2971
  + (", ".join(plan["matched_routes"]) or "(none)")
@@ -4560,6 +4643,51 @@ def _agent_execution_plan(
4560
4643
  })
4561
4644
 
4562
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
+
4563
4691
  def _resolve_execution_plan(
4564
4692
  cfg: dict,
4565
4693
  repo: Path,
@@ -4720,6 +4848,14 @@ def _resolve_execution_plan(
4720
4848
  parallel_writers=writer_count,
4721
4849
  review_required=review_required,
4722
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
+ )
4723
4859
  return {
4724
4860
  **impact,
4725
4861
  "contract_version": _AGENT_CONTRACT_VERSION,
@@ -4758,6 +4894,7 @@ def _resolve_execution_plan(
4758
4894
  review_required=review_required,
4759
4895
  ),
4760
4896
  "agent_plan": agent_plan,
4897
+ "mechanism_plan": mechanism_plan,
4761
4898
  }
4762
4899
 
4763
4900
 
@@ -4809,6 +4946,14 @@ def cmd_classify(args: argparse.Namespace) -> None:
4809
4946
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
4810
4947
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
4811
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
+ )
4812
4957
  for stage in result["agent_plan"]["stages"]:
4813
4958
  print(
4814
4959
  "[classify] agent_stage="
@@ -4848,7 +4993,10 @@ def cmd_run(args: argparse.Namespace) -> None:
4848
4993
  def cmd_light_gate(args: argparse.Namespace) -> None:
4849
4994
  repo = Path(args.repo).resolve()
4850
4995
  light_gate_start = time.time()
4996
+ monotonic_start = time.monotonic()
4851
4997
  cfg = _load_cfg(repo)
4998
+ budget = _final_gate_budget(cfg)
4999
+ deadline = monotonic_start + budget["total_seconds"]
4852
5000
  requested_scope = _text(getattr(args, "scope", "")).lower()
4853
5001
  if requested_scope not in {"", "auto", "changed"}:
4854
5002
  raise APError(
@@ -4870,9 +5018,20 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
4870
5018
 
4871
5019
  selected_scope = "changed"
4872
5020
  paths = list(plan.get("changed_files") or [])
4873
- 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
+ )
4874
5028
 
4875
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
+ )
4876
5035
  executed.append("diff_check")
4877
5036
  duration_s = time.time() - light_gate_start
4878
5037
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
@@ -5143,6 +5302,10 @@ def cmd_doctor(args: argparse.Namespace) -> None:
5143
5302
  on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
5144
5303
  if on_unmapped not in {"error", "fallback"}:
5145
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))
5146
5309
  routes = validation_cfg.get("routes") or []
5147
5310
  if not isinstance(routes, list):
5148
5311
  validation_errors.append("validation.routes must be a list")
@@ -6517,6 +6680,17 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6517
6680
  planned_paths=owned_paths,
6518
6681
  parallel_writers=writer_count,
6519
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
+ )
6520
6694
  review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
6521
6695
  registry_dir = _task_state_root(repo) / "tasks"
6522
6696
  other_active = any(
@@ -7859,6 +8033,11 @@ def main(argv: Optional[List[str]] = None) -> int:
7859
8033
  s.add_argument("--writers", type=int, default=1)
7860
8034
  s.add_argument("--isolated", action="store_true")
7861
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
+ )
7862
8041
  s.add_argument("--owned-path", action="append")
7863
8042
  s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
7864
8043
  s.add_argument("--no-fetch", action="store_true")
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import os
8
8
  import re
9
+ import signal
9
10
  import shutil
10
11
  import subprocess
11
12
  from pathlib import Path
@@ -108,8 +109,23 @@ def find_config(repo: Path) -> Path:
108
109
  )
109
110
 
110
111
 
111
- def run_shell(command: str, cwd: Optional[Path] = None) -> None:
112
- """Run shell command via bash -lc for cross-tool compatibility."""
113
- p = subprocess.run(["bash", "-lc", command], cwd=str(cwd) if cwd else None, text=True)
114
- if p.returncode != 0:
115
- raise APError(f"Command failed ({p.returncode}): {command}")
112
+ def run_shell(command: str, cwd: Optional[Path] = None, timeout_s: Optional[float] = None) -> None:
113
+ """Run a shell command and terminate its process group on timeout."""
114
+ p = subprocess.Popen(
115
+ ["bash", "-lc", command],
116
+ cwd=str(cwd) if cwd else None,
117
+ text=True,
118
+ start_new_session=True,
119
+ )
120
+ try:
121
+ returncode = p.wait(timeout=timeout_s)
122
+ except subprocess.TimeoutExpired as exc:
123
+ os.killpg(p.pid, signal.SIGTERM)
124
+ try:
125
+ p.wait(timeout=2)
126
+ except subprocess.TimeoutExpired:
127
+ os.killpg(p.pid, signal.SIGKILL)
128
+ p.wait()
129
+ raise APError(f"Command timed out after {timeout_s:.1f}s: {command}") from exc
130
+ if returncode != 0:
131
+ raise APError(f"Command failed ({returncode}): {command}")