@elvis1513/auto-coding-skill 3.0.4 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,7 +49,7 @@ _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
49
49
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
50
50
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
51
51
  "schema_version": 1,
52
- "managed_versions": {"agents": "3.0.3", "engineering": "3.0.3"},
52
+ "managed_versions": {"agents": "4.0.0", "engineering": "4.0.0"},
53
53
  "known_official_engineering_body_sha256": [
54
54
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
55
55
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -170,10 +170,12 @@ def _append_jsonl(path: Path, payload: dict) -> None:
170
170
 
171
171
  def _evidence_log_path(repo: Path, cfg: dict) -> Path:
172
172
  manifest = _active_task_manifest(repo)
173
- if manifest:
174
- docs_cfg = cfg.get("docs") or {}
173
+ docs_cfg = cfg.get("docs") or {}
174
+ if manifest and _bool_config(docs_cfg.get("track_task_evidence"), False):
175
175
  task_dir = _text(docs_cfg.get("task_evidence_dir")) or "docs/tasks/evidence"
176
176
  return Path(repo, task_dir, f"{manifest['task_id']}.jsonl")
177
+ if _bool_config(docs_cfg.get("track_evidence"), False) and _text(docs_cfg.get("evidence_log")):
178
+ return Path(repo, _text(docs_cfg.get("evidence_log")))
177
179
  return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
178
180
 
179
181
 
@@ -577,10 +579,7 @@ _MANAGED_EXTRA_CLEANUP_DIRS = {
577
579
  Path("data/templates/bridges"),
578
580
  }
579
581
 
580
- _CORE_DOC_TEMPLATES = [
581
- Path("tasks/taskbook.md"),
582
- Path("tasks/closure-log.md"),
583
- ]
582
+ _CORE_DOC_TEMPLATES: list[Path] = []
584
583
 
585
584
 
586
585
  def _inferred_gate_commands(repo: Path) -> dict[str, str]:
@@ -595,7 +594,7 @@ def _inferred_gate_commands(repo: Path) -> dict[str, str]:
595
594
  if not isinstance(scripts, dict):
596
595
  return {}
597
596
  if isinstance(scripts.get("test:changed"), str) and scripts["test:changed"].strip():
598
- return {"gate_changed": "npm run test:changed"}
597
+ return {"project_fast": "npm run test:changed"}
599
598
  return {}
600
599
 
601
600
 
@@ -635,17 +634,25 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
635
634
  if _text(workflow_cfg.get("completion")).lower() != "push":
636
635
  workflow_cfg["completion"] = "push"
637
636
  changed.append("workflow.completion")
637
+ if _text(workflow_cfg.get("skill_version")) != "4.0.0":
638
+ workflow_cfg["skill_version"] = "4.0.0"
639
+ changed.append("workflow.skill_version")
638
640
 
639
641
  commands_cfg = cfg.setdefault("commands", {})
640
642
  if not isinstance(commands_cfg, dict):
641
643
  commands_cfg = {}
642
644
  cfg["commands"] = commands_cfg
643
645
  current_changed_gate = _text(commands_cfg.get("gate_changed"))
644
- if current_changed_gate in {"", "npm test"}:
645
- replacement = _inferred_gate_commands(repo).get("gate_changed", "git diff --check")
646
- if current_changed_gate != replacement:
647
- commands_cfg["gate_changed"] = replacement
648
- changed.append("commands.gate_changed")
646
+ project_fast = _text(commands_cfg.get("project_fast"))
647
+ inferred_fast = _inferred_gate_commands(repo).get("project_fast", "")
648
+ if not project_fast:
649
+ replacement = (
650
+ current_changed_gate
651
+ if current_changed_gate and current_changed_gate not in {"git diff --check", "npm test"}
652
+ else inferred_fast
653
+ )
654
+ commands_cfg["project_fast"] = replacement
655
+ changed.append("commands.project_fast")
649
656
 
650
657
  gate_cfg = cfg.setdefault("gate", {})
651
658
  if not isinstance(gate_cfg, dict):
@@ -662,21 +669,63 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
662
669
  del gate_cfg["full_on"]
663
670
  changed.append("gate.full_on")
664
671
  raw_rules = gate_cfg.get("rules")
672
+ risk_cfg = cfg.setdefault("risk", {})
673
+ if not isinstance(risk_cfg, dict):
674
+ risk_cfg = {}
675
+ cfg["risk"] = risk_cfg
676
+ risk_rules = risk_cfg.setdefault("rules", [])
677
+ if not isinstance(risk_rules, list):
678
+ risk_rules = []
679
+ risk_cfg["rules"] = risk_rules
680
+ validation_cfg = cfg.setdefault("validation", {})
681
+ if not isinstance(validation_cfg, dict):
682
+ validation_cfg = {}
683
+ cfg["validation"] = validation_cfg
684
+ if _text(validation_cfg.get("on_unmapped")).lower() != "error":
685
+ validation_cfg["on_unmapped"] = "error"
686
+ changed.append("validation.on_unmapped")
687
+ validation_routes = validation_cfg.setdefault("routes", [])
688
+ if not isinstance(validation_routes, list):
689
+ validation_routes = []
690
+ validation_cfg["routes"] = validation_routes
665
691
  if isinstance(raw_rules, list):
666
692
  migrated_rules: list = []
667
693
  for index, rule in enumerate(raw_rules):
668
694
  if not isinstance(rule, dict):
669
695
  migrated_rules.append(rule)
670
696
  continue
671
- migrated_rule = dict(rule)
672
- for legacy_key in ["scope", "commands"]:
673
- if legacy_key in migrated_rule:
674
- del migrated_rule[legacy_key]
675
- changed.append(f"gate.rules[{index}].{legacy_key}")
676
- if migrated_rule:
677
- migrated_rules.append(migrated_rule)
697
+ migrated_rule = {
698
+ key: value
699
+ for key, value in rule.items()
700
+ if key in {"name", "paths", "profile", "review", "design"}
701
+ }
702
+ if migrated_rule and migrated_rule not in risk_rules:
703
+ risk_rules.append(migrated_rule)
704
+ changed.append(f"risk.rules[{len(risk_rules) - 1}]")
705
+ legacy_commands = _as_list(rule.get("commands"))
706
+ if legacy_commands and _as_list(rule.get("paths")):
707
+ route = {
708
+ "name": _text(rule.get("name")) or f"migrated-{index + 1}",
709
+ "paths": _as_list(rule.get("paths")),
710
+ "commands": [_command_name(item) for item in legacy_commands if _command_name(item)],
711
+ }
712
+ if route["commands"] and route not in validation_routes:
713
+ validation_routes.append(route)
714
+ changed.append(f"validation.routes[{len(validation_routes) - 1}]")
678
715
  if migrated_rules != raw_rules:
679
- gate_cfg["rules"] = migrated_rules
716
+ gate_cfg["rules"] = []
717
+ changed.append("gate.rules")
718
+
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]")
680
729
 
681
730
  concurrency_cfg = cfg.setdefault("concurrency", {})
682
731
  if not isinstance(concurrency_cfg, dict):
@@ -1607,11 +1656,14 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1607
1656
  "owned_paths for an in-flight task. Finish or clean it with the previously installed "
1608
1657
  "runtime before running autocoding sync, or restore the 3.0.0 runtime."
1609
1658
  )
1659
+ execution_mode = _text(manifest.get("execution_mode")).lower() or "isolated"
1660
+ if execution_mode not in {"direct", "isolated"}:
1661
+ raise APError(f"Task {task_id} has an invalid execution_mode: {execution_mode!r}")
1610
1662
  task_uuid = _text(manifest.get("task_uuid"))
1611
1663
  if not re.fullmatch(r"[0-9a-f]{32}", task_uuid):
1612
1664
  raise APError(f"Invalid task manifest UUID for {task_id}; refusing Git operations.")
1613
1665
  task_branch = _text(manifest.get("task_branch"))
1614
- if not task_branch.endswith(f"/{task_id}") or run(
1666
+ if (execution_mode == "isolated" and not task_branch.endswith(f"/{task_id}")) or run(
1615
1667
  ["git", "check-ref-format", "--branch", task_branch],
1616
1668
  cwd=repo,
1617
1669
  check=False,
@@ -1638,7 +1690,11 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1638
1690
  raise APError(f"Task manifest paths must be absolute for {task_id}.")
1639
1691
  worktree = worktree.resolve()
1640
1692
  control = control.resolve()
1641
- if worktree == control or control in worktree.parents or worktree in control.parents:
1693
+ if execution_mode == "direct" and worktree != control:
1694
+ raise APError(f"Direct task {task_id} must use its control checkout.")
1695
+ if execution_mode == "isolated" and (
1696
+ worktree == control or control in worktree.parents or worktree in control.parents
1697
+ ):
1642
1698
  raise APError(
1643
1699
  f"Task worktree must be outside its control checkout for {task_id}: {worktree}"
1644
1700
  )
@@ -1669,6 +1725,9 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
1669
1725
  "changes-requested",
1670
1726
  }:
1671
1727
  raise APError(f"Task {task_id} has an invalid review contract.")
1728
+ review_required = manifest.get("review_required", schema < 3)
1729
+ if not isinstance(review_required, bool):
1730
+ raise APError(f"Task {task_id} has an invalid review_required flag.")
1672
1731
  return manifest
1673
1732
 
1674
1733
 
@@ -1767,12 +1826,12 @@ def _task_runtime_paths(repo: Path, cfg: dict, manifest: Optional[dict]) -> set[
1767
1826
  paths = {
1768
1827
  _text(gate_cfg.get("profile_log")) or ".local/auto-coding-skill/gate-profile.jsonl",
1769
1828
  }
1770
- if manifest:
1829
+ if manifest and _bool_config(docs_cfg.get("track_task_evidence"), False):
1771
1830
  task_id = _validate_task_id(_text(manifest.get("task_id")))
1772
1831
  evidence_dir = _text(docs_cfg.get("task_evidence_dir")) or "docs/tasks/evidence"
1773
1832
  paths.add(f"{evidence_dir.rstrip('/')}/{task_id}.jsonl")
1774
1833
  else:
1775
- paths.add(_text(docs_cfg.get("evidence_log")) or "docs/tasks/evidence.jsonl")
1834
+ paths.add(".local/auto-coding-skill/evidence.jsonl")
1776
1835
  normalized: set[str] = set()
1777
1836
  for path in paths:
1778
1837
  value = path.replace("\\", "/")
@@ -1895,6 +1954,8 @@ def _path_is_owned(path: str, owned_paths: list[str]) -> bool:
1895
1954
 
1896
1955
 
1897
1956
  def _task_managed_paths(cfg: dict, manifest: dict) -> list[str]:
1957
+ if int(manifest.get("schema") or 2) >= 3:
1958
+ return []
1898
1959
  docs_cfg = cfg.get("docs") or {}
1899
1960
  task_id = _validate_task_id(_text(manifest.get("task_id")))
1900
1961
  return sorted(
@@ -2020,6 +2081,8 @@ def _require_approved_review(repo: Path, cfg: dict, manifest: dict) -> str:
2020
2081
  if unowned:
2021
2082
  raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
2022
2083
  fingerprint = _task_review_fingerprint(repo, manifest)
2084
+ if not bool(manifest.get("review_required", int(manifest.get("schema") or 2) < 3)):
2085
+ return fingerprint
2023
2086
  review = manifest.get("review") or {}
2024
2087
  if _text(review.get("verdict")) != "approved":
2025
2088
  raise APError("Task review must be approved before commit-push or integration.")
@@ -2058,9 +2121,9 @@ def _require_task_context(repo: Path, cfg: dict, task_id: str) -> dict:
2058
2121
  "return to the primary checkout and create or recover the task with task-start."
2059
2122
  )
2060
2123
  raise APError(
2061
- "This project requires an isolated task worktree. "
2124
+ "This checkout has no active task. "
2062
2125
  f"Run `python3 docs/tools/autopipeline/ap.py task-start {task_id}` from the main checkout, "
2063
- "then continue in the returned worktree."
2126
+ "then continue in the current checkout or returned worktree."
2064
2127
  )
2065
2128
  expected_task = _validate_task_id(task_id)
2066
2129
  actual_task = _text(manifest.get("task_id"))
@@ -2289,6 +2352,16 @@ def _gate_cfg(cfg: dict) -> dict:
2289
2352
  return gate_cfg if isinstance(gate_cfg, dict) else {}
2290
2353
 
2291
2354
 
2355
+ def _risk_cfg(cfg: dict) -> dict:
2356
+ value = cfg.get("risk") or {}
2357
+ return value if isinstance(value, dict) else {}
2358
+
2359
+
2360
+ def _validation_cfg(cfg: dict) -> dict:
2361
+ value = cfg.get("validation") or {}
2362
+ return value if isinstance(value, dict) else {}
2363
+
2364
+
2292
2365
  def _as_list(value: object) -> list:
2293
2366
  if value is None:
2294
2367
  return []
@@ -2330,8 +2403,8 @@ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str
2330
2403
  executed.append(name)
2331
2404
  else:
2332
2405
  missing.append(name)
2333
- if missing and not executed:
2334
- raise APError("Gate rule references missing commands: " + ", ".join(missing))
2406
+ if missing:
2407
+ raise APError("Validation route references missing commands: " + ", ".join(missing))
2335
2408
  return executed
2336
2409
 
2337
2410
 
@@ -2457,6 +2530,14 @@ def _gate_rules(gate_cfg: dict) -> list[dict]:
2457
2530
  return [rule for rule in rules if isinstance(rule, dict)]
2458
2531
 
2459
2532
 
2533
+ def _risk_rules(cfg: dict) -> list[dict]:
2534
+ rules = _risk_cfg(cfg).get("rules") or []
2535
+ current = [rule for rule in rules if isinstance(rule, dict)]
2536
+ # Keep reading 3.x gate.rules while projects migrate. They remain planning
2537
+ # metadata only and never execute validation commands.
2538
+ return current or _gate_rules(_gate_cfg(cfg))
2539
+
2540
+
2460
2541
  def _matching_gate_rules(paths: list[str], gate_cfg: dict) -> list[dict]:
2461
2542
  matches = []
2462
2543
  for rule in _gate_rules(gate_cfg):
@@ -2466,6 +2547,106 @@ def _matching_gate_rules(paths: list[str], gate_cfg: dict) -> list[dict]:
2466
2547
  return matches
2467
2548
 
2468
2549
 
2550
+ def _matching_risk_rules(paths: list[str], cfg: dict) -> list[dict]:
2551
+ matches: list[dict] = []
2552
+ for rule in _risk_rules(cfg):
2553
+ patterns = _as_list(rule.get("paths"))
2554
+ if patterns and any(_path_matches(path, patterns) for path in paths):
2555
+ matches.append(rule)
2556
+ return matches
2557
+
2558
+
2559
+ def _validation_routes(cfg: dict) -> list[dict]:
2560
+ routes = _validation_cfg(cfg).get("routes") or []
2561
+ return [route for route in routes if isinstance(route, dict)]
2562
+
2563
+
2564
+ def _validation_route_matches(path: str, route: dict) -> bool:
2565
+ patterns = _as_list(route.get("paths"))
2566
+ excludes = _as_list(route.get("exclude"))
2567
+ return bool(patterns) and _path_matches(path, patterns) and not _path_matches(path, excludes)
2568
+
2569
+
2570
+ def _validation_plan(cfg: dict, paths: list[str]) -> dict:
2571
+ """Resolve one deterministic changed-scope validation plan.
2572
+
2573
+ Risk rules deliberately live under ``risk.rules``. Validation routes are a
2574
+ separate execution surface so classification cannot silently turn into an
2575
+ expensive full gate and a documentation check cannot masquerade as code
2576
+ validation.
2577
+ """
2578
+ normalized = _unique_paths(paths)
2579
+ routes = _validation_routes(cfg)
2580
+ command_names: list[str] = []
2581
+ matched_routes: list[str] = []
2582
+ coverage: dict[str, list[str]] = {}
2583
+ unmapped: list[str] = []
2584
+
2585
+ for path in normalized:
2586
+ names: list[str] = []
2587
+ for index, route in enumerate(routes):
2588
+ if not _validation_route_matches(path, route):
2589
+ continue
2590
+ route_name = _text(route.get("name")) or f"route-{index + 1}"
2591
+ names.append(route_name)
2592
+ if route_name not in matched_routes:
2593
+ matched_routes.append(route_name)
2594
+ for command_ref in _as_list(route.get("commands")):
2595
+ command_name = _command_name(command_ref)
2596
+ if command_name and command_name not in command_names:
2597
+ command_names.append(command_name)
2598
+ coverage[path] = names
2599
+ if not names and not _path_matches(path, _DOC_PATH_PATTERNS):
2600
+ unmapped.append(path)
2601
+
2602
+ validation_cfg = _validation_cfg(cfg)
2603
+ compatibility_command = ""
2604
+ if not routes:
2605
+ compatibility_command = _command_name(validation_cfg.get("fallback_command"))
2606
+ if not compatibility_command and _configured_command(cfg, "gate_changed"):
2607
+ compatibility_command = "gate_changed"
2608
+ if compatibility_command:
2609
+ command_names.append(compatibility_command)
2610
+ matched_routes.append("3.x-compatibility-fallback")
2611
+ unmapped = []
2612
+
2613
+ on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
2614
+ if on_unmapped not in {"error", "fallback"}:
2615
+ raise APError("validation.on_unmapped must be error or fallback")
2616
+ if unmapped and on_unmapped == "fallback":
2617
+ fallback = _command_name(validation_cfg.get("fallback_command"))
2618
+ if fallback and fallback not in command_names:
2619
+ command_names.append(fallback)
2620
+ matched_routes.append("unmapped-fallback")
2621
+ unmapped = []
2622
+
2623
+ return {
2624
+ "paths": normalized,
2625
+ "commands": command_names,
2626
+ "matched_routes": matched_routes,
2627
+ "coverage": coverage,
2628
+ "unmapped": unmapped,
2629
+ "docs_only": _docs_only(normalized),
2630
+ "compatibility_fallback": compatibility_command,
2631
+ }
2632
+
2633
+
2634
+ def _validate_validation_plan(cfg: dict, plan: dict) -> None:
2635
+ missing = [name for name in plan["commands"] if not _configured_command(cfg, name)]
2636
+ if missing:
2637
+ raise APError("Validation route references missing commands: " + ", ".join(missing))
2638
+ if plan["unmapped"]:
2639
+ raise APError(
2640
+ "Changed code paths have no validation route:\n- "
2641
+ + "\n- ".join(plan["unmapped"])
2642
+ + "\nAdd validation.routes entries in docs/ENGINEERING.md."
2643
+ )
2644
+ if plan["paths"] and not plan["docs_only"] and not plan["commands"]:
2645
+ raise APError(
2646
+ "Changed code has no fast validation command. Add validation.routes with project-native commands."
2647
+ )
2648
+
2649
+
2469
2650
  def _gate_full_patterns(gate_cfg: dict) -> list:
2470
2651
  full_on = gate_cfg.get("full_on") or {}
2471
2652
  patterns = list(_DEFAULT_FULL_PATH_PATTERNS)
@@ -2518,7 +2699,8 @@ def _impact_summary(
2518
2699
  for path in ignored_runtime_paths
2519
2700
  }
2520
2701
  paths = [path for path in paths if path not in ignored_runtime_paths]
2521
- scope, reasons, matching_rules = _select_gate_scope(cfg, requested_scope, paths)
2702
+ scope, reasons, _ = _select_gate_scope(cfg, requested_scope, paths)
2703
+ matching_rules = _matching_risk_rules(paths, cfg)
2522
2704
  return {
2523
2705
  "requested_scope": requested_scope or _text(_gate_cfg(cfg).get("default_scope")) or "standard",
2524
2706
  "selected_scope": scope,
@@ -2551,31 +2733,54 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
2551
2733
 
2552
2734
 
2553
2735
  def _run_changed_gate(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2554
- # The generic scaffold uses this command as its whole fast gate. The
2555
- # built-in diff check below covers working tree, index, and task commits, so
2556
- # do not execute the narrower configured spelling first as a duplicate.
2557
- if _configured_command(cfg, "gate_changed").strip() == "git diff --check":
2558
- print("[gate] gate_changed is handled by the built-in diff check")
2559
- return []
2560
-
2561
- fallback_commands = ["gate_changed"]
2562
- if _docs_only(paths):
2563
- fallback_commands.append("docs_check")
2564
- command = _run_first_configured_command(repo, cfg, fallback_commands)
2565
- if command:
2566
- return [command]
2567
-
2568
- if _docs_only(paths):
2569
- print("[gate] docs-only change with no changed-gate command configured; running built-in post checks only.")
2736
+ plan = _validation_plan(cfg, paths)
2737
+ _validate_validation_plan(cfg, plan)
2738
+ if not paths:
2739
+ print("[validation] no changed files; no project command needed")
2740
+ return ["no_changes"]
2741
+ if plan["docs_only"] and not plan["commands"]:
2742
+ print("[validation] docs-only change; built-in diff check is sufficient")
2570
2743
  return ["docs_only_builtin"]
2744
+ if plan["compatibility_fallback"]:
2745
+ print(
2746
+ "[validation] WARN: using 3.x compatibility fallback; migrate to validation.routes",
2747
+ file=sys.stderr,
2748
+ )
2749
+ executed = _run_configured_command_list(repo, cfg, plan["commands"])
2750
+ print(
2751
+ "[validation] routes="
2752
+ + (", ".join(plan["matched_routes"]) or "(none)")
2753
+ + " commands="
2754
+ + (", ".join(executed) or "(none)")
2755
+ )
2756
+ return executed
2571
2757
 
2572
- fallback = _run_first_configured_command(repo, cfg, ["quick_test"])
2573
- if fallback:
2574
- return [fallback]
2575
2758
 
2576
- raise APError(
2577
- "Changed gate has no fast command. Add commands.gate_changed or commands.quick_test. "
2578
- "gate.rules commands are never executed by the automatic development flow."
2759
+ def cmd_validation_map_check(args: argparse.Namespace) -> None:
2760
+ repo = Path(args.repo).resolve()
2761
+ cfg = _load_cfg(repo)
2762
+ explicit_paths = list(getattr(args, "path", []) or [])
2763
+ if explicit_paths:
2764
+ paths = _unique_paths(explicit_paths)
2765
+ elif bool(getattr(args, "tracked", False)):
2766
+ paths = _tracked_files(repo)
2767
+ else:
2768
+ paths = _changed_files(repo, _text(getattr(args, "base", "")))
2769
+ plan = _validation_plan(cfg, paths)
2770
+ _validate_validation_plan(cfg, plan)
2771
+ result = {
2772
+ "paths": plan["paths"],
2773
+ "commands": plan["commands"],
2774
+ "matched_routes": plan["matched_routes"],
2775
+ "coverage": plan["coverage"],
2776
+ "docs_only": plan["docs_only"],
2777
+ }
2778
+ if bool(getattr(args, "json", False)):
2779
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2780
+ return
2781
+ print(
2782
+ f"[validation-map] OK paths={len(plan['paths'])} "
2783
+ f"routes={len(plan['matched_routes'])} commands={len(plan['commands'])}"
2579
2784
  )
2580
2785
 
2581
2786
 
@@ -4050,9 +4255,22 @@ def _configured_workflow_profile(cfg: dict) -> str:
4050
4255
  return _normalize_workflow_profile((cfg.get("workflow") or {}).get("profile"))
4051
4256
 
4052
4257
 
4053
- def _recommended_agents(profile: str, categories: set[str], classification: dict) -> list[str]:
4258
+ def _recommended_agents(
4259
+ profile: str,
4260
+ categories: set[str],
4261
+ classification: dict,
4262
+ *,
4263
+ parallel_writers: int = 1,
4264
+ review_required: bool = False,
4265
+ ) -> list[str]:
4054
4266
  roles: list[str] = []
4055
- for stage in _agent_execution_plan(profile, categories, classification)["stages"]:
4267
+ for stage in _agent_execution_plan(
4268
+ profile,
4269
+ categories,
4270
+ classification,
4271
+ parallel_writers=parallel_writers,
4272
+ review_required=review_required,
4273
+ )["stages"]:
4056
4274
  for role in stage["roles"]:
4057
4275
  if role != "main" and role not in roles:
4058
4276
  roles.append(role)
@@ -4127,122 +4345,84 @@ def _validate_agent_plan(plan: dict) -> dict:
4127
4345
  return plan
4128
4346
 
4129
4347
 
4130
- def _agent_execution_plan(profile: str, categories: set[str], classification: dict) -> dict:
4348
+ def _agent_execution_plan(
4349
+ profile: str,
4350
+ categories: set[str],
4351
+ classification: dict,
4352
+ *,
4353
+ parallel_writers: int = 1,
4354
+ review_required: bool = False,
4355
+ ) -> dict:
4131
4356
  assignment_contract, result_contract = _agent_contract_shape()
4132
- if profile == "micro":
4133
- return _validate_agent_plan({
4134
- "contract_version": _AGENT_CONTRACT_VERSION,
4135
- "contract_schema": _AGENT_CONTRACT_SCHEMA,
4136
- "strategy": "main-only",
4137
- "policies": {
4138
- "one_writer_per_worktree": True,
4139
- "workspace_isolation": "adaptive-clean-current-or-isolated",
4140
- "path_ownership": "explicit-non-overlapping",
4141
- "dependency_policy": "integrate-before-dependent-start",
4142
- "review_feedback_owner": "main",
4143
- "review_binding": "diff-fingerprint",
4144
- "lifecycle_owner": "main",
4145
- "gate_owner": "main",
4146
- },
4147
- "assignment_contract": assignment_contract,
4148
- "result_contract": result_contract,
4149
- "stages": [
4150
- {
4151
- "id": "delivery",
4152
- "mode": "serial",
4153
- "roles": ["main"],
4154
- "depends_on": [],
4155
- }
4156
- ],
4157
- "constraints": [
4158
- "Do not create subagents when the task has no independent work worth delegating.",
4159
- "The main agent owns the fast gate, Git integration, push, and cleanup.",
4160
- ],
4161
- })
4162
-
4163
- discovery_roles = ["explorer"]
4357
+ discovery_roles: list[str] = []
4164
4358
  if categories & {"api", "release_or_tooling"}:
4165
4359
  discovery_roles.append("docs_researcher")
4166
4360
  if classification.get("needs_browser"):
4167
4361
  discovery_roles.append("browser_debugger")
4362
+ if profile == "high-risk" and not discovery_roles:
4363
+ discovery_roles.append("explorer")
4364
+
4365
+ policies = {
4366
+ "one_writer_per_worktree": True,
4367
+ "workspace_isolation": "adaptive-clean-current-or-isolated",
4368
+ "path_ownership": "explicit-only-for-isolated-or-delegated-work",
4369
+ "dependency_policy": "integrate-before-dependent-start",
4370
+ "review_feedback_owner": "owning-fixer" if review_required else "main",
4371
+ "review_binding": "diff-fingerprint-when-required",
4372
+ "lifecycle_owner": "main",
4373
+ "gate_owner": "main",
4374
+ }
4375
+ constraints = [
4376
+ "Delegate only when independent work has a clear latency or expertise benefit.",
4377
+ "A clean single-writer checkout stays on its current branch; dirty or parallel work is isolated.",
4378
+ "Never run two writers in one worktree.",
4379
+ "The main agent runs one final changed-scope gate, pushes, and cleans only temporary branches actually created.",
4380
+ ]
4381
+
4382
+ if parallel_writers <= 1 and not discovery_roles and not review_required:
4383
+ stages = [{"id": "delivery", "mode": "serial", "roles": ["main"], "depends_on": []}]
4384
+ strategy = "main-only"
4385
+ else:
4386
+ stages = [
4387
+ {"id": "decomposition", "mode": "serial", "roles": ["main"], "depends_on": []}
4388
+ ]
4389
+ previous = "decomposition"
4390
+ if discovery_roles:
4391
+ stages.append(
4392
+ {
4393
+ "id": "discovery",
4394
+ "mode": "parallel" if len(discovery_roles) > 1 else "serial",
4395
+ "roles": discovery_roles,
4396
+ "depends_on": [previous],
4397
+ }
4398
+ )
4399
+ previous = "discovery"
4400
+ delivery_roles = ["main"]
4401
+ delivery_mode = "serial"
4402
+ if parallel_writers > 1:
4403
+ delivery_roles = ["fixer", "main"]
4404
+ delivery_mode = "parallel-isolated"
4405
+ if review_required:
4406
+ delivery_roles.append("reviewer")
4407
+ stages.append(
4408
+ {
4409
+ "id": "delivery",
4410
+ "mode": delivery_mode,
4411
+ "roles": delivery_roles,
4412
+ "depends_on": [previous],
4413
+ }
4414
+ )
4415
+ strategy = "parallel-writers" if parallel_writers > 1 else "risk-assisted"
4168
4416
 
4169
4417
  return _validate_agent_plan({
4170
4418
  "contract_version": _AGENT_CONTRACT_VERSION,
4171
4419
  "contract_schema": _AGENT_CONTRACT_SCHEMA,
4172
- "strategy": "orchestrated-subagents",
4173
- "policies": {
4174
- "one_writer_per_worktree": True,
4175
- "workspace_isolation": "adaptive-clean-current-or-isolated",
4176
- "path_ownership": "explicit-non-overlapping",
4177
- "dependency_policy": "integrate-before-dependent-start",
4178
- "review_feedback_owner": "owning-fixer",
4179
- "review_binding": "diff-fingerprint",
4180
- "lifecycle_owner": "main",
4181
- "gate_owner": "main",
4182
- },
4420
+ "strategy": strategy,
4421
+ "policies": policies,
4183
4422
  "assignment_contract": assignment_contract,
4184
4423
  "result_contract": result_contract,
4185
- "stages": [
4186
- {
4187
- "id": "decomposition",
4188
- "mode": "serial",
4189
- "roles": ["main"],
4190
- "depends_on": [],
4191
- },
4192
- {
4193
- "id": "discovery",
4194
- "mode": "parallel",
4195
- "roles": discovery_roles,
4196
- "depends_on": ["decomposition"],
4197
- },
4198
- {
4199
- "id": "design",
4200
- "mode": "serial",
4201
- "roles": ["main"],
4202
- "depends_on": ["discovery"],
4203
- },
4204
- {
4205
- "id": "delivery",
4206
- "mode": "dependency-waves",
4207
- "roles": ["fixer", "reviewer", "main"],
4208
- "depends_on": ["design"],
4209
- "scale": "one fixer per independent development unit in the current dependency layer",
4210
- "wave_phases": [
4211
- {
4212
- "id": "implementation",
4213
- "mode": "parallel-isolated",
4214
- "roles": ["fixer"],
4215
- },
4216
- {
4217
- "id": "review",
4218
- "mode": "parallel-read-only",
4219
- "roles": ["reviewer"],
4220
- "feedback_to": "owning fixer",
4221
- },
4222
- {
4223
- "id": "gate-integrate",
4224
- "mode": "serial",
4225
- "roles": ["main"],
4226
- },
4227
- ],
4228
- "next_wave": "start only after every prerequisite in the next layer is integrated",
4229
- },
4230
- {
4231
- "id": "closure",
4232
- "mode": "serial",
4233
- "roles": ["main"],
4234
- "depends_on": ["delivery"],
4235
- },
4236
- ],
4237
- "constraints": [
4238
- "Delegate only independent bounded work and declare dependencies before dispatch.",
4239
- "One serial fixer may use a clean current branch; dirty or parallel writers require registered task branches/worktrees.",
4240
- "Never run two writers in one worktree or let the main agent edit a fixer-owned worktree concurrently.",
4241
- "Start a dependent write task only after its prerequisite has been integrated into the target branch.",
4242
- "Subagents do not commit, push, integrate, or clean task branches.",
4243
- "Reviewers inspect a stable diff; changes-requested returns to the owning fixer and any edit requires re-review.",
4244
- "The main agent routes review feedback, runs one fast gate, pushes, and cleans only temporary branches/worktrees that were actually created.",
4245
- ],
4424
+ "stages": stages,
4425
+ "constraints": constraints,
4246
4426
  })
4247
4427
 
4248
4428
 
@@ -4257,6 +4437,7 @@ def _resolve_execution_plan(
4257
4437
  changed_paths: Optional[list[str]] = None,
4258
4438
  planned_paths: Optional[list[str]] = None,
4259
4439
  intent: str = "",
4440
+ parallel_writers: int = 1,
4260
4441
  ) -> dict:
4261
4442
  impact = _impact_summary(
4262
4443
  cfg,
@@ -4275,7 +4456,7 @@ def _resolve_execution_plan(
4275
4456
  merged_categories = set(classification["categories"]) | set(intent_categories)
4276
4457
  classification = _classification_for_categories(merged_categories, len(classification_inputs))
4277
4458
  categories = set(classification["categories"])
4278
- matching_rules = _matching_gate_rules(classification_inputs, _gate_cfg(cfg))
4459
+ matching_rules = _matching_risk_rules(classification_inputs, cfg)
4279
4460
  configured_profile = _configured_workflow_profile(cfg)
4280
4461
  requested_profile_value = _normalize_workflow_profile(requested_profile) if requested_profile else ""
4281
4462
  configured_mode = _workflow_mode(cfg)
@@ -4353,11 +4534,50 @@ def _resolve_execution_plan(
4353
4534
  execution_reasons = list(impact.get("reasons") or [])
4354
4535
  execution_reasons.append("Jenkins/build/deploy and owner acceptance happen after coding completion")
4355
4536
 
4537
+ try:
4538
+ writer_count = max(1, int(parallel_writers or 1))
4539
+ except (TypeError, ValueError) as exc:
4540
+ raise APError("parallel writer count must be a positive integer") from exc
4541
+ module_roots = {
4542
+ path.split("/", 1)[0]
4543
+ for path in classification_inputs
4544
+ if path and not _path_matches(path, _DOC_PATH_PATTERNS)
4545
+ }
4546
+ cross_module = len(module_roots) > 1
4547
+ rule_review = any(
4548
+ _text(rule.get("review")).lower() in {"required", "true", "yes"}
4549
+ for rule in matching_rules
4550
+ )
4551
+ rule_design = any(
4552
+ _text(rule.get("design")).lower() in {"required", "true", "yes"}
4553
+ for rule in matching_rules
4554
+ )
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))
4557
+ has_task_signal = bool(classification_inputs or _text(intent))
4558
+ workspace_dirty = bool(_working_tree_paths(repo))
4559
+ configured_isolation = _task_isolation(cfg)
4560
+ if not has_task_signal:
4561
+ execution_mode = "none"
4562
+ elif configured_isolation == "worktree" or writer_count > 1 or workspace_dirty:
4563
+ execution_mode = "isolated"
4564
+ else:
4565
+ execution_mode = "direct"
4566
+ execution_reasons.append(
4567
+ "execution mode is adaptive: clean single-writer work is direct; dirty or parallel work is isolated"
4568
+ )
4569
+
4356
4570
  needs_jenkins = False
4357
4571
  needs_target = False
4358
- needs_dd = bool(classification["needs_dd"] or effective_profile == "high-risk")
4359
-
4360
- agent_plan = _agent_execution_plan(effective_profile, categories, classification)
4572
+ needs_dd = design_required
4573
+
4574
+ agent_plan = _agent_execution_plan(
4575
+ effective_profile,
4576
+ categories,
4577
+ classification,
4578
+ parallel_writers=writer_count,
4579
+ review_required=review_required,
4580
+ )
4361
4581
  return {
4362
4582
  **impact,
4363
4583
  "contract_version": _AGENT_CONTRACT_VERSION,
@@ -4374,6 +4594,12 @@ def _resolve_execution_plan(
4374
4594
  "configured_mode": configured_mode,
4375
4595
  "requested_mode": requested_mode_value or None,
4376
4596
  "effective_mode": effective_mode,
4597
+ "execution_mode": execution_mode,
4598
+ "workspace_dirty": workspace_dirty,
4599
+ "parallel_writers": writer_count,
4600
+ "cross_module": cross_module,
4601
+ "review_required": review_required,
4602
+ "design_required": design_required,
4377
4603
  "selected_scope": selected_scope,
4378
4604
  "categories": sorted(categories),
4379
4605
  "needs_dd": needs_dd,
@@ -4381,7 +4607,13 @@ def _resolve_execution_plan(
4381
4607
  "needs_browser": classification["needs_browser"],
4382
4608
  "needs_jenkins": needs_jenkins,
4383
4609
  "needs_target": needs_target,
4384
- "recommended_agents": _recommended_agents(effective_profile, categories, classification),
4610
+ "recommended_agents": _recommended_agents(
4611
+ effective_profile,
4612
+ categories,
4613
+ classification,
4614
+ parallel_writers=writer_count,
4615
+ review_required=review_required,
4616
+ ),
4385
4617
  "agent_plan": agent_plan,
4386
4618
  }
4387
4619
 
@@ -4410,6 +4642,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
4410
4642
  base_ref=_text(getattr(args, "base", "")),
4411
4643
  planned_paths=list(getattr(args, "planned_path", []) or []),
4412
4644
  intent="\n".join(part for part in intent_parts if part),
4645
+ parallel_writers=int(getattr(args, "writers", 1) or 1),
4413
4646
  )
4414
4647
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
4415
4648
  commands: list[str] = []
@@ -4426,6 +4659,9 @@ def cmd_classify(args: argparse.Namespace) -> None:
4426
4659
  print(f"[classify] risk={risk}")
4427
4660
  print(f"[classify] profile={result['profile']}")
4428
4661
  print(f"[classify] effective_mode={result['effective_mode']}")
4662
+ print(f"[classify] execution_mode={result['execution_mode']}")
4663
+ print(f"[classify] review_required={str(result['review_required']).lower()}")
4664
+ print(f"[classify] design_required={str(result['design_required']).lower()}")
4429
4665
  print(f"[classify] selected_scope={result['selected_scope']}")
4430
4666
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
4431
4667
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
@@ -4741,13 +4977,59 @@ def cmd_doctor(args: argparse.Namespace) -> None:
4741
4977
  f"gate.rules[{index}].commands is legacy automatic gate escalation; run ap.py upgrade"
4742
4978
  )
4743
4979
 
4744
- if not (_configured_command(cfg, "gate_changed") or _configured_command(cfg, "quick_test")):
4745
- missing.append("fast gate command: commands.gate_changed or commands.quick_test")
4980
+ risk_rules = _risk_cfg(cfg).get("rules") or []
4981
+ if not isinstance(risk_rules, list):
4982
+ validation_errors.append("risk.rules must be a list")
4983
+ risk_rules = []
4984
+ for index, rule in enumerate(risk_rules):
4985
+ if not isinstance(rule, dict):
4986
+ validation_errors.append(f"risk.rules[{index}] must be a mapping")
4987
+ continue
4988
+ if not _as_list(rule.get("paths")):
4989
+ validation_errors.append(f"risk.rules[{index}].paths must not be empty")
4990
+ rule_profile = _text(rule.get("profile")).lower()
4991
+ if rule_profile and rule_profile not in _WORKFLOW_PROFILES - {"auto"}:
4992
+ validation_errors.append(
4993
+ f"risk.rules[{index}].profile must be micro, standard, or high-risk"
4994
+ )
4746
4995
 
4747
- repo_docs = {
4748
- "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
4749
- "docs.closure_log": Path(repo, str(docs_cfg.get("closure_log", "docs/tasks/closure-log.md"))),
4750
- }
4996
+ validation_cfg = _validation_cfg(cfg)
4997
+ on_unmapped = _text(validation_cfg.get("on_unmapped")).lower() or "error"
4998
+ if on_unmapped not in {"error", "fallback"}:
4999
+ validation_errors.append("validation.on_unmapped must be error or fallback")
5000
+ routes = validation_cfg.get("routes") or []
5001
+ if not isinstance(routes, list):
5002
+ validation_errors.append("validation.routes must be a list")
5003
+ routes = []
5004
+ for index, route in enumerate(routes):
5005
+ if not isinstance(route, dict):
5006
+ validation_errors.append(f"validation.routes[{index}] must be a mapping")
5007
+ continue
5008
+ if not _as_list(route.get("paths")):
5009
+ validation_errors.append(f"validation.routes[{index}].paths must not be empty")
5010
+ commands = [_command_name(item) for item in _as_list(route.get("commands"))]
5011
+ if not commands:
5012
+ validation_errors.append(f"validation.routes[{index}].commands must not be empty")
5013
+ for command_name in commands:
5014
+ if command_name and not _configured_command(cfg, command_name):
5015
+ validation_errors.append(
5016
+ f"validation.routes[{index}] references missing commands.{command_name}"
5017
+ )
5018
+ fallback_name = _command_name(validation_cfg.get("fallback_command"))
5019
+ if on_unmapped == "fallback" and not fallback_name:
5020
+ validation_errors.append(
5021
+ "validation.fallback_command is required when validation.on_unmapped=fallback"
5022
+ )
5023
+ if fallback_name and not _configured_command(cfg, fallback_name):
5024
+ validation_errors.append(
5025
+ f"validation.fallback_command references missing commands.{fallback_name}"
5026
+ )
5027
+ if not routes and not (_configured_command(cfg, "gate_changed") or fallback_name):
5028
+ validation_errors.append(
5029
+ "validation.routes is empty and no 3.x commands.gate_changed compatibility fallback exists"
5030
+ )
5031
+
5032
+ repo_docs: dict[str, Path] = {}
4751
5033
  api_doc = Path(repo, str(docs_cfg.get("api_doc", "docs/interfaces/api.md")))
4752
5034
  api_change_log = Path(repo, str(docs_cfg.get("api_change_log", "docs/interfaces/api-change-log.md")))
4753
5035
  api_docs_enabled = (
@@ -5990,7 +6272,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
5990
6272
  ensure_git_repo(repo)
5991
6273
  cfg = _load_cfg(repo)
5992
6274
  _require_workflow_policy_clean(repo, cfg)
5993
- _task_isolation(cfg)
6275
+ configured_isolation = _task_isolation(cfg)
5994
6276
  access_issues = _access_config_issues(cfg)
5995
6277
  if access_issues:
5996
6278
  raise APError(
@@ -6010,8 +6292,6 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6010
6292
  if _read_json_object(_task_registry_path(repo, task_id)):
6011
6293
  raise APError(f"Task is already registered: {task_id}")
6012
6294
 
6013
- common_submodule_config = _common_submodule_config(repo)
6014
- _seed_control_submodule_config(repo)
6015
6295
  task_uuid = uuid.uuid4().hex
6016
6296
 
6017
6297
  if not getattr(args, "no_fetch", False) and base_ref.startswith(f"{remote}/"):
@@ -6041,6 +6321,86 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6041
6321
  if not owner:
6042
6322
  raise APError("task-start requires --owner or CODEX_THREAD_ID.")
6043
6323
  writer = _text(getattr(args, "writer", "")) or owner
6324
+ writer_count = max(1, int(getattr(args, "writers", 1) or 1))
6325
+ plan = _resolve_execution_plan(
6326
+ cfg,
6327
+ repo,
6328
+ planned_paths=owned_paths,
6329
+ parallel_writers=writer_count,
6330
+ )
6331
+ review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
6332
+ registry_dir = _task_state_root(repo) / "tasks"
6333
+ other_active = any(
6334
+ _text((payload or {}).get("state"))
6335
+ not in {"", "integrated", "cleanup-pending"}
6336
+ for payload in (
6337
+ _read_json_object(path)
6338
+ for path in sorted(registry_dir.glob("*.json"))
6339
+ )
6340
+ ) if registry_dir.exists() else False
6341
+ current_branch = _current_branch(repo)
6342
+ direct = bool(
6343
+ configured_isolation == "adaptive"
6344
+ and not bool(getattr(args, "isolated", False))
6345
+ and writer_count == 1
6346
+ and not other_active
6347
+ and not _task_commit_paths(repo)
6348
+ and current_branch
6349
+ and current_branch == target_branch
6350
+ )
6351
+ if direct:
6352
+ direct_base = _resolve_commit(repo, "HEAD")
6353
+ manifest = {
6354
+ "schema": 3,
6355
+ "execution_mode": "direct",
6356
+ "review_required": review_required,
6357
+ "task_id": task_id,
6358
+ "task_uuid": task_uuid,
6359
+ "owner": owner,
6360
+ "base_ref": "HEAD",
6361
+ "base_sha": direct_base,
6362
+ "remote": remote,
6363
+ "target_branch": current_branch,
6364
+ "task_branch": current_branch,
6365
+ "worktree_path": str(repo.resolve()),
6366
+ "control_worktree_path": str(repo.resolve()),
6367
+ "cleanup_policy": _cleanup_policy(cfg),
6368
+ "state": "active",
6369
+ "created_at": _now_iso(),
6370
+ "initial_untracked": [],
6371
+ "owned_paths": owned_paths,
6372
+ "depends_on": depends_on,
6373
+ "prerequisite_shas": prerequisite_shas,
6374
+ "writer_lease": {
6375
+ "holder": writer,
6376
+ "generation": 1,
6377
+ "state": "active",
6378
+ "acquired_at": _now_iso(),
6379
+ },
6380
+ "review": {
6381
+ "verdict": "pending",
6382
+ "diff_base": direct_base,
6383
+ "diff_head": "",
6384
+ "diff_fingerprint": "",
6385
+ "reviewer": "",
6386
+ "reviewed_at": "",
6387
+ "reason": "review required" if review_required else "review not required",
6388
+ },
6389
+ "claimed_paths": [],
6390
+ "remote_task_tip": "",
6391
+ "common_submodule_config": {},
6392
+ }
6393
+ _save_task_manifest(repo, manifest)
6394
+ print(f"[task-start] task={task_id}")
6395
+ print("[task-start] execution_mode=direct")
6396
+ print(f"[task-start] branch={current_branch}")
6397
+ print(f"[task-start] base=HEAD@{direct_base}")
6398
+ print(f"[task-start] worktree={repo}")
6399
+ print("[task-start] no temporary branch or worktree created")
6400
+ return
6401
+
6402
+ common_submodule_config = _common_submodule_config(repo)
6403
+ _seed_control_submodule_config(repo)
6044
6404
  prefix = _task_branch_prefix(cfg)
6045
6405
  task_branch = f"{prefix}{task_id}"
6046
6406
  check_ref = run(["git", "check-ref-format", "--branch", task_branch], cwd=repo, check=False)
@@ -6070,7 +6430,9 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6070
6430
  cwd=repo,
6071
6431
  )
6072
6432
  manifest = {
6073
- "schema": 2,
6433
+ "schema": 3,
6434
+ "execution_mode": "isolated",
6435
+ "review_required": review_required,
6074
6436
  "task_id": task_id,
6075
6437
  "task_uuid": task_uuid,
6076
6438
  "owner": owner,
@@ -6142,9 +6504,9 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6142
6504
  f"branch={initial_branch or '(detached)'} head={initial_head}\n{initial_status}"
6143
6505
  )
6144
6506
  _save_task_manifest(repo, manifest)
6145
- _create_active_task_doc(worktree, cfg, manifest)
6146
6507
 
6147
6508
  print(f"[task-start] task={task_id}")
6509
+ print("[task-start] execution_mode=isolated")
6148
6510
  print(f"[task-start] branch={task_branch}")
6149
6511
  print(f"[task-start] base={base_ref}@{base_sha}")
6150
6512
  print(f"[task-start] worktree={worktree}")
@@ -6530,6 +6892,14 @@ def cmd_task_finish(args: argparse.Namespace) -> None:
6530
6892
  cfg = _load_cfg(repo)
6531
6893
  task_id = _validate_task_id(args.task_id)
6532
6894
  manifest = _load_task_manifest(repo, task_id)
6895
+ if _text(manifest.get("execution_mode")).lower() == "direct":
6896
+ if repo.resolve() != Path(_text(manifest.get("worktree_path"))).resolve():
6897
+ raise APError("Run task-finish for a direct task from its current checkout.")
6898
+ if _task_commit_paths(repo) or _resolve_commit(repo, "HEAD") != _text(manifest.get("base_sha")):
6899
+ raise APError("Direct task still has changes or commits; use commit-push instead of task-finish.")
6900
+ _clear_direct_task(repo, manifest)
6901
+ print(f"[task-finish] OK task={task_id} execution_mode=direct no temporary branch existed")
6902
+ return
6533
6903
  _require_control_checkout(repo, manifest)
6534
6904
  timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
6535
6905
  with (
@@ -6555,6 +6925,8 @@ def cmd_task_integrate(args: argparse.Namespace) -> None:
6555
6925
  cfg = _load_cfg(repo)
6556
6926
  task_id = _validate_task_id(args.task_id)
6557
6927
  manifest = _load_task_manifest(repo, task_id)
6928
+ if _text(manifest.get("execution_mode")).lower() == "direct":
6929
+ raise APError("Direct tasks push their current target branch in commit-push and do not use task-integrate.")
6558
6930
  _require_control_checkout(repo, manifest)
6559
6931
  _require_current_writer(manifest, args)
6560
6932
  worktree = Path(_text(manifest.get("worktree_path")))
@@ -6914,12 +7286,119 @@ def _push_current_task(repo: Path, manifest: dict, expected_commit: str = "") ->
6914
7286
  return commit_sha
6915
7287
 
6916
7288
 
7289
+ def _clear_direct_task(repo: Path, manifest: dict) -> None:
7290
+ active_path = _worktree_manifest_path(repo)
7291
+ active = _read_json_object(active_path)
7292
+ if active and _text(active.get("task_uuid")) == _text(manifest.get("task_uuid")):
7293
+ active_path.unlink(missing_ok=True)
7294
+ _delete_task_manifest(repo, manifest)
7295
+
7296
+
7297
+ def _cmd_direct_commit_push_locked(
7298
+ args: argparse.Namespace,
7299
+ repo: Path,
7300
+ cfg: dict,
7301
+ manifest: dict,
7302
+ ) -> None:
7303
+ _require_current_writer(manifest, args)
7304
+ _require_dependencies(repo, manifest, _text(manifest.get("base_sha")))
7305
+ _require_approved_review(repo, cfg, manifest)
7306
+ branch = _current_branch(repo)
7307
+ target = _text(manifest.get("target_branch"))
7308
+ if branch != target:
7309
+ raise APError(f"Direct task branch changed: current={branch or '(detached)'}, expected={target}.")
7310
+ working_paths = _task_commit_paths(repo)
7311
+ head = _resolve_commit(repo, "HEAD")
7312
+ pending_commit = _text(manifest.get("last_commit"))
7313
+ if not working_paths and not (pending_commit and pending_commit == head):
7314
+ if head != _text(manifest.get("base_sha")):
7315
+ raise APError(
7316
+ "Direct task HEAD moved without a recorded commit-push result; refusing to guess ownership."
7317
+ )
7318
+ _clear_direct_task(repo, manifest)
7319
+ print(f"[commit-push] NOOP task={manifest['task_id']} execution_mode=direct; no changes")
7320
+ return
7321
+
7322
+ if pending_commit and pending_commit == head and not working_paths:
7323
+ commit_sha = pending_commit
7324
+ plan = _resolve_execution_plan(cfg, repo, base_ref=_text(manifest.get("base_sha")))
7325
+ else:
7326
+ cmd_doctor(
7327
+ argparse.Namespace(
7328
+ repo=str(repo),
7329
+ profile=_text(getattr(args, "profile", "")).lower(),
7330
+ mode=_text(getattr(args, "mode", "")).lower(),
7331
+ )
7332
+ )
7333
+ plan = _resolve_execution_plan(
7334
+ cfg,
7335
+ repo,
7336
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
7337
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
7338
+ base_ref=_text(manifest.get("base_sha")),
7339
+ )
7340
+ before_gate = _task_content_fingerprint(repo, cfg, manifest)
7341
+ cmd_light_gate(
7342
+ argparse.Namespace(
7343
+ repo=str(repo),
7344
+ scope="changed",
7345
+ profile=plan["profile"],
7346
+ mode="dev",
7347
+ base=_text(manifest.get("base_sha")),
7348
+ explain=False,
7349
+ )
7350
+ )
7351
+ after_gate = _task_content_fingerprint(repo, cfg, manifest)
7352
+ if after_gate != before_gate:
7353
+ raise APError("The final gate changed direct-task files; inspect them and retry commit-push.")
7354
+ manifest = _require_task_context(repo, cfg, args.task_id)
7355
+ _require_current_writer(manifest, args)
7356
+ _require_approved_review(repo, cfg, manifest)
7357
+ task_paths = _task_commit_paths(repo)
7358
+ staged = _stage_exact_paths(repo, task_paths)
7359
+ if not staged:
7360
+ _clear_direct_task(repo, manifest)
7361
+ print(f"[commit-push] NOOP task={manifest['task_id']} execution_mode=direct; no changes")
7362
+ return
7363
+ unstaged = _unstaged_task_paths(repo)
7364
+ if unstaged:
7365
+ raise APError("Direct-task files changed while staging; refusing to commit:\n- " + "\n- ".join(unstaged))
7366
+ commit_sha = _commit_exact_index(repo, args.msg)
7367
+ manifest["state"] = "push-pending"
7368
+ manifest["last_commit"] = commit_sha
7369
+ _save_task_manifest(repo, manifest)
7370
+ remote = _text(manifest.get("remote")) or "origin"
7371
+ push = run(
7372
+ ["git", "push", "--set-upstream", remote, f"{commit_sha}:refs/heads/{target}"],
7373
+ cwd=repo,
7374
+ check=False,
7375
+ )
7376
+ if push.returncode != 0:
7377
+ raise APError(
7378
+ f"Direct target push failed; the local commit is preserved on {branch}.\n"
7379
+ f"{push.stdout}\n{push.stderr}"
7380
+ )
7381
+ remote_tip = _remote_branch_tip(repo, remote, target)
7382
+ if remote_tip != commit_sha:
7383
+ raise APError(
7384
+ f"Direct target verification failed: expected {commit_sha}, got {remote_tip or '(missing)'}"
7385
+ )
7386
+ _clear_direct_task(repo, manifest)
7387
+ print(
7388
+ f"[commit-push] OK task={manifest['task_id']} execution_mode=direct "
7389
+ f"profile={plan['profile']} scope=changed commit={commit_sha}"
7390
+ )
7391
+
7392
+
6917
7393
  def _cmd_commit_push_locked(
6918
7394
  args: argparse.Namespace,
6919
7395
  repo: Path,
6920
7396
  cfg: dict,
6921
7397
  manifest: dict,
6922
7398
  ) -> None:
7399
+ if _text(manifest.get("execution_mode")).lower() == "direct":
7400
+ _cmd_direct_commit_push_locked(args, repo, cfg, manifest)
7401
+ return
6923
7402
  control_repo = Path(_text(manifest.get("control_worktree_path"))).resolve()
6924
7403
  _sync_task_submodule_config(
6925
7404
  control_repo,
@@ -6954,8 +7433,6 @@ def _cmd_commit_push_locked(
6954
7433
  _validate_closure_result(mode, str(args.result))
6955
7434
 
6956
7435
  msg = args.msg
6957
- structure_check_status = "not part of the fast local gate"
6958
-
6959
7436
  before_gate = _task_content_fingerprint(repo, cfg, manifest)
6960
7437
  cmd_light_gate(
6961
7438
  argparse.Namespace(
@@ -6984,22 +7461,6 @@ def _cmd_commit_push_locked(
6984
7461
  "no files were staged or restored."
6985
7462
  )
6986
7463
 
6987
- dev_verification = args.verification or [
6988
- "fast changed-scope gate passed",
6989
- "project commit/push hooks remain enabled",
6990
- ]
6991
- _record_commit_push_closure(
6992
- repo,
6993
- args,
6994
- commit="generated by this commit-push run",
6995
- jenkins="owner-managed after push",
6996
- target_env="owner-managed acceptance",
6997
- verification=dev_verification,
6998
- result=args.result or "DEV-CLOSED",
6999
- follow_up=args.follow_up or "Complete the push stage with task-integrate; do not wait for Jenkins.",
7000
- structure_check=args.structure_check or structure_check_status,
7001
- )
7002
-
7003
7464
  protected = set(manifest.get("initial_untracked") or [])
7004
7465
  _cleanup_generated_noise(repo, protected_paths=protected)
7005
7466
  pre_stage_fingerprint = _task_content_fingerprint(repo, cfg, manifest)
@@ -7099,9 +7560,17 @@ def main(argv: Optional[List[str]] = None) -> int:
7099
7560
  s.add_argument("--planned-path", action="append")
7100
7561
  s.add_argument("--intent")
7101
7562
  s.add_argument("--intent-file")
7563
+ s.add_argument("--writers", type=int, default=1)
7102
7564
  s.add_argument("--json", action="store_true")
7103
7565
  s.set_defaults(func=cmd_classify)
7104
7566
 
7567
+ s = sp.add_parser("validation-map-check")
7568
+ s.add_argument("--base")
7569
+ s.add_argument("--path", action="append")
7570
+ s.add_argument("--tracked", action="store_true")
7571
+ s.add_argument("--json", action="store_true")
7572
+ s.set_defaults(func=cmd_validation_map_check)
7573
+
7105
7574
  s = sp.add_parser("structure-check")
7106
7575
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
7107
7576
  s.add_argument("--base")
@@ -7196,6 +7665,9 @@ def main(argv: Optional[List[str]] = None) -> int:
7196
7665
  s.add_argument("--worktree-root")
7197
7666
  s.add_argument("--owner")
7198
7667
  s.add_argument("--writer")
7668
+ s.add_argument("--writers", type=int, default=1)
7669
+ s.add_argument("--isolated", action="store_true")
7670
+ s.add_argument("--review-required", action="store_true")
7199
7671
  s.add_argument("--owned-path", action="append")
7200
7672
  s.add_argument("--depends-on", action="append", metavar="TASK_ID=SHA")
7201
7673
  s.add_argument("--no-fetch", action="store_true")