@elvis1513/auto-coding-skill 2.1.0 → 2.1.2

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,515 @@ 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
+ "archived",
1884
+ "completed",
1885
+ "deployed",
1886
+ "done",
1887
+ "closed",
1888
+ "dev-closed",
1889
+ "external",
1890
+ "pass",
1891
+ "passed",
1892
+ "fail",
1893
+ "failed",
1894
+ "partial",
1895
+ "superseded",
1896
+ "完成",
1897
+ "已完成",
1898
+ "关闭",
1899
+ "已关闭",
1900
+ "已部署",
1901
+ "已归档",
1902
+ "外部依赖",
1903
+ "已转外部依赖",
1904
+ "被替代",
1905
+ "已替代",
1906
+ "废弃",
1907
+ "已废弃",
1908
+ }
1909
+
1910
+
1911
+ def _normalize_task_id(task_id: str) -> str:
1912
+ return str(task_id or "").strip().upper()
1913
+
1914
+
1915
+ def _resolve_archive_period(period: str) -> str:
1916
+ value = str(period or "").strip()
1917
+ if not value:
1918
+ return _dt.date.today().strftime("%Y-%m")
1919
+ if not re.fullmatch(r"\d{4}-\d{2}", value):
1920
+ raise APError("--period must use YYYY-MM")
1921
+ month = int(value.split("-", 1)[1])
1922
+ if month < 1 or month > 12:
1923
+ raise APError("--period month must be between 01 and 12")
1924
+ return value
1925
+
1926
+
1927
+ def _split_markdown_sections(text: str, heading_re: re.Pattern[str]) -> tuple[list[str], list[dict]]:
1928
+ preamble: list[str] = []
1929
+ sections: list[dict] = []
1930
+ current: Optional[dict] = None
1931
+
1932
+ for line in text.splitlines():
1933
+ match = heading_re.match(line.strip())
1934
+ if match:
1935
+ if current is not None:
1936
+ sections.append(current)
1937
+ current = {"id": match.group(1), "lines": [line]}
1938
+ continue
1939
+ if current is None:
1940
+ preamble.append(line)
1941
+ else:
1942
+ current["lines"].append(line)
1943
+
1944
+ if current is not None:
1945
+ sections.append(current)
1946
+ return preamble, sections
1947
+
1948
+
1949
+ def _section_text(section: dict) -> str:
1950
+ lines = section.get("lines") or []
1951
+ return "\n".join(str(line) for line in lines).rstrip() + "\n"
1952
+
1953
+
1954
+ def _render_markdown_doc(preamble: list[str], sections: list[dict]) -> str:
1955
+ parts: list[str] = []
1956
+ preamble_text = "\n".join(preamble).rstrip()
1957
+ if preamble_text:
1958
+ parts.append(preamble_text)
1959
+ for section in sections:
1960
+ text = _section_text(section).rstrip()
1961
+ if text:
1962
+ parts.append(text)
1963
+ return "\n\n".join(parts).rstrip() + "\n"
1964
+
1965
+
1966
+ def _is_closed_task_section(section: dict) -> bool:
1967
+ text = _section_text(section)
1968
+ if _TASK_RESULT_RE.search(text):
1969
+ return True
1970
+ status_match = _TASK_STATUS_RE.search(text)
1971
+ if not status_match:
1972
+ return False
1973
+ status = status_match.group(1).strip()
1974
+ normalized = re.sub(r"\s+", " ", status).strip().lower()
1975
+ first_token = re.split(r"[\s/,,;;。]+", normalized, maxsplit=1)[0].strip()
1976
+ if first_token in _CLOSED_TASK_STATUSES or normalized in _CLOSED_TASK_STATUSES:
1977
+ return True
1978
+ return normalized.startswith((
1979
+ "local pass",
1980
+ "local verified",
1981
+ "本地通过",
1982
+ "本地验证通过",
1983
+ ))
1984
+
1985
+
1986
+ def _append_archive_sections(path: Path, title: str, period: str, sections: list[dict]) -> bool:
1987
+ if not sections:
1988
+ return False
1989
+ path.parent.mkdir(parents=True, exist_ok=True)
1990
+ existing = path.read_text(encoding="utf-8") if path.exists() else ""
1991
+ header = f"# {title} — {period}\n\n"
1992
+ body = "\n\n".join(_section_text(section).rstrip() for section in sections).rstrip() + "\n"
1993
+ if existing.strip():
1994
+ path.write_text(existing.rstrip() + "\n\n" + body, encoding="utf-8")
1995
+ else:
1996
+ path.write_text(header + body, encoding="utf-8")
1997
+ return True
1998
+
1999
+
2000
+ def _append_archive_index(repo: Path, archive_index: Path, period: str, result: dict) -> bool:
2001
+ counts = result.get("counts") or {}
2002
+ if not any(int(counts.get(key) or 0) for key in ["taskbook_sections", "closure_sections", "design_files"]):
2003
+ return False
2004
+
2005
+ paths = result.get("paths") or {}
2006
+ entry = (
2007
+ f"## {period}\n"
2008
+ f"- Generated: {_now_iso()}\n"
2009
+ f"- Taskbook archive: `{paths.get('taskbook_archive', '')}` ({counts.get('taskbook_sections', 0)} sections)\n"
2010
+ f"- Closure archive: `{paths.get('closure_archive', '')}` ({counts.get('closure_sections', 0)} sections)\n"
2011
+ f"- Design archive: `{paths.get('design_archive_dir', '')}` ({counts.get('design_files', 0)} files)\n"
2012
+ )
2013
+ archive_index.parent.mkdir(parents=True, exist_ok=True)
2014
+ existing = archive_index.read_text(encoding="utf-8") if archive_index.exists() else ""
2015
+ if existing.strip():
2016
+ archive_index.write_text(existing.rstrip() + "\n\n" + entry, encoding="utf-8")
2017
+ else:
2018
+ archive_index.write_text("# Docs Archive Index\n\n" + entry, encoding="utf-8")
2019
+ return True
2020
+
2021
+
2022
+ def _plan_docs_ledger_archive(repo: Path, cfg: dict, period: str) -> dict:
2023
+ _docs_cfg_value, paths = _docs_ledger_paths(repo, cfg)
2024
+ taskbook = paths["taskbook"]
2025
+ closure_log = paths["closure_log"]
2026
+ design_dir = paths["design_dir"]
2027
+ task_archive_dir = paths["task_archive_dir"] / period
2028
+ design_archive_dir = paths["design_archive_dir"] / period
2029
+ taskbook_archive = task_archive_dir / "taskbook.md"
2030
+ closure_archive = task_archive_dir / "closure-log.md"
2031
+
2032
+ if not taskbook.exists() or not taskbook.is_file():
2033
+ raise APError(f"docs.taskbook missing on disk: {_repo_rel(repo, taskbook)}")
2034
+ if not closure_log.exists() or not closure_log.is_file():
2035
+ raise APError(f"docs.closure_log missing on disk: {_repo_rel(repo, closure_log)}")
2036
+
2037
+ taskbook_preamble, taskbook_sections = _split_markdown_sections(
2038
+ taskbook.read_text(encoding="utf-8"),
2039
+ _TASKBOOK_ARCHIVE_HEADING_RE,
2040
+ )
2041
+ closure_preamble, closure_sections = _split_markdown_sections(
2042
+ closure_log.read_text(encoding="utf-8"),
2043
+ _CLOSURE_ARCHIVE_HEADING_RE,
2044
+ )
2045
+
2046
+ closed_taskbook_sections = [section for section in taskbook_sections if _is_closed_task_section(section)]
2047
+ active_taskbook_sections = [section for section in taskbook_sections if not _is_closed_task_section(section)]
2048
+ active_task_ids = {_normalize_task_id(section["id"]) for section in active_taskbook_sections}
2049
+ conflicting_closure_sections = [
2050
+ section for section in closure_sections if _normalize_task_id(section["id"]) in active_task_ids
2051
+ ]
2052
+ archivable_closure_sections = [
2053
+ section for section in closure_sections if _normalize_task_id(section["id"]) not in active_task_ids
2054
+ ]
2055
+ closure_ids = {_normalize_task_id(section["id"]) for section in archivable_closure_sections}
2056
+ closed_task_ids = {_normalize_task_id(section["id"]) for section in closed_taskbook_sections}
2057
+ archived_task_ids = closed_task_ids | closure_ids
2058
+ blocking = [
2059
+ 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"
2060
+ for section in conflicting_closure_sections
2061
+ ]
2062
+
2063
+ design_files: list[Path] = []
2064
+ if design_dir.exists() and design_dir.is_dir():
2065
+ for path in sorted(design_dir.glob("T*.md")):
2066
+ match = _DESIGN_TASK_FILE_RE.match(path.name)
2067
+ if match and _normalize_task_id(match.group(1)) in archived_task_ids:
2068
+ design_files.append(path)
2069
+
2070
+ return {
2071
+ "enabled": True,
2072
+ "period": period,
2073
+ "paths": {
2074
+ "taskbook": _repo_rel(repo, taskbook),
2075
+ "closure_log": _repo_rel(repo, closure_log),
2076
+ "design_dir": _repo_rel(repo, design_dir),
2077
+ "taskbook_archive": _repo_rel(repo, taskbook_archive),
2078
+ "closure_archive": _repo_rel(repo, closure_archive),
2079
+ "design_archive_dir": _repo_rel(repo, design_archive_dir),
2080
+ "archive_index": _repo_rel(repo, paths["archive_index"]),
2081
+ },
2082
+ "counts": {
2083
+ "taskbook_sections": len(closed_taskbook_sections),
2084
+ "closure_sections": len(archivable_closure_sections),
2085
+ "blocked_closure_sections": len(conflicting_closure_sections),
2086
+ "design_files": len(design_files),
2087
+ "active_taskbook_sections_after": len(active_taskbook_sections),
2088
+ },
2089
+ "archived_task_ids": sorted(archived_task_ids),
2090
+ "active_task_conflicts": sorted(_normalize_task_id(section["id"]) for section in conflicting_closure_sections),
2091
+ "blocking": blocking,
2092
+ "taskbook_preamble": taskbook_preamble,
2093
+ "active_taskbook_sections": active_taskbook_sections,
2094
+ "closed_taskbook_sections": closed_taskbook_sections,
2095
+ "closure_preamble": closure_preamble,
2096
+ "closure_sections": archivable_closure_sections,
2097
+ "design_files": design_files,
2098
+ "archive_index": paths["archive_index"],
2099
+ "taskbook_archive": taskbook_archive,
2100
+ "closure_archive": closure_archive,
2101
+ "design_archive_dir": design_archive_dir,
2102
+ "taskbook_path": taskbook,
2103
+ "closure_log_path": closure_log,
2104
+ }
2105
+
2106
+
2107
+ def _public_docs_ledger_archive_result(repo: Path, result: dict, mode: str, wrote: bool, index_updated: bool = False) -> dict:
2108
+ return {
2109
+ "enabled": result.get("enabled", True),
2110
+ "mode": mode,
2111
+ "wrote": wrote,
2112
+ "archive_index_updated": index_updated,
2113
+ "period": result.get("period"),
2114
+ "paths": result.get("paths"),
2115
+ "counts": result.get("counts"),
2116
+ "archived_task_ids": result.get("archived_task_ids"),
2117
+ "active_task_conflicts": result.get("active_task_conflicts"),
2118
+ "blocking": result.get("blocking"),
2119
+ "design_files": [_repo_rel(repo, path) if isinstance(path, Path) else str(path) for path in result.get("design_files", [])],
2120
+ }
2121
+
2122
+
2123
+ def cmd_docs_ledger_archive(args: argparse.Namespace) -> None:
2124
+ repo = Path(args.repo).resolve()
2125
+ ensure_git_repo(repo)
2126
+ cfg = _load_cfg(repo)
2127
+ period = _resolve_archive_period(getattr(args, "period", ""))
2128
+ plan = _plan_docs_ledger_archive(repo, cfg, period)
2129
+ write = bool(getattr(args, "write", False))
2130
+ index_updated = False
2131
+
2132
+ if write and plan.get("blocking"):
2133
+ raise APError("docs-ledger-archive has blocking issue(s):\n- " + "\n- ".join(plan["blocking"]))
2134
+
2135
+ if write:
2136
+ design_archive_dir: Path = plan["design_archive_dir"]
2137
+ for src in plan["design_files"]:
2138
+ dst = design_archive_dir / src.name
2139
+ if dst.exists():
2140
+ raise APError(f"archive destination already exists: {_repo_rel(repo, dst)}")
2141
+
2142
+ taskbook_path: Path = plan["taskbook_path"]
2143
+ closure_log_path: Path = plan["closure_log_path"]
2144
+ taskbook_path.write_text(_render_markdown_doc(plan["taskbook_preamble"], plan["active_taskbook_sections"]), encoding="utf-8")
2145
+ closure_log_path.write_text(_render_markdown_doc(plan["closure_preamble"], []), encoding="utf-8")
2146
+ _append_archive_sections(plan["taskbook_archive"], "Taskbook Archive", period, plan["closed_taskbook_sections"])
2147
+ _append_archive_sections(plan["closure_archive"], "Closure Log Archive", period, plan["closure_sections"])
2148
+
2149
+ for src in plan["design_files"]:
2150
+ dst = design_archive_dir / src.name
2151
+ dst.parent.mkdir(parents=True, exist_ok=True)
2152
+ src.replace(dst)
2153
+ index_updated = _append_archive_index(repo, plan["archive_index"], period, _public_docs_ledger_archive_result(repo, plan, "write", True))
2154
+
2155
+ public_result = _public_docs_ledger_archive_result(repo, plan, "write" if write else "plan", write, index_updated=index_updated)
2156
+ if getattr(args, "json", False):
2157
+ print(json.dumps(public_result, ensure_ascii=False, indent=2))
2158
+ else:
2159
+ counts = public_result.get("counts") or {}
2160
+ print(
2161
+ "[docs-ledger-archive] "
2162
+ f"mode={public_result['mode']} period={period} "
2163
+ f"taskbook_sections={counts.get('taskbook_sections', 0)} "
2164
+ f"closure_sections={counts.get('closure_sections', 0)} "
2165
+ f"design_files={counts.get('design_files', 0)}"
2166
+ )
2167
+ if not write:
2168
+ print("[docs-ledger-archive] plan only; re-run with --write to apply")
2169
+ elif not any(int(counts.get(key) or 0) for key in ["taskbook_sections", "closure_sections", "design_files"]):
2170
+ print("[docs-ledger-archive] no closed ledger content to archive")
2171
+ else:
2172
+ print("[docs-ledger-archive] OK")
2173
+ _print_limited("[docs-ledger-archive] blocking", public_result.get("blocking") or [])
2174
+
2175
+ if plan.get("blocking"):
2176
+ raise APError(f"docs-ledger-archive blocked with {len(plan['blocking'])} issue(s)")
2177
+
2178
+ if write:
2179
+ _record_evidence(repo, cfg, "docs_ledger_archive", "pass", public_result)
2180
+
2181
+
2182
+ def cmd_docs_ledger_check(args: argparse.Namespace) -> None:
2183
+ repo = Path(args.repo).resolve()
2184
+ ensure_git_repo(repo)
2185
+ cfg = _load_cfg(repo)
2186
+ result = _docs_ledger_check_result(repo, cfg)
2187
+ if getattr(args, "json", False):
2188
+ print(json.dumps(result, ensure_ascii=False, indent=2))
2189
+ else:
2190
+ if not result.get("enabled", True):
2191
+ print("[docs-ledger-check] disabled")
2192
+ else:
2193
+ counts = result.get("counts") or {}
2194
+ print(
2195
+ "[docs-ledger-check] "
2196
+ f"taskbook_lines={counts.get('taskbook_lines')} "
2197
+ f"closure_log_lines={counts.get('closure_log_lines')} "
2198
+ f"active_design_files={counts.get('active_design_files')} "
2199
+ f"task_archive_files={counts.get('task_archive_files')} "
2200
+ f"design_archive_files={counts.get('design_archive_files')}"
2201
+ )
2202
+ _print_limited("[docs-ledger-check] blocking", result.get("blocking") or [])
2203
+ _print_limited("[docs-ledger-check] warnings", result.get("warnings") or [])
2204
+
2205
+ if result.get("blocking"):
2206
+ _record_evidence(repo, cfg, "docs_ledger_check", "fail", result)
2207
+ raise APError(f"docs-ledger-check failed with {len(result['blocking'])} blocking issue(s)")
2208
+
2209
+ _record_evidence(repo, cfg, "docs_ledger_check", "pass", result)
2210
+ if not getattr(args, "json", False) and result.get("enabled", True):
2211
+ print("[docs-ledger-check] OK")
2212
+
2213
+
1600
2214
  def _structure_gate_enabled(cfg: dict) -> bool:
1601
2215
  structure_cfg = cfg.get("structure")
1602
2216
  if isinstance(structure_cfg, dict) and not _bool_config(structure_cfg.get("enabled"), default=True):
@@ -2049,11 +2663,15 @@ def cmd_classify(args: argparse.Namespace) -> None:
2049
2663
  impact = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
2050
2664
  paths = list(impact.get("changed_files") or [])
2051
2665
  path_classification = _classify_paths(paths)
2666
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
2667
+ target_env_required = _verification_required(cfg, "target_env", default=True)
2668
+ needs_jenkins = bool(path_classification["needs_jenkins"] and jenkins_required)
2669
+ needs_target = bool(path_classification["needs_target"] and target_env_required)
2052
2670
  selected_scope = str(impact["selected_scope"])
2053
2671
  risk = "P3"
2054
- if path_classification["needs_jenkins"] or selected_scope == "full":
2672
+ if needs_jenkins or selected_scope == "full":
2055
2673
  risk = "P1"
2056
- elif path_classification["needs_target"] or path_classification["needs_dd"]:
2674
+ elif needs_target or path_classification["needs_dd"]:
2057
2675
  risk = "P2"
2058
2676
  elif not paths:
2059
2677
  risk = "P3"
@@ -2062,7 +2680,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
2062
2680
  "python3 docs/tools/autopipeline/ap.py structure-check --scope auto",
2063
2681
  f"python3 docs/tools/autopipeline/ap.py light-gate --scope {selected_scope} --explain",
2064
2682
  ]
2065
- if path_classification["needs_jenkins"]:
2683
+ if needs_jenkins:
2066
2684
  commands.append("python3 docs/tools/autopipeline/ap.py verify-jenkins")
2067
2685
  result = {
2068
2686
  "requested_scope": impact["requested_scope"],
@@ -2073,8 +2691,8 @@ def cmd_classify(args: argparse.Namespace) -> None:
2073
2691
  "needs_dd": path_classification["needs_dd"],
2074
2692
  "needs_adr": path_classification["needs_adr"],
2075
2693
  "needs_browser": path_classification["needs_browser"],
2076
- "needs_jenkins": path_classification["needs_jenkins"],
2077
- "needs_target": path_classification["needs_target"],
2694
+ "needs_jenkins": needs_jenkins,
2695
+ "needs_target": needs_target,
2078
2696
  "recommended_commands": commands,
2079
2697
  "reasons": impact.get("reasons") or [],
2080
2698
  "matched_rules": impact.get("matched_rules") or [],
@@ -2140,8 +2758,12 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
2140
2758
 
2141
2759
  _run_git_diff_check(repo, cfg)
2142
2760
  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"])
2761
+ executed.extend(["diff_check", "verify_api_docs"])
2762
+ if _verification_required(cfg, "jenkins", default=True):
2763
+ cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
2764
+ executed.append("verify_jenkins")
2765
+ else:
2766
+ executed.append("verify_jenkins_skipped")
2145
2767
  duration_s = time.time() - light_gate_start
2146
2768
  _record_gate_profile(repo, cfg, "light_gate", "pass", duration_s, scope=selected_scope, detail=", ".join(executed))
2147
2769
  _record_evidence(
@@ -2313,6 +2935,8 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2313
2935
  validation_errors: List[str] = []
2314
2936
 
2315
2937
  mode = str(workflow_cfg.get("mode") or "dev").strip().lower()
2938
+ target_env_required = _verification_required(cfg, "target_env", default=True)
2939
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
2316
2940
  if mode not in {"dev", "verify"}:
2317
2941
  missing.append("workflow.mode (must be dev or verify)")
2318
2942
  if not str(project_cfg.get("name") or "").strip():
@@ -2331,28 +2955,30 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2331
2955
  "commands.gate_changed/gate_standard/gate_full, commands.light_gate, "
2332
2956
  "commands.quick_test, commands.test, or commands.build"
2333
2957
  )
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")
2958
+ if target_env_required:
2959
+ _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
2960
+ _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
2961
+ _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
2962
+ _require_secret_reference(missing, "target_env", target_cfg, "frontend_password")
2963
+ _require_explicit_field(missing, "target_env.backend_base_url", target_cfg.get("backend_base_url"))
2964
+ _require_explicit_field(missing, "target_env.backend_username", target_cfg.get("backend_username"))
2965
+ _require_secret_reference(missing, "target_env", target_cfg, "backend_password")
2966
+ _require_explicit_field(missing, "target_env.backend_root_username", target_cfg.get("backend_root_username"))
2967
+ _require_secret_reference(missing, "target_env", target_cfg, "backend_root_password")
2968
+ _require_explicit_field(missing, "target_env.health_base_url", target_cfg.get("health_base_url"))
2969
+ _require_explicit_field(missing, "target_env.health_path", target_cfg.get("health_path"))
2970
+
2971
+ if jenkins_required:
2972
+ _require_explicit_field(missing, "jenkins.base_url", jenkins_cfg.get("base_url"))
2973
+ _require_explicit_field(missing, "jenkins.ui_username", jenkins_cfg.get("ui_username"))
2974
+ _require_secret_reference(missing, "jenkins", jenkins_cfg, "ui_password")
2975
+ _require_explicit_field(missing, "jenkins.job_url", jenkins_cfg.get("job_url"))
2976
+ _require_explicit_field(missing, "jenkins.trigger_branch", jenkins_cfg.get("trigger_branch"))
2977
+ _require_explicit_field(missing, "jenkins.image_repository", jenkins_cfg.get("image_repository"))
2978
+ _require_explicit_field(missing, "jenkins.image_tag_strategy", jenkins_cfg.get("image_tag_strategy"))
2979
+ _require_explicit_field(missing, "jenkins.deploy_env", jenkins_cfg.get("deploy_env"))
2980
+ _require_explicit_field(missing, "jenkins.api_user", jenkins_cfg.get("api_user"))
2981
+ _require_secret_reference(missing, "jenkins", jenkins_cfg, "api_password")
2356
2982
 
2357
2983
  repo_docs = {
2358
2984
  "docs.taskbook": Path(repo, str(docs_cfg.get("taskbook", "docs/tasks/taskbook.md"))),
@@ -2375,12 +3001,21 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2375
3001
  if runtime_enabled and not str(runtime_cfg.get("docker_compose_file") or "").strip():
2376
3002
  validation_errors.append("runtime config is partially enabled but runtime.docker_compose_file is missing")
2377
3003
 
3004
+ ledger_result = _docs_ledger_check_result(repo, cfg)
3005
+ ledger_status = "skipped" if not ledger_result.get("enabled", True) else ("fail" if ledger_result.get("blocking") else "pass")
3006
+ _record_evidence(repo, cfg, "docs_ledger_check", ledger_status, ledger_result)
3007
+ for issue in ledger_result.get("blocking") or []:
3008
+ validation_errors.append(f"docs-ledger: {issue}")
3009
+ for warning in ledger_result.get("warnings") or []:
3010
+ print(f"[doctor] WARN docs-ledger: {warning}")
3011
+
2378
3012
  try:
2379
3013
  timeout_s = int(jenkins_cfg.get("deploy_timeout_sec") or 0)
2380
- if timeout_s <= 0:
3014
+ if (jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec"))) and timeout_s <= 0:
2381
3015
  validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
2382
3016
  except Exception:
2383
- validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
3017
+ if jenkins_required or _is_explicit_fill(jenkins_cfg.get("deploy_timeout_sec")):
3018
+ validation_errors.append("jenkins.deploy_timeout_sec must be a positive integer")
2384
3019
 
2385
3020
  missing.extend(validation_errors)
2386
3021
 
@@ -2388,7 +3023,13 @@ def cmd_doctor(args: argparse.Namespace) -> None:
2388
3023
  _record_evidence(repo, cfg, "doctor", "fail", {"issues": missing})
2389
3024
  raise APError("Doctor found blocking config issues:\n- " + "\n- ".join(missing))
2390
3025
 
2391
- _record_evidence(repo, cfg, "doctor", "pass", {"mode": mode})
3026
+ _record_evidence(
3027
+ repo,
3028
+ cfg,
3029
+ "doctor",
3030
+ "pass",
3031
+ {"mode": mode, "target_env_required": target_env_required, "jenkins_required": jenkins_required},
3032
+ )
2392
3033
  print("[doctor] OK")
2393
3034
 
2394
3035
 
@@ -2562,7 +3203,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
2562
3203
  f"## {task_id} — {title} — {timestamp}",
2563
3204
  f"- Task: {task_id}",
2564
3205
  f"- Commit: {commit_value}",
2565
- f"- Jenkins Build: {jenkins_build}",
3206
+ f"- CI/Jenkins Build: {jenkins_build}",
2566
3207
  f"- Target Env: {target_env}",
2567
3208
  f"- Verification: {verification_text}",
2568
3209
  f"- Structure Check: {structure_check}",
@@ -2572,7 +3213,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
2572
3213
  if str(args.initial_commit or "").strip():
2573
3214
  lines.append(f"- Initial Commit: {args.initial_commit.strip()}")
2574
3215
  if str(args.jenkins_failure or "").strip():
2575
- lines.append(f"- Jenkins Failure: {args.jenkins_failure.strip()}")
3216
+ lines.append(f"- CI/Jenkins Failure: {args.jenkins_failure.strip()}")
2576
3217
  if str(args.fix_commit or "").strip():
2577
3218
  lines.append(f"- Fix Commit: {args.fix_commit.strip()}")
2578
3219
 
@@ -2629,6 +3270,8 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2629
3270
  cfg = _load_cfg(repo)
2630
3271
  mode = _workflow_mode(cfg, args)
2631
3272
  target_cfg = (cfg.get("target_env") or {})
3273
+ target_env_required = _verification_required(cfg, "target_env", default=True)
3274
+ jenkins_required = _verification_required(cfg, "jenkins", default=True)
2632
3275
 
2633
3276
  msg = args.msg
2634
3277
  structure_check_status = "skipped"
@@ -2649,21 +3292,22 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2649
3292
  if mode == "dev":
2650
3293
  dev_verification = args.verification or [
2651
3294
  "light-gate only",
2652
- "Jenkins triggered by push; build not verified in dev mode",
3295
+ "configured CI/Jenkins not verified in dev mode",
2653
3296
  "target environment not verified in dev mode",
2654
3297
  ]
2655
3298
  _record_commit_push_closure(
2656
3299
  repo,
2657
3300
  args,
2658
3301
  commit="generated by this commit-push run",
2659
- jenkins=args.jenkins_build or "triggered by push, not verified in dev mode",
3302
+ jenkins=args.jenkins_build or "not verified in dev mode",
2660
3303
  target_env=args.target_env or "not verified in dev mode",
2661
3304
  verification=dev_verification,
2662
3305
  result=args.result or "DEV-CLOSED",
2663
- follow_up=args.follow_up or "Run verify mode when Jenkins and target-environment evidence is required.",
3306
+ follow_up=args.follow_up or "Run verify mode when configured CI/Jenkins and target-environment evidence is required.",
2664
3307
  structure_check=args.structure_check or structure_check_status,
2665
3308
  )
2666
3309
 
3310
+ _cleanup_generated_noise(repo)
2667
3311
  run(["git", "add", "-A"], cwd=repo)
2668
3312
  diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
2669
3313
  if not diff:
@@ -2673,47 +3317,63 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
2673
3317
  run(["git", "push"], cwd=repo)
2674
3318
 
2675
3319
  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,
3320
+ if jenkins_required:
3321
+ jenkins_build = cmd_verify_jenkins_build(
3322
+ argparse.Namespace(
3323
+ repo=str(repo),
3324
+ git_ref="HEAD",
3325
+ job_name=args.job_name,
3326
+ job_url=args.job_url,
3327
+ multibranch_root_job=args.multibranch_root_job,
3328
+ branch_name=args.branch_name,
3329
+ build_number=args.build_number,
3330
+ max_builds=args.max_builds,
3331
+ timeout_sec=args.timeout_sec,
3332
+ poll_sec=args.poll_sec,
3333
+ allow_no_deploy=args.allow_no_deploy,
3334
+ )
2689
3335
  )
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,
3336
+ else:
3337
+ jenkins_build = "skipped by verification.jenkins_required=false"
3338
+
3339
+ if target_env_required:
3340
+ target_summary = cmd_verify_target(
3341
+ argparse.Namespace(
3342
+ repo=str(repo),
3343
+ backend_path=args.backend_path,
3344
+ frontend_path=args.frontend_path,
3345
+ backend_basic_auth=args.backend_basic_auth,
3346
+ frontend_basic_auth=args.frontend_basic_auth,
3347
+ )
2698
3348
  )
2699
- )
3349
+ else:
3350
+ target_summary = "skipped by verification.target_env_required=false"
2700
3351
  if args.require_matrix:
2701
3352
  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
- ]
3353
+ verification = args.verification
3354
+ if not verification:
3355
+ verification = []
3356
+ if jenkins_required:
3357
+ verification.append(f"CI/Jenkins build verified: {jenkins_build or 'verified by git-ref HEAD'}")
3358
+ else:
3359
+ verification.append("CI/Jenkins verification skipped by verification.jenkins_required=false")
3360
+ if target_env_required:
3361
+ verification.append(f"Target verification: {target_summary}")
3362
+ else:
3363
+ verification.append("Target verification skipped by verification.target_env_required=false")
2706
3364
  _record_commit_push_closure(
2707
3365
  repo,
2708
3366
  args,
2709
3367
  commit="HEAD",
2710
3368
  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(),
3369
+ target_env=args.target_env
3370
+ or (str(target_cfg.get("name") or "").strip() if target_env_required else "skipped by verification.target_env_required=false"),
2712
3371
  verification=verification,
2713
3372
  result=args.result or "PASS",
2714
3373
  follow_up=args.follow_up or "none",
2715
3374
  structure_check=args.structure_check or structure_check_status,
2716
3375
  )
3376
+ _cleanup_generated_noise(repo)
2717
3377
  run(["git", "add", "-A"], cwd=repo)
2718
3378
  closure_diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
2719
3379
  if closure_diff:
@@ -2741,6 +3401,7 @@ def main(argv: Optional[List[str]] = None) -> int:
2741
3401
 
2742
3402
  s = sp.add_parser("install")
2743
3403
  s.add_argument("--bridges", action="store_true")
3404
+ s.add_argument("--force", action="store_true")
2744
3405
  s.set_defaults(func=cmd_install)
2745
3406
 
2746
3407
  s = sp.add_parser("upgrade")
@@ -2794,6 +3455,18 @@ def main(argv: Optional[List[str]] = None) -> int:
2794
3455
  s.add_argument("--json", action="store_true")
2795
3456
  s.set_defaults(func=cmd_gate_profile)
2796
3457
 
3458
+ s = sp.add_parser("docs-ledger-check")
3459
+ s.add_argument("--json", action="store_true")
3460
+ s.set_defaults(func=cmd_docs_ledger_check)
3461
+
3462
+ s = sp.add_parser("docs-ledger-archive")
3463
+ mode = s.add_mutually_exclusive_group(required=True)
3464
+ mode.add_argument("--plan", action="store_true")
3465
+ mode.add_argument("--write", action="store_true")
3466
+ s.add_argument("--period", help="Archive period in YYYY-MM; defaults to current month")
3467
+ s.add_argument("--json", action="store_true")
3468
+ s.set_defaults(func=cmd_docs_ledger_archive)
3469
+
2797
3470
  s = sp.add_parser("light-gate")
2798
3471
  s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
2799
3472
  s.add_argument("--base")
@@ -2843,14 +3516,14 @@ def main(argv: Optional[List[str]] = None) -> int:
2843
3516
  s.add_argument("task_id")
2844
3517
  s.add_argument("--title")
2845
3518
  s.add_argument("--commit", default="HEAD")
2846
- s.add_argument("--jenkins")
3519
+ s.add_argument("--ci-build", "--jenkins", dest="jenkins", metavar="CI_BUILD")
2847
3520
  s.add_argument("--target-env")
2848
3521
  s.add_argument("--verification", action="append")
2849
3522
  s.add_argument("--structure-check")
2850
3523
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"], required=True)
2851
3524
  s.add_argument("--follow-up")
2852
3525
  s.add_argument("--initial-commit")
2853
- s.add_argument("--jenkins-failure")
3526
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
2854
3527
  s.add_argument("--fix-commit")
2855
3528
  s.set_defaults(func=cmd_record_closure)
2856
3529
 
@@ -2877,14 +3550,14 @@ def main(argv: Optional[List[str]] = None) -> int:
2877
3550
  s.add_argument("--frontend-path", action="append")
2878
3551
  s.add_argument("--backend-basic-auth", action="store_true")
2879
3552
  s.add_argument("--frontend-basic-auth", action="store_true")
2880
- s.add_argument("--jenkins-build")
3553
+ s.add_argument("--ci-build", "--jenkins-build", dest="jenkins_build", metavar="CI_BUILD")
2881
3554
  s.add_argument("--target-env")
2882
3555
  s.add_argument("--verification", action="append")
2883
3556
  s.add_argument("--structure-check")
2884
3557
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"])
2885
3558
  s.add_argument("--follow-up")
2886
3559
  s.add_argument("--initial-commit")
2887
- s.add_argument("--jenkins-failure")
3560
+ s.add_argument("--ci-failure", "--jenkins-failure", dest="jenkins_failure", metavar="CI_FAILURE")
2888
3561
  s.add_argument("--fix-commit")
2889
3562
  s.set_defaults(func=cmd_commit_push)
2890
3563