@elvis1513/auto-coding-skill 2.1.0 → 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.
@@ -30,6 +30,14 @@ from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_confi
30
30
 
31
31
  _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
32
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
+ ]
33
41
 
34
42
 
35
43
  def _skill_root() -> Path:
@@ -466,24 +474,62 @@ def _assert_jenkins_build_success(build: dict, identifier: str, allow_no_deploy:
466
474
  return result, description
467
475
 
468
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
+
469
493
  def cmd_install(args: argparse.Namespace) -> None:
470
494
  repo = Path(args.repo).resolve()
471
495
  templates = _skill_root() / "data" / "templates"
472
496
 
473
- copy_tree(templates / "docs", repo / "docs")
474
- 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
+ ]
475
501
 
476
502
  if args.bridges:
477
- copy_tree(templates / "bridges", repo)
503
+ planned_copies.append((templates / "bridges" / "AGENTS.md", repo / "AGENTS.md"))
478
504
 
479
505
  tools_dir = repo / "docs" / "tools" / "autopipeline"
480
- tools_dir.mkdir(parents=True, exist_ok=True)
481
- copy_tree(Path(__file__).resolve(), tools_dir / "ap.py")
482
- copy_tree(Path(__file__).resolve().parent / "core.py", tools_dir / "core.py")
483
- 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)
484
527
 
485
528
  print(f"[install] OK: scaffold installed into {repo}")
486
- 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
+ )
487
533
 
488
534
 
489
535
  def cmd_upgrade(args: argparse.Namespace) -> None:
@@ -539,9 +585,14 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
539
585
  for dst in _iter_files(project_skill):
540
586
  rel = dst.relative_to(project_skill)
541
587
  if not (source_root / rel).exists():
542
- add_action("skill", dst, "extra", "present only in project copy")
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")
543
594
  else:
544
- add_action("skill", project_skill, "missing", "run autocoding init --ai codex --mode project --force")
595
+ add_action("skill", project_skill, "missing", "run autocoding init --mode project --force")
545
596
 
546
597
  docs_template = templates / "docs"
547
598
  for src in _iter_files(docs_template):
@@ -668,11 +719,11 @@ def cmd_gen_summary(args: argparse.Namespace) -> None:
668
719
  - 变更记录位置:`{api_change_log}`
669
720
 
670
721
  ## 4. 质量证据
671
- - 本地轻量校验: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
672
723
  - 结构检查:structure-check — TODO
673
724
  - 结构化证据:docs/tasks/evidence.jsonl — TODO
674
725
  - 门禁画像:.local/auto-coding-skill/gate-profile.jsonl — TODO
675
- - Jenkins Build:TODO
726
+ - CI/Jenkins Build:TODO
676
727
  - 目标环境验证:TODO
677
728
  - 闭环记录:TODO
678
729
  - 回归矩阵(如有):`{regression_matrix}`
@@ -758,13 +809,28 @@ def _load_cfg(repo: Path) -> dict:
758
809
 
759
810
 
760
811
  def _candidate_skill_roots(repo: Path) -> list[Path]:
761
- return [
762
- _skill_root(),
763
- repo / ".agents" / "skills" / "auto-coding-skill",
764
- Path.home() / ".agents" / "skills" / "auto-coding-skill",
765
- repo / ".claude" / "skills" / "auto-coding-skill",
766
- Path.home() / ".claude" / "skills" / "auto-coding-skill",
767
- ]
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
768
834
 
769
835
 
770
836
  def _find_skill_asset_root(repo: Path) -> Path:
@@ -772,7 +838,7 @@ def _find_skill_asset_root(repo: Path) -> Path:
772
838
  if (root / "data" / "templates").exists() and (root / "scripts" / "ap.py").exists():
773
839
  return root
774
840
  raise APError(
775
- "Cannot find auto-coding-skill asset root. Run `autocoding init --ai codex --mode global --force` "
841
+ "Cannot find auto-coding-skill asset root. Run `autocoding init --mode global --force` "
776
842
  "or execute this command from an installed skill copy."
777
843
  )
778
844
 
@@ -924,7 +990,6 @@ _GATE_SCOPES = {"auto", "changed", "standard", "full"}
924
990
  _DOC_PATH_PATTERNS = ["*.md", "docs/**"]
925
991
  _DEFAULT_FULL_PATH_PATTERNS = [
926
992
  ".agents/**",
927
- ".claude/**",
928
993
  ".github/workflows/**",
929
994
  "Jenkinsfile",
930
995
  "Jenkinsfile.*",
@@ -1015,11 +1080,17 @@ def _path_matches(path: str, patterns: list) -> bool:
1015
1080
  return False
1016
1081
 
1017
1082
 
1083
+ def _is_generated_noise_path(path: str) -> bool:
1084
+ return _path_matches(path, _GENERATED_NOISE_PATTERNS)
1085
+
1086
+
1018
1087
  def _unique_paths(paths: list[str]) -> list[str]:
1019
1088
  seen = set()
1020
1089
  out = []
1021
1090
  for path in paths:
1022
1091
  normalized = path.replace("\\", "/").strip()
1092
+ if _is_generated_noise_path(normalized):
1093
+ continue
1023
1094
  if not normalized or normalized in seen:
1024
1095
  continue
1025
1096
  seen.add(normalized)
@@ -1053,6 +1124,25 @@ def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
1053
1124
  return _unique_paths(paths)
1054
1125
 
1055
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
+
1056
1146
  def _docs_only(paths: list[str]) -> bool:
1057
1147
  return bool(paths) and all(_path_matches(path, _DOC_PATH_PATTERNS) for path in paths)
1058
1148
 
@@ -1222,7 +1312,6 @@ def _run_git_diff_check(repo: Path, cfg: dict) -> None:
1222
1312
  _DEFAULT_STRUCTURE_ALLOW_PATTERNS = [
1223
1313
  ".git/**",
1224
1314
  ".agents/skills/**",
1225
- ".claude/skills/**",
1226
1315
  ".next/**",
1227
1316
  ".nuxt/**",
1228
1317
  ".svelte-kit/**",
@@ -1385,6 +1474,11 @@ def _optimization_cfg(cfg: dict) -> dict:
1385
1474
  return value if isinstance(value, dict) else {}
1386
1475
 
1387
1476
 
1477
+ def _verification_cfg(cfg: dict) -> dict:
1478
+ value = cfg.get("verification") or {}
1479
+ return value if isinstance(value, dict) else {}
1480
+
1481
+
1388
1482
  def _bool_config(value: object, default: bool = False) -> bool:
1389
1483
  if value is None:
1390
1484
  return default
@@ -1407,6 +1501,17 @@ def _int_config(value: object, default: int) -> int:
1407
1501
  return default
1408
1502
 
1409
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
+
1410
1515
  def _tracked_files(repo: Path) -> list[str]:
1411
1516
  return _unique_paths(_git_lines(repo, ["git", "ls-files"]))
1412
1517
 
@@ -1486,7 +1591,7 @@ def _added_lines_by_path(repo: Path, base_ref: str = "") -> dict[str, int]:
1486
1591
  if path:
1487
1592
  added[path] = added.get(path, 0) + count
1488
1593
 
1489
- 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"])):
1490
1595
  lines = _read_text_lines(repo, path)
1491
1596
  if lines is not None:
1492
1597
  added[path] = added.get(path, 0) + len(lines)
@@ -1597,6 +1702,494 @@ def _configured_structure_docs(cfg: dict) -> dict[str, str]:
1597
1702
  }
1598
1703
 
1599
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
+
1600
2193
  def _structure_gate_enabled(cfg: dict) -> bool:
1601
2194
  structure_cfg = cfg.get("structure")
1602
2195
  if isinstance(structure_cfg, dict) and not _bool_config(structure_cfg.get("enabled"), default=True):
@@ -2049,11 +2642,15 @@ def cmd_classify(args: argparse.Namespace) -> None:
2049
2642
  impact = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
2050
2643
  paths = list(impact.get("changed_files") or [])
2051
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)
2052
2649
  selected_scope = str(impact["selected_scope"])
2053
2650
  risk = "P3"
2054
- if path_classification["needs_jenkins"] or selected_scope == "full":
2651
+ if needs_jenkins or selected_scope == "full":
2055
2652
  risk = "P1"
2056
- elif path_classification["needs_target"] or path_classification["needs_dd"]:
2653
+ elif needs_target or path_classification["needs_dd"]:
2057
2654
  risk = "P2"
2058
2655
  elif not paths:
2059
2656
  risk = "P3"
@@ -2062,7 +2659,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
2062
2659
  "python3 docs/tools/autopipeline/ap.py structure-check --scope auto",
2063
2660
  f"python3 docs/tools/autopipeline/ap.py light-gate --scope {selected_scope} --explain",
2064
2661
  ]
2065
- if path_classification["needs_jenkins"]:
2662
+ if needs_jenkins:
2066
2663
  commands.append("python3 docs/tools/autopipeline/ap.py verify-jenkins")
2067
2664
  result = {
2068
2665
  "requested_scope": impact["requested_scope"],
@@ -2073,8 +2670,8 @@ def cmd_classify(args: argparse.Namespace) -> None:
2073
2670
  "needs_dd": path_classification["needs_dd"],
2074
2671
  "needs_adr": path_classification["needs_adr"],
2075
2672
  "needs_browser": path_classification["needs_browser"],
2076
- "needs_jenkins": path_classification["needs_jenkins"],
2077
- "needs_target": path_classification["needs_target"],
2673
+ "needs_jenkins": needs_jenkins,
2674
+ "needs_target": needs_target,
2078
2675
  "recommended_commands": commands,
2079
2676
  "reasons": impact.get("reasons") or [],
2080
2677
  "matched_rules": impact.get("matched_rules") or [],
@@ -2140,8 +2737,12 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
2140
2737
 
2141
2738
  _run_git_diff_check(repo, cfg)
2142
2739
  cmd_verify_api_docs(argparse.Namespace(repo=str(repo)))
2143
- cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
2144
- 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")
2145
2746
  duration_s = time.time() - light_gate_start
2146
2747
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
2147
2748
  _record_evidence(
@@ -2313,6 +2914,8 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2313
2914
  validation_errors: List[str] = []
2314
2915
 
2315
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)
2316
2919
  if mode not in {"dev", "verify"}:
2317
2920
  missing.append("workflow.mode (must be dev or verify)")
2318
2921
  if not str(project_cfg.get("name") or "").strip():
@@ -2331,28 +2934,30 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2331
2934
  "commands.gate_changed/gate_standard/gate_full, commands.light_gate, "
2332
2935
  "commands.quick_test, commands.test, or commands.build"
2333
2936
  )
2334
- _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
2335
- _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
2336
- _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
2337
- _require_secret_reference(missing, "target_env", target_cfg, "frontend_password")
2338
- _require_explicit_field(missing, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
2339
- _require_explicit_field(missing, "target_env.backend_username", target_cfg.get("backend_username"))
2340
- _require_secret_reference(missing, "target_env", target_cfg, "backend_password")
2341
- _require_explicit_field(missing, "target_env.backend_root_username", target_cfg.get("backend_root_username"))
2342
- _require_secret_reference(missing, "target_env", target_cfg, "backend_root_password")
2343
- _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
2344
- _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
2345
-
2346
- _require_explicit_field(missing, "jenkins.base_url", jenkins_cfg.get("base_url"))
2347
- _require_explicit_field(missing, "jenkins.ui_username", jenkins_cfg.get("ui_username"))
2348
- _require_secret_reference(missing, "jenkins", jenkins_cfg, "ui_password")
2349
- _require_explicit_field(missing, "jenkins.job_url", jenkins_cfg.get("job_url"))
2350
- _require_explicit_field(missing, "jenkins.trigger_branch", jenkins_cfg.get("trigger_branch"))
2351
- _require_explicit_field(missing, "jenkins.image_repository", jenkins_cfg.get("image_repository"))
2352
- _require_explicit_field(missing, "jenkins.image_tag_strategy", jenkins_cfg.get("image_tag_strategy"))
2353
- _require_explicit_field(missing, "jenkins.deploy_env", jenkins_cfg.get("deploy_env"))
2354
- _require_explicit_field(missing, "jenkins.api_user", jenkins_cfg.get("api_user"))
2355
- _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")
2356
2961
 
2357
2962
  repo_docs = {
2358
2963
  "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
@@ -2375,12 +2980,21 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2375
2980
  if runtime_enabled and not str(runtime_cfg.get("docker_compose_file") or "").strip():
2376
2981
  validation_errors.append("runtime config is partially enabled but runtime.docker_compose_file is missing")
2377
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
+
2378
2991
  try:
2379
2992
  timeout_s = int(jenkins_cfg.get("deploy_timeout_sec") or 0)
2380
- if timeout_s <= 0:
2993
+ if (jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec"))) and timeout_s <= 0:
2381
2994
  validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
2382
2995
  except Exception:
2383
- 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")
2384
2998
 
2385
2999
  missing.extend(validation_errors)
2386
3000
 
@@ -2388,7 +3002,13 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2388
3002
  _record_evidence(repo, cfg, "doctor", "fail", {"issues": missing})
2389
3003
  raise APError("Doctor found blocking config issues:\n- " + "\n- ".join(missing))
2390
3004
 
2391
- _record_evidence(repo, cfg, "doctor", "pass", {"mode": mode})
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
+ )
2392
3012
  print("[doctor] OK")
2393
3013
 
2394
3014
 
@@ -2562,7 +3182,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
2562
3182
  f"## {task_id} — {title} — {timestamp}",
2563
3183
  f"- Task: {task_id}",
2564
3184
  f"- Commit: {commit_value}",
2565
- f"- Jenkins Build: {jenkins_build}",
3185
+ f"- CI/Jenkins Build: {jenkins_build}",
2566
3186
  f"- Target Env: {target_env}",
2567
3187
  f"- Verification: {verification_text}",
2568
3188
  f"- Structure Check: {structure_check}",
@@ -2572,7 +3192,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
2572
3192
  if str(args.initial_commit or "").strip():
2573
3193
  lines.append(f"- Initial Commit: {args.initial_commit.strip()}")
2574
3194
  if str(args.jenkins_failure or "").strip():
2575
- lines.append(f"- Jenkins Failure: {args.jenkins_failure.strip()}")
3195
+ lines.append(f"- CI/Jenkins Failure: {args.jenkins_failure.strip()}")
2576
3196
  if str(args.fix_commit or "").strip():
2577
3197
  lines.append(f"- Fix Commit: {args.fix_commit.strip()}")
2578
3198
 
@@ -2629,6 +3249,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2629
3249
  cfg = _load_cfg(repo)
2630
3250
  mode = _workflow_mode(cfg, args)
2631
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)
2632
3254
 
2633
3255
  msg = args.msg
2634
3256
  structure_check_status = "skipped"
@@ -2649,21 +3271,22 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2649
3271
  if mode == "dev":
2650
3272
  dev_verification = args.verification or [
2651
3273
  "light-gate only",
2652
- "Jenkins triggered by push; build not verified in dev mode",
3274
+ "configured CI/Jenkins not verified in dev mode",
2653
3275
  "target environment not verified in dev mode",
2654
3276
  ]
2655
3277
  _record_commit_push_closure(
2656
3278
  repo,
2657
3279
  args,
2658
3280
  commit="generated by this commit-push run",
2659
- jenkins=args.jenkins_build or "triggered by push, not verified in dev mode",
3281
+ jenkins=args.jenkins_build or "not verified in dev mode",
2660
3282
  target_env=args.target_env or "not verified in dev mode",
2661
3283
  verification=dev_verification,
2662
3284
  result=args.result or "DEV-CLOSED",
2663
- 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.",
2664
3286
  structure_check=args.structure_check or structure_check_status,
2665
3287
  )
2666
3288
 
3289
+ _cleanup_generated_noise(repo)
2667
3290
  run(["git", "add", "-A"], cwd=repo)
2668
3291
  diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
2669
3292
  if not diff:
@@ -2673,47 +3296,63 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2673
3296
  run(["git", "push"], cwd=repo)
2674
3297
 
2675
3298
  if mode == "verify":
2676
- jenkins_build = cmd_verify_jenkins_build(
2677
- argparse.Namespace(
2678
- repo=str(repo),
2679
- git_ref="HEAD",
2680
- job_name=args.job_name,
2681
- job_url=args.job_url,
2682
- multibranch_root_job=args.multibranch_root_job,
2683
- branch_name=args.branch_name,
2684
- build_number=args.build_number,
2685
- max_builds=args.max_builds,
2686
- timeout_sec=args.timeout_sec,
2687
- poll_sec=args.poll_sec,
2688
- 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
+ )
2689
3314
  )
2690
- )
2691
- target_summary = cmd_verify_target(
2692
- argparse.Namespace(
2693
- repo=str(repo),
2694
- backend_path=args.backend_path,
2695
- frontend_path=args.frontend_path,
2696
- backend_basic_auth=args.backend_basic_auth,
2697
- 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
+ )
2698
3327
  )
2699
- )
3328
+ else:
3329
+ target_summary = "skipped by verification.target_env_required=false"
2700
3330
  if args.require_matrix:
2701
3331
  cmd_check_matrix(argparse.Namespace(repo=str(repo)))
2702
- verification = args.verification or [
2703
- f"Jenkins build verified: {jenkins_build or 'verified by git-ref HEAD'}",
2704
- f"Target verification: {target_summary}",
2705
- ]
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")
2706
3343
  _record_commit_push_closure(
2707
3344
  repo,
2708
3345
  args,
2709
3346
  commit="HEAD",
2710
3347
  jenkins=args.jenkins_build or jenkins_build or "verified by git-ref HEAD",
2711
- 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"),
2712
3350
  verification=verification,
2713
3351
  result=args.result or "PASS",
2714
3352
  follow_up=args.follow_up or "none",
2715
3353
  structure_check=args.structure_check or structure_check_status,
2716
3354
  )
3355
+ _cleanup_generated_noise(repo)
2717
3356
  run(["git", "add", "-A"], cwd=repo)
2718
3357
  closure_diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
2719
3358
  if closure_diff:
@@ -2741,6 +3380,7 @@ def main(argv: Optional[List[str]] = None) -> int:
2741
3380
 
2742
3381
  s = sp.add_parser("install")
2743
3382
  s.add_argument("--bridges", action="store_true")
3383
+ s.add_argument("--force", action="store_true")
2744
3384
  s.set_defaults(func=cmd_install)
2745
3385
 
2746
3386
  s = sp.add_parser("upgrade")
@@ -2794,6 +3434,18 @@ def main(argv: Optional[List[str]] = None) -> int:
2794
3434
  s.add_argument("--json", action="store_true")
2795
3435
  s.set_defaults(func=cmd_gate_profile)
2796
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
+
2797
3449
  s = sp.add_parser("light-gate")
2798
3450
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
2799
3451
  s.add_argument("--base")
@@ -2843,14 +3495,14 @@ def main(argv: Optional[List[str]] = None) -> int:
2843
3495
  s.add_argument("task_id")
2844
3496
  s.add_argument("--title")
2845
3497
  s.add_argument("--commit", default="HEAD")
2846
- s.add_argument("--jenkins")
3498
+ s.add_argument("--ci-build", "--jenkins", dest="jenkins", metavar="CI_BUILD")
2847
3499
  s.add_argument("--target-env")
2848
3500
  s.add_argument("--verification", action="append")
2849
3501
  s.add_argument("--structure-check")
2850
3502
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"], required=True)
2851
3503
  s.add_argument("--follow-up")
2852
3504
  s.add_argument("--initial-commit")
2853
- s.add_argument("--jenkins-failure")
3505
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
2854
3506
  s.add_argument("--fix-commit")
2855
3507
  s.set_defaults(func=cmd_record_closure)
2856
3508
 
@@ -2877,14 +3529,14 @@ def main(argv: Optional[List[str]] = None) -> int:
2877
3529
  s.add_argument("--frontend-path", action="append")
2878
3530
  s.add_argument("--backend-basic-auth", action="store_true")
2879
3531
  s.add_argument("--frontend-basic-auth", action="store_true")
2880
- s.add_argument("--jenkins-build")
3532
+ s.add_argument("--ci-build", "--jenkins-build", dest="jenkins_build", metavar="CI_BUILD")
2881
3533
  s.add_argument("--target-env")
2882
3534
  s.add_argument("--verification", action="append")
2883
3535
  s.add_argument("--structure-check")
2884
3536
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"])
2885
3537
  s.add_argument("--follow-up")
2886
3538
  s.add_argument("--initial-commit")
2887
- s.add_argument("--jenkins-failure")
3539
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
2888
3540
  s.add_argument("--fix-commit")
2889
3541
  s.set_defaults(func=cmd_commit_push)
2890
3542