@walvka-code/proj-doc-builder 0.0.0-stage → 4.5.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -3
  3. package/README.zh-CN.md +258 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +11 -0
  6. package/index.js +164 -0
  7. package/locale/en.json +6 -0
  8. package/locale/zh.json +6 -0
  9. package/package.json +59 -4
  10. package/skills/proj-doc-builder/SKILL.md +412 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +103 -0
  12. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  13. package/skills/proj-doc-builder/references/checklist.md +90 -0
  14. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  15. package/skills/proj-doc-builder/references/linking.md +83 -0
  16. package/skills/proj-doc-builder/references/migration.md +32 -0
  17. package/skills/proj-doc-builder/references/phase4.md +200 -0
  18. package/skills/proj-doc-builder/references/templates.md +212 -0
  19. package/skills/proj-doc-builder/tests/claims.json +76 -0
  20. package/skills/proj-doc-builder/tests/conftest.py +23 -0
  21. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  22. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  23. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  24. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  25. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
  26. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  27. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  28. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
  29. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  30. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  31. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  32. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  33. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  34. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  35. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  36. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  37. package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
  38. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  39. package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
  40. package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
  41. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  42. package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
  43. package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
  44. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
  45. package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
  46. package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
  47. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
  48. package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
  49. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  50. package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
  51. package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
  52. package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
  53. package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
  54. package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
  55. package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
@@ -0,0 +1,239 @@
1
+ # -*- coding: utf-8 -*-
2
+ """安全、确定地计算和校验 ``project_docs`` 文档链接。"""
3
+
4
+ from __future__ import annotations
5
+ import sys as _bootstrap_sys
6
+ from pathlib import Path as _bootstrap_path
7
+ _bootstrap_sys.dont_write_bytecode = True
8
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
9
+ import _paths # noqa: E402
10
+ _paths.install()
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import Any, Mapping, Sequence
18
+
19
+ from project_docs_contract import (
20
+ JsonContractError,
21
+ LinkDisposition,
22
+ ProjectDocsContractError,
23
+ atomic_write_json,
24
+ compute_relative_doc_link,
25
+ configure_stdio_utf8,
26
+ read_json_strict,
27
+ read_markdown_links,
28
+ resolve_docs_root,
29
+ stable_json_dumps,
30
+ )
31
+
32
+
33
+ def _docs_root(project_docs_dir: str | os.PathLike[str]) -> Path:
34
+ return resolve_docs_root(project_docs_dir)
35
+
36
+
37
+ def _contract_doc_path(value: str | os.PathLike[str], root: Path) -> str | Path:
38
+ """把旧 CLI 的 ``project_docs/...`` 写法转换为契约路径。"""
39
+
40
+ raw = os.fspath(value)
41
+ candidate = Path(raw)
42
+ if candidate.is_absolute():
43
+ return candidate
44
+ if "\\" in raw:
45
+ raise ValueError(f"文档路径必须使用正斜杠: {raw!r}")
46
+ pure = PurePosixPath(raw)
47
+ if pure.parts and pure.parts[0] == root.name:
48
+ pure = PurePosixPath(*pure.parts[1:])
49
+ return pure.as_posix()
50
+
51
+
52
+ def compute_relative_link(
53
+ from_doc: str,
54
+ to_doc: str,
55
+ project_docs_dir: str = "project_docs",
56
+ *,
57
+ must_exist: bool = False,
58
+ ) -> str:
59
+ """计算两个受信文档之间的 POSIX 相对链接。"""
60
+
61
+ root = _docs_root(project_docs_dir)
62
+ return compute_relative_doc_link(
63
+ _contract_doc_path(from_doc, root),
64
+ _contract_doc_path(to_doc, root),
65
+ root,
66
+ must_exist=must_exist,
67
+ )
68
+
69
+
70
+ def validate_doc_links(doc_path: str, project_docs_dir: str) -> list[dict[str, Any]]:
71
+ """返回文档中的无效或不存在本地文档链接。"""
72
+
73
+ root = _docs_root(project_docs_dir)
74
+ source = _contract_doc_path(doc_path, root)
75
+ broken: list[dict[str, Any]] = []
76
+ for link in read_markdown_links(source, root):
77
+ if link.disposition is LinkDisposition.SKIPPED:
78
+ continue
79
+ if link.disposition is LinkDisposition.INVALID or link.exists is False:
80
+ broken.append(
81
+ {
82
+ "text": link.text,
83
+ "target": link.raw_target,
84
+ "resolved": link.project_relative_path
85
+ or link.normalized_target
86
+ or "",
87
+ "kind": (
88
+ "invalid"
89
+ if link.disposition is LinkDisposition.INVALID
90
+ else "missing"
91
+ ),
92
+ "reason": link.reason,
93
+ }
94
+ )
95
+ return broken
96
+
97
+
98
+ def batch_compute(
99
+ pairs: Sequence[Mapping[str, Any]],
100
+ project_docs_dir: str = "project_docs",
101
+ *,
102
+ must_exist: bool = False,
103
+ ) -> list[dict[str, str]]:
104
+ """批量计算 ``from``/``to`` 文档对。"""
105
+
106
+ if isinstance(pairs, (str, bytes)):
107
+ raise JsonContractError("批量输入必须是对象数组")
108
+ results: list[dict[str, str]] = []
109
+ for index, pair in enumerate(pairs):
110
+ if not isinstance(pair, Mapping):
111
+ raise JsonContractError(f"pairs[{index}] 必须是对象")
112
+ from_doc = pair.get("from")
113
+ to_doc = pair.get("to")
114
+ if not isinstance(from_doc, str) or not isinstance(to_doc, str):
115
+ raise JsonContractError(f"pairs[{index}] 必须包含字符串 from/to")
116
+ results.append(
117
+ {
118
+ "from": from_doc,
119
+ "to": to_doc,
120
+ "link": compute_relative_link(
121
+ from_doc,
122
+ to_doc,
123
+ project_docs_dir,
124
+ must_exist=must_exist,
125
+ ),
126
+ }
127
+ )
128
+ return results
129
+
130
+
131
+ def _load_pairs(path: str | os.PathLike[str]) -> Sequence[Mapping[str, Any]]:
132
+ value = read_json_strict(path)
133
+ pairs = value.get("pairs") if isinstance(value, Mapping) else value
134
+ if not isinstance(pairs, list):
135
+ raise JsonContractError("批量 JSON 必须是数组或包含 pairs 数组的对象")
136
+ return pairs
137
+
138
+
139
+ def _parser() -> argparse.ArgumentParser:
140
+ parser = argparse.ArgumentParser(description="计算并校验 project_docs 文档链接")
141
+ parser.add_argument("--from", dest="from_doc", help="源文档路径")
142
+ parser.add_argument("--to", dest="to_doc", help="目标文档路径")
143
+ parser.add_argument("--validate", help="校验单个文档中的全部链接")
144
+ parser.add_argument(
145
+ "--project-docs",
146
+ default="project_docs",
147
+ help="project_docs 目录(默认: project_docs)",
148
+ )
149
+ parser.add_argument("--batch", help="批量输入 JSON")
150
+ parser.add_argument("--output", "-o", help="批量结果输出文件")
151
+ parser.add_argument(
152
+ "--must-exist", action="store_true", help="计算时要求两端文档存在"
153
+ )
154
+ parser.add_argument("--json", action="store_true", help="仅向 stdout 输出 JSON")
155
+ return parser
156
+
157
+
158
+ def main(argv: Sequence[str] | None = None) -> int:
159
+ configure_stdio_utf8()
160
+ parser = _parser()
161
+ args = parser.parse_args(argv)
162
+ try:
163
+ modes = (
164
+ int(bool(args.from_doc or args.to_doc))
165
+ + int(bool(args.validate))
166
+ + int(bool(args.batch))
167
+ )
168
+ if modes != 1:
169
+ raise ValueError("必须且只能选择 from/to、validate 或 batch 一种模式")
170
+ if bool(args.from_doc) != bool(args.to_doc):
171
+ raise ValueError("--from 与 --to 必须同时提供")
172
+
173
+ if args.from_doc:
174
+ link = compute_relative_link(
175
+ args.from_doc,
176
+ args.to_doc,
177
+ args.project_docs,
178
+ must_exist=args.must_exist,
179
+ )
180
+ if args.json:
181
+ print(stable_json_dumps({"link": link}), end="")
182
+ else:
183
+ print(link)
184
+ return 0
185
+
186
+ if args.validate:
187
+ broken = validate_doc_links(args.validate, args.project_docs)
188
+ result = {
189
+ "document": args.validate,
190
+ "broken_count": len(broken),
191
+ "broken": broken,
192
+ "valid": not broken,
193
+ }
194
+ if args.json:
195
+ print(stable_json_dumps(result), end="")
196
+ elif broken:
197
+ print(f"发现 {len(broken)} 条无效链接: {args.validate}")
198
+ for item in broken:
199
+ print(
200
+ f" [{item['text']}]({item['target']}) -> "
201
+ f"{item['resolved']} ({item['reason']})"
202
+ )
203
+ else:
204
+ print(f"链接有效: {args.validate}")
205
+ return 1 if broken else 0
206
+
207
+ results = batch_compute(
208
+ _load_pairs(args.batch),
209
+ args.project_docs,
210
+ must_exist=args.must_exist,
211
+ )
212
+ if args.output:
213
+ written = atomic_write_json(args.output, results)
214
+ if args.json:
215
+ print(
216
+ stable_json_dumps(
217
+ {
218
+ "ok": True,
219
+ "count": len(results),
220
+ "written": written.as_posix(),
221
+ }
222
+ ),
223
+ end="",
224
+ )
225
+ elif args.json:
226
+ print(stable_json_dumps({"results": results}), end="")
227
+ else:
228
+ print(json.dumps(results, ensure_ascii=False, indent=2))
229
+ return 0
230
+ except (OSError, ValueError, ProjectDocsContractError) as exc:
231
+ if args.json:
232
+ print(stable_json_dumps({"error": str(exc), "ok": False}), end="")
233
+ else:
234
+ print(f"ERROR: {exc}", file=sys.stderr)
235
+ return 2
236
+
237
+
238
+ if __name__ == "__main__":
239
+ raise SystemExit(main())
@@ -0,0 +1,460 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Unified project-level configuration loader for ``proj-doc-builder``.
3
+
4
+ Reads optional ``.projdoc.toml`` from the project root using Python 3.12+
5
+ standard library ``tomllib``. When absent, all settings fall back to safe,
6
+ backward-compatible defaults so existing repositories and tests behave
7
+ identically out of the box.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import fnmatch
13
+ import os
14
+ import stat
15
+ import tomllib
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Mapping, Sequence
19
+
20
+ CONFIG_FILENAME = ".projdoc.toml"
21
+
22
+ DEFAULT_EXCLUDE_NAMES: frozenset[str] = frozenset(
23
+ {
24
+ ".git",
25
+ ".svn",
26
+ ".venv",
27
+ "__pycache__",
28
+ ".pytest_cache",
29
+ ".mypy_cache",
30
+ "node_modules",
31
+ ".lingma",
32
+ ".deepseek",
33
+ ".vscode",
34
+ ".idea",
35
+ ".settings",
36
+ ".dsh",
37
+ "Debug",
38
+ "test_reports",
39
+ "_extract",
40
+ "target",
41
+ "project_docs",
42
+ "sub_plan",
43
+ ".hypothesis",
44
+ }
45
+ )
46
+
47
+ DEFAULT_MAX_DEPTH = 8
48
+ DEFAULT_CLAUDE_MAX_BYTES = 24_576
49
+ DEFAULT_CLAUDE_MAX_DEPTH = 0
50
+ DEFAULT_CLAUDE_COLLAPSE_THRESHOLD = 20
51
+ DEFAULT_PUBLISH_MAX_HISTORY = 10
52
+
53
+
54
+ class ConfigError(ValueError):
55
+ """Raised when ``.projdoc.toml`` is malformed, unsafe, or invalid."""
56
+
57
+
58
+ def is_placeholder_directory(
59
+ files: Sequence[str], subdirs: Sequence[str]
60
+ ) -> bool:
61
+ """Canonical placeholder directory predicate shared by scanner and validator.
62
+
63
+ A directory is a placeholder iff it has no non-excluded subdirectories and
64
+ its visible files are empty or solely ``__init__.py``.
65
+ """
66
+
67
+ if subdirs:
68
+ return False
69
+ return {name.casefold() for name in files}.issubset({"__init__.py"})
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class ExpectedFailureRule:
74
+ """Known expected validation failure exempted from ``audit_failures``."""
75
+
76
+ path: str
77
+ check_id: int
78
+ reason: str
79
+ review_date: str = ""
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class ValidationConfig:
84
+ """Validation customization and known-issue allowlist settings."""
85
+
86
+ architecture_terms: tuple[str, ...] = ()
87
+ relation_terms: tuple[str, ...] = ()
88
+ extra_architecture_terms: tuple[str, ...] = ()
89
+ extra_relation_terms: tuple[str, ...] = ()
90
+ expected_failures: tuple[ExpectedFailureRule, ...] = ()
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class ScanConfig:
95
+ """Scanner exclusion, depth, and caching settings."""
96
+
97
+ max_depth: int = DEFAULT_MAX_DEPTH
98
+ exclude_names: frozenset[str] = DEFAULT_EXCLUDE_NAMES
99
+ exclude_paths: tuple[str, ...] = ()
100
+ use_mtime_cache: bool = False
101
+ exclude_names_folded: frozenset[str] = field(init=False)
102
+ exclude_paths_folded: tuple[str, ...] = field(init=False)
103
+
104
+ def __post_init__(self) -> None:
105
+ object.__setattr__(
106
+ self,
107
+ "exclude_names_folded",
108
+ frozenset(name.casefold() for name in self.exclude_names),
109
+ )
110
+ object.__setattr__(
111
+ self,
112
+ "exclude_paths_folded",
113
+ tuple(path.casefold() for path in self.exclude_paths),
114
+ )
115
+
116
+
117
+ @dataclass(frozen=True)
118
+ class ClaudeIndexConfig:
119
+ """Budget and folding settings for the root ``CLAUDE.md`` document tree."""
120
+
121
+ max_bytes: int = DEFAULT_CLAUDE_MAX_BYTES
122
+ max_depth: int = DEFAULT_CLAUDE_MAX_DEPTH
123
+ collapse_threshold: int = DEFAULT_CLAUDE_COLLAPSE_THRESHOLD
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class PublishConfig:
128
+ """Coordinator publish retention settings."""
129
+
130
+ max_history_entries: int = DEFAULT_PUBLISH_MAX_HISTORY
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class ProjectDocConfig:
135
+ """Complete resolved configuration for a project root."""
136
+
137
+ scan: ScanConfig = field(default_factory=ScanConfig)
138
+ claude_index: ClaudeIndexConfig = field(default_factory=ClaudeIndexConfig)
139
+ publish: PublishConfig = field(default_factory=PublishConfig)
140
+ validation: ValidationConfig = field(default_factory=ValidationConfig)
141
+ strict_config: bool = False
142
+ warnings: tuple[str, ...] = ()
143
+ config_path: str | None = None
144
+
145
+
146
+ DEFAULT_CONFIG = ProjectDocConfig()
147
+
148
+
149
+ def _is_reparse(stat_result: os.stat_result) -> bool:
150
+ attributes = getattr(stat_result, "st_file_attributes", 0)
151
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
152
+ return bool(attributes & reparse_flag)
153
+
154
+
155
+ def _normalize_exclude_path(raw: str) -> str:
156
+ value = raw.strip().replace("\\", "/").strip("/")
157
+ if not value or "\0" in value or ".." in value.split("/"):
158
+ raise ConfigError(f"invalid exclude_paths pattern: {raw!r}")
159
+ return value
160
+
161
+
162
+ def _require_non_negative_int(
163
+ table: Mapping[str, Any], key: str, default: int, *, minimum: int = 0
164
+ ) -> int:
165
+ if key not in table:
166
+ return default
167
+ value = table[key]
168
+ if type(value) is not int or value < minimum:
169
+ raise ConfigError(f"{key} must be an integer >= {minimum}, got {value!r}")
170
+ return value
171
+
172
+
173
+ def _require_bool(table: Mapping[str, Any], key: str, default: bool) -> bool:
174
+ if key not in table:
175
+ return default
176
+ value = table[key]
177
+ if type(value) is not bool:
178
+ raise ConfigError(f"{key} must be a boolean, got {value!r}")
179
+ return value
180
+
181
+
182
+ def _require_string_list(table: Mapping[str, Any], key: str) -> tuple[str, ...]:
183
+ if key not in table:
184
+ return ()
185
+ value = table[key]
186
+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
187
+ raise ConfigError(f"{key} must be an array of strings")
188
+ return tuple(item.strip() for item in value if item.strip())
189
+
190
+
191
+ def _handle_unknown_keys(
192
+ label: str,
193
+ unknown: set[str],
194
+ *,
195
+ strict: bool,
196
+ warnings: list[str],
197
+ ) -> None:
198
+ if not unknown:
199
+ return
200
+ message = f"unknown {label}: {sorted(unknown)}"
201
+ if strict:
202
+ raise ConfigError(message)
203
+ warnings.append(message)
204
+
205
+
206
+ def _parse_expected_failures(raw: Any) -> tuple[ExpectedFailureRule, ...]:
207
+ if raw is None:
208
+ return ()
209
+ if not isinstance(raw, list):
210
+ raise ConfigError(
211
+ "[validation].expected_failures must be an array of tables"
212
+ )
213
+ rules: list[ExpectedFailureRule] = []
214
+ for index, item in enumerate(raw):
215
+ if not isinstance(item, Mapping):
216
+ raise ConfigError(
217
+ f"validation.expected_failures[{index}] must be a table"
218
+ )
219
+ raw_path = item.get("path")
220
+ if not isinstance(raw_path, str) or not raw_path.strip():
221
+ raise ConfigError(
222
+ f"validation.expected_failures[{index}].path must be a non-empty string"
223
+ )
224
+ norm_path = raw_path.strip().replace("\\", "/").strip("/")
225
+ if not norm_path or "\0" in norm_path or ".." in norm_path.split("/"):
226
+ raise ConfigError(
227
+ f"validation.expected_failures[{index}].path is invalid: {raw_path!r}"
228
+ )
229
+ check_id = item.get("check_id")
230
+ if type(check_id) is not int or not (1 <= check_id <= 12):
231
+ raise ConfigError(
232
+ f"validation.expected_failures[{index}].check_id must be an integer 1..12"
233
+ )
234
+ reason = item.get("reason")
235
+ if not isinstance(reason, str) or not reason.strip():
236
+ raise ConfigError(
237
+ f"validation.expected_failures[{index}].reason must be a non-empty string"
238
+ )
239
+ review_date = item.get("review_date", "")
240
+ if not isinstance(review_date, str):
241
+ raise ConfigError(
242
+ f"validation.expected_failures[{index}].review_date must be a string"
243
+ )
244
+ rules.append(
245
+ ExpectedFailureRule(
246
+ path=norm_path,
247
+ check_id=check_id,
248
+ reason=reason.strip(),
249
+ review_date=review_date.strip(),
250
+ )
251
+ )
252
+ return tuple(rules)
253
+
254
+
255
+ def parse_config_dict(
256
+ data: Mapping[str, Any], *, config_path: str | None = None
257
+ ) -> ProjectDocConfig:
258
+ """Validate and build a :class:`ProjectDocConfig` from parsed TOML data."""
259
+
260
+ strict_config = _require_bool(data, "strict_config", False)
261
+ warnings: list[str] = []
262
+
263
+ allowed_top = {"strict_config", "scan", "claude_index", "publish", "validation"}
264
+ _handle_unknown_keys(
265
+ "top-level config section(s)",
266
+ set(data) - allowed_top,
267
+ strict=strict_config,
268
+ warnings=warnings,
269
+ )
270
+
271
+ raw_scan = data.get("scan", {})
272
+ if not isinstance(raw_scan, Mapping):
273
+ raise ConfigError("[scan] must be a table")
274
+ _handle_unknown_keys(
275
+ "[scan] key(s)",
276
+ set(raw_scan)
277
+ - {
278
+ "max_depth",
279
+ "exclude_names",
280
+ "exclude_paths",
281
+ "use_mtime_cache",
282
+ },
283
+ strict=strict_config,
284
+ warnings=warnings,
285
+ )
286
+ extra_names = _require_string_list(raw_scan, "exclude_names")
287
+ raw_paths = _require_string_list(raw_scan, "exclude_paths")
288
+ exclude_paths = tuple(_normalize_exclude_path(item) for item in raw_paths)
289
+ scan_cfg = ScanConfig(
290
+ max_depth=_require_non_negative_int(
291
+ raw_scan, "max_depth", DEFAULT_MAX_DEPTH, minimum=1
292
+ ),
293
+ exclude_names=DEFAULT_EXCLUDE_NAMES | frozenset(extra_names),
294
+ exclude_paths=exclude_paths,
295
+ use_mtime_cache=_require_bool(raw_scan, "use_mtime_cache", False),
296
+ )
297
+
298
+ raw_claude = data.get("claude_index", {})
299
+ if not isinstance(raw_claude, Mapping):
300
+ raise ConfigError("[claude_index] must be a table")
301
+ _handle_unknown_keys(
302
+ "[claude_index] key(s)",
303
+ set(raw_claude)
304
+ - {
305
+ "max_bytes",
306
+ "max_depth",
307
+ "collapse_threshold",
308
+ },
309
+ strict=strict_config,
310
+ warnings=warnings,
311
+ )
312
+ claude_cfg = ClaudeIndexConfig(
313
+ max_bytes=_require_non_negative_int(
314
+ raw_claude, "max_bytes", DEFAULT_CLAUDE_MAX_BYTES, minimum=0
315
+ ),
316
+ max_depth=_require_non_negative_int(
317
+ raw_claude, "max_depth", DEFAULT_CLAUDE_MAX_DEPTH, minimum=0
318
+ ),
319
+ collapse_threshold=_require_non_negative_int(
320
+ raw_claude,
321
+ "collapse_threshold",
322
+ DEFAULT_CLAUDE_COLLAPSE_THRESHOLD,
323
+ minimum=2,
324
+ ),
325
+ )
326
+
327
+ raw_publish = data.get("publish", {})
328
+ if not isinstance(raw_publish, Mapping):
329
+ raise ConfigError("[publish] must be a table")
330
+ _handle_unknown_keys(
331
+ "[publish] key(s)",
332
+ set(raw_publish) - {"max_history_entries"},
333
+ strict=strict_config,
334
+ warnings=warnings,
335
+ )
336
+ publish_cfg = PublishConfig(
337
+ max_history_entries=_require_non_negative_int(
338
+ raw_publish,
339
+ "max_history_entries",
340
+ DEFAULT_PUBLISH_MAX_HISTORY,
341
+ minimum=0,
342
+ )
343
+ )
344
+
345
+ raw_validation = data.get("validation", {})
346
+ if not isinstance(raw_validation, Mapping):
347
+ raise ConfigError("[validation] must be a table")
348
+ _handle_unknown_keys(
349
+ "[validation] key(s)",
350
+ set(raw_validation)
351
+ - {
352
+ "architecture_terms",
353
+ "relation_terms",
354
+ "extra_architecture_terms",
355
+ "extra_relation_terms",
356
+ "expected_failures",
357
+ },
358
+ strict=strict_config,
359
+ warnings=warnings,
360
+ )
361
+ validation_cfg = ValidationConfig(
362
+ architecture_terms=_require_string_list(raw_validation, "architecture_terms"),
363
+ relation_terms=_require_string_list(raw_validation, "relation_terms"),
364
+ extra_architecture_terms=_require_string_list(
365
+ raw_validation, "extra_architecture_terms"
366
+ ),
367
+ extra_relation_terms=_require_string_list(
368
+ raw_validation, "extra_relation_terms"
369
+ ),
370
+ expected_failures=_parse_expected_failures(
371
+ raw_validation.get("expected_failures")
372
+ ),
373
+ )
374
+
375
+ return ProjectDocConfig(
376
+ scan=scan_cfg,
377
+ claude_index=claude_cfg,
378
+ publish=publish_cfg,
379
+ validation=validation_cfg,
380
+ strict_config=strict_config,
381
+ warnings=tuple(warnings),
382
+ config_path=config_path,
383
+ )
384
+
385
+
386
+ def load_project_config(project_root: str | os.PathLike[str] | None) -> ProjectDocConfig:
387
+ """Load optional ``.projdoc.toml`` from ``project_root``; fail closed if invalid."""
388
+
389
+ if project_root is None:
390
+ return DEFAULT_CONFIG
391
+ root = Path(project_root)
392
+ config_file = root / CONFIG_FILENAME
393
+ try:
394
+ info = config_file.lstat()
395
+ except FileNotFoundError:
396
+ return DEFAULT_CONFIG
397
+ except OSError as exc:
398
+ raise ConfigError(f"cannot inspect {CONFIG_FILENAME}: {exc}") from exc
399
+
400
+ if config_file.is_symlink() or _is_reparse(info):
401
+ raise ConfigError(f"{CONFIG_FILENAME} must not be a symlink or reparse point")
402
+ if not stat.S_ISREG(info.st_mode):
403
+ raise ConfigError(f"{CONFIG_FILENAME} must be a regular file")
404
+
405
+ try:
406
+ resolved_root = root.resolve(strict=True)
407
+ resolved_config = config_file.resolve(strict=True)
408
+ resolved_config.relative_to(resolved_root)
409
+ except (OSError, RuntimeError, ValueError) as exc:
410
+ raise ConfigError(f"{CONFIG_FILENAME} resolves outside project root") from exc
411
+
412
+ try:
413
+ raw_bytes = config_file.read_bytes()
414
+ text = raw_bytes.decode("utf-8", errors="strict")
415
+ except (OSError, UnicodeDecodeError) as exc:
416
+ raise ConfigError(f"{CONFIG_FILENAME} must be strict UTF-8: {exc}") from exc
417
+
418
+ try:
419
+ parsed = tomllib.loads(text)
420
+ except tomllib.TOMLDecodeError as exc:
421
+ raise ConfigError(f"{CONFIG_FILENAME} TOML parse error: {exc}") from exc
422
+ if not isinstance(parsed, Mapping):
423
+ raise ConfigError(f"{CONFIG_FILENAME} root must be a table")
424
+ return parse_config_dict(parsed, config_path=CONFIG_FILENAME)
425
+
426
+
427
+ def should_exclude_directory(
428
+ name: str,
429
+ relative_path: str = "",
430
+ *,
431
+ config: ProjectDocConfig | ScanConfig | None = None,
432
+ extra_exclude_names: Sequence[str] | frozenset[str] = (),
433
+ ) -> bool:
434
+ """Return whether a directory should be pruned from source scanning."""
435
+
436
+ scan_cfg = (
437
+ config.scan
438
+ if isinstance(config, ProjectDocConfig)
439
+ else config if isinstance(config, ScanConfig) else DEFAULT_CONFIG.scan
440
+ )
441
+ folded_name = name.casefold()
442
+ if name.startswith(".") or folded_name in scan_cfg.exclude_names_folded:
443
+ return True
444
+ if extra_exclude_names and folded_name in {
445
+ item.casefold() for item in extra_exclude_names
446
+ }:
447
+ return True
448
+
449
+ if relative_path and scan_cfg.exclude_paths_folded:
450
+ norm_rel = relative_path.replace("\\", "/").strip("/").casefold()
451
+ for pattern in scan_cfg.exclude_paths_folded:
452
+ if pattern.startswith("**/"):
453
+ tail = pattern[3:]
454
+ if norm_rel == tail or norm_rel.endswith("/" + tail) or fnmatch.fnmatchcase(norm_rel, pattern):
455
+ return True
456
+ if norm_rel == pattern or norm_rel.startswith(pattern + "/"):
457
+ return True
458
+ if any(ch in pattern for ch in "*?[") and fnmatch.fnmatchcase(norm_rel, pattern):
459
+ return True
460
+ return False