@elvis1513/auto-coding-skill 2.1.4 → 2.2.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.
Files changed (30) hide show
  1. package/README.md +163 -554
  2. package/cli/assets/agents/browser-debugger.toml +0 -1
  3. package/cli/assets/agents/docs-researcher.toml +0 -1
  4. package/cli/assets/agents/explorer.toml +1 -2
  5. package/cli/assets/agents/fixer.toml +2 -3
  6. package/cli/assets/agents/reviewer.toml +1 -2
  7. package/cli/assets/skill/SKILL.md +98 -207
  8. package/cli/assets/skill/data/templates/ENGINEERING.md +113 -468
  9. package/cli/assets/skill/data/templates/docs/tasks/closure-log.md +11 -22
  10. package/cli/assets/skill/data/templates/docs/tasks/taskbook.md +16 -39
  11. package/cli/assets/skill/data/templates/tools/ap.py +16 -0
  12. package/cli/assets/skill/scripts/ap.py +703 -138
  13. package/cli/assets/skill/scripts/scaffold_templates.py +136 -0
  14. package/cli/src/index.js +317 -42
  15. package/cli/tests/ap_profiles_test.py +428 -0
  16. package/cli/tests/index.test.js +376 -87
  17. package/package.json +3 -3
  18. package/cli/assets/skill/data/templates/docs/architecture/adr/_TEMPLATE-ADR.md +0 -38
  19. package/cli/assets/skill/data/templates/docs/architecture/structure-standard.md +0 -92
  20. package/cli/assets/skill/data/templates/docs/bugs/bug-list.md +0 -5
  21. package/cli/assets/skill/data/templates/docs/deployment/deploy-records/_TEMPLATE-DEPLOY-RECORD.md +0 -19
  22. package/cli/assets/skill/data/templates/docs/deployment/deploy-runbook.md +0 -11
  23. package/cli/assets/skill/data/templates/docs/design/_TEMPLATE-DD.md +0 -49
  24. package/cli/assets/skill/data/templates/docs/interfaces/api-change-log.md +0 -11
  25. package/cli/assets/skill/data/templates/docs/interfaces/api.md +0 -36
  26. package/cli/assets/skill/data/templates/docs/reviews/_TEMPLATE-REVIEW.md +0 -36
  27. package/cli/assets/skill/data/templates/docs/reviews/optimization-backlog.md +0 -25
  28. package/cli/assets/skill/data/templates/docs/reviews/project-health-baseline.md +0 -66
  29. package/cli/assets/skill/data/templates/docs/tasks/summaries/_TEMPLATE-TASK-SUMMARY.md +0 -35
  30. package/cli/assets/skill/data/templates/docs/testing/regression-matrix.md +0 -11
@@ -26,6 +26,7 @@ except Exception:
26
26
  yaml = None
27
27
 
28
28
  from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_config, run_shell, http_get_status
29
+ from scaffold_templates import scaffold_groups, templates_for
29
30
 
30
31
 
31
32
  _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
@@ -489,25 +490,105 @@ _MANAGED_EXTRA_CLEANUP_DIRS = {
489
490
  Path("data/templates/bridges"),
490
491
  }
491
492
 
493
+ _CORE_DOC_TEMPLATES = [
494
+ Path("tasks/taskbook.md"),
495
+ Path("tasks/closure-log.md"),
496
+ ]
497
+
498
+
499
+ def _inferred_gate_commands(repo: Path) -> dict[str, str]:
500
+ package_json = repo / "package.json"
501
+ if not package_json.exists():
502
+ return {}
503
+ try:
504
+ payload = json.loads(package_json.read_text(encoding="utf-8"))
505
+ except Exception:
506
+ return {}
507
+ scripts = payload.get("scripts") or {}
508
+ if not isinstance(scripts, dict):
509
+ return {}
510
+ inferred: dict[str, str] = {}
511
+ if isinstance(scripts.get("test"), str) and scripts["test"].strip():
512
+ inferred["gate_changed"] = (
513
+ "npm run test:changed"
514
+ if isinstance(scripts.get("test:changed"), str) and scripts["test:changed"].strip()
515
+ else "npm test"
516
+ )
517
+ inferred["gate_standard"] = (
518
+ "npm run test:standard"
519
+ if isinstance(scripts.get("test:standard"), str) and scripts["test:standard"].strip()
520
+ else "npm test"
521
+ )
522
+ if isinstance(scripts.get("test:full"), str) and scripts["test:full"].strip():
523
+ inferred["gate_full"] = "npm run test:full"
524
+ return inferred
525
+
526
+
527
+ def _initialize_engineering_defaults(path: Path, repo: Path) -> None:
528
+ if not path.exists():
529
+ return
530
+ text = path.read_text(encoding="utf-8")
531
+ updated = text.replace(
532
+ 'project:\n name: ""',
533
+ f"project:\n name: {json.dumps(repo.name, ensure_ascii=False)}",
534
+ 1,
535
+ )
536
+ for key, gate_command in _inferred_gate_commands(repo).items():
537
+ updated = updated.replace(
538
+ f' {key}: ""',
539
+ f" {key}: {json.dumps(gate_command)}",
540
+ 1,
541
+ )
542
+ if updated != text:
543
+ path.write_text(updated, encoding="utf-8")
544
+
545
+
546
+ def cmd_scaffold(args: argparse.Namespace) -> None:
547
+ repo = Path(args.repo).resolve()
548
+ group = str(args.group or "").strip().lower()
549
+ try:
550
+ selected = templates_for(group)
551
+ except KeyError as exc:
552
+ choices = ", ".join(scaffold_groups() + ["all"])
553
+ raise APError(f"Unknown scaffold group '{group}'. Choose one of: {choices}") from exc
554
+
555
+ write = bool(args.write)
556
+ force = bool(args.force)
557
+ actions: list[dict] = []
558
+ for rel, content in sorted(selected.items()):
559
+ path = repo / rel
560
+ if path.exists() and not force:
561
+ actions.append({"path": rel, "action": "exists"})
562
+ continue
563
+ action = "write" if write else "would-write"
564
+ actions.append({"path": rel, "action": action})
565
+ if write:
566
+ path.parent.mkdir(parents=True, exist_ok=True)
567
+ path.write_text(content, encoding="utf-8")
568
+
569
+ result = {"group": group, "mode": "write" if write else "plan", "actions": actions}
570
+ if args.json:
571
+ print(json.dumps(result, ensure_ascii=False, indent=2))
572
+ return
573
+ for item in actions:
574
+ print(f"[scaffold] {item['action']}: {item['path']}")
575
+ if not write:
576
+ print("[scaffold] plan only; re-run with --write to create missing files")
577
+
492
578
 
493
579
  def cmd_install(args: argparse.Namespace) -> None:
494
580
  repo = Path(args.repo).resolve()
495
581
  templates = _skill_root() / "data" / "templates"
496
582
 
497
- planned_copies = [
498
- (templates / "docs", repo / "docs"),
499
- (templates / "ENGINEERING.md", repo / "docs" / "ENGINEERING.md"),
500
- ]
583
+ planned_copies = [(templates / "ENGINEERING.md", repo / "docs" / "ENGINEERING.md")]
584
+ for rel in _CORE_DOC_TEMPLATES:
585
+ planned_copies.append((templates / "docs" / rel, repo / "docs" / rel))
501
586
 
502
587
  if args.bridges:
503
588
  planned_copies.append((templates / "bridges" / "AGENTS.md", repo / "AGENTS.md"))
504
589
 
505
590
  tools_dir = repo / "docs" / "tools" / "autopipeline"
506
- planned_copies.extend([
507
- (Path(__file__).resolve(), tools_dir / "ap.py"),
508
- (Path(__file__).resolve().parent / "core.py", tools_dir / "core.py"),
509
- (Path(__file__).resolve().parent / "http_checks.py", tools_dir / "http_checks.py"),
510
- ])
591
+ planned_copies.append((templates / "tools" / "ap.py", tools_dir / "ap.py"))
511
592
 
512
593
  conflicts: list[Path] = []
513
594
  for src, dst in planned_copies:
@@ -525,7 +606,14 @@ def cmd_install(args: argparse.Namespace) -> None:
525
606
  for src, dst in planned_copies:
526
607
  copy_tree(src, dst)
527
608
 
528
- print(f"[install] OK: scaffold installed into {repo}")
609
+ _initialize_engineering_defaults(repo / "docs" / "ENGINEERING.md", repo)
610
+ if args.full:
611
+ cmd_scaffold(
612
+ argparse.Namespace(repo=str(repo), group="all", write=True, force=args.force, json=False)
613
+ )
614
+
615
+ layout = "full" if args.full else "minimal"
616
+ print(f"[install] OK: {layout} scaffold installed into {repo}")
529
617
  print(
530
618
  "[install] Next: edit docs/ENGINEERING.md frontmatter, set verification.*_required, "
531
619
  "fill only enabled environment fields, and commit that file into Git."
@@ -549,9 +637,10 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
549
637
  })
550
638
 
551
639
  tool_files = [
552
- (source_root / "scripts" / "ap.py", repo / "docs" / "tools" / "autopipeline" / "ap.py"),
553
- (source_root / "scripts" / "core.py", repo / "docs" / "tools" / "autopipeline" / "core.py"),
554
- (source_root / "scripts" / "http_checks.py", repo / "docs" / "tools" / "autopipeline" / "http_checks.py"),
640
+ (
641
+ source_root / "data" / "templates" / "tools" / "ap.py",
642
+ repo / "docs" / "tools" / "autopipeline" / "ap.py",
643
+ ),
555
644
  ]
556
645
  for src, dst in tool_files:
557
646
  if not src.exists():
@@ -585,6 +674,8 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
585
674
  for dst in _iter_files(project_skill):
586
675
  rel = dst.relative_to(project_skill)
587
676
  if not (source_root / rel).exists():
677
+ if rel.parts[:3] == ("data", "templates", "docs"):
678
+ continue
588
679
  if rel.parent in _MANAGED_EXTRA_CLEANUP_DIRS:
589
680
  add_action("skill", dst, "delete", "stale managed template")
590
681
  if write:
@@ -592,11 +683,15 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
592
683
  else:
593
684
  add_action("skill", dst, "extra", "present only in project copy")
594
685
  else:
595
- add_action("skill", project_skill, "missing", "run autocoding init --mode project --force")
686
+ add_action("skill", project_skill, "create", "install runtime required by the project launcher")
687
+ if write:
688
+ copy_tree(source_root, project_skill)
596
689
 
597
690
  docs_template = templates / "docs"
598
- for src in _iter_files(docs_template):
599
- rel = src.relative_to(docs_template)
691
+ for rel in _CORE_DOC_TEMPLATES:
692
+ src = docs_template / rel
693
+ if not src.exists():
694
+ continue
600
695
  dst = repo / "docs" / rel
601
696
  if not dst.exists():
602
697
  add_action("doc", dst, "create")
@@ -624,6 +719,7 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
624
719
  add_action("config", engineering, "create")
625
720
  if write:
626
721
  copy_tree(template_engineering, engineering)
722
+ _initialize_engineering_defaults(engineering, repo)
627
723
 
628
724
  result = {
629
725
  "source_root": str(source_root),
@@ -746,7 +842,9 @@ def cmd_check_matrix(args: argparse.Namespace) -> None:
746
842
  docs_cfg = (cfg.get("docs") or {})
747
843
  matrix = Path(repo, str(docs_cfg.get("regression_matrix", "docs/testing/regression-matrix.md")))
748
844
  if not matrix.exists():
749
- raise APError(f"Matrix not found: {matrix}")
845
+ raise APError(
846
+ f"Matrix not found: {matrix}. Create it with `ap.py scaffold testing --write`."
847
+ )
750
848
 
751
849
  rows = 0
752
850
  fail = []
@@ -813,15 +911,9 @@ def _candidate_skill_roots(repo: Path) -> list[Path]:
813
911
  project_root = repo / ".agents" / "skills" / "auto-coding-skill"
814
912
  global_root = Path.home() / ".agents" / "skills" / "auto-coding-skill"
815
913
 
816
- # When upgrade is launched from a project-local skill copy, that copy may be
817
- # stale. Prefer an external source or the global installation, and use the
818
- # project-local copy only as a last resort.
819
- candidates = []
820
- if local_root != project_root:
821
- candidates.append(local_root)
822
- candidates.extend([global_root, project_root])
823
- if local_root == project_root:
824
- candidates.append(local_root)
914
+ # The runtime executing this command is authoritative. In particular, a
915
+ # modern project copy must not be overwritten by an older global copy.
916
+ candidates = [local_root, project_root, global_root]
825
917
 
826
918
  unique: list[Path] = []
827
919
  seen: set[Path] = set()
@@ -834,8 +926,23 @@ def _candidate_skill_roots(repo: Path) -> list[Path]:
834
926
 
835
927
 
836
928
  def _find_skill_asset_root(repo: Path) -> Path:
837
- for root in _candidate_skill_roots(repo):
838
- if (root / "data" / "templates").exists() and (root / "scripts" / "ap.py").exists():
929
+ candidates = _candidate_skill_roots(repo)
930
+
931
+ def is_asset_root(root: Path) -> bool:
932
+ return (root / "data" / "templates").exists() and (root / "scripts" / "ap.py").exists()
933
+
934
+ def has_modern_layout(root: Path) -> bool:
935
+ return (
936
+ is_asset_root(root)
937
+ and (root / "data" / "templates" / "tools" / "ap.py").exists()
938
+ and (root / "scripts" / "scaffold_templates.py").exists()
939
+ )
940
+
941
+ for root in candidates:
942
+ if has_modern_layout(root):
943
+ return root
944
+ for root in candidates:
945
+ if is_asset_root(root):
839
946
  return root
840
947
  raise APError(
841
948
  "Cannot find auto-coding-skill asset root. Run `autocoding init --mode global --force` "
@@ -987,6 +1094,10 @@ def _resolve_secret(section_name: str, section_cfg: dict, field: str) -> str:
987
1094
 
988
1095
 
989
1096
  _GATE_SCOPES = {"auto", "changed", "standard", "full"}
1097
+ _WORKFLOW_PROFILES = {"auto", "micro", "standard", "high-risk"}
1098
+ _PROFILE_GATE_SCOPE = {"micro": "changed", "standard": "standard", "high-risk": "full"}
1099
+ _PROFILE_RANK = {"micro": 0, "standard": 1, "high-risk": 2}
1100
+ _SCOPE_RANK = {"changed": 0, "standard": 1, "full": 2}
990
1101
  _DOC_PATH_PATTERNS = ["*.md", "docs/**"]
991
1102
  _DEFAULT_FULL_PATH_PATTERNS = [
992
1103
  ".agents/**",
@@ -1124,6 +1235,27 @@ def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
1124
1235
  return _unique_paths(paths)
1125
1236
 
1126
1237
 
1238
+ def _commit_changed_files(repo: Path, ref: str) -> list[str]:
1239
+ commit_ref = _text(ref) or "HEAD"
1240
+ result = run(
1241
+ [
1242
+ "git",
1243
+ "diff-tree",
1244
+ "--root",
1245
+ "--no-commit-id",
1246
+ "--name-only",
1247
+ "-r",
1248
+ "--diff-filter=ACMRTUXB",
1249
+ commit_ref,
1250
+ ],
1251
+ cwd=repo,
1252
+ check=False,
1253
+ )
1254
+ if result.returncode != 0:
1255
+ return []
1256
+ return _unique_paths([line.strip() for line in result.stdout.splitlines() if line.strip()])
1257
+
1258
+
1127
1259
  def _cleanup_generated_noise(repo: Path) -> None:
1128
1260
  candidates = [
1129
1261
  rel for rel in _git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"])
@@ -1147,6 +1279,16 @@ def _docs_only(paths: list[str]) -> bool:
1147
1279
  return bool(paths) and all(_path_matches(path, _DOC_PATH_PATTERNS) for path in paths)
1148
1280
 
1149
1281
 
1282
+ def _tests_only(paths: list[str]) -> bool:
1283
+ non_docs = [path for path in paths if not _path_matches(path, _DOC_PATH_PATTERNS)]
1284
+ if not non_docs:
1285
+ return False
1286
+ return all(
1287
+ re.search(r"(^|[/_.-])(test|tests|spec|specs)([/_.-]|$)", path.lower())
1288
+ for path in non_docs
1289
+ )
1290
+
1291
+
1150
1292
  def _gate_rules(gate_cfg: dict) -> list[dict]:
1151
1293
  rules = gate_cfg.get("rules") or []
1152
1294
  return [rule for rule in rules if isinstance(rule, dict)]
@@ -1189,6 +1331,12 @@ def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tup
1189
1331
  matching_rules = _matching_gate_rules(paths, gate_cfg)
1190
1332
  reasons: list[str] = []
1191
1333
 
1334
+ rule_scopes = {_text(rule.get("scope")).lower() for rule in matching_rules if _text(rule.get("scope"))}
1335
+ if "full" in rule_scopes:
1336
+ return "full", ["matched gate rule with scope=full"], matching_rules
1337
+ if any(_path_matches(path, _gate_full_patterns(gate_cfg)) for path in paths):
1338
+ return "full", ["changed files match full-gate patterns"], matching_rules
1339
+
1192
1340
  if scope != "auto":
1193
1341
  return scope, [f"requested scope: {scope}"], matching_rules
1194
1342
 
@@ -1198,15 +1346,9 @@ def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tup
1198
1346
  fallback = "standard"
1199
1347
  return fallback, ["no changed files detected"], matching_rules
1200
1348
 
1201
- rule_scopes = {_text(rule.get("scope")).lower() for rule in matching_rules if _text(rule.get("scope"))}
1202
- if "full" in rule_scopes:
1203
- return "full", ["matched gate rule with scope=full"], matching_rules
1204
1349
  if "standard" in rule_scopes:
1205
1350
  return "standard", ["matched gate rule with scope=standard"], matching_rules
1206
1351
 
1207
- if any(_path_matches(path, _gate_full_patterns(gate_cfg)) for path in paths):
1208
- return "full", ["changed files match full-gate patterns"], matching_rules
1209
-
1210
1352
  if _docs_only(paths):
1211
1353
  return "changed", ["docs-only change"], matching_rules
1212
1354
 
@@ -1222,8 +1364,25 @@ def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tup
1222
1364
  return fallback, reasons, matching_rules
1223
1365
 
1224
1366
 
1225
- def _impact_summary(cfg: dict, repo: Path, requested_scope: str, base_ref: str = "") -> dict:
1226
- paths = _changed_files(repo, base_ref=base_ref)
1367
+ def _impact_summary(
1368
+ cfg: dict,
1369
+ repo: Path,
1370
+ requested_scope: str,
1371
+ base_ref: str = "",
1372
+ changed_paths: Optional[list[str]] = None,
1373
+ ) -> dict:
1374
+ paths = _changed_files(repo, base_ref=base_ref) if changed_paths is None else _unique_paths(changed_paths)
1375
+ docs_cfg = cfg.get("docs") or {}
1376
+ ignored_runtime_paths = {
1377
+ _text(docs_cfg.get("evidence_log")) or "docs/tasks/evidence.jsonl",
1378
+ _text(docs_cfg.get("closure_log")) or "docs/tasks/closure-log.md",
1379
+ _text(_gate_cfg(cfg).get("profile_log")) or ".local/auto-coding-skill/gate-profile.jsonl",
1380
+ }
1381
+ ignored_runtime_paths = {
1382
+ path[2:] if path.startswith("./") else path
1383
+ for path in ignored_runtime_paths
1384
+ }
1385
+ paths = [path for path in paths if path not in ignored_runtime_paths]
1227
1386
  scope, reasons, matching_rules = _select_gate_scope(cfg, requested_scope, paths)
1228
1387
  return {
1229
1388
  "requested_scope": requested_scope or _text(_gate_cfg(cfg).get("default_scope")) or "standard",
@@ -1240,6 +1399,10 @@ def _print_impact(summary: dict, as_json: bool = False) -> None:
1240
1399
  return
1241
1400
  print(f"[impact] requested_scope={summary['requested_scope']}")
1242
1401
  print(f"[impact] selected_scope={summary['selected_scope']}")
1402
+ if summary.get("profile"):
1403
+ print(f"[impact] profile={summary['profile']}")
1404
+ if summary.get("effective_mode"):
1405
+ print(f"[impact] effective_mode={summary['effective_mode']}")
1243
1406
  for reason in summary.get("reasons") or []:
1244
1407
  print(f"[impact] reason: {reason}")
1245
1408
  for rule in summary.get("matched_rules") or []:
@@ -1291,11 +1454,11 @@ def _run_standard_gate(repo: Path, cfg: dict) -> list[str]:
1291
1454
 
1292
1455
 
1293
1456
  def _run_full_gate(repo: Path, cfg: dict) -> list[str]:
1294
- command = _run_first_configured_command(repo, cfg, ["gate_full", "full_gate", "gate_standard", "light_gate", "test", "build"])
1457
+ command = _run_first_configured_command(repo, cfg, ["gate_full", "full_gate"])
1295
1458
  if not command:
1296
1459
  raise APError(
1297
- "Full gate is under-configured. Add commands.gate_full, commands.full_gate, commands.test, "
1298
- "commands.build, or commands.light_gate."
1460
+ "Full gate is under-configured. High-risk and verify work requires "
1461
+ "commands.gate_full or commands.full_gate; light/standard fallbacks do not count."
1299
1462
  )
1300
1463
  return [command]
1301
1464
 
@@ -1782,9 +1945,6 @@ def _docs_ledger_check_result(repo: Path, cfg: dict) -> dict:
1782
1945
  blocking.append(f"docs.taskbook missing or unreadable: {_repo_rel(repo, taskbook)}")
1783
1946
  if closure_lines is None:
1784
1947
  blocking.append(f"docs.closure_log missing or unreadable: {_repo_rel(repo, closure_log)}")
1785
- if not design_dir.exists() or not design_dir.is_dir():
1786
- blocking.append(f"docs.design_dir missing on disk: {_repo_rel(repo, design_dir)}")
1787
-
1788
1948
  if taskbook_lines is not None and taskbook_max > 0 and taskbook_lines > taskbook_max:
1789
1949
  exceeded.append("taskbook")
1790
1950
  _ledger_message(
@@ -1971,8 +2131,8 @@ def _is_closed_task_section(section: dict) -> bool:
1971
2131
  if not status_match:
1972
2132
  return False
1973
2133
  status = status_match.group(1).strip()
1974
- normalized = re.sub(r"\s+", " ", status).strip().lower()
1975
- first_token = re.split(r"[\s/,,;;。]+", normalized, maxsplit=1)[0].strip()
2134
+ normalized = re.sub(r"\s+", " ", status).strip().lower().strip("`*_")
2135
+ first_token = re.split(r"[\s/,,;;。()()]+", normalized, maxsplit=1)[0].strip("`*_")
1976
2136
  if first_token in _CLOSED_TASK_STATUSES or normalized in _CLOSED_TASK_STATUSES:
1977
2137
  return True
1978
2138
  return normalized.startswith((
@@ -2003,19 +2163,47 @@ def _append_archive_index(repo: Path, archive_index: Path, period: str, result:
2003
2163
  return False
2004
2164
 
2005
2165
  paths = result.get("paths") or {}
2166
+ taskbook_archive = Path(repo, str(paths.get("taskbook_archive") or ""))
2167
+ closure_archive = Path(repo, str(paths.get("closure_archive") or ""))
2168
+ design_archive_dir = Path(repo, str(paths.get("design_archive_dir") or ""))
2169
+
2170
+ taskbook_sections = 0
2171
+ if taskbook_archive.is_file():
2172
+ _preamble, sections = _split_markdown_sections(
2173
+ taskbook_archive.read_text(encoding="utf-8"),
2174
+ _TASKBOOK_ARCHIVE_HEADING_RE,
2175
+ )
2176
+ taskbook_sections = len(sections)
2177
+
2178
+ closure_sections = 0
2179
+ if closure_archive.is_file():
2180
+ _preamble, sections = _split_markdown_sections(
2181
+ closure_archive.read_text(encoding="utf-8"),
2182
+ _CLOSURE_ARCHIVE_HEADING_RE,
2183
+ )
2184
+ closure_sections = len(sections)
2185
+
2186
+ design_files = 0
2187
+ if design_archive_dir.is_dir():
2188
+ design_files = sum(1 for path in design_archive_dir.rglob("*") if path.is_file())
2189
+
2006
2190
  entry = (
2007
2191
  f"## {period}\n"
2008
2192
  f"- Generated: {_now_iso()}\n"
2009
- f"- Taskbook archive: `{paths.get('taskbook_archive', '')}` ({counts.get('taskbook_sections', 0)} sections)\n"
2010
- f"- Closure archive: `{paths.get('closure_archive', '')}` ({counts.get('closure_sections', 0)} sections)\n"
2011
- f"- Design archive: `{paths.get('design_archive_dir', '')}` ({counts.get('design_files', 0)} files)\n"
2193
+ f"- Taskbook archive: `{paths.get('taskbook_archive', '')}` ({taskbook_sections} sections)\n"
2194
+ f"- Closure archive: `{paths.get('closure_archive', '')}` ({closure_sections} sections)\n"
2195
+ f"- Design archive: `{paths.get('design_archive_dir', '')}` ({design_files} files)\n"
2012
2196
  )
2013
2197
  archive_index.parent.mkdir(parents=True, exist_ok=True)
2014
2198
  existing = archive_index.read_text(encoding="utf-8") if archive_index.exists() else ""
2015
- if existing.strip():
2016
- archive_index.write_text(existing.rstrip() + "\n\n" + entry, encoding="utf-8")
2017
- else:
2018
- archive_index.write_text("# Docs Archive Index\n\n" + entry, encoding="utf-8")
2199
+ period_section = re.compile(
2200
+ rf"^##\s+{re.escape(period)}\s*$.*?(?=^##\s+|\Z)",
2201
+ re.MULTILINE | re.DOTALL,
2202
+ )
2203
+ retained = period_section.sub("", existing).rstrip()
2204
+ if not retained:
2205
+ retained = "# Docs Archive Index"
2206
+ archive_index.write_text(retained + "\n\n" + entry, encoding="utf-8")
2019
2207
  return True
2020
2208
 
2021
2209
 
@@ -2242,6 +2430,9 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
2242
2430
 
2243
2431
  structure_cfg = _structure_cfg(cfg)
2244
2432
  optimization_cfg = _optimization_cfg(cfg)
2433
+ enforcement = _text(structure_cfg.get("enforcement")).lower() or "advisory"
2434
+ if enforcement not in {"advisory", "blocking"}:
2435
+ raise APError("structure.enforcement must be 'advisory' or 'blocking'")
2245
2436
  warn_file_lines = _int_config(structure_cfg.get("max_file_lines_warn"), 800)
2246
2437
  block_file_lines = _int_config(structure_cfg.get("max_file_lines_block"), 1500)
2247
2438
  warn_function_lines = _int_config(structure_cfg.get("max_function_lines_warn"), 120)
@@ -2294,18 +2485,25 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
2294
2485
  else:
2295
2486
  warnings.extend(boundary_issues)
2296
2487
 
2297
- missing_docs: list[str] = []
2298
- for key, rel_path in _configured_structure_docs(cfg).items():
2299
- if rel_path and not Path(repo, rel_path).exists():
2300
- missing_docs.append(f"{key} missing on disk: {rel_path}")
2301
2488
  require_baseline = _bool_config(optimization_cfg.get("require_baseline_for_global_review"), True)
2302
- if missing_docs and selected_scope == "full" and require_baseline:
2303
- blocking.extend(missing_docs)
2304
- else:
2305
- warnings.extend(missing_docs)
2489
+ if require_baseline:
2490
+ missing_docs = [
2491
+ f"{key} missing on disk: {rel_path}"
2492
+ for key, rel_path in _configured_structure_docs(cfg).items()
2493
+ if rel_path and not Path(repo, rel_path).exists()
2494
+ ]
2495
+ if selected_scope == "full":
2496
+ blocking.extend(missing_docs)
2497
+ else:
2498
+ warnings.extend(missing_docs)
2499
+
2500
+ if enforcement == "advisory" and blocking:
2501
+ warnings.extend(f"{message} [advisory]" for message in blocking)
2502
+ blocking = []
2306
2503
 
2307
2504
  result = {
2308
2505
  "scope": selected_scope,
2506
+ "enforcement": enforcement,
2309
2507
  "inspected_files": inspected,
2310
2508
  "blocking": blocking,
2311
2509
  "warnings": warnings,
@@ -2630,14 +2828,23 @@ def _classify_paths(paths: list[str]) -> dict:
2630
2828
  categories: set[str] = set()
2631
2829
  for path in paths:
2632
2830
  lower = path.lower()
2831
+ words = {word for word in re.split(r"[^a-z0-9]+", lower) if word}
2633
2832
  if _path_matches(path, _DEFAULT_FULL_PATH_PATTERNS):
2634
2833
  categories.add("release_or_tooling")
2635
- if any(token in lower for token in ["migration", "schema", "database", "/db/", "/sql/"]) or lower.endswith(".sql"):
2834
+ if words & {"migration", "migrations", "schema", "database", "db", "sql"} or lower.endswith(".sql"):
2636
2835
  categories.add("db")
2637
2836
  if any(token in lower for token in ["api", "controller", "handler", "route", "server"]):
2638
2837
  categories.add("api")
2639
- if any(token in lower for token in ["auth", "permission", "role", "tenant", "security"]):
2838
+ if words & {"auth", "authentication", "authorization", "permission", "permissions", "role", "roles", "tenant", "security"}:
2640
2839
  categories.add("auth")
2840
+ if words & {"payment", "payments", "billing", "invoice", "invoices", "checkout", "order", "orders"}:
2841
+ categories.add("payment")
2842
+ if words & {"upload", "uploads", "download", "downloads", "attachment", "attachments"}:
2843
+ categories.add("file_transfer")
2844
+ if words & {"nginx", "gateway", "ingress"} or {"reverse", "proxy"} <= words:
2845
+ categories.add("gateway")
2846
+ if "production" in words or "prod" in words and "config" in words or ".env.prod" in lower:
2847
+ categories.add("prod_config")
2641
2848
  if any(token in lower for token in ["page", "component", "view", "frontend", "miniapp", ".tsx", ".jsx", ".vue", ".scss", ".css"]):
2642
2849
  categories.add("ui")
2643
2850
  if any(token in lower for token in ["test", "spec", "__tests__"]):
@@ -2648,61 +2855,222 @@ def _classify_paths(paths: list[str]) -> dict:
2648
2855
  categories.add("structure")
2649
2856
  return {
2650
2857
  "categories": sorted(categories),
2651
- "needs_dd": bool(categories & {"api", "db", "auth", "release_or_tooling"}) or len(paths) > 12,
2858
+ "needs_dd": bool(
2859
+ categories
2860
+ & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config", "release_or_tooling"}
2861
+ )
2862
+ or len(paths) > 12,
2652
2863
  "needs_adr": bool(categories & {"structure", "release_or_tooling"}) and not categories <= {"docs"},
2653
2864
  "needs_browser": "ui" in categories,
2654
- "needs_jenkins": bool(categories & {"release_or_tooling", "db", "auth"}),
2655
- "needs_target": bool(categories & {"api", "db", "auth", "ui"}),
2865
+ "needs_jenkins": bool(
2866
+ categories & {"release_or_tooling", "db", "auth", "payment", "gateway", "prod_config"}
2867
+ ),
2868
+ "needs_target": bool(
2869
+ categories & {"api", "db", "auth", "payment", "file_transfer", "gateway", "prod_config", "ui"}
2870
+ ),
2656
2871
  }
2657
2872
 
2658
2873
 
2659
- def cmd_classify(args: argparse.Namespace) -> None:
2660
- repo = Path(args.repo).resolve()
2661
- cfg = _load_cfg(repo)
2662
- scope = str(args.scope or "").strip().lower()
2663
- impact = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
2874
+ def _normalize_workflow_profile(value: object, default: str = "auto") -> str:
2875
+ profile = _text(value).lower() or default
2876
+ if profile not in _WORKFLOW_PROFILES:
2877
+ raise APError("workflow.profile must be one of: " + ", ".join(sorted(_WORKFLOW_PROFILES)))
2878
+ return profile
2879
+
2880
+
2881
+ def _configured_workflow_profile(cfg: dict) -> str:
2882
+ return _normalize_workflow_profile((cfg.get("workflow") or {}).get("profile"))
2883
+
2884
+
2885
+ def _recommended_agents(profile: str, categories: set[str], classification: dict) -> list[str]:
2886
+ if profile == "micro":
2887
+ return []
2888
+ roles = ["explorer"]
2889
+ if categories & {"api", "release_or_tooling"}:
2890
+ roles.append("docs_researcher")
2891
+ roles.append("fixer")
2892
+ if classification.get("needs_browser"):
2893
+ roles.append("browser_debugger")
2894
+ if profile == "high-risk":
2895
+ roles.append("reviewer")
2896
+ return roles
2897
+
2898
+
2899
+ def _resolve_execution_plan(
2900
+ cfg: dict,
2901
+ repo: Path,
2902
+ *,
2903
+ requested_scope: str = "",
2904
+ requested_profile: str = "",
2905
+ requested_mode: str = "",
2906
+ base_ref: str = "",
2907
+ changed_paths: Optional[list[str]] = None,
2908
+ ) -> dict:
2909
+ impact = _impact_summary(
2910
+ cfg,
2911
+ repo,
2912
+ requested_scope=requested_scope,
2913
+ base_ref=base_ref,
2914
+ changed_paths=changed_paths,
2915
+ )
2664
2916
  paths = list(impact.get("changed_files") or [])
2665
- path_classification = _classify_paths(paths)
2917
+ classification = _classify_paths(paths)
2918
+ categories = set(classification["categories"])
2919
+ matching_rules = _matching_gate_rules(paths, _gate_cfg(cfg))
2920
+ configured_profile = _configured_workflow_profile(cfg)
2921
+ requested_profile_value = _normalize_workflow_profile(requested_profile) if requested_profile else ""
2922
+ configured_mode = _workflow_mode(cfg)
2923
+ requested_mode_value = _text(requested_mode).lower()
2924
+ if requested_mode_value and requested_mode_value not in {"dev", "verify"}:
2925
+ raise APError("workflow.mode must be 'dev' or 'verify'.")
2926
+
2927
+ detected_profile = "standard"
2928
+ profile_reasons: list[str] = []
2929
+ docs_only_paths = _docs_only(paths)
2930
+ docs_or_tests_only = bool(paths) and (
2931
+ (docs_only_paths and str(impact["selected_scope"]) != "full") or _tests_only(paths)
2932
+ )
2933
+ if docs_or_tests_only and str(impact["selected_scope"]) != "full":
2934
+ detected_profile = "micro"
2935
+ profile_reasons.append("only docs/test files changed")
2936
+
2937
+ raw_rule_profiles = {_text(rule.get("profile")).lower() for rule in matching_rules if _text(rule.get("profile"))}
2938
+ invalid_rule_profiles = raw_rule_profiles - (_WORKFLOW_PROFILES - {"auto"})
2939
+ if invalid_rule_profiles:
2940
+ raise APError(
2941
+ "matched gate rule has invalid profile: " + ", ".join(sorted(invalid_rule_profiles))
2942
+ )
2943
+ rule_profiles = raw_rule_profiles
2944
+ if "micro" in rule_profiles and detected_profile == "standard":
2945
+ detected_profile = "micro"
2946
+ profile_reasons.append("matched gate rule with profile=micro")
2947
+ if "standard" in rule_profiles and detected_profile == "micro":
2948
+ detected_profile = "standard"
2949
+ profile_reasons.append("matched gate rule with profile=standard")
2950
+
2951
+ high_categories = {
2952
+ "db",
2953
+ "auth",
2954
+ "payment",
2955
+ "file_transfer",
2956
+ "gateway",
2957
+ "prod_config",
2958
+ "release_or_tooling",
2959
+ }
2960
+ high_signals: list[str] = []
2961
+ if categories & high_categories and not docs_or_tests_only:
2962
+ high_signals.append("high-risk category: " + ", ".join(sorted(categories & high_categories)))
2963
+ if str(impact["selected_scope"]) == "full":
2964
+ high_signals.append("impact requires full gate")
2965
+ if "high-risk" in rule_profiles:
2966
+ high_signals.append("matched gate rule with profile=high-risk")
2967
+ if len(paths) > 12 and not docs_or_tests_only:
2968
+ high_signals.append("change spans more than 12 files")
2969
+ if requested_scope == "full":
2970
+ high_signals.append("full scope explicitly requested")
2971
+
2972
+ if high_signals:
2973
+ detected_profile = "high-risk"
2974
+ profile_reasons.extend(high_signals)
2975
+
2976
+ effective_profile = detected_profile if configured_profile == "auto" else configured_profile
2977
+ if configured_profile != "auto":
2978
+ profile_reasons.append(f"configured profile baseline: {configured_profile}")
2979
+ if requested_profile_value:
2980
+ requested_effective = detected_profile if requested_profile_value == "auto" else requested_profile_value
2981
+ configured_floor = None if configured_profile == "auto" else configured_profile
2982
+ if configured_floor and _PROFILE_RANK[requested_effective] < _PROFILE_RANK[configured_floor]:
2983
+ effective_profile = configured_floor
2984
+ profile_reasons.append(
2985
+ f"configured profile={configured_floor} cannot be downgraded to {requested_effective}"
2986
+ )
2987
+ else:
2988
+ effective_profile = requested_effective
2989
+ if detected_profile == "high-risk" and effective_profile != "high-risk":
2990
+ effective_profile = "high-risk"
2991
+ profile_reasons.append("high-risk signals cannot be downgraded")
2992
+ effective_mode = requested_mode_value or configured_mode
2993
+ if configured_mode == "verify":
2994
+ effective_mode = "verify"
2995
+ if effective_mode == "verify" and effective_profile != "high-risk":
2996
+ effective_profile = "high-risk"
2997
+ profile_reasons.append("verify mode requires high-risk execution")
2998
+ if not profile_reasons:
2999
+ profile_reasons.append(f"configured profile={configured_profile}")
3000
+
3001
+ selected_scope = _PROFILE_GATE_SCOPE[effective_profile]
3002
+ explicit_scope = _text(requested_scope).lower()
3003
+ if explicit_scope in _SCOPE_RANK and _SCOPE_RANK[explicit_scope] > _SCOPE_RANK[selected_scope]:
3004
+ selected_scope = explicit_scope
3005
+ if str(impact["selected_scope"]) == "full":
3006
+ selected_scope = "full"
3007
+ effective_mode = "verify" if effective_profile == "high-risk" else effective_mode
3008
+ execution_reasons = list(impact.get("reasons") or [])
3009
+ if selected_scope != str(impact["selected_scope"]):
3010
+ execution_reasons.append(f"profile={effective_profile} requires scope={selected_scope}")
3011
+
2666
3012
  jenkins_required = _verification_required(cfg, "jenkins", default=True)
2667
3013
  target_env_required = _verification_required(cfg, "target_env", default=True)
2668
- needs_jenkins = bool(path_classification["needs_jenkins"] and jenkins_required)
2669
- needs_target = bool(path_classification["needs_target"] and target_env_required)
2670
- selected_scope = str(impact["selected_scope"])
2671
- risk = "P3"
2672
- if needs_jenkins or selected_scope == "full":
2673
- risk = "P1"
2674
- elif needs_target or path_classification["needs_dd"]:
2675
- risk = "P2"
2676
- elif not paths:
2677
- risk = "P3"
3014
+ needs_jenkins = bool(classification["needs_jenkins"] and jenkins_required)
3015
+ needs_target = bool(classification["needs_target"] and target_env_required)
3016
+ needs_dd = bool(classification["needs_dd"] or effective_profile == "high-risk")
3017
+
3018
+ return {
3019
+ **impact,
3020
+ "reasons": execution_reasons,
3021
+ "configured_profile": configured_profile,
3022
+ "requested_profile": requested_profile_value or None,
3023
+ "profile": effective_profile,
3024
+ "profile_reasons": profile_reasons,
3025
+ "configured_mode": configured_mode,
3026
+ "requested_mode": requested_mode_value or None,
3027
+ "effective_mode": effective_mode,
3028
+ "selected_scope": selected_scope,
3029
+ "categories": sorted(categories),
3030
+ "needs_dd": needs_dd,
3031
+ "needs_adr": classification["needs_adr"],
3032
+ "needs_browser": classification["needs_browser"],
3033
+ "needs_jenkins": needs_jenkins,
3034
+ "needs_target": needs_target,
3035
+ "recommended_agents": _recommended_agents(effective_profile, categories, classification),
3036
+ }
3037
+
3038
+
3039
+ def cmd_classify(args: argparse.Namespace) -> None:
3040
+ repo = Path(args.repo).resolve()
3041
+ cfg = _load_cfg(repo)
3042
+ plan = _resolve_execution_plan(
3043
+ cfg,
3044
+ repo,
3045
+ requested_scope=_text(getattr(args, "scope", "")).lower(),
3046
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3047
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3048
+ base_ref=_text(getattr(args, "base", "")),
3049
+ )
3050
+ risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
2678
3051
  commands = [
2679
3052
  "python3 docs/tools/autopipeline/ap.py impact --scope auto",
2680
3053
  "python3 docs/tools/autopipeline/ap.py structure-check --scope auto",
2681
- f"python3 docs/tools/autopipeline/ap.py light-gate --scope {selected_scope} --explain",
3054
+ f"python3 docs/tools/autopipeline/ap.py light-gate --profile {plan['profile']} --explain",
2682
3055
  ]
2683
- if needs_jenkins:
3056
+ if plan["needs_dd"]:
3057
+ commands.append("python3 docs/tools/autopipeline/ap.py scaffold design --write")
3058
+ if plan["needs_jenkins"]:
2684
3059
  commands.append("python3 docs/tools/autopipeline/ap.py verify-jenkins")
2685
3060
  result = {
2686
- "requested_scope": impact["requested_scope"],
2687
- "selected_scope": selected_scope,
3061
+ **plan,
2688
3062
  "risk": risk,
2689
- "changed_files": paths,
2690
- "categories": path_classification["categories"],
2691
- "needs_dd": path_classification["needs_dd"],
2692
- "needs_adr": path_classification["needs_adr"],
2693
- "needs_browser": path_classification["needs_browser"],
2694
- "needs_jenkins": needs_jenkins,
2695
- "needs_target": needs_target,
2696
3063
  "recommended_commands": commands,
2697
- "reasons": impact.get("reasons") or [],
2698
- "matched_rules": impact.get("matched_rules") or [],
2699
3064
  }
2700
3065
  if args.json:
2701
3066
  print(json.dumps(result, ensure_ascii=False, indent=2))
2702
3067
  else:
2703
3068
  print(f"[classify] risk={risk}")
2704
- print(f"[classify] selected_scope={selected_scope}")
3069
+ print(f"[classify] profile={result['profile']}")
3070
+ print(f"[classify] effective_mode={result['effective_mode']}")
3071
+ print(f"[classify] selected_scope={result['selected_scope']}")
2705
3072
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
3073
+ print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
2706
3074
  for key in ["needs_dd", "needs_adr", "needs_browser", "needs_jenkins", "needs_target"]:
2707
3075
  print(f"[classify] {key}={result[key]}")
2708
3076
  for command in commands:
@@ -2736,15 +3104,29 @@ def cmd_run(args: argparse.Namespace) -> None:
2736
3104
  def cmd_light_gate(args: argparse.Namespace) -> None:
2737
3105
  repo = Path(args.repo).resolve()
2738
3106
  light_gate_start = time.time()
2739
- cmd_doctor(argparse.Namespace(repo=str(repo)))
3107
+ cmd_doctor(
3108
+ argparse.Namespace(
3109
+ repo=str(repo),
3110
+ profile=_text(getattr(args, "profile", "")).lower(),
3111
+ mode=_text(getattr(args, "mode", "")).lower(),
3112
+ )
3113
+ )
2740
3114
  cfg = _load_cfg(repo)
2741
- requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
2742
- impact = _impact_summary(cfg, repo, requested_scope=requested_scope, base_ref=str(getattr(args, "base", "") or ""))
3115
+ plan = _resolve_execution_plan(
3116
+ cfg,
3117
+ repo,
3118
+ requested_scope=_text(getattr(args, "scope", "")).lower(),
3119
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3120
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3121
+ base_ref=_text(getattr(args, "base", "")),
3122
+ )
2743
3123
  if getattr(args, "explain", False):
2744
- _print_impact(impact)
3124
+ _print_impact(plan)
3125
+ for reason in plan["profile_reasons"]:
3126
+ print(f"[impact] profile_reason: {reason}")
2745
3127
 
2746
- selected_scope = str(impact["selected_scope"])
2747
- paths = list(impact.get("changed_files") or [])
3128
+ selected_scope = str(plan["selected_scope"])
3129
+ paths = list(plan.get("changed_files") or [])
2748
3130
  matching_rules = _matching_gate_rules(paths, _gate_cfg(cfg))
2749
3131
  executed: list[str] = []
2750
3132
  executed.extend(_run_structure_check_for_gate(repo, cfg, selected_scope, str(getattr(args, "base", "") or "")))
@@ -2771,16 +3153,32 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
2771
3153
  cfg,
2772
3154
  "light_gate",
2773
3155
  "pass",
2774
- {"scope": selected_scope, "executed": executed, "duration_s": round(duration_s, 3), "changed_files": paths},
3156
+ {
3157
+ "profile": plan["profile"],
3158
+ "effective_mode": plan["effective_mode"],
3159
+ "scope": selected_scope,
3160
+ "executed": executed,
3161
+ "duration_s": round(duration_s, 3),
3162
+ "changed_files": paths,
3163
+ },
3164
+ )
3165
+ print(
3166
+ f"[light-gate] OK profile={plan['profile']} mode={plan['effective_mode']} "
3167
+ f"scope={selected_scope}: " + ", ".join(executed)
2775
3168
  )
2776
- print(f"[light-gate] OK scope={selected_scope}: " + ", ".join(executed))
2777
3169
 
2778
3170
 
2779
3171
  def cmd_impact(args: argparse.Namespace) -> None:
2780
3172
  repo = Path(args.repo).resolve()
2781
3173
  cfg = _load_cfg(repo)
2782
- scope = str(args.scope or "").strip().lower()
2783
- summary = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
3174
+ summary = _resolve_execution_plan(
3175
+ cfg,
3176
+ repo,
3177
+ requested_scope=_text(getattr(args, "scope", "")).lower(),
3178
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3179
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3180
+ base_ref=_text(getattr(args, "base", "")),
3181
+ )
2784
3182
  _print_impact(summary, as_json=bool(args.json))
2785
3183
  _record_evidence(repo, cfg, "impact", "pass", summary)
2786
3184
 
@@ -2930,41 +3328,100 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2930
3328
  jenkins_cfg = (cfg.get("jenkins") or {})
2931
3329
  docs_cfg = (cfg.get("docs") or {})
2932
3330
  runtime_cfg = (cfg.get("runtime") or {})
3331
+ structure_cfg = _structure_cfg(cfg)
2933
3332
 
2934
3333
  missing: List[str] = []
2935
3334
  validation_errors: List[str] = []
2936
3335
 
2937
3336
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
3337
+ profile = str(workflow_cfg.get("profile") or "auto").strip().lower()
2938
3338
  target_env_required = _verification_required(cfg, "target_env", default=True)
2939
3339
  jenkins_required = _verification_required(cfg, "jenkins", default=True)
2940
3340
  if mode not in {"dev", "verify"}:
2941
3341
  missing.append("workflow.mode (must be dev or verify)")
3342
+ if profile not in _WORKFLOW_PROFILES:
3343
+ missing.append("workflow.profile (must be auto, micro, standard, or high-risk)")
2942
3344
  if not str(project_cfg.get("name") or "").strip():
2943
3345
  missing.append("project.name")
2944
- if not (
2945
- str(commands.get("gate_changed") or "").strip()
2946
- or str(commands.get("gate_standard") or "").strip()
2947
- or str(commands.get("gate_full") or "").strip()
2948
- or str(commands.get("full_gate") or "").strip()
2949
- or str(commands.get("light_gate") or "").strip()
2950
- or str(commands.get("quick_test") or "").strip()
2951
- or str(commands.get("test") or "").strip()
2952
- or str(commands.get("build") or "").strip()
2953
- ):
2954
- missing.append(
2955
- "commands.gate_changed/gate_standard/gate_full, commands.light_gate, "
2956
- "commands.quick_test, commands.test, or commands.build"
2957
- )
3346
+ enforcement = _text(structure_cfg.get("enforcement")).lower()
3347
+ if enforcement and enforcement not in {"advisory", "blocking"}:
3348
+ validation_errors.append("structure.enforcement must be advisory or blocking")
3349
+ gate_cfg = _gate_cfg(cfg)
3350
+ raw_rules = gate_cfg.get("rules") or []
3351
+ rules_valid = isinstance(raw_rules, list)
3352
+ if not rules_valid:
3353
+ validation_errors.append("gate.rules must be a list")
3354
+ raw_rules = []
3355
+ for index, rule in enumerate(raw_rules):
3356
+ if not isinstance(rule, dict):
3357
+ rules_valid = False
3358
+ validation_errors.append(f"gate.rules[{index}] must be a mapping")
3359
+ continue
3360
+ rule_profile = _text(rule.get("profile")).lower()
3361
+ if rule_profile and rule_profile not in _WORKFLOW_PROFILES - {"auto"}:
3362
+ rules_valid = False
3363
+ validation_errors.append(
3364
+ f"gate.rules[{index}].profile must be micro, standard, or high-risk"
3365
+ )
3366
+ rule_scope = _text(rule.get("scope")).lower()
3367
+ if rule_scope and rule_scope not in {"changed", "standard", "full"}:
3368
+ rules_valid = False
3369
+ validation_errors.append(
3370
+ f"gate.rules[{index}].scope must be changed, standard, or full"
3371
+ )
3372
+
3373
+ if mode in {"dev", "verify"} and profile in _WORKFLOW_PROFILES and rules_valid:
3374
+ try:
3375
+ plan = _resolve_execution_plan(
3376
+ cfg,
3377
+ repo,
3378
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3379
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3380
+ )
3381
+ except APError as exc:
3382
+ validation_errors.append(str(exc))
3383
+ else:
3384
+ effective_profile = str(plan["profile"])
3385
+ changed_files = list(plan.get("changed_files") or [])
3386
+ matching_rules = _matching_gate_rules(changed_files, gate_cfg)
3387
+ rule_changed_gate = any(
3388
+ any(_configured_command(cfg, _command_name(ref)) for ref in _as_list(rule.get("commands")))
3389
+ for rule in matching_rules
3390
+ )
3391
+ changed_gate = bool(
3392
+ _configured_command(cfg, "gate_changed")
3393
+ or _configured_command(cfg, "quick_test")
3394
+ or _configured_command(cfg, "test")
3395
+ or _configured_command(cfg, "build")
3396
+ or rule_changed_gate
3397
+ or _docs_only(changed_files)
3398
+ )
3399
+ standard_gate = bool(
3400
+ _configured_command(cfg, "gate_standard")
3401
+ or _configured_command(cfg, "light_gate")
3402
+ or _configured_command(cfg, "quick_test")
3403
+ or _configured_command(cfg, "test")
3404
+ or _configured_command(cfg, "build")
3405
+ )
3406
+ full_gate = bool(
3407
+ _configured_command(cfg, "gate_full")
3408
+ or _configured_command(cfg, "full_gate")
3409
+ )
3410
+ if effective_profile == "micro" and not changed_gate:
3411
+ missing.append(
3412
+ "micro gate command: commands.gate_changed, quick_test, test, build, "
3413
+ "or a matching gate rule command"
3414
+ )
3415
+ elif effective_profile == "standard" and not standard_gate:
3416
+ missing.append(
3417
+ "standard gate command: commands.gate_standard, light_gate, quick_test, test, or build"
3418
+ )
3419
+ elif effective_profile == "high-risk" and not full_gate:
3420
+ missing.append(
3421
+ "full gate command: commands.gate_full or commands.full_gate "
3422
+ "(required for high-risk/verify execution)"
3423
+ )
2958
3424
  if target_env_required:
2959
- _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
2960
- _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
2961
- _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
2962
- _require_secret_reference(missing, "target_env", target_cfg, "frontend_password")
2963
- _require_explicit_field(missing, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
2964
- _require_explicit_field(missing, "target_env.backend_username", target_cfg.get("backend_username"))
2965
- _require_secret_reference(missing, "target_env", target_cfg, "backend_password")
2966
- _require_explicit_field(missing, "target_env.backend_root_username", target_cfg.get("backend_root_username"))
2967
- _require_secret_reference(missing, "target_env", target_cfg, "backend_root_password")
2968
3425
  _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
2969
3426
  _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
2970
3427
 
@@ -2983,9 +3440,17 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2983
3440
  repo_docs = {
2984
3441
  "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
2985
3442
  "docs.closure_log": Path(repo, str(docs_cfg.get("closure_log", "docs/tasks/closure-log.md"))),
2986
- "docs.api_doc": Path(repo, str(docs_cfg.get("api_doc", "docs/interfaces/api.md"))),
2987
- "docs.api_change_log": Path(repo, str(docs_cfg.get("api_change_log", "docs/interfaces/api-change-log.md"))),
2988
3443
  }
3444
+ api_doc = Path(repo, str(docs_cfg.get("api_doc", "docs/interfaces/api.md")))
3445
+ api_change_log = Path(repo, str(docs_cfg.get("api_change_log", "docs/interfaces/api-change-log.md")))
3446
+ api_docs_enabled = (
3447
+ _bool_config(docs_cfg.get("api_docs_required"), False)
3448
+ if "api_docs_required" in docs_cfg
3449
+ else api_doc.exists() or api_change_log.exists()
3450
+ )
3451
+ if api_docs_enabled:
3452
+ repo_docs["docs.api_doc"] = api_doc
3453
+ repo_docs["docs.api_change_log"] = api_change_log
2989
3454
  for key, path in repo_docs.items():
2990
3455
  if not path.exists():
2991
3456
  validation_errors.append(f"{key} missing on disk: {path}")
@@ -3163,23 +3628,76 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
3163
3628
 
3164
3629
 
3165
3630
  def cmd_verify_api_docs(args: argparse.Namespace) -> None:
3166
- """Ensure API markdown doc and change-log exist."""
3631
+ """Ensure enabled or already materialized API docs are complete."""
3167
3632
  repo = Path(args.repo).resolve()
3168
3633
  cfg = _load_cfg(repo)
3169
3634
  docs = (cfg.get("docs") or {})
3170
3635
  api_doc = Path(repo, str(docs.get("api_doc", "docs/interfaces/api.md")))
3171
3636
  change_log = Path(repo, str(docs.get("api_change_log", "docs/interfaces/api-change-log.md")))
3637
+ if "api_docs_required" in docs:
3638
+ required = _bool_config(docs.get("api_docs_required"), False)
3639
+ else:
3640
+ required = api_doc.exists() or change_log.exists()
3641
+ if not required:
3642
+ _record_evidence(repo, cfg, "verify_api_docs", "skipped", {"reason": "api_docs_required=false"})
3643
+ print("[verify-api-docs] skipped: optional API docs are not enabled")
3644
+ return
3172
3645
  missing = [p for p in [api_doc, change_log] if not p.exists()]
3173
3646
  if missing:
3174
- raise APError("Missing API docs: " + ", ".join([str(p) for p in missing]))
3647
+ raise APError(
3648
+ "Missing API docs: "
3649
+ + ", ".join([str(p) for p in missing])
3650
+ + ". Create them with `ap.py scaffold api --write`."
3651
+ )
3175
3652
  _record_evidence(repo, cfg, "verify_api_docs", "pass", {"api_doc": str(api_doc), "api_change_log": str(change_log)})
3176
3653
  print(f"[verify-api-docs] OK: {api_doc} + {change_log}")
3177
3654
 
3178
3655
 
3656
+ def _validate_closure_result(effective_mode: str, result: str) -> None:
3657
+ mode = _text(effective_mode).lower()
3658
+ normalized_result = _text(result).upper()
3659
+ if mode == "dev" and normalized_result == "PASS":
3660
+ raise APError("PASS requires verify mode; use DEV-CLOSED, PARTIAL, or FAIL for dev execution.")
3661
+ if mode == "verify" and normalized_result == "DEV-CLOSED":
3662
+ raise APError("DEV-CLOSED is only valid for dev mode; use PASS, PARTIAL, or FAIL for verify execution.")
3663
+
3664
+
3665
+ def _validate_closure_evidence(result: str, verification_items: list[str]) -> None:
3666
+ if _text(result).upper() != "PASS":
3667
+ return
3668
+ meaningful = [
3669
+ _text(item)
3670
+ for item in verification_items
3671
+ if _text(item) and not _is_placeholder(item) and _text(item).lower() not in {"none", "n/a", "not run"}
3672
+ ]
3673
+ if not meaningful:
3674
+ raise APError("PASS requires at least one concrete --verification evidence item.")
3675
+
3676
+
3179
3677
  def cmd_record_closure(args: argparse.Namespace) -> None:
3180
3678
  repo = Path(args.repo).resolve()
3181
3679
  ensure_git_repo(repo)
3182
3680
  cfg = _load_cfg(repo)
3681
+ plan = _resolve_execution_plan(
3682
+ cfg,
3683
+ repo,
3684
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3685
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3686
+ )
3687
+ if not plan.get("changed_files"):
3688
+ commit_paths = _commit_changed_files(repo, _text(getattr(args, "commit", "")) or "HEAD")
3689
+ if commit_paths:
3690
+ plan = _resolve_execution_plan(
3691
+ cfg,
3692
+ repo,
3693
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3694
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3695
+ changed_paths=commit_paths,
3696
+ )
3697
+ profile = str(plan["profile"])
3698
+ _validate_closure_result(str(plan["effective_mode"]), str(args.result))
3699
+ verification_items = list(args.verification or [])
3700
+ _validate_closure_evidence(str(args.result), verification_items)
3183
3701
  docs_cfg = (cfg.get("docs") or {})
3184
3702
  target_cfg = (cfg.get("target_env") or {})
3185
3703
  taskbook = Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md")))
@@ -3193,12 +3711,10 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
3193
3711
  timestamp = _dt.datetime.now().strftime("%Y-%m-%d %H:%M")
3194
3712
  commit_value = _resolve_git_short_sha(repo, args.commit)
3195
3713
  target_env = str(args.target_env or target_cfg.get("name") or "").strip() or "(not set)"
3196
- verification_items = args.verification or []
3197
3714
  verification_text = "; ".join(verification_items) if verification_items else "TODO"
3198
3715
  follow_up = str(args.follow_up or "").strip() or "none"
3199
3716
  jenkins_build = str(args.jenkins or "").strip() or "TODO"
3200
3717
  structure_check = str(getattr(args, "structure_check", "") or "").strip() or "TODO"
3201
-
3202
3718
  lines = [
3203
3719
  f"## {task_id} — {title} — {timestamp}",
3204
3720
  f"- Task: {task_id}",
@@ -3206,6 +3722,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
3206
3722
  f"- CI/Jenkins Build: {jenkins_build}",
3207
3723
  f"- Target Env: {target_env}",
3208
3724
  f"- Verification: {verification_text}",
3725
+ f"- Effective Profile: {profile}",
3209
3726
  f"- Structure Check: {structure_check}",
3210
3727
  f"- Result: {args.result}",
3211
3728
  f"- Follow-up: {follow_up}",
@@ -3227,7 +3744,13 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
3227
3744
  cfg,
3228
3745
  "record_closure",
3229
3746
  "pass",
3230
- {"task_id": task_id, "result": args.result, "commit": commit_value, "structure_check": structure_check},
3747
+ {
3748
+ "task_id": task_id,
3749
+ "result": args.result,
3750
+ "commit": commit_value,
3751
+ "profile": profile,
3752
+ "structure_check": structure_check,
3753
+ },
3231
3754
  )
3232
3755
  print(f"[record-closure] OK: {closure_log}")
3233
3756
 
@@ -3255,6 +3778,7 @@ def _record_commit_push_closure(
3255
3778
  verification=verification,
3256
3779
  result=result,
3257
3780
  follow_up=follow_up,
3781
+ profile=str(getattr(args, "effective_profile", "") or getattr(args, "profile", "") or ""),
3258
3782
  structure_check=structure_check,
3259
3783
  initial_commit=args.initial_commit,
3260
3784
  jenkins_failure=args.jenkins_failure,
@@ -3266,9 +3790,25 @@ def _record_commit_push_closure(
3266
3790
  def cmd_commit_push(args: argparse.Namespace) -> None:
3267
3791
  repo = Path(args.repo).resolve()
3268
3792
  ensure_git_repo(repo)
3269
- cmd_doctor(argparse.Namespace(repo=str(repo)))
3793
+ cmd_doctor(
3794
+ argparse.Namespace(
3795
+ repo=str(repo),
3796
+ profile=_text(getattr(args, "profile", "")).lower(),
3797
+ mode=_text(getattr(args, "mode", "")).lower(),
3798
+ )
3799
+ )
3270
3800
  cfg = _load_cfg(repo)
3271
- mode = _workflow_mode(cfg, args)
3801
+ plan = _resolve_execution_plan(
3802
+ cfg,
3803
+ repo,
3804
+ requested_scope="",
3805
+ requested_profile=_text(getattr(args, "profile", "")).lower(),
3806
+ requested_mode=_text(getattr(args, "mode", "")).lower(),
3807
+ )
3808
+ mode = str(plan["effective_mode"])
3809
+ args.effective_profile = str(plan["profile"])
3810
+ if args.result:
3811
+ _validate_closure_result(mode, str(args.result))
3272
3812
  target_cfg = (cfg.get("target_env") or {})
3273
3813
  target_env_required = _verification_required(cfg, "target_env", default=True)
3274
3814
  jenkins_required = _verification_required(cfg, "jenkins", default=True)
@@ -3280,7 +3820,16 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
3280
3820
  cmd_wait_health(argparse.Namespace(repo=str(repo), scope="runtime"))
3281
3821
 
3282
3822
  if mode in {"dev", "verify"} or args.require_light_gate:
3283
- cmd_light_gate(argparse.Namespace(repo=str(repo)))
3823
+ cmd_light_gate(
3824
+ argparse.Namespace(
3825
+ repo=str(repo),
3826
+ scope=plan["selected_scope"],
3827
+ profile=plan["profile"],
3828
+ mode=mode,
3829
+ base="",
3830
+ explain=False,
3831
+ )
3832
+ )
3284
3833
  structure_check_status = "passed via light-gate" if _structure_gate_enabled(cfg) else "skipped (structure disabled)"
3285
3834
 
3286
3835
  if args.require_jenkins:
@@ -3391,7 +3940,7 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
3391
3940
  follow_up=args.follow_up or "none",
3392
3941
  structure_check=args.structure_check or structure_check_status,
3393
3942
  )
3394
- print(f"[commit-push] OK - mode={mode}")
3943
+ print(f"[commit-push] OK - profile={plan['profile']} mode={mode} scope={plan['selected_scope']}")
3395
3944
 
3396
3945
 
3397
3946
  def main(argv: Optional[List[str]] = None) -> int:
@@ -3402,8 +3951,16 @@ def main(argv: Optional[List[str]] = None) -> int:
3402
3951
  s = sp.add_parser("install")
3403
3952
  s.add_argument("--bridges", action="store_true")
3404
3953
  s.add_argument("--force", action="store_true")
3954
+ s.add_argument("--full", action="store_true", help="Also materialize all optional document templates")
3405
3955
  s.set_defaults(func=cmd_install)
3406
3956
 
3957
+ s = sp.add_parser("scaffold")
3958
+ s.add_argument("group", choices=scaffold_groups() + ["all"])
3959
+ s.add_argument("--write", action="store_true")
3960
+ s.add_argument("--force", action="store_true")
3961
+ s.add_argument("--json", action="store_true")
3962
+ s.set_defaults(func=cmd_scaffold)
3963
+
3407
3964
  s = sp.add_parser("upgrade")
3408
3965
  s.add_argument("--dry-run", action="store_true")
3409
3966
  s.add_argument("--write", action="store_true")
@@ -3434,12 +3991,16 @@ def main(argv: Optional[List[str]] = None) -> int:
3434
3991
 
3435
3992
  s = sp.add_parser("impact")
3436
3993
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
3994
+ s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
3995
+ s.add_argument("--mode", choices=["dev", "verify"], default="")
3437
3996
  s.add_argument("--base")
3438
3997
  s.add_argument("--json", action="store_true")
3439
3998
  s.set_defaults(func=cmd_impact)
3440
3999
 
3441
4000
  s = sp.add_parser("classify")
3442
4001
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
4002
+ s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
4003
+ s.add_argument("--mode", choices=["dev", "verify"], default="")
3443
4004
  s.add_argument("--base")
3444
4005
  s.add_argument("--json", action="store_true")
3445
4006
  s.set_defaults(func=cmd_classify)
@@ -3469,6 +4030,8 @@ def main(argv: Optional[List[str]] = None) -> int:
3469
4030
 
3470
4031
  s = sp.add_parser("light-gate")
3471
4032
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
4033
+ s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES), default="")
4034
+ s.add_argument("--mode", choices=["dev", "verify"], default="")
3472
4035
  s.add_argument("--base")
3473
4036
  s.add_argument("--explain", action="store_true")
3474
4037
  s.set_defaults(func=cmd_light_gate)
@@ -3519,6 +4082,7 @@ def main(argv: Optional[List[str]] = None) -> int:
3519
4082
  s.add_argument("--ci-build", "--jenkins", dest="jenkins", metavar="CI_BUILD")
3520
4083
  s.add_argument("--target-env")
3521
4084
  s.add_argument("--verification", action="append")
4085
+ s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES - {"auto"}))
3522
4086
  s.add_argument("--structure-check")
3523
4087
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"], required=True)
3524
4088
  s.add_argument("--follow-up")
@@ -3532,6 +4096,7 @@ def main(argv: Optional[List[str]] = None) -> int:
3532
4096
  s.add_argument("--title")
3533
4097
  s.add_argument("--msg", required=True)
3534
4098
  s.add_argument("--mode", choices=["dev", "verify"])
4099
+ s.add_argument("--profile", choices=sorted(_WORKFLOW_PROFILES))
3535
4100
  s.add_argument("--require-light-gate", action="store_true")
3536
4101
  s.add_argument("--require-runtime-health", action="store_true")
3537
4102
  s.add_argument("--require-jenkins", action="store_true")