@elvis1513/auto-coding-skill 2.0.6 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import argparse
8
8
  import base64
9
+ import hashlib
9
10
  import datetime as _dt
10
11
  import fnmatch
11
12
  import json
@@ -19,11 +20,24 @@ import urllib.request
19
20
  from pathlib import Path
20
21
  from typing import Optional, List
21
22
 
23
+ try:
24
+ import yaml # type: ignore
25
+ except Exception:
26
+ yaml = None
27
+
22
28
  from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_config, run_shell, http_get_status
23
29
 
24
30
 
25
31
  _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
26
32
  _INVALID_PLACEHOLDERS = {"N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME", "PLACEHOLDER", "XXX"}
33
+ _GENERATED_NOISE_PATTERNS = [
34
+ "__pycache__/**",
35
+ "**/__pycache__/**",
36
+ "*.pyc",
37
+ "**/*.pyc",
38
+ ".DS_Store",
39
+ "**/.DS_Store",
40
+ ]
27
41
 
28
42
 
29
43
  def _skill_root() -> Path:
@@ -51,14 +65,92 @@ def _join_url(base: str, path: str) -> str:
51
65
  return base + path
52
66
 
53
67
 
68
+ def _now_iso() -> str:
69
+ return _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds")
70
+
71
+
72
+ def _repo_rel(repo: Path, path: Path) -> str:
73
+ try:
74
+ return str(path.resolve().relative_to(repo.resolve())).replace("\\", "/")
75
+ except Exception:
76
+ return str(path).replace("\\", "/")
77
+
78
+
79
+ def _append_jsonl(path: Path, payload: dict) -> None:
80
+ path.parent.mkdir(parents=True, exist_ok=True)
81
+ with path.open("a", encoding="utf-8") as handle:
82
+ handle.write(json.dumps(payload, ensure_ascii=False, sort_keys=True))
83
+ handle.write("\n")
84
+
85
+
86
+ def _evidence_log_path(repo: Path, cfg: dict) -> Path:
87
+ docs_cfg = cfg.get("docs") or {}
88
+ rel = _text(docs_cfg.get("evidence_log")) or "docs/tasks/evidence.jsonl"
89
+ return Path(repo, rel)
90
+
91
+
92
+ def _gate_profile_path(repo: Path, cfg: dict) -> Path:
93
+ gate_cfg = _gate_cfg(cfg)
94
+ rel = _text(gate_cfg.get("profile_log")) or ".local/auto-coding-skill/gate-profile.jsonl"
95
+ return Path(repo, rel)
96
+
97
+
98
+ def _record_evidence(repo: Path, cfg: dict, event: str, status: str, payload: Optional[dict] = None) -> None:
99
+ record = {
100
+ "timestamp": _now_iso(),
101
+ "event": event,
102
+ "status": status,
103
+ "repo": str(repo),
104
+ }
105
+ if payload:
106
+ record.update(payload)
107
+ try:
108
+ _append_jsonl(_evidence_log_path(repo, cfg), record)
109
+ except Exception as exc:
110
+ print(f"[evidence] WARN: failed to write evidence log: {exc}", file=sys.stderr)
111
+
112
+
113
+ def _record_gate_profile(
114
+ repo: Path,
115
+ cfg: dict,
116
+ name: str,
117
+ status: str,
118
+ duration_s: float,
119
+ scope: str = "",
120
+ detail: str = "",
121
+ ) -> None:
122
+ record = {
123
+ "timestamp": _now_iso(),
124
+ "name": name,
125
+ "status": status,
126
+ "duration_s": round(duration_s, 3),
127
+ "scope": scope,
128
+ "detail": detail,
129
+ }
130
+ try:
131
+ _append_jsonl(_gate_profile_path(repo, cfg), record)
132
+ except Exception as exc:
133
+ print(f"[gate-profile] WARN: failed to write profile log: {exc}", file=sys.stderr)
134
+
135
+
54
136
  def _run_configured_command(repo: Path, cfg: dict, name: str) -> bool:
55
137
  commands = (cfg.get("commands") or {})
56
138
  command = str(commands.get(name) or "").strip()
57
139
  if not command:
58
140
  return False
59
141
  print(f"[run] {name}: {command}")
60
- run_shell(command, cwd=repo)
61
- print(f"[run] OK: {name}")
142
+ start = time.time()
143
+ try:
144
+ run_shell(command, cwd=repo)
145
+ except APError as exc:
146
+ duration_s = time.time() - start
147
+ _record_gate_profile(repo, cfg, name, "fail", duration_s, detail=str(exc))
148
+ _record_evidence(repo, cfg, "command", "fail", {"name": name, "duration_s": round(duration_s, 3)})
149
+ raise
150
+ duration_s = time.time() - start
151
+ _record_gate_profile(repo, cfg, name, "pass", duration_s)
152
+ _record_evidence(repo, cfg, "command", "pass", {"name": name, "duration_s": round(duration_s, 3)})
153
+ print(f"[run] OK: {name} ({duration_s:.1f}s)")
62
154
  return True
63
155
 
64
156
 
@@ -382,24 +474,182 @@ def _assert_jenkins_build_success(build: dict, identifier: str, allow_no_deploy:
382
474
  return result, description
383
475
 
384
476
 
477
+ def _copy_conflicts(src: Path, dst: Path) -> list[Path]:
478
+ if src.is_file():
479
+ return [dst] if dst.exists() else []
480
+ conflicts: list[Path] = []
481
+ for path in _iter_files(src):
482
+ target = dst / path.relative_to(src)
483
+ if target.exists():
484
+ conflicts.append(target)
485
+ return conflicts
486
+
487
+
488
+ _MANAGED_EXTRA_CLEANUP_DIRS = {
489
+ Path("data/templates/bridges"),
490
+ }
491
+
492
+
385
493
  def cmd_install(args: argparse.Namespace) -> None:
386
494
  repo = Path(args.repo).resolve()
387
495
  templates = _skill_root() / "data" / "templates"
388
496
 
389
- copy_tree(templates / "docs", repo / "docs")
390
- copy_tree(templates / "ENGINEERING.md", repo / "docs" / "ENGINEERING.md")
497
+ planned_copies = [
498
+ (templates / "docs", repo / "docs"),
499
+ (templates / "ENGINEERING.md", repo / "docs" / "ENGINEERING.md"),
500
+ ]
391
501
 
392
502
  if args.bridges:
393
- copy_tree(templates / "bridges", repo)
503
+ planned_copies.append((templates / "bridges" / "AGENTS.md", repo / "AGENTS.md"))
394
504
 
395
505
  tools_dir = repo / "docs" / "tools" / "autopipeline"
396
- tools_dir.mkdir(parents=True, exist_ok=True)
397
- copy_tree(Path(__file__).resolve(), tools_dir / "ap.py")
398
- copy_tree(Path(__file__).resolve().parent / "core.py", tools_dir / "core.py")
399
- copy_tree(Path(__file__).resolve().parent / "http_checks.py", tools_dir / "http_checks.py")
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
+ ])
511
+
512
+ conflicts: list[Path] = []
513
+ for src, dst in planned_copies:
514
+ conflicts.extend(_copy_conflicts(src, dst))
515
+ if conflicts and not args.force:
516
+ conflict_list = "\n".join(f"- {_repo_rel(repo, path)}" for path in conflicts[:20])
517
+ extra = "" if len(conflicts) <= 20 else f"\n- ... and {len(conflicts) - 20} more"
518
+ raise APError(
519
+ "Install would overwrite existing files:\n"
520
+ f"{conflict_list}{extra}\n"
521
+ "For existing projects, run `ap.py upgrade --dry-run` then `ap.py upgrade --write`. "
522
+ "Use `install --force` only when intentionally resetting generated docs/tooling."
523
+ )
524
+
525
+ for src, dst in planned_copies:
526
+ copy_tree(src, dst)
400
527
 
401
528
  print(f"[install] OK: scaffold installed into {repo}")
402
- print("[install] Next: edit docs/ENGINEERING.md frontmatter, fill all platform credentials, and commit that file into Git.")
529
+ print(
530
+ "[install] Next: edit docs/ENGINEERING.md frontmatter, set verification.*_required, "
531
+ "fill only enabled environment fields, and commit that file into Git."
532
+ )
533
+
534
+
535
+ def cmd_upgrade(args: argparse.Namespace) -> None:
536
+ repo = Path(args.repo).resolve()
537
+ ensure_git_repo(repo)
538
+ write = bool(args.write) and not bool(args.dry_run)
539
+ source_root = _find_skill_asset_root(repo)
540
+ templates = source_root / "data" / "templates"
541
+ actions: list[dict] = []
542
+
543
+ def add_action(kind: str, path: Path, action: str, detail: str = "") -> None:
544
+ actions.append({
545
+ "kind": kind,
546
+ "path": _repo_rel(repo, path),
547
+ "action": action,
548
+ "detail": detail,
549
+ })
550
+
551
+ 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"),
555
+ ]
556
+ for src, dst in tool_files:
557
+ if not src.exists():
558
+ continue
559
+ if not dst.exists():
560
+ add_action("tool", dst, "create")
561
+ if write:
562
+ copy_tree(src, dst)
563
+ elif _files_differ(src, dst):
564
+ add_action("tool", dst, "update")
565
+ if write:
566
+ copy_tree(src, dst)
567
+ else:
568
+ add_action("tool", dst, "ok")
569
+
570
+ project_skill = repo / ".agents" / "skills" / "auto-coding-skill"
571
+ if project_skill.exists():
572
+ for src in _iter_files(source_root):
573
+ if ".git" in src.parts:
574
+ continue
575
+ rel = src.relative_to(source_root)
576
+ dst = project_skill / rel
577
+ if not dst.exists():
578
+ add_action("skill", dst, "create")
579
+ if write:
580
+ copy_tree(src, dst)
581
+ elif _files_differ(src, dst):
582
+ add_action("skill", dst, "update")
583
+ if write:
584
+ copy_tree(src, dst)
585
+ for dst in _iter_files(project_skill):
586
+ rel = dst.relative_to(project_skill)
587
+ if not (source_root / rel).exists():
588
+ if rel.parent in _MANAGED_EXTRA_CLEANUP_DIRS:
589
+ add_action("skill", dst, "delete", "stale managed template")
590
+ if write:
591
+ dst.unlink()
592
+ else:
593
+ add_action("skill", dst, "extra", "present only in project copy")
594
+ else:
595
+ add_action("skill", project_skill, "missing", "run autocoding init --mode project --force")
596
+
597
+ docs_template = templates / "docs"
598
+ for src in _iter_files(docs_template):
599
+ rel = src.relative_to(docs_template)
600
+ dst = repo / "docs" / rel
601
+ if not dst.exists():
602
+ add_action("doc", dst, "create")
603
+ if write:
604
+ copy_tree(src, dst)
605
+ elif _files_differ(src, dst) and str(rel).startswith(("architecture/", "reviews/optimization-backlog.md", "reviews/project-health-baseline.md")):
606
+ add_action("doc", dst, "stale", "kept unchanged; review manually")
607
+ else:
608
+ add_action("doc", dst, "ok")
609
+
610
+ engineering = repo / "docs" / "ENGINEERING.md"
611
+ template_engineering = templates / "ENGINEERING.md"
612
+ if engineering.exists() and template_engineering.exists():
613
+ current_cfg, body = _read_frontmatter_markdown(engineering)
614
+ template_cfg, _ = _read_frontmatter_markdown(template_engineering)
615
+ merged_cfg = json.loads(json.dumps(current_cfg))
616
+ added_keys = _deep_merge_missing(merged_cfg, template_cfg)
617
+ if added_keys:
618
+ add_action("config", engineering, "merge", ", ".join(added_keys))
619
+ if write:
620
+ _write_frontmatter_markdown(engineering, merged_cfg, body)
621
+ else:
622
+ add_action("config", engineering, "ok")
623
+ elif template_engineering.exists():
624
+ add_action("config", engineering, "create")
625
+ if write:
626
+ copy_tree(template_engineering, engineering)
627
+
628
+ result = {
629
+ "source_root": str(source_root),
630
+ "mode": "write" if write else "dry-run",
631
+ "actions": actions,
632
+ }
633
+ if args.json:
634
+ print(json.dumps(result, ensure_ascii=False, indent=2))
635
+ else:
636
+ print(f"[upgrade] source={source_root}")
637
+ print(f"[upgrade] mode={'write' if write else 'dry-run'}")
638
+ for item in actions:
639
+ if item["action"] == "ok":
640
+ continue
641
+ detail = f" - {item['detail']}" if item.get("detail") else ""
642
+ print(f"[upgrade] {item['action']} {item['kind']}: {item['path']}{detail}")
643
+ if not any(item["action"] != "ok" for item in actions):
644
+ print("[upgrade] OK: no changes needed")
645
+ elif not write:
646
+ print("[upgrade] dry-run only; re-run with --write to apply safe updates")
647
+ try:
648
+ cfg = _load_cfg(repo)
649
+ except Exception:
650
+ cfg = {}
651
+ if cfg and write:
652
+ _record_evidence(repo, cfg, "upgrade", "pass", {"mode": result["mode"], "action_count": len(actions)})
403
653
 
404
654
 
405
655
  def _infer_title(taskbook: Path, task_id: str) -> str:
@@ -469,9 +719,11 @@ def cmd_gen_summary(args: argparse.Namespace) -> None:
469
719
  - 变更记录位置:`{api_change_log}`
470
720
 
471
721
  ## 4. 质量证据
472
- - 本地轻量校验:light_gate or quick_test/test/build / api docs / jenkins / diff-check — TODO
722
+ - 本地轻量校验:light_gate or quick_test/test/build / api docs / CI/Jenkins / diff-check — TODO
473
723
  - 结构检查:structure-check — TODO
474
- - Jenkins Build:TODO
724
+ - 结构化证据:docs/tasks/evidence.jsonl — TODO
725
+ - 门禁画像:.local/auto-coding-skill/gate-profile.jsonl — TODO
726
+ - CI/Jenkins Build:TODO
475
727
  - 目标环境验证:TODO
476
728
  - 闭环记录:TODO
477
729
  - 回归矩阵(如有):`{regression_matrix}`
@@ -556,6 +808,98 @@ def _load_cfg(repo: Path) -> dict:
556
808
  return load_yaml(cfg_path)
557
809
 
558
810
 
811
+ def _candidate_skill_roots(repo: Path) -> list[Path]:
812
+ local_root = _skill_root()
813
+ project_root = repo / ".agents" / "skills" / "auto-coding-skill"
814
+ global_root = Path.home() / ".agents" / "skills" / "auto-coding-skill"
815
+
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)
825
+
826
+ unique: list[Path] = []
827
+ seen: set[Path] = set()
828
+ for root in candidates:
829
+ if root in seen:
830
+ continue
831
+ seen.add(root)
832
+ unique.append(root)
833
+ return unique
834
+
835
+
836
+ 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():
839
+ return root
840
+ raise APError(
841
+ "Cannot find auto-coding-skill asset root. Run `autocoding init --mode global --force` "
842
+ "or execute this command from an installed skill copy."
843
+ )
844
+
845
+
846
+ def _file_sha256(path: Path) -> str:
847
+ if not path.exists() or not path.is_file():
848
+ return ""
849
+ h = hashlib.sha256()
850
+ with path.open("rb") as handle:
851
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
852
+ h.update(chunk)
853
+ return h.hexdigest()
854
+
855
+
856
+ def _files_differ(a: Path, b: Path) -> bool:
857
+ return _file_sha256(a) != _file_sha256(b)
858
+
859
+
860
+ def _read_frontmatter_markdown(path: Path) -> tuple[dict, str]:
861
+ if not path.exists():
862
+ return {}, ""
863
+ text = path.read_text(encoding="utf-8")
864
+ m = re.match(r"^---\s*\n(.*?)\n---\s*(\n|$)(.*)$", text, flags=re.DOTALL)
865
+ if not m:
866
+ raise APError(f"Markdown frontmatter not found: {path}")
867
+ if yaml is None:
868
+ raise APError("PyYAML not installed. Install dependencies with: pip install pyyaml requests")
869
+ data = yaml.safe_load(m.group(1)) or {}
870
+ return data, m.group(3)
871
+
872
+
873
+ def _write_frontmatter_markdown(path: Path, data: dict, body: str) -> None:
874
+ if yaml is None:
875
+ raise APError("PyYAML not installed. Install dependencies with: pip install pyyaml requests")
876
+ dumped = yaml.safe_dump(data, allow_unicode=True, sort_keys=False).strip()
877
+ path.write_text(f"---\n{dumped}\n---\n{body}", encoding="utf-8")
878
+
879
+
880
+ def _deep_merge_missing(target: dict, template: dict, prefix: str = "") -> list[str]:
881
+ added: list[str] = []
882
+ for key, value in template.items():
883
+ field = f"{prefix}.{key}" if prefix else str(key)
884
+ if key not in target or target.get(key) is None:
885
+ target[key] = value
886
+ added.append(field)
887
+ continue
888
+ if isinstance(target.get(key), dict) and isinstance(value, dict):
889
+ added.extend(_deep_merge_missing(target[key], value, field))
890
+ return added
891
+
892
+
893
+ def _iter_files(root: Path) -> list[Path]:
894
+ if not root.exists():
895
+ return []
896
+ out: list[Path] = []
897
+ for path in root.rglob("*"):
898
+ if path.is_file() and "__pycache__" not in path.parts and path.name != ".DS_Store" and not path.name.endswith(".pyc"):
899
+ out.append(path)
900
+ return sorted(out)
901
+
902
+
559
903
  def _workflow_mode(cfg: dict, args: Optional[argparse.Namespace] = None) -> str:
560
904
  explicit = str(getattr(args, "mode", "") or "").strip().lower() if args else ""
561
905
  configured = str(((cfg.get("workflow") or {}).get("mode")) or "dev").strip().lower()
@@ -646,7 +990,6 @@ _GATE_SCOPES = {"auto", "changed", "standard", "full"}
646
990
  _DOC_PATH_PATTERNS = ["*.md", "docs/**"]
647
991
  _DEFAULT_FULL_PATH_PATTERNS = [
648
992
  ".agents/**",
649
- ".claude/**",
650
993
  ".github/workflows/**",
651
994
  "Jenkinsfile",
652
995
  "Jenkinsfile.*",
@@ -737,11 +1080,17 @@ def _path_matches(path: str, patterns: list) -> bool:
737
1080
  return False
738
1081
 
739
1082
 
1083
+ def _is_generated_noise_path(path: str) -> bool:
1084
+ return _path_matches(path, _GENERATED_NOISE_PATTERNS)
1085
+
1086
+
740
1087
  def _unique_paths(paths: list[str]) -> list[str]:
741
1088
  seen = set()
742
1089
  out = []
743
1090
  for path in paths:
744
1091
  normalized = path.replace("\\", "/").strip()
1092
+ if _is_generated_noise_path(normalized):
1093
+ continue
745
1094
  if not normalized or normalized in seen:
746
1095
  continue
747
1096
  seen.add(normalized)
@@ -775,6 +1124,25 @@ def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
775
1124
  return _unique_paths(paths)
776
1125
 
777
1126
 
1127
+ def _cleanup_generated_noise(repo: Path) -> None:
1128
+ candidates = [
1129
+ rel for rel in _git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"])
1130
+ if _is_generated_noise_path(rel)
1131
+ ]
1132
+ for rel in candidates:
1133
+ path = repo / rel
1134
+ if path.is_file():
1135
+ path.unlink(missing_ok=True)
1136
+ for rel in sorted(candidates, key=lambda item: item.count("/"), reverse=True):
1137
+ parent = (repo / rel).parent
1138
+ while parent != repo and parent.name == "__pycache__":
1139
+ try:
1140
+ parent.rmdir()
1141
+ except OSError:
1142
+ break
1143
+ parent = parent.parent
1144
+
1145
+
778
1146
  def _docs_only(paths: list[str]) -> bool:
779
1147
  return bool(paths) and all(_path_matches(path, _DOC_PATH_PATTERNS) for path in paths)
780
1148
 
@@ -934,14 +1302,16 @@ def _run_full_gate(repo: Path, cfg: dict) -> list[str]:
934
1302
 
935
1303
  def _run_git_diff_check(repo: Path, cfg: dict) -> None:
936
1304
  print("[diff-check] git diff --check")
1305
+ start = time.time()
937
1306
  run(["git", "diff", "--check"], cwd=repo)
1307
+ _record_gate_profile(repo, cfg, "diff_check", "pass", time.time() - start)
1308
+ _record_evidence(repo, cfg, "diff_check", "pass")
938
1309
  print("[diff-check] OK")
939
1310
 
940
1311
 
941
1312
  _DEFAULT_STRUCTURE_ALLOW_PATTERNS = [
942
1313
  ".git/**",
943
1314
  ".agents/skills/**",
944
- ".claude/skills/**",
945
1315
  ".next/**",
946
1316
  ".nuxt/**",
947
1317
  ".svelte-kit/**",
@@ -1028,6 +1398,70 @@ _FUNCTION_START_RE = re.compile(
1028
1398
  r"|^\s*(?:public|private|protected|static|final|async|\s)+\s*[\w<>\[\], ?]+\s+[A-Za-z_]\w*\s*\([^;]*\)\s*\{"
1029
1399
  r"|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_]\w*\s*=\s*(?:async\s*)?\([^)]*\)\s*=>"
1030
1400
  )
1401
+ _IMPORT_PATTERNS = [
1402
+ re.compile(r"^\s*import\s+(?:.+?\s+from\s+)?[\"']([^\"']+)[\"']"),
1403
+ re.compile(r"\brequire\(\s*[\"']([^\"']+)[\"']\s*\)"),
1404
+ re.compile(r"\bimport\(\s*[\"']([^\"']+)[\"']\s*\)"),
1405
+ re.compile(r"^\s*from\s+([A-Za-z_][\w.]*)\s+import\b"),
1406
+ re.compile(r"^\s*import\s+([A-Za-z_][\w.]*)(?:\s+as\s+\w+)?\s*$"),
1407
+ re.compile(r"^\s*import\s+[\"']([^\"']+)[\"']\s*$"),
1408
+ re.compile(r"^\s*[\"']([^\"']+/[^\"']*)[\"']\s*$"),
1409
+ ]
1410
+ _DEFAULT_LAYER_RULES = {
1411
+ "enabled": True,
1412
+ "block": True,
1413
+ "rules": [
1414
+ {
1415
+ "name": "domain",
1416
+ "paths": ["**/domain/**", "**/domains/**", "**/model/**", "**/models/**"],
1417
+ "forbidden_imports": [
1418
+ "**/infrastructure/**",
1419
+ "**/infra/**",
1420
+ "**/adapter/**",
1421
+ "**/repository/**",
1422
+ "**/repositories/**",
1423
+ "**/client/**",
1424
+ "**/clients/**",
1425
+ "**/controller/**",
1426
+ "**/handler/**",
1427
+ "**/page/**",
1428
+ "**/pages/**",
1429
+ "**/component/**",
1430
+ "**/components/**",
1431
+ "**/view/**",
1432
+ "**/views/**",
1433
+ ],
1434
+ },
1435
+ {
1436
+ "name": "application",
1437
+ "paths": ["**/application/**", "**/service/**", "**/services/**", "**/usecase/**", "**/usecases/**"],
1438
+ "forbidden_imports": [
1439
+ "**/controller/**",
1440
+ "**/handler/**",
1441
+ "**/page/**",
1442
+ "**/pages/**",
1443
+ "**/component/**",
1444
+ "**/components/**",
1445
+ "**/view/**",
1446
+ "**/views/**",
1447
+ ],
1448
+ },
1449
+ {
1450
+ "name": "shared",
1451
+ "paths": ["**/shared/**", "**/common/**", "**/utils/**", "**/lib/**"],
1452
+ "forbidden_imports": [
1453
+ "**/domain/**",
1454
+ "**/application/**",
1455
+ "**/service/**",
1456
+ "**/services/**",
1457
+ "**/infrastructure/**",
1458
+ "**/controller/**",
1459
+ "**/page/**",
1460
+ "**/pages/**",
1461
+ ],
1462
+ },
1463
+ ],
1464
+ }
1031
1465
 
1032
1466
 
1033
1467
  def _structure_cfg(cfg: dict) -> dict:
@@ -1040,6 +1474,11 @@ def _optimization_cfg(cfg: dict) -> dict:
1040
1474
  return value if isinstance(value, dict) else {}
1041
1475
 
1042
1476
 
1477
+ def _verification_cfg(cfg: dict) -> dict:
1478
+ value = cfg.get("verification") or {}
1479
+ return value if isinstance(value, dict) else {}
1480
+
1481
+
1043
1482
  def _bool_config(value: object, default: bool = False) -> bool:
1044
1483
  if value is None:
1045
1484
  return default
@@ -1062,6 +1501,17 @@ def _int_config(value: object, default: int) -> int:
1062
1501
  return default
1063
1502
 
1064
1503
 
1504
+ def _verification_required(cfg: dict, key: str, default: bool = True) -> bool:
1505
+ verification_cfg = _verification_cfg(cfg)
1506
+ required_key = f"{key}_required"
1507
+ enabled_key = f"{key}_enabled"
1508
+ if required_key in verification_cfg:
1509
+ return _bool_config(verification_cfg.get(required_key), default)
1510
+ if enabled_key in verification_cfg:
1511
+ return _bool_config(verification_cfg.get(enabled_key), default)
1512
+ return default
1513
+
1514
+
1065
1515
  def _tracked_files(repo: Path) -> list[str]:
1066
1516
  return _unique_paths(_git_lines(repo, ["git", "ls-files"]))
1067
1517
 
@@ -1141,7 +1591,7 @@ def _added_lines_by_path(repo: Path, base_ref: str = "") -> dict[str, int]:
1141
1591
  if path:
1142
1592
  added[path] = added.get(path, 0) + count
1143
1593
 
1144
- for path in _git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"]):
1594
+ for path in _unique_paths(_git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"])):
1145
1595
  lines = _read_text_lines(repo, path)
1146
1596
  if lines is not None:
1147
1597
  added[path] = added.get(path, 0) + len(lines)
@@ -1164,6 +1614,85 @@ def _function_size_warnings(path: str, lines: list[str], threshold: int) -> list
1164
1614
  return warnings
1165
1615
 
1166
1616
 
1617
+ def _layer_rules_config(structure_cfg: dict) -> dict:
1618
+ raw = structure_cfg.get("layer_rules")
1619
+ if not isinstance(raw, dict):
1620
+ return dict(_DEFAULT_LAYER_RULES)
1621
+ merged = dict(_DEFAULT_LAYER_RULES)
1622
+ merged.update(raw)
1623
+ if "rules" not in raw:
1624
+ merged["rules"] = _DEFAULT_LAYER_RULES["rules"]
1625
+ return merged
1626
+
1627
+
1628
+ def _extract_import_targets(path: str, lines: list[str]) -> list[tuple[int, str]]:
1629
+ suffix = Path(path).suffix.lower()
1630
+ if suffix not in {".py", ".js", ".jsx", ".ts", ".tsx", ".vue", ".go", ".java", ".kt", ".kts", ".rs", ".swift"}:
1631
+ return []
1632
+ targets: list[tuple[int, str]] = []
1633
+ for index, line in enumerate(lines):
1634
+ stripped = line.strip()
1635
+ if not stripped or stripped.startswith(("#", "//", "*")):
1636
+ continue
1637
+ for pattern in _IMPORT_PATTERNS:
1638
+ match = pattern.search(line)
1639
+ if match:
1640
+ targets.append((index + 1, match.group(1).strip()))
1641
+ break
1642
+ return targets
1643
+
1644
+
1645
+ def _resolve_relative_import(source_path: str, target: str) -> str:
1646
+ normalized = target.replace("\\", "/")
1647
+ if not normalized.startswith("."):
1648
+ return normalized
1649
+ source_dir = Path(source_path).parent
1650
+ parts = []
1651
+ for part in (source_dir / normalized).parts:
1652
+ if part in {"", "."}:
1653
+ continue
1654
+ if part == "..":
1655
+ if parts:
1656
+ parts.pop()
1657
+ continue
1658
+ parts.append(part)
1659
+ return "/".join(parts)
1660
+
1661
+
1662
+ def _import_matches_pattern(target: str, pattern: str) -> bool:
1663
+ normalized = target.replace("\\", "/").lstrip("./")
1664
+ dotted_as_path = normalized.replace(".", "/")
1665
+ pat = pattern.replace("\\", "/").lstrip("./")
1666
+ if _path_matches(normalized, [pat]) or _path_matches(dotted_as_path, [pat]):
1667
+ return True
1668
+ marker = pat.replace("**/", "").replace("/**", "").strip("/")
1669
+ if marker and (f"/{marker}/" in f"/{normalized}/" or f"/{marker}/" in f"/{dotted_as_path}/"):
1670
+ return True
1671
+ return False
1672
+
1673
+
1674
+ def _structure_boundary_issues(path: str, lines: list[str], structure_cfg: dict) -> list[str]:
1675
+ layer_cfg = _layer_rules_config(structure_cfg)
1676
+ if not _bool_config(layer_cfg.get("enabled"), True):
1677
+ return []
1678
+ rules = [rule for rule in _as_list(layer_cfg.get("rules")) if isinstance(rule, dict)]
1679
+ if not rules:
1680
+ return []
1681
+ matching_rules = [rule for rule in rules if _path_matches(path, _as_list(rule.get("paths")))]
1682
+ if not matching_rules:
1683
+ return []
1684
+ imports = _extract_import_targets(path, lines)
1685
+ issues: list[str] = []
1686
+ for rule in matching_rules:
1687
+ name = _text(rule.get("name")) or "layer"
1688
+ forbidden = _as_list(rule.get("forbidden_imports"))
1689
+ for line_no, target in imports:
1690
+ resolved = _resolve_relative_import(path, target)
1691
+ if any(_import_matches_pattern(target, pattern) or _import_matches_pattern(resolved, pattern) for pattern in forbidden):
1692
+ issues.append(f"{path}:{line_no} layer '{name}' imports forbidden target '{target}'")
1693
+ return issues
1694
+
1695
+
1167
1696
  def _configured_structure_docs(cfg: dict) -> dict[str, str]:
1168
1697
  docs_cfg = cfg.get("docs") or {}
1169
1698
  return {
@@ -1173,6 +1702,494 @@ def _configured_structure_docs(cfg: dict) -> dict[str, str]:
1173
1702
  }
1174
1703
 
1175
1704
 
1705
+ def _docs_cfg(cfg: dict) -> dict:
1706
+ value = cfg.get("docs") or {}
1707
+ return value if isinstance(value, dict) else {}
1708
+
1709
+
1710
+ def _docs_ledger_paths(repo: Path, cfg: dict) -> tuple[dict, dict[str, Path]]:
1711
+ docs_cfg = _docs_cfg(cfg)
1712
+ return docs_cfg, {
1713
+ "taskbook": Path(repo, _text(docs_cfg.get("taskbook")) or "docs/tasks/taskbook.md"),
1714
+ "closure_log": Path(repo, _text(docs_cfg.get("closure_log")) or "docs/tasks/closure-log.md"),
1715
+ "design_dir": Path(repo, _text(docs_cfg.get("design_dir")) or "docs/design"),
1716
+ "task_archive_dir": Path(repo, _text(docs_cfg.get("task_archive_dir")) or "docs/tasks/archives"),
1717
+ "design_archive_dir": Path(repo, _text(docs_cfg.get("design_archive_dir")) or "docs/archive/design"),
1718
+ "archive_index": Path(repo, _text(docs_cfg.get("archive_index")) or "docs/tasks/archive-index.md"),
1719
+ }
1720
+
1721
+
1722
+ def _count_lines(path: Path) -> Optional[int]:
1723
+ if not path.exists() or not path.is_file():
1724
+ return None
1725
+ try:
1726
+ return len(path.read_text(encoding="utf-8").splitlines())
1727
+ except UnicodeDecodeError:
1728
+ return None
1729
+ except OSError:
1730
+ return None
1731
+
1732
+
1733
+ def _count_files(root: Path, pattern: str, recursive: bool = True) -> int:
1734
+ if not root.exists() or not root.is_dir():
1735
+ return 0
1736
+ iterator = root.rglob(pattern) if recursive else root.glob(pattern)
1737
+ return sum(1 for path in iterator if path.is_file())
1738
+
1739
+
1740
+ def _ledger_message(blocking: list[str], warnings: list[str], block: bool, message: str) -> None:
1741
+ if block:
1742
+ blocking.append(message)
1743
+ else:
1744
+ warnings.append(message)
1745
+
1746
+
1747
+ def _docs_ledger_check_result(repo: Path, cfg: dict) -> dict:
1748
+ docs_cfg, paths = _docs_ledger_paths(repo, cfg)
1749
+ enabled = _bool_config(docs_cfg.get("ledger_check_enabled"), True)
1750
+ block_on_exceed = _bool_config(docs_cfg.get("ledger_block_on_exceed"), True)
1751
+
1752
+ taskbook = paths["taskbook"]
1753
+ closure_log = paths["closure_log"]
1754
+ design_dir = paths["design_dir"]
1755
+ task_archive_dir = paths["task_archive_dir"]
1756
+ design_archive_dir = paths["design_archive_dir"]
1757
+ archive_index = paths["archive_index"]
1758
+
1759
+ taskbook_max = _int_config(docs_cfg.get("active_taskbook_max_lines"), 1200)
1760
+ closure_max = _int_config(docs_cfg.get("active_closure_log_max_lines"), 800)
1761
+ design_max = _int_config(docs_cfg.get("active_design_max_files"), 120)
1762
+
1763
+ taskbook_lines = _count_lines(taskbook)
1764
+ closure_lines = _count_lines(closure_log)
1765
+ active_design_files = _count_files(design_dir, "T*.md", recursive=False)
1766
+ task_archive_files = _count_files(task_archive_dir, "*.md", recursive=True)
1767
+ design_archive_files = _count_files(design_archive_dir, "T*.md", recursive=True)
1768
+ archive_index_exists = archive_index.exists()
1769
+
1770
+ blocking: list[str] = []
1771
+ warnings: list[str] = []
1772
+ exceeded: list[str] = []
1773
+
1774
+ if not enabled:
1775
+ return {
1776
+ "enabled": False,
1777
+ "blocking": blocking,
1778
+ "warnings": warnings,
1779
+ }
1780
+
1781
+ if taskbook_lines is None:
1782
+ blocking.append(f"docs.taskbook missing or unreadable: {_repo_rel(repo, taskbook)}")
1783
+ if closure_lines is None:
1784
+ 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
+ if taskbook_lines is not None and taskbook_max > 0 and taskbook_lines > taskbook_max:
1789
+ exceeded.append("taskbook")
1790
+ _ledger_message(
1791
+ blocking,
1792
+ warnings,
1793
+ block_on_exceed,
1794
+ f"docs.taskbook has {taskbook_lines} lines (max {taskbook_max}); "
1795
+ f"physically archive closed tasks under {_repo_rel(repo, task_archive_dir)} instead of keeping an index-only ledger",
1796
+ )
1797
+ if task_archive_files == 0:
1798
+ _ledger_message(
1799
+ blocking,
1800
+ warnings,
1801
+ block_on_exceed,
1802
+ f"docs.taskbook exceeds the active ledger budget but docs.task_archive_dir has no archive files: {_repo_rel(repo, task_archive_dir)}",
1803
+ )
1804
+
1805
+ if closure_lines is not None and closure_max > 0 and closure_lines > closure_max:
1806
+ exceeded.append("closure_log")
1807
+ _ledger_message(
1808
+ blocking,
1809
+ warnings,
1810
+ block_on_exceed,
1811
+ f"docs.closure_log has {closure_lines} lines (max {closure_max}); "
1812
+ f"physically archive historical closure entries under {_repo_rel(repo, task_archive_dir)}",
1813
+ )
1814
+ if task_archive_files == 0:
1815
+ _ledger_message(
1816
+ blocking,
1817
+ warnings,
1818
+ block_on_exceed,
1819
+ f"docs.closure_log exceeds the active ledger budget but docs.task_archive_dir has no archive files: {_repo_rel(repo, task_archive_dir)}",
1820
+ )
1821
+
1822
+ if design_max > 0 and active_design_files > design_max:
1823
+ exceeded.append("design_dir")
1824
+ _ledger_message(
1825
+ blocking,
1826
+ warnings,
1827
+ block_on_exceed,
1828
+ f"docs.design_dir has {active_design_files} top-level T*.md files (max {design_max}); "
1829
+ f"move historical DD files under {_repo_rel(repo, design_archive_dir)}",
1830
+ )
1831
+ if design_archive_files == 0:
1832
+ _ledger_message(
1833
+ blocking,
1834
+ warnings,
1835
+ block_on_exceed,
1836
+ f"docs.design_dir exceeds the active DD budget but docs.design_archive_dir has no archived T*.md files: {_repo_rel(repo, design_archive_dir)}",
1837
+ )
1838
+
1839
+ if exceeded and archive_index_exists and task_archive_files == 0 and design_archive_files == 0:
1840
+ _ledger_message(
1841
+ blocking,
1842
+ warnings,
1843
+ block_on_exceed,
1844
+ f"{_repo_rel(repo, archive_index)} exists, but no physical docs archives were found; "
1845
+ "archive indexes are navigation aids and do not satisfy active-ledger slimming",
1846
+ )
1847
+
1848
+ return {
1849
+ "enabled": True,
1850
+ "limits": {
1851
+ "active_taskbook_max_lines": taskbook_max,
1852
+ "active_closure_log_max_lines": closure_max,
1853
+ "active_design_max_files": design_max,
1854
+ },
1855
+ "paths": {
1856
+ "taskbook": _repo_rel(repo, taskbook),
1857
+ "closure_log": _repo_rel(repo, closure_log),
1858
+ "design_dir": _repo_rel(repo, design_dir),
1859
+ "task_archive_dir": _repo_rel(repo, task_archive_dir),
1860
+ "design_archive_dir": _repo_rel(repo, design_archive_dir),
1861
+ "archive_index": _repo_rel(repo, archive_index),
1862
+ },
1863
+ "counts": {
1864
+ "taskbook_lines": taskbook_lines,
1865
+ "closure_log_lines": closure_lines,
1866
+ "active_design_files": active_design_files,
1867
+ "task_archive_files": task_archive_files,
1868
+ "design_archive_files": design_archive_files,
1869
+ "archive_index_exists": archive_index_exists,
1870
+ },
1871
+ "exceeded": exceeded,
1872
+ "blocking": blocking,
1873
+ "warnings": warnings,
1874
+ }
1875
+
1876
+
1877
+ _TASKBOOK_ARCHIVE_HEADING_RE = re.compile(r"^##\s+Task\s+([A-Za-z][A-Za-z0-9]*\d+(?:-\d+)?)\b")
1878
+ _CLOSURE_ARCHIVE_HEADING_RE = re.compile(r"^##\s+([A-Za-z][A-Za-z0-9]*\d+(?:-\d+)?)\b")
1879
+ _TASK_RESULT_RE = re.compile(r"(?:^|\n)\s*-\s*Result\s*[::]\s*(DEV-CLOSED|PASS|FAIL|PARTIAL)\b", re.IGNORECASE)
1880
+ _TASK_STATUS_RE = re.compile(r"(?:^|\n)\s*-\s*(?:状态|Status)\s*[::]\s*([^|\n]+)", re.IGNORECASE)
1881
+ _DESIGN_TASK_FILE_RE = re.compile(r"^([Tt][A-Za-z0-9]*\d+(?:-\d+)?)")
1882
+ _CLOSED_TASK_STATUSES = {
1883
+ "done",
1884
+ "closed",
1885
+ "dev-closed",
1886
+ "pass",
1887
+ "passed",
1888
+ "fail",
1889
+ "failed",
1890
+ "partial",
1891
+ "完成",
1892
+ "已完成",
1893
+ "关闭",
1894
+ "已关闭",
1895
+ }
1896
+
1897
+
1898
+ def _normalize_task_id(task_id: str) -> str:
1899
+ return str(task_id or "").strip().upper()
1900
+
1901
+
1902
+ def _resolve_archive_period(period: str) -> str:
1903
+ value = str(period or "").strip()
1904
+ if not value:
1905
+ return _dt.date.today().strftime("%Y-%m")
1906
+ if not re.fullmatch(r"\d{4}-\d{2}", value):
1907
+ raise APError("--period must use YYYY-MM")
1908
+ month = int(value.split("-", 1)[1])
1909
+ if month < 1 or month > 12:
1910
+ raise APError("--period month must be between 01 and 12")
1911
+ return value
1912
+
1913
+
1914
+ def _split_markdown_sections(text: str, heading_re: re.Pattern[str]) -> tuple[list[str], list[dict]]:
1915
+ preamble: list[str] = []
1916
+ sections: list[dict] = []
1917
+ current: Optional[dict] = None
1918
+
1919
+ for line in text.splitlines():
1920
+ match = heading_re.match(line.strip())
1921
+ if match:
1922
+ if current is not None:
1923
+ sections.append(current)
1924
+ current = {"id": match.group(1), "lines": [line]}
1925
+ continue
1926
+ if current is None:
1927
+ preamble.append(line)
1928
+ else:
1929
+ current["lines"].append(line)
1930
+
1931
+ if current is not None:
1932
+ sections.append(current)
1933
+ return preamble, sections
1934
+
1935
+
1936
+ def _section_text(section: dict) -> str:
1937
+ lines = section.get("lines") or []
1938
+ return "\n".join(str(line) for line in lines).rstrip() + "\n"
1939
+
1940
+
1941
+ def _render_markdown_doc(preamble: list[str], sections: list[dict]) -> str:
1942
+ parts: list[str] = []
1943
+ preamble_text = "\n".join(preamble).rstrip()
1944
+ if preamble_text:
1945
+ parts.append(preamble_text)
1946
+ for section in sections:
1947
+ text = _section_text(section).rstrip()
1948
+ if text:
1949
+ parts.append(text)
1950
+ return "\n\n".join(parts).rstrip() + "\n"
1951
+
1952
+
1953
+ def _is_closed_task_section(section: dict) -> bool:
1954
+ text = _section_text(section)
1955
+ if _TASK_RESULT_RE.search(text):
1956
+ return True
1957
+ status_match = _TASK_STATUS_RE.search(text)
1958
+ if not status_match:
1959
+ return False
1960
+ status = status_match.group(1).strip()
1961
+ status = re.split(r"[\s/,,;;。]+", status, maxsplit=1)[0].strip().lower()
1962
+ return status in _CLOSED_TASK_STATUSES
1963
+
1964
+
1965
+ def _append_archive_sections(path: Path, title: str, period: str, sections: list[dict]) -> bool:
1966
+ if not sections:
1967
+ return False
1968
+ path.parent.mkdir(parents=True, exist_ok=True)
1969
+ existing = path.read_text(encoding="utf-8") if path.exists() else ""
1970
+ header = f"# {title} — {period}\n\n"
1971
+ body = "\n\n".join(_section_text(section).rstrip() for section in sections).rstrip() + "\n"
1972
+ if existing.strip():
1973
+ path.write_text(existing.rstrip() + "\n\n" + body, encoding="utf-8")
1974
+ else:
1975
+ path.write_text(header + body, encoding="utf-8")
1976
+ return True
1977
+
1978
+
1979
+ def _append_archive_index(repo: Path, archive_index: Path, period: str, result: dict) -> bool:
1980
+ counts = result.get("counts") or {}
1981
+ if not any(int(counts.get(key) or 0) for key in ["taskbook_sections", "closure_sections", "design_files"]):
1982
+ return False
1983
+
1984
+ paths = result.get("paths") or {}
1985
+ entry = (
1986
+ f"## {period}\n"
1987
+ f"- Generated: {_now_iso()}\n"
1988
+ f"- Taskbook archive: `{paths.get('taskbook_archive', '')}` ({counts.get('taskbook_sections', 0)} sections)\n"
1989
+ f"- Closure archive: `{paths.get('closure_archive', '')}` ({counts.get('closure_sections', 0)} sections)\n"
1990
+ f"- Design archive: `{paths.get('design_archive_dir', '')}` ({counts.get('design_files', 0)} files)\n"
1991
+ )
1992
+ archive_index.parent.mkdir(parents=True, exist_ok=True)
1993
+ existing = archive_index.read_text(encoding="utf-8") if archive_index.exists() else ""
1994
+ if existing.strip():
1995
+ archive_index.write_text(existing.rstrip() + "\n\n" + entry, encoding="utf-8")
1996
+ else:
1997
+ archive_index.write_text("# Docs Archive Index\n\n" + entry, encoding="utf-8")
1998
+ return True
1999
+
2000
+
2001
+ def _plan_docs_ledger_archive(repo: Path, cfg: dict, period: str) -> dict:
2002
+ _docs_cfg_value, paths = _docs_ledger_paths(repo, cfg)
2003
+ taskbook = paths["taskbook"]
2004
+ closure_log = paths["closure_log"]
2005
+ design_dir = paths["design_dir"]
2006
+ task_archive_dir = paths["task_archive_dir"] / period
2007
+ design_archive_dir = paths["design_archive_dir"] / period
2008
+ taskbook_archive = task_archive_dir / "taskbook.md"
2009
+ closure_archive = task_archive_dir / "closure-log.md"
2010
+
2011
+ if not taskbook.exists() or not taskbook.is_file():
2012
+ raise APError(f"docs.taskbook missing on disk: {_repo_rel(repo, taskbook)}")
2013
+ if not closure_log.exists() or not closure_log.is_file():
2014
+ raise APError(f"docs.closure_log missing on disk: {_repo_rel(repo, closure_log)}")
2015
+
2016
+ taskbook_preamble, taskbook_sections = _split_markdown_sections(
2017
+ taskbook.read_text(encoding="utf-8"),
2018
+ _TASKBOOK_ARCHIVE_HEADING_RE,
2019
+ )
2020
+ closure_preamble, closure_sections = _split_markdown_sections(
2021
+ closure_log.read_text(encoding="utf-8"),
2022
+ _CLOSURE_ARCHIVE_HEADING_RE,
2023
+ )
2024
+
2025
+ closed_taskbook_sections = [section for section in taskbook_sections if _is_closed_task_section(section)]
2026
+ active_taskbook_sections = [section for section in taskbook_sections if not _is_closed_task_section(section)]
2027
+ active_task_ids = {_normalize_task_id(section["id"]) for section in active_taskbook_sections}
2028
+ conflicting_closure_sections = [
2029
+ section for section in closure_sections if _normalize_task_id(section["id"]) in active_task_ids
2030
+ ]
2031
+ archivable_closure_sections = [
2032
+ section for section in closure_sections if _normalize_task_id(section["id"]) not in active_task_ids
2033
+ ]
2034
+ closure_ids = {_normalize_task_id(section["id"]) for section in archivable_closure_sections}
2035
+ closed_task_ids = {_normalize_task_id(section["id"]) for section in closed_taskbook_sections}
2036
+ archived_task_ids = closed_task_ids | closure_ids
2037
+ blocking = [
2038
+ f"closure record {section['id']} exists but the taskbook section is still active; update taskbook status to Done/Closed or repair the stale closure before archiving"
2039
+ for section in conflicting_closure_sections
2040
+ ]
2041
+
2042
+ design_files: list[Path] = []
2043
+ if design_dir.exists() and design_dir.is_dir():
2044
+ for path in sorted(design_dir.glob("T*.md")):
2045
+ match = _DESIGN_TASK_FILE_RE.match(path.name)
2046
+ if match and _normalize_task_id(match.group(1)) in archived_task_ids:
2047
+ design_files.append(path)
2048
+
2049
+ return {
2050
+ "enabled": True,
2051
+ "period": period,
2052
+ "paths": {
2053
+ "taskbook": _repo_rel(repo, taskbook),
2054
+ "closure_log": _repo_rel(repo, closure_log),
2055
+ "design_dir": _repo_rel(repo, design_dir),
2056
+ "taskbook_archive": _repo_rel(repo, taskbook_archive),
2057
+ "closure_archive": _repo_rel(repo, closure_archive),
2058
+ "design_archive_dir": _repo_rel(repo, design_archive_dir),
2059
+ "archive_index": _repo_rel(repo, paths["archive_index"]),
2060
+ },
2061
+ "counts": {
2062
+ "taskbook_sections": len(closed_taskbook_sections),
2063
+ "closure_sections": len(archivable_closure_sections),
2064
+ "blocked_closure_sections": len(conflicting_closure_sections),
2065
+ "design_files": len(design_files),
2066
+ "active_taskbook_sections_after": len(active_taskbook_sections),
2067
+ },
2068
+ "archived_task_ids": sorted(archived_task_ids),
2069
+ "active_task_conflicts": sorted(_normalize_task_id(section["id"]) for section in conflicting_closure_sections),
2070
+ "blocking": blocking,
2071
+ "taskbook_preamble": taskbook_preamble,
2072
+ "active_taskbook_sections": active_taskbook_sections,
2073
+ "closed_taskbook_sections": closed_taskbook_sections,
2074
+ "closure_preamble": closure_preamble,
2075
+ "closure_sections": archivable_closure_sections,
2076
+ "design_files": design_files,
2077
+ "archive_index": paths["archive_index"],
2078
+ "taskbook_archive": taskbook_archive,
2079
+ "closure_archive": closure_archive,
2080
+ "design_archive_dir": design_archive_dir,
2081
+ "taskbook_path": taskbook,
2082
+ "closure_log_path": closure_log,
2083
+ }
2084
+
2085
+
2086
+ def _public_docs_ledger_archive_result(repo: Path, result: dict, mode: str, wrote: bool, index_updated: bool = False) -> dict:
2087
+ return {
2088
+ "enabled": result.get("enabled", True),
2089
+ "mode": mode,
2090
+ "wrote": wrote,
2091
+ "archive_index_updated": index_updated,
2092
+ "period": result.get("period"),
2093
+ "paths": result.get("paths"),
2094
+ "counts": result.get("counts"),
2095
+ "archived_task_ids": result.get("archived_task_ids"),
2096
+ "active_task_conflicts": result.get("active_task_conflicts"),
2097
+ "blocking": result.get("blocking"),
2098
+ "design_files": [_repo_rel(repo, path) if isinstance(path, Path) else str(path) for path in result.get("design_files", [])],
2099
+ }
2100
+
2101
+
2102
+ def cmd_docs_ledger_archive(args: argparse.Namespace) -> None:
2103
+ repo = Path(args.repo).resolve()
2104
+ ensure_git_repo(repo)
2105
+ cfg = _load_cfg(repo)
2106
+ period = _resolve_archive_period(getattr(args, "period", ""))
2107
+ plan = _plan_docs_ledger_archive(repo, cfg, period)
2108
+ write = bool(getattr(args, "write", False))
2109
+ index_updated = False
2110
+
2111
+ if write and plan.get("blocking"):
2112
+ raise APError("docs-ledger-archive has blocking issue(s):\n- " + "\n- ".join(plan["blocking"]))
2113
+
2114
+ if write:
2115
+ design_archive_dir: Path = plan["design_archive_dir"]
2116
+ for src in plan["design_files"]:
2117
+ dst = design_archive_dir / src.name
2118
+ if dst.exists():
2119
+ raise APError(f"archive destination already exists: {_repo_rel(repo, dst)}")
2120
+
2121
+ taskbook_path: Path = plan["taskbook_path"]
2122
+ closure_log_path: Path = plan["closure_log_path"]
2123
+ taskbook_path.write_text(_render_markdown_doc(plan["taskbook_preamble"], plan["active_taskbook_sections"]), encoding="utf-8")
2124
+ closure_log_path.write_text(_render_markdown_doc(plan["closure_preamble"], []), encoding="utf-8")
2125
+ _append_archive_sections(plan["taskbook_archive"], "Taskbook Archive", period, plan["closed_taskbook_sections"])
2126
+ _append_archive_sections(plan["closure_archive"], "Closure Log Archive", period, plan["closure_sections"])
2127
+
2128
+ for src in plan["design_files"]:
2129
+ dst = design_archive_dir / src.name
2130
+ dst.parent.mkdir(parents=True, exist_ok=True)
2131
+ src.replace(dst)
2132
+ index_updated = _append_archive_index(repo, plan["archive_index"], period, _public_docs_ledger_archive_result(repo, plan, "write", True))
2133
+
2134
+ public_result = _public_docs_ledger_archive_result(repo, plan, "write" if write else "plan", write, index_updated=index_updated)
2135
+ if getattr(args, "json", False):
2136
+ print(json.dumps(public_result, ensure_ascii=False, indent=2))
2137
+ else:
2138
+ counts = public_result.get("counts") or {}
2139
+ print(
2140
+ "[docs-ledger-archive] "
2141
+ f"mode={public_result['mode']} period={period} "
2142
+ f"taskbook_sections={counts.get('taskbook_sections', 0)} "
2143
+ f"closure_sections={counts.get('closure_sections', 0)} "
2144
+ f"design_files={counts.get('design_files', 0)}"
2145
+ )
2146
+ if not write:
2147
+ print("[docs-ledger-archive] plan only; re-run with --write to apply")
2148
+ elif not any(int(counts.get(key) or 0) for key in ["taskbook_sections", "closure_sections", "design_files"]):
2149
+ print("[docs-ledger-archive] no closed ledger content to archive")
2150
+ else:
2151
+ print("[docs-ledger-archive] OK")
2152
+ _print_limited("[docs-ledger-archive] blocking", public_result.get("blocking") or [])
2153
+
2154
+ if plan.get("blocking"):
2155
+ raise APError(f"docs-ledger-archive blocked with {len(plan['blocking'])} issue(s)")
2156
+
2157
+ if write:
2158
+ _record_evidence(repo, cfg, "docs_ledger_archive", "pass", public_result)
2159
+
2160
+
2161
+ def cmd_docs_ledger_check(args: argparse.Namespace) -> None:
2162
+ repo = Path(args.repo).resolve()
2163
+ ensure_git_repo(repo)
2164
+ cfg = _load_cfg(repo)
2165
+ result = _docs_ledger_check_result(repo, cfg)
2166
+ if getattr(args, "json", False):
2167
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2168
+ else:
2169
+ if not result.get("enabled", True):
2170
+ print("[docs-ledger-check] disabled")
2171
+ else:
2172
+ counts = result.get("counts") or {}
2173
+ print(
2174
+ "[docs-ledger-check] "
2175
+ f"taskbook_lines={counts.get('taskbook_lines')} "
2176
+ f"closure_log_lines={counts.get('closure_log_lines')} "
2177
+ f"active_design_files={counts.get('active_design_files')} "
2178
+ f"task_archive_files={counts.get('task_archive_files')} "
2179
+ f"design_archive_files={counts.get('design_archive_files')}"
2180
+ )
2181
+ _print_limited("[docs-ledger-check] blocking", result.get("blocking") or [])
2182
+ _print_limited("[docs-ledger-check] warnings", result.get("warnings") or [])
2183
+
2184
+ if result.get("blocking"):
2185
+ _record_evidence(repo, cfg, "docs_ledger_check", "fail", result)
2186
+ raise APError(f"docs-ledger-check failed with {len(result['blocking'])} blocking issue(s)")
2187
+
2188
+ _record_evidence(repo, cfg, "docs_ledger_check", "pass", result)
2189
+ if not getattr(args, "json", False) and result.get("enabled", True):
2190
+ print("[docs-ledger-check] OK")
2191
+
2192
+
1176
2193
  def _structure_gate_enabled(cfg: dict) -> bool:
1177
2194
  structure_cfg = cfg.get("structure")
1178
2195
  if isinstance(structure_cfg, dict) and not _bool_config(structure_cfg.get("enabled"), default=True):
@@ -1209,6 +2226,8 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
1209
2226
  warn_function_lines = _int_config(structure_cfg.get("max_function_lines_warn"), 120)
1210
2227
  max_added_to_large = _int_config(structure_cfg.get("max_added_lines_to_large_file"), 80)
1211
2228
  block_large_growth = _bool_config(structure_cfg.get("block_new_responsibility_in_large_file"), True)
2229
+ layer_cfg = _layer_rules_config(structure_cfg)
2230
+ block_layer_violations = _bool_config(layer_cfg.get("block"), True)
1212
2231
 
1213
2232
  paths = _structure_paths_for_scope(repo, selected_scope, base_ref, structure_cfg)
1214
2233
  added_by_path = _added_lines_by_path(repo, base_ref=base_ref) if selected_scope != "full" else {}
@@ -1248,6 +2267,11 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
1248
2267
  )
1249
2268
 
1250
2269
  warnings.extend(_function_size_warnings(path, lines, warn_function_lines))
2270
+ boundary_issues = _structure_boundary_issues(path, lines, structure_cfg)
2271
+ if block_layer_violations:
2272
+ blocking.extend(boundary_issues)
2273
+ else:
2274
+ warnings.extend(boundary_issues)
1251
2275
 
1252
2276
  missing_docs: list[str] = []
1253
2277
  for key, rel_path in _configured_structure_docs(cfg).items():
@@ -1272,8 +2296,10 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
1272
2296
  _print_limited("[structure-check] warnings", warnings)
1273
2297
 
1274
2298
  if blocking:
2299
+ _record_evidence(repo, cfg, "structure_check", "fail", result)
1275
2300
  raise APError(f"structure-check failed with {len(blocking)} blocking issue(s)")
1276
2301
 
2302
+ _record_evidence(repo, cfg, "structure_check", "pass", result)
1277
2303
  if not getattr(args, "json", False):
1278
2304
  print(f"[structure-check] OK scope={selected_scope} inspected={inspected} warnings={len(warnings)}")
1279
2305
 
@@ -1295,6 +2321,374 @@ def _run_structure_check_for_gate(repo: Path, cfg: dict, selected_scope: str, ba
1295
2321
  return ["structure_check"]
1296
2322
 
1297
2323
 
2324
+ def _current_git_ref(repo: Path) -> str:
2325
+ value = run(["git", "rev-parse", "--short=12", "HEAD"], cwd=repo, check=False).stdout.strip()
2326
+ return value or "uncommitted"
2327
+
2328
+
2329
+ def _directory_hotspots(paths: list[str]) -> list[tuple[str, int]]:
2330
+ counts: dict[str, int] = {}
2331
+ for path in paths:
2332
+ parts = path.split("/")
2333
+ if len(parts) <= 1:
2334
+ key = "."
2335
+ elif parts[0] in {"frontend", "backend", "packages", "apps", "services"} and len(parts) >= 3:
2336
+ key = "/".join(parts[:3])
2337
+ else:
2338
+ key = "/".join(parts[:2])
2339
+ counts[key] = counts.get(key, 0) + 1
2340
+ return sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:20]
2341
+
2342
+
2343
+ def _scan_structure_inventory(repo: Path, cfg: dict) -> dict:
2344
+ structure_cfg = _structure_cfg(cfg)
2345
+ warn_file_lines = _int_config(structure_cfg.get("max_file_lines_warn"), 800)
2346
+ block_file_lines = _int_config(structure_cfg.get("max_file_lines_block"), 1500)
2347
+ paths = [path for path in _tracked_files(repo) if _is_structure_candidate(path, structure_cfg)]
2348
+ large_files: list[dict] = []
2349
+ for path in paths:
2350
+ lines = _read_text_lines(repo, path)
2351
+ if lines is None:
2352
+ continue
2353
+ line_count = len(lines)
2354
+ if line_count > warn_file_lines:
2355
+ large_files.append({
2356
+ "path": path,
2357
+ "lines": line_count,
2358
+ "priority": "P1" if block_file_lines > 0 and line_count > block_file_lines else "P2",
2359
+ })
2360
+ large_files.sort(key=lambda item: (-int(item["lines"]), str(item["path"])))
2361
+ return {
2362
+ "files_inspected": len(paths),
2363
+ "large_files": large_files,
2364
+ "hotspots": _directory_hotspots(paths),
2365
+ }
2366
+
2367
+
2368
+ def _render_health_baseline(repo: Path, cfg: dict, inventory: dict) -> str:
2369
+ date = _dt.date.today().isoformat()
2370
+ commit = _current_git_ref(repo)
2371
+ large_rows = "\n".join(
2372
+ f"| `{item['path']}` | {item['lines']} lines | Accepted for baseline; no large new additions without extraction | {date} |"
2373
+ for item in inventory["large_files"][:30]
2374
+ ) or "| (none) | | | |"
2375
+ debt_rows = "\n".join(
2376
+ f"| DEBT-{idx:03d} | {item['priority']} | `{item['path']}` | Large file baseline: {item['lines']} lines | Existing state at baseline | New large additions or touched feature work |"
2377
+ for idx, item in enumerate(inventory["large_files"][:30], start=1)
2378
+ ) or "| (none) | | | | | |"
2379
+ return f"""# Project Health Baseline
2380
+
2381
+ > Generated by `ap.py baseline init`. Update this file when accepted structure debt changes.
2382
+
2383
+ - Baseline date: {date}
2384
+ - Baseline commit: `{commit}`
2385
+ - Owner: TODO
2386
+ - Review scope: repo
2387
+ - Standard: `docs/architecture/structure-standard.md`
2388
+ - Files inspected: {inventory['files_inspected']}
2389
+
2390
+ ## 1. Current Accepted Structure
2391
+
2392
+ | Area | Current state | Accepted because | Review date |
2393
+ | --- | --- | --- | --- |
2394
+ {large_rows}
2395
+
2396
+ ## 2. Closed Optimization Scope
2397
+
2398
+ | ID | Closed date | Scope | Acceptance evidence |
2399
+ | --- | --- | --- | --- |
2400
+ | (none) | | | |
2401
+
2402
+ ## 3. Accepted Debt
2403
+
2404
+ | ID | Priority | Scope | Debt | Why accepted | Revisit trigger |
2405
+ | --- | --- | --- | --- | --- | --- |
2406
+ {debt_rows}
2407
+
2408
+ ## 4. Priority Rules
2409
+
2410
+ - P0: blocks build, release, deploy, core user flow, data integrity, security, or compliance.
2411
+ - P1: clear architectural violation, contract drift, missing test around high-risk change, or recently introduced maintainability risk.
2412
+ - P2: planned debt such as large files, hot directories, module extraction, stronger tests, or tool consolidation.
2413
+ - P3: optional naming, style, polish, or further abstraction.
2414
+
2415
+ ## 5. Completion Standard
2416
+
2417
+ An optimization task is complete when all are true:
2418
+
2419
+ - The scoped P0/P1/P2 items listed for this task are closed.
2420
+ - Local gate passed, including structure check when enabled.
2421
+ - No new unclassified P0/P1 was introduced.
2422
+ - Remaining P2/P3 items are either in `docs/reviews/optimization-backlog.md` or accepted debt above.
2423
+ - Review output says explicitly whether the project meets this baseline.
2424
+
2425
+ ## 6. New Review Instructions
2426
+
2427
+ - Read this baseline first.
2428
+ - Read `docs/reviews/optimization-backlog.md` second.
2429
+ - Report only new or worsened issues, unrecorded P0/P1, priority upgrades, or baseline drift.
2430
+ """
2431
+
2432
+
2433
+ def _render_optimization_backlog(inventory: dict) -> str:
2434
+ date = _dt.date.today().isoformat()
2435
+ rows = "\n".join(
2436
+ f"| OPT-{idx:03d} | {item['priority']} | accepted-debt | `{item['path']}` | Split or reduce {item['lines']}-line file | Existing large file baseline | No new responsibilities; extract during touched feature work | {date} |"
2437
+ for idx, item in enumerate(inventory["large_files"][:30], start=1)
2438
+ ) or "| (none) | | | | | | | |"
2439
+ hotspot_rows = "\n".join(
2440
+ f"| HOT-{idx:03d} | P3 | open | `{path}` | Review module cohesion ({count} tracked source files) | Hotspot directory | Split only when feature work naturally touches this area | {date} |"
2441
+ for idx, (path, count) in enumerate(inventory["hotspots"][:10], start=1)
2442
+ )
2443
+ if hotspot_rows:
2444
+ rows = rows + "\n" + hotspot_rows
2445
+ return f"""# Optimization Backlog
2446
+
2447
+ > Generated by `ap.py baseline init`. Accepted debt is not a current-task failure unless it worsens or is touched by new feature work.
2448
+
2449
+ ## Status Values
2450
+
2451
+ - `open`: confirmed and waiting for planning.
2452
+ - `accepted-debt`: accepted current debt with a revisit trigger.
2453
+ - `in-progress`: currently being handled.
2454
+ - `closed`: completed with evidence.
2455
+ - `superseded`: replaced by another item.
2456
+
2457
+ ## Backlog
2458
+
2459
+ | ID | Priority | Status | Scope | Item | Reason | Acceptance | Last reviewed |
2460
+ | --- | --- | --- | --- | --- | --- | --- | --- |
2461
+ {rows}
2462
+
2463
+ ## Review Rules
2464
+
2465
+ - P0/P1 cannot remain in backlog without immediate owner and plan.
2466
+ - P2 needs scope, reason, and acceptance.
2467
+ - P3 does not block completion.
2468
+ - New reviews update existing rows instead of duplicating equivalent findings.
2469
+ """
2470
+
2471
+
2472
+ def _update_accepted_debt_paths(repo: Path, cfg: dict, paths: list[str]) -> list[str]:
2473
+ if not paths:
2474
+ return []
2475
+ engineering = find_config(repo)
2476
+ current_cfg, body = _read_frontmatter_markdown(engineering)
2477
+ structure_cfg = current_cfg.setdefault("structure", {})
2478
+ existing = [str(item) for item in _as_list(structure_cfg.get("accepted_debt_paths")) if str(item).strip()]
2479
+ added = [path for path in paths if path not in existing]
2480
+ if added:
2481
+ structure_cfg["accepted_debt_paths"] = existing + added
2482
+ _write_frontmatter_markdown(engineering, current_cfg, body)
2483
+ return added
2484
+
2485
+
2486
+ def cmd_baseline_init(args: argparse.Namespace) -> None:
2487
+ repo = Path(args.repo).resolve()
2488
+ ensure_git_repo(repo)
2489
+ cfg = _load_cfg(repo)
2490
+ docs_cfg = cfg.get("docs") or {}
2491
+ inventory = _scan_structure_inventory(repo, cfg)
2492
+ health_path = Path(repo, _text(docs_cfg.get("health_baseline")) or "docs/reviews/project-health-baseline.md")
2493
+ backlog_path = Path(repo, _text(docs_cfg.get("optimization_backlog")) or "docs/reviews/optimization-backlog.md")
2494
+ write = bool(args.write)
2495
+ force = bool(args.force)
2496
+ update_config = bool(args.update_config)
2497
+
2498
+ actions: list[dict] = []
2499
+ for path, content, label in [
2500
+ (health_path, _render_health_baseline(repo, cfg, inventory), "health_baseline"),
2501
+ (backlog_path, _render_optimization_backlog(inventory), "optimization_backlog"),
2502
+ ]:
2503
+ if path.exists() and not force:
2504
+ actions.append({"path": _repo_rel(repo, path), "action": "exists", "kind": label})
2505
+ continue
2506
+ actions.append({"path": _repo_rel(repo, path), "action": "write" if write else "would-write", "kind": label})
2507
+ if write:
2508
+ path.parent.mkdir(parents=True, exist_ok=True)
2509
+ path.write_text(content, encoding="utf-8")
2510
+
2511
+ accepted_added: list[str] = []
2512
+ accepted_paths = [str(item["path"]) for item in inventory["large_files"] if item["priority"] in {"P1", "P2"}]
2513
+ if write and update_config:
2514
+ accepted_added = _update_accepted_debt_paths(repo, cfg, accepted_paths)
2515
+ if accepted_added:
2516
+ actions.append({
2517
+ "path": "docs/ENGINEERING.md",
2518
+ "action": "merge",
2519
+ "kind": "accepted_debt_paths",
2520
+ "detail": ", ".join(accepted_added),
2521
+ })
2522
+
2523
+ result = {
2524
+ "files_inspected": inventory["files_inspected"],
2525
+ "large_files": inventory["large_files"],
2526
+ "hotspots": inventory["hotspots"],
2527
+ "actions": actions,
2528
+ "updated_accepted_debt_paths": accepted_added,
2529
+ }
2530
+ if args.json:
2531
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2532
+ else:
2533
+ print(f"[baseline] files_inspected={inventory['files_inspected']}")
2534
+ print(f"[baseline] large_files={len(inventory['large_files'])}")
2535
+ for item in actions:
2536
+ detail = f" - {item.get('detail')}" if item.get("detail") else ""
2537
+ print(f"[baseline] {item['action']} {item['kind']}: {item['path']}{detail}")
2538
+ if not write:
2539
+ print("[baseline] dry-run only; re-run with --write to create baseline files")
2540
+
2541
+ if write:
2542
+ _record_evidence(
2543
+ repo,
2544
+ cfg,
2545
+ "baseline_init",
2546
+ "pass",
2547
+ {"write": write, "large_file_count": len(inventory["large_files"]), "files_inspected": inventory["files_inspected"]},
2548
+ )
2549
+
2550
+
2551
+ def _read_jsonl(path: Path) -> list[dict]:
2552
+ if not path.exists():
2553
+ return []
2554
+ records: list[dict] = []
2555
+ for line in path.read_text(encoding="utf-8").splitlines():
2556
+ if not line.strip():
2557
+ continue
2558
+ try:
2559
+ records.append(json.loads(line))
2560
+ except json.JSONDecodeError:
2561
+ continue
2562
+ return records
2563
+
2564
+
2565
+ def cmd_gate_profile(args: argparse.Namespace) -> None:
2566
+ repo = Path(args.repo).resolve()
2567
+ cfg = _load_cfg(repo)
2568
+ records = _read_jsonl(_gate_profile_path(repo, cfg))
2569
+ limit = int(args.limit or 20)
2570
+ by_name: dict[str, dict] = {}
2571
+ for record in records:
2572
+ name = _text(record.get("name")) or "(unknown)"
2573
+ bucket = by_name.setdefault(name, {"name": name, "runs": 0, "failures": 0, "total_duration_s": 0.0, "max_duration_s": 0.0})
2574
+ duration = float(record.get("duration_s") or 0)
2575
+ bucket["runs"] += 1
2576
+ bucket["total_duration_s"] += duration
2577
+ bucket["max_duration_s"] = max(float(bucket["max_duration_s"]), duration)
2578
+ if _text(record.get("status")) != "pass":
2579
+ bucket["failures"] += 1
2580
+ summary = []
2581
+ for bucket in by_name.values():
2582
+ runs = int(bucket["runs"])
2583
+ total = float(bucket["total_duration_s"])
2584
+ summary.append({
2585
+ "name": bucket["name"],
2586
+ "runs": runs,
2587
+ "failures": int(bucket["failures"]),
2588
+ "failure_rate": round(int(bucket["failures"]) / runs, 3) if runs else 0,
2589
+ "avg_duration_s": round(total / runs, 3) if runs else 0,
2590
+ "max_duration_s": round(float(bucket["max_duration_s"]), 3),
2591
+ })
2592
+ summary.sort(key=lambda item: (-float(item["avg_duration_s"]), str(item["name"])))
2593
+ result = {"profile_log": str(_gate_profile_path(repo, cfg)), "commands": summary[:limit], "record_count": len(records)}
2594
+ if args.json:
2595
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2596
+ else:
2597
+ print(f"[gate-profile] log={result['profile_log']}")
2598
+ print(f"[gate-profile] records={len(records)}")
2599
+ if not summary:
2600
+ print("[gate-profile] no profile records yet; run light-gate or configured commands first")
2601
+ for item in summary[:limit]:
2602
+ print(
2603
+ f"[gate-profile] {item['name']}: runs={item['runs']} "
2604
+ f"avg={item['avg_duration_s']}s max={item['max_duration_s']}s failures={item['failures']}"
2605
+ )
2606
+
2607
+
2608
+ def _classify_paths(paths: list[str]) -> dict:
2609
+ categories: set[str] = set()
2610
+ for path in paths:
2611
+ lower = path.lower()
2612
+ if _path_matches(path, _DEFAULT_FULL_PATH_PATTERNS):
2613
+ categories.add("release_or_tooling")
2614
+ if any(token in lower for token in ["migration", "schema", "database", "/db/", "/sql/"]) or lower.endswith(".sql"):
2615
+ categories.add("db")
2616
+ if any(token in lower for token in ["api", "controller", "handler", "route", "server"]):
2617
+ categories.add("api")
2618
+ if any(token in lower for token in ["auth", "permission", "role", "tenant", "security"]):
2619
+ categories.add("auth")
2620
+ if any(token in lower for token in ["page", "component", "view", "frontend", "miniapp", ".tsx", ".jsx", ".vue", ".scss", ".css"]):
2621
+ categories.add("ui")
2622
+ if any(token in lower for token in ["test", "spec", "__tests__"]):
2623
+ categories.add("test")
2624
+ if lower.startswith("docs/") or lower.endswith(".md"):
2625
+ categories.add("docs")
2626
+ if any(token in lower for token in ["domain", "service", "usecase", "repository", "infrastructure", "adapter", "shared", "utils"]):
2627
+ categories.add("structure")
2628
+ return {
2629
+ "categories": sorted(categories),
2630
+ "needs_dd": bool(categories & {"api", "db", "auth", "release_or_tooling"}) or len(paths) > 12,
2631
+ "needs_adr": bool(categories & {"structure", "release_or_tooling"}) and not categories <= {"docs"},
2632
+ "needs_browser": "ui" in categories,
2633
+ "needs_jenkins": bool(categories & {"release_or_tooling", "db", "auth"}),
2634
+ "needs_target": bool(categories & {"api", "db", "auth", "ui"}),
2635
+ }
2636
+
2637
+
2638
+ def cmd_classify(args: argparse.Namespace) -> None:
2639
+ repo = Path(args.repo).resolve()
2640
+ cfg = _load_cfg(repo)
2641
+ scope = str(args.scope or "").strip().lower()
2642
+ impact = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
2643
+ paths = list(impact.get("changed_files") or [])
2644
+ path_classification = _classify_paths(paths)
2645
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
2646
+ target_env_required = _verification_required(cfg, "target_env", default=True)
2647
+ needs_jenkins = bool(path_classification["needs_jenkins"] and jenkins_required)
2648
+ needs_target = bool(path_classification["needs_target"] and target_env_required)
2649
+ selected_scope = str(impact["selected_scope"])
2650
+ risk = "P3"
2651
+ if needs_jenkins or selected_scope == "full":
2652
+ risk = "P1"
2653
+ elif needs_target or path_classification["needs_dd"]:
2654
+ risk = "P2"
2655
+ elif not paths:
2656
+ risk = "P3"
2657
+ commands = [
2658
+ "python3 docs/tools/autopipeline/ap.py impact --scope auto",
2659
+ "python3 docs/tools/autopipeline/ap.py structure-check --scope auto",
2660
+ f"python3 docs/tools/autopipeline/ap.py light-gate --scope {selected_scope} --explain",
2661
+ ]
2662
+ if needs_jenkins:
2663
+ commands.append("python3 docs/tools/autopipeline/ap.py verify-jenkins")
2664
+ result = {
2665
+ "requested_scope": impact["requested_scope"],
2666
+ "selected_scope": selected_scope,
2667
+ "risk": risk,
2668
+ "changed_files": paths,
2669
+ "categories": path_classification["categories"],
2670
+ "needs_dd": path_classification["needs_dd"],
2671
+ "needs_adr": path_classification["needs_adr"],
2672
+ "needs_browser": path_classification["needs_browser"],
2673
+ "needs_jenkins": needs_jenkins,
2674
+ "needs_target": needs_target,
2675
+ "recommended_commands": commands,
2676
+ "reasons": impact.get("reasons") or [],
2677
+ "matched_rules": impact.get("matched_rules") or [],
2678
+ }
2679
+ if args.json:
2680
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2681
+ else:
2682
+ print(f"[classify] risk={risk}")
2683
+ print(f"[classify] selected_scope={selected_scope}")
2684
+ print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
2685
+ for key in ["needs_dd", "needs_adr", "needs_browser", "needs_jenkins", "needs_target"]:
2686
+ print(f"[classify] {key}={result[key]}")
2687
+ for command in commands:
2688
+ print(f"[classify] command: {command}")
2689
+ _record_evidence(repo, cfg, "classify", "pass", result)
2690
+
2691
+
1298
2692
  def cmd_run(args: argparse.Namespace) -> None:
1299
2693
  """
1300
2694
  Run any configured gate command by name.
@@ -1320,6 +2714,7 @@ def cmd_run(args: argparse.Namespace) -> None:
1320
2714
 
1321
2715
  def cmd_light_gate(args: argparse.Namespace) -> None:
1322
2716
  repo = Path(args.repo).resolve()
2717
+ light_gate_start = time.time()
1323
2718
  cmd_doctor(argparse.Namespace(repo=str(repo)))
1324
2719
  cfg = _load_cfg(repo)
1325
2720
  requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
@@ -1342,8 +2737,21 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
1342
2737
 
1343
2738
  _run_git_diff_check(repo, cfg)
1344
2739
  cmd_verify_api_docs(argparse.Namespace(repo=str(repo)))
1345
- cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
1346
- executed.extend(["diff_check", "verify_api_docs", "verify_jenkins"])
2740
+ executed.extend(["diff_check", "verify_api_docs"])
2741
+ if _verification_required(cfg, "jenkins", default=True):
2742
+ cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
2743
+ executed.append("verify_jenkins")
2744
+ else:
2745
+ executed.append("verify_jenkins_skipped")
2746
+ duration_s = time.time() - light_gate_start
2747
+ _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
2748
+ _record_evidence(
2749
+ repo,
2750
+ cfg,
2751
+ "light_gate",
2752
+ "pass",
2753
+ {"scope": selected_scope, "executed": executed, "duration_s": round(duration_s, 3), "changed_files": paths},
2754
+ )
1347
2755
  print(f"[light-gate] OK scope={selected_scope}: " + ", ".join(executed))
1348
2756
 
1349
2757
 
@@ -1353,6 +2761,7 @@ def cmd_impact(args: argparse.Namespace) -> None:
1353
2761
  scope = str(args.scope or "").strip().lower()
1354
2762
  summary = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
1355
2763
  _print_impact(summary, as_json=bool(args.json))
2764
+ _record_evidence(repo, cfg, "impact", "pass", summary)
1356
2765
 
1357
2766
 
1358
2767
  def cmd_runtime_up(args: argparse.Namespace) -> None:
@@ -1458,6 +2867,7 @@ def cmd_verify_target(args: argparse.Namespace) -> None:
1458
2867
  checks.append(f"frontend:{url}->{status}")
1459
2868
 
1460
2869
  summary = ", ".join(checks) if checks else "health-only"
2870
+ _record_evidence(repo, cfg, "verify_target", "pass", {"summary": summary, "checks": checks})
1461
2871
  print(f"[verify-target] OK: {summary}")
1462
2872
  return summary
1463
2873
 
@@ -1485,6 +2895,7 @@ def cmd_verify_jenkins(args: argparse.Namespace) -> None:
1485
2895
  missing = [name for name, value in required if not str(value or "").strip()]
1486
2896
  if missing:
1487
2897
  raise APError("Missing Jenkins config: " + ", ".join(missing))
2898
+ _record_evidence(repo, cfg, "verify_jenkins", "pass", {"jenkinsfile": str(jenkinsfile)})
1488
2899
  print(f"[verify-jenkins] OK: {jenkinsfile}")
1489
2900
 
1490
2901
 
@@ -1503,6 +2914,8 @@ def cmd_doctor(args: argparse.Namespace) -> None:
1503
2914
  validation_errors: List[str] = []
1504
2915
 
1505
2916
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
2917
+ target_env_required = _verification_required(cfg, "target_env", default=True)
2918
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
1506
2919
  if mode not in {"dev", "verify"}:
1507
2920
  missing.append("workflow.mode (must be dev or verify)")
1508
2921
  if not str(project_cfg.get("name") or "").strip():
@@ -1521,28 +2934,30 @@ def cmd_doctor(args: argparse.Namespace) -> None:
1521
2934
  "commands.gate_changed/gate_standard/gate_full, commands.light_gate, "
1522
2935
  "commands.quick_test, commands.test, or commands.build"
1523
2936
  )
1524
- _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
1525
- _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
1526
- _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
1527
- _require_secret_reference(missing, "target_env", target_cfg, "frontend_password")
1528
- _require_explicit_field(missing, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
1529
- _require_explicit_field(missing, "target_env.backend_username", target_cfg.get("backend_username"))
1530
- _require_secret_reference(missing, "target_env", target_cfg, "backend_password")
1531
- _require_explicit_field(missing, "target_env.backend_root_username", target_cfg.get("backend_root_username"))
1532
- _require_secret_reference(missing, "target_env", target_cfg, "backend_root_password")
1533
- _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
1534
- _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
1535
-
1536
- _require_explicit_field(missing, "jenkins.base_url", jenkins_cfg.get("base_url"))
1537
- _require_explicit_field(missing, "jenkins.ui_username", jenkins_cfg.get("ui_username"))
1538
- _require_secret_reference(missing, "jenkins", jenkins_cfg, "ui_password")
1539
- _require_explicit_field(missing, "jenkins.job_url", jenkins_cfg.get("job_url"))
1540
- _require_explicit_field(missing, "jenkins.trigger_branch", jenkins_cfg.get("trigger_branch"))
1541
- _require_explicit_field(missing, "jenkins.image_repository", jenkins_cfg.get("image_repository"))
1542
- _require_explicit_field(missing, "jenkins.image_tag_strategy", jenkins_cfg.get("image_tag_strategy"))
1543
- _require_explicit_field(missing, "jenkins.deploy_env", jenkins_cfg.get("deploy_env"))
1544
- _require_explicit_field(missing, "jenkins.api_user", jenkins_cfg.get("api_user"))
1545
- _require_secret_reference(missing, "jenkins", jenkins_cfg, "api_password")
2937
+ if target_env_required:
2938
+ _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
2939
+ _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
2940
+ _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
2941
+ _require_secret_reference(missing, "target_env", target_cfg, "frontend_password")
2942
+ _require_explicit_field(missing, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
2943
+ _require_explicit_field(missing, "target_env.backend_username", target_cfg.get("backend_username"))
2944
+ _require_secret_reference(missing, "target_env", target_cfg, "backend_password")
2945
+ _require_explicit_field(missing, "target_env.backend_root_username", target_cfg.get("backend_root_username"))
2946
+ _require_secret_reference(missing, "target_env", target_cfg, "backend_root_password")
2947
+ _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
2948
+ _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
2949
+
2950
+ if jenkins_required:
2951
+ _require_explicit_field(missing, "jenkins.base_url", jenkins_cfg.get("base_url"))
2952
+ _require_explicit_field(missing, "jenkins.ui_username", jenkins_cfg.get("ui_username"))
2953
+ _require_secret_reference(missing, "jenkins", jenkins_cfg, "ui_password")
2954
+ _require_explicit_field(missing, "jenkins.job_url", jenkins_cfg.get("job_url"))
2955
+ _require_explicit_field(missing, "jenkins.trigger_branch", jenkins_cfg.get("trigger_branch"))
2956
+ _require_explicit_field(missing, "jenkins.image_repository", jenkins_cfg.get("image_repository"))
2957
+ _require_explicit_field(missing, "jenkins.image_tag_strategy", jenkins_cfg.get("image_tag_strategy"))
2958
+ _require_explicit_field(missing, "jenkins.deploy_env", jenkins_cfg.get("deploy_env"))
2959
+ _require_explicit_field(missing, "jenkins.api_user", jenkins_cfg.get("api_user"))
2960
+ _require_secret_reference(missing, "jenkins", jenkins_cfg, "api_password")
1546
2961
 
1547
2962
  repo_docs = {
1548
2963
  "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
@@ -1565,18 +2980,35 @@ def cmd_doctor(args: argparse.Namespace) -> None:
1565
2980
  if runtime_enabled and not str(runtime_cfg.get("docker_compose_file") or "").strip():
1566
2981
  validation_errors.append("runtime config is partially enabled but runtime.docker_compose_file is missing")
1567
2982
 
2983
+ ledger_result = _docs_ledger_check_result(repo, cfg)
2984
+ ledger_status = "skipped" if not ledger_result.get("enabled", True) else ("fail" if ledger_result.get("blocking") else "pass")
2985
+ _record_evidence(repo, cfg, "docs_ledger_check", ledger_status, ledger_result)
2986
+ for issue in ledger_result.get("blocking") or []:
2987
+ validation_errors.append(f"docs-ledger: {issue}")
2988
+ for warning in ledger_result.get("warnings") or []:
2989
+ print(f"[doctor] WARN docs-ledger: {warning}")
2990
+
1568
2991
  try:
1569
2992
  timeout_s = int(jenkins_cfg.get("deploy_timeout_sec") or 0)
1570
- if timeout_s <= 0:
2993
+ if (jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec"))) and timeout_s <= 0:
1571
2994
  validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
1572
2995
  except Exception:
1573
- validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
2996
+ if jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec")):
2997
+ validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
1574
2998
 
1575
2999
  missing.extend(validation_errors)
1576
3000
 
1577
3001
  if missing:
3002
+ _record_evidence(repo, cfg, "doctor", "fail", {"issues": missing})
1578
3003
  raise APError("Doctor found blocking config issues:\n- " + "\n- ".join(missing))
1579
3004
 
3005
+ _record_evidence(
3006
+ repo,
3007
+ cfg,
3008
+ "doctor",
3009
+ "pass",
3010
+ {"mode": mode, "target_env_required": target_env_required, "jenkins_required": jenkins_required},
3011
+ )
1580
3012
  print("[doctor] OK")
1581
3013
 
1582
3014
 
@@ -1643,6 +3075,13 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
1643
3075
  args.allow_no_deploy,
1644
3076
  )
1645
3077
  build_url = str(payload.get("url") or "").strip()
3078
+ _record_evidence(
3079
+ repo,
3080
+ cfg,
3081
+ "verify_jenkins_build",
3082
+ "pass",
3083
+ {"job": job_label, "build": payload.get("number"), "result": result, "url": build_url},
3084
+ )
1646
3085
  print(
1647
3086
  "[verify-jenkins-build] OK: "
1648
3087
  f"job={job_label} "
@@ -1683,6 +3122,13 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
1683
3122
  args.allow_no_deploy,
1684
3123
  )
1685
3124
  build_url = str(matched.get("url") or "").strip()
3125
+ _record_evidence(
3126
+ repo,
3127
+ cfg,
3128
+ "verify_jenkins_build",
3129
+ "pass",
3130
+ {"commit": git_short_sha, "job": job_label, "build": matched.get("number"), "result": result, "url": build_url},
3131
+ )
1686
3132
  print(
1687
3133
  "[verify-jenkins-build] OK: "
1688
3134
  f"commit={git_short_sha} "
@@ -1705,6 +3151,7 @@ def cmd_verify_api_docs(args: argparse.Namespace) -> None:
1705
3151
  missing = [p for p in [api_doc, change_log] if not p.exists()]
1706
3152
  if missing:
1707
3153
  raise APError("Missing API docs: " + ", ".join([str(p) for p in missing]))
3154
+ _record_evidence(repo, cfg, "verify_api_docs", "pass", {"api_doc": str(api_doc), "api_change_log": str(change_log)})
1708
3155
  print(f"[verify-api-docs] OK: {api_doc} + {change_log}")
1709
3156
 
1710
3157
 
@@ -1735,7 +3182,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
1735
3182
  f"## {task_id} — {title} — {timestamp}",
1736
3183
  f"- Task: {task_id}",
1737
3184
  f"- Commit: {commit_value}",
1738
- f"- Jenkins Build: {jenkins_build}",
3185
+ f"- CI/Jenkins Build: {jenkins_build}",
1739
3186
  f"- Target Env: {target_env}",
1740
3187
  f"- Verification: {verification_text}",
1741
3188
  f"- Structure Check: {structure_check}",
@@ -1745,7 +3192,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
1745
3192
  if str(args.initial_commit or "").strip():
1746
3193
  lines.append(f"- Initial Commit: {args.initial_commit.strip()}")
1747
3194
  if str(args.jenkins_failure or "").strip():
1748
- lines.append(f"- Jenkins Failure: {args.jenkins_failure.strip()}")
3195
+ lines.append(f"- CI/Jenkins Failure: {args.jenkins_failure.strip()}")
1749
3196
  if str(args.fix_commit or "").strip():
1750
3197
  lines.append(f"- Fix Commit: {args.fix_commit.strip()}")
1751
3198
 
@@ -1754,6 +3201,13 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
1754
3201
  f.write("\n")
1755
3202
  f.write("\n".join(lines))
1756
3203
  f.write("\n")
3204
+ _record_evidence(
3205
+ repo,
3206
+ cfg,
3207
+ "record_closure",
3208
+ "pass",
3209
+ {"task_id": task_id, "result": args.result, "commit": commit_value, "structure_check": structure_check},
3210
+ )
1757
3211
  print(f"[record-closure] OK: {closure_log}")
1758
3212
 
1759
3213
 
@@ -1795,6 +3249,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1795
3249
  cfg = _load_cfg(repo)
1796
3250
  mode = _workflow_mode(cfg, args)
1797
3251
  target_cfg = (cfg.get("target_env") or {})
3252
+ target_env_required = _verification_required(cfg, "target_env", default=True)
3253
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
1798
3254
 
1799
3255
  msg = args.msg
1800
3256
  structure_check_status = "skipped"
@@ -1815,21 +3271,22 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1815
3271
  if mode == "dev":
1816
3272
  dev_verification = args.verification or [
1817
3273
  "light-gate only",
1818
- "Jenkins triggered by push; build not verified in dev mode",
3274
+ "configured CI/Jenkins not verified in dev mode",
1819
3275
  "target environment not verified in dev mode",
1820
3276
  ]
1821
3277
  _record_commit_push_closure(
1822
3278
  repo,
1823
3279
  args,
1824
3280
  commit="generated by this commit-push run",
1825
- jenkins=args.jenkins_build or "triggered by push, not verified in dev mode",
3281
+ jenkins=args.jenkins_build or "not verified in dev mode",
1826
3282
  target_env=args.target_env or "not verified in dev mode",
1827
3283
  verification=dev_verification,
1828
3284
  result=args.result or "DEV-CLOSED",
1829
- follow_up=args.follow_up or "Run verify mode when Jenkins and target-environment evidence is required.",
3285
+ follow_up=args.follow_up or "Run verify mode when configured CI/Jenkins and target-environment evidence is required.",
1830
3286
  structure_check=args.structure_check or structure_check_status,
1831
3287
  )
1832
3288
 
3289
+ _cleanup_generated_noise(repo)
1833
3290
  run(["git", "add", "-A"], cwd=repo)
1834
3291
  diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
1835
3292
  if not diff:
@@ -1839,47 +3296,63 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1839
3296
  run(["git", "push"], cwd=repo)
1840
3297
 
1841
3298
  if mode == "verify":
1842
- jenkins_build = cmd_verify_jenkins_build(
1843
- argparse.Namespace(
1844
- repo=str(repo),
1845
- git_ref="HEAD",
1846
- job_name=args.job_name,
1847
- job_url=args.job_url,
1848
- multibranch_root_job=args.multibranch_root_job,
1849
- branch_name=args.branch_name,
1850
- build_number=args.build_number,
1851
- max_builds=args.max_builds,
1852
- timeout_sec=args.timeout_sec,
1853
- poll_sec=args.poll_sec,
1854
- allow_no_deploy=args.allow_no_deploy,
3299
+ if jenkins_required:
3300
+ jenkins_build = cmd_verify_jenkins_build(
3301
+ argparse.Namespace(
3302
+ repo=str(repo),
3303
+ git_ref="HEAD",
3304
+ job_name=args.job_name,
3305
+ job_url=args.job_url,
3306
+ multibranch_root_job=args.multibranch_root_job,
3307
+ branch_name=args.branch_name,
3308
+ build_number=args.build_number,
3309
+ max_builds=args.max_builds,
3310
+ timeout_sec=args.timeout_sec,
3311
+ poll_sec=args.poll_sec,
3312
+ allow_no_deploy=args.allow_no_deploy,
3313
+ )
1855
3314
  )
1856
- )
1857
- target_summary = cmd_verify_target(
1858
- argparse.Namespace(
1859
- repo=str(repo),
1860
- backend_path=args.backend_path,
1861
- frontend_path=args.frontend_path,
1862
- backend_basic_auth=args.backend_basic_auth,
1863
- frontend_basic_auth=args.frontend_basic_auth,
3315
+ else:
3316
+ jenkins_build = "skipped by verification.jenkins_required=false"
3317
+
3318
+ if target_env_required:
3319
+ target_summary = cmd_verify_target(
3320
+ argparse.Namespace(
3321
+ repo=str(repo),
3322
+ backend_path=args.backend_path,
3323
+ frontend_path=args.frontend_path,
3324
+ backend_basic_auth=args.backend_basic_auth,
3325
+ frontend_basic_auth=args.frontend_basic_auth,
3326
+ )
1864
3327
  )
1865
- )
3328
+ else:
3329
+ target_summary = "skipped by verification.target_env_required=false"
1866
3330
  if args.require_matrix:
1867
3331
  cmd_check_matrix(argparse.Namespace(repo=str(repo)))
1868
- verification = args.verification or [
1869
- f"Jenkins build verified: {jenkins_build or 'verified by git-ref HEAD'}",
1870
- f"Target verification: {target_summary}",
1871
- ]
3332
+ verification = args.verification
3333
+ if not verification:
3334
+ verification = []
3335
+ if jenkins_required:
3336
+ verification.append(f"CI/Jenkins build verified: {jenkins_build or 'verified by git-ref HEAD'}")
3337
+ else:
3338
+ verification.append("CI/Jenkins verification skipped by verification.jenkins_required=false")
3339
+ if target_env_required:
3340
+ verification.append(f"Target verification: {target_summary}")
3341
+ else:
3342
+ verification.append("Target verification skipped by verification.target_env_required=false")
1872
3343
  _record_commit_push_closure(
1873
3344
  repo,
1874
3345
  args,
1875
3346
  commit="HEAD",
1876
3347
  jenkins=args.jenkins_build or jenkins_build or "verified by git-ref HEAD",
1877
- target_env=args.target_env or str(target_cfg.get("name") or "").strip(),
3348
+ target_env=args.target_env
3349
+ or (str(target_cfg.get("name") or "").strip() if target_env_required else "skipped by verification.target_env_required=false"),
1878
3350
  verification=verification,
1879
3351
  result=args.result or "PASS",
1880
3352
  follow_up=args.follow_up or "none",
1881
3353
  structure_check=args.structure_check or structure_check_status,
1882
3354
  )
3355
+ _cleanup_generated_noise(repo)
1883
3356
  run(["git", "add", "-A"], cwd=repo)
1884
3357
  closure_diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
1885
3358
  if closure_diff:
@@ -1907,8 +3380,24 @@ def main(argv: Optional[List[str]] = None) -> int:
1907
3380
 
1908
3381
  s = sp.add_parser("install")
1909
3382
  s.add_argument("--bridges", action="store_true")
3383
+ s.add_argument("--force", action="store_true")
1910
3384
  s.set_defaults(func=cmd_install)
1911
3385
 
3386
+ s = sp.add_parser("upgrade")
3387
+ s.add_argument("--dry-run", action="store_true")
3388
+ s.add_argument("--write", action="store_true")
3389
+ s.add_argument("--json", action="store_true")
3390
+ s.set_defaults(func=cmd_upgrade)
3391
+
3392
+ s = sp.add_parser("baseline")
3393
+ baseline_sp = s.add_subparsers(dest="baseline_cmd", required=True)
3394
+ b = baseline_sp.add_parser("init")
3395
+ b.add_argument("--write", action="store_true")
3396
+ b.add_argument("--force", action="store_true")
3397
+ b.add_argument("--update-config", action="store_true")
3398
+ b.add_argument("--json", action="store_true")
3399
+ b.set_defaults(func=cmd_baseline_init)
3400
+
1912
3401
  s = sp.add_parser("gen-summary")
1913
3402
  s.add_argument("task_id")
1914
3403
  s.add_argument("--title")
@@ -1928,12 +3417,35 @@ def main(argv: Optional[List[str]] = None) -> int:
1928
3417
  s.add_argument("--json", action="store_true")
1929
3418
  s.set_defaults(func=cmd_impact)
1930
3419
 
3420
+ s = sp.add_parser("classify")
3421
+ s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
3422
+ s.add_argument("--base")
3423
+ s.add_argument("--json", action="store_true")
3424
+ s.set_defaults(func=cmd_classify)
3425
+
1931
3426
  s = sp.add_parser("structure-check")
1932
3427
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
1933
3428
  s.add_argument("--base")
1934
3429
  s.add_argument("--json", action="store_true")
1935
3430
  s.set_defaults(func=cmd_structure_check)
1936
3431
 
3432
+ s = sp.add_parser("gate-profile")
3433
+ s.add_argument("--limit", type=int, default=20)
3434
+ s.add_argument("--json", action="store_true")
3435
+ s.set_defaults(func=cmd_gate_profile)
3436
+
3437
+ s = sp.add_parser("docs-ledger-check")
3438
+ s.add_argument("--json", action="store_true")
3439
+ s.set_defaults(func=cmd_docs_ledger_check)
3440
+
3441
+ s = sp.add_parser("docs-ledger-archive")
3442
+ mode = s.add_mutually_exclusive_group(required=True)
3443
+ mode.add_argument("--plan", action="store_true")
3444
+ mode.add_argument("--write", action="store_true")
3445
+ s.add_argument("--period", help="Archive period in YYYY-MM; defaults to current month")
3446
+ s.add_argument("--json", action="store_true")
3447
+ s.set_defaults(func=cmd_docs_ledger_archive)
3448
+
1937
3449
  s = sp.add_parser("light-gate")
1938
3450
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
1939
3451
  s.add_argument("--base")
@@ -1983,14 +3495,14 @@ def main(argv: Optional[List[str]] = None) -> int:
1983
3495
  s.add_argument("task_id")
1984
3496
  s.add_argument("--title")
1985
3497
  s.add_argument("--commit", default="HEAD")
1986
- s.add_argument("--jenkins")
3498
+ s.add_argument("--ci-build", "--jenkins", dest="jenkins", metavar="CI_BUILD")
1987
3499
  s.add_argument("--target-env")
1988
3500
  s.add_argument("--verification", action="append")
1989
3501
  s.add_argument("--structure-check")
1990
3502
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"], required=True)
1991
3503
  s.add_argument("--follow-up")
1992
3504
  s.add_argument("--initial-commit")
1993
- s.add_argument("--jenkins-failure")
3505
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
1994
3506
  s.add_argument("--fix-commit")
1995
3507
  s.set_defaults(func=cmd_record_closure)
1996
3508
 
@@ -2017,14 +3529,14 @@ def main(argv: Optional[List[str]] = None) -> int:
2017
3529
  s.add_argument("--frontend-path", action="append")
2018
3530
  s.add_argument("--backend-basic-auth", action="store_true")
2019
3531
  s.add_argument("--frontend-basic-auth", action="store_true")
2020
- s.add_argument("--jenkins-build")
3532
+ s.add_argument("--ci-build", "--jenkins-build", dest="jenkins_build", metavar="CI_BUILD")
2021
3533
  s.add_argument("--target-env")
2022
3534
  s.add_argument("--verification", action="append")
2023
3535
  s.add_argument("--structure-check")
2024
3536
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"])
2025
3537
  s.add_argument("--follow-up")
2026
3538
  s.add_argument("--initial-commit")
2027
- s.add_argument("--jenkins-failure")
3539
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
2028
3540
  s.add_argument("--fix-commit")
2029
3541
  s.set_defaults(func=cmd_commit_push)
2030
3542