@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.
- package/LICENSE +21 -0
- package/README.md +290 -3
- package/README.zh-CN.md +258 -0
- package/cordis.patch.yml +8 -0
- package/icon.svg +11 -0
- package/index.js +164 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +59 -4
- package/skills/proj-doc-builder/SKILL.md +412 -0
- package/skills/proj-doc-builder/references/audit_script.md +103 -0
- package/skills/proj-doc-builder/references/batch-generation.md +55 -0
- package/skills/proj-doc-builder/references/checklist.md +90 -0
- package/skills/proj-doc-builder/references/exclusions.md +79 -0
- package/skills/proj-doc-builder/references/linking.md +83 -0
- package/skills/proj-doc-builder/references/migration.md +32 -0
- package/skills/proj-doc-builder/references/phase4.md +200 -0
- package/skills/proj-doc-builder/references/templates.md +212 -0
- package/skills/proj-doc-builder/tests/claims.json +76 -0
- package/skills/proj-doc-builder/tests/conftest.py +23 -0
- package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
- package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
- package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
- package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
- package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
- package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
- package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
- package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
- package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
- package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
- package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
- package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
- package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
- package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
- package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
- package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
- package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
- package/skills/proj-doc-builder/tools/_paths.py +39 -0
- package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
- package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
- package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
- package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
- package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
- package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
- package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
- package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
- package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
- package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
- package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
- package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
- package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
- package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
- package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
- package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
- package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
|
@@ -0,0 +1,1911 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Validate one generated ``project_docs`` document against its source directory.
|
|
3
|
+
|
|
4
|
+
The validator keeps the historical positional document argument and
|
|
5
|
+
``--source-dir``/``--strict``/``--json`` options, while adding explicit roots and
|
|
6
|
+
standard/placeholder profiles. Structural (critical) failures always produce a
|
|
7
|
+
non-zero CLI status; ``--strict`` also makes editorial failures fatal.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
import sys as _bootstrap_sys
|
|
12
|
+
from pathlib import Path as _bootstrap_path
|
|
13
|
+
_bootstrap_sys.dont_write_bytecode = True
|
|
14
|
+
_bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
|
|
15
|
+
import _paths # noqa: E402
|
|
16
|
+
_paths.install()
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import ast
|
|
20
|
+
import concurrent.futures
|
|
21
|
+
import functools
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import stat
|
|
25
|
+
import sys
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
28
|
+
from typing import Any, Sequence
|
|
29
|
+
from urllib.parse import unquote
|
|
30
|
+
|
|
31
|
+
import proj_doc_config
|
|
32
|
+
from project_docs_contract import (
|
|
33
|
+
LinkDisposition,
|
|
34
|
+
PathValidationError,
|
|
35
|
+
ProjectDocsContractError,
|
|
36
|
+
StrictUtf8Error,
|
|
37
|
+
discover_active_markdown_paths,
|
|
38
|
+
parse_markdown_links,
|
|
39
|
+
read_utf8,
|
|
40
|
+
stable_json_dumps,
|
|
41
|
+
validate_manifest_relative_path,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
EXIT_OK = 0
|
|
45
|
+
EXIT_VALIDATION_FAILED = 1
|
|
46
|
+
EXIT_CRITICAL_ERROR = 2
|
|
47
|
+
RESULT_SCHEMA_VERSION = 1
|
|
48
|
+
|
|
49
|
+
PROFILE_AUTO = "auto"
|
|
50
|
+
PROFILE_STANDARD = "standard"
|
|
51
|
+
PROFILE_PLACEHOLDER = "placeholder"
|
|
52
|
+
PROFILES = (PROFILE_AUTO, PROFILE_STANDARD, PROFILE_PLACEHOLDER)
|
|
53
|
+
|
|
54
|
+
BANNED_WORDS = [
|
|
55
|
+
"工具文件",
|
|
56
|
+
"辅助函数",
|
|
57
|
+
"辅助功能",
|
|
58
|
+
"杂项",
|
|
59
|
+
"其他文件",
|
|
60
|
+
"各种工具",
|
|
61
|
+
"一些常量",
|
|
62
|
+
"一些函数",
|
|
63
|
+
"一些类",
|
|
64
|
+
"杂项文件",
|
|
65
|
+
"核心业务逻辑与基础设施功能",
|
|
66
|
+
"规范化的接口抽象",
|
|
67
|
+
"高可用与高一致性",
|
|
68
|
+
"接受全流程自动化测试与验证",
|
|
69
|
+
"范围内的具体实现或资料",
|
|
70
|
+
"向上承接上级模块调度",
|
|
71
|
+
"输出对应的代码或数据产物",
|
|
72
|
+
"承载该子模块的具体实现",
|
|
73
|
+
"提供目录归属、公共基础设施与配置支撑",
|
|
74
|
+
"性能良好",
|
|
75
|
+
"性能优异",
|
|
76
|
+
"高可靠性与高可用性",
|
|
77
|
+
"提供必要的支撑功能",
|
|
78
|
+
"相关数据与状态管理",
|
|
79
|
+
"相关性能与资源特征",
|
|
80
|
+
]
|
|
81
|
+
DEFAULT_ARCHITECTURE_TERMS = (
|
|
82
|
+
"子系统",
|
|
83
|
+
"协议栈",
|
|
84
|
+
"模块",
|
|
85
|
+
"组件",
|
|
86
|
+
"算法",
|
|
87
|
+
"固件",
|
|
88
|
+
"PC 端",
|
|
89
|
+
"测试层",
|
|
90
|
+
"数据层",
|
|
91
|
+
"接口层",
|
|
92
|
+
)
|
|
93
|
+
DEFAULT_RELATION_TERMS = (
|
|
94
|
+
"上游",
|
|
95
|
+
"下游",
|
|
96
|
+
"依赖",
|
|
97
|
+
"调用",
|
|
98
|
+
"协作",
|
|
99
|
+
"输入",
|
|
100
|
+
"输出",
|
|
101
|
+
"数据流",
|
|
102
|
+
"提供",
|
|
103
|
+
"使用",
|
|
104
|
+
"传递",
|
|
105
|
+
"导出",
|
|
106
|
+
"被",
|
|
107
|
+
)
|
|
108
|
+
STATUS_ICONS = ("✅", "🔶", "⬜", "📦", "❓")
|
|
109
|
+
# Kept for callers that imported this historical module-level constant.
|
|
110
|
+
PY_EXTENSIONS = {".py", ".pyx", ".pyi"}
|
|
111
|
+
EXCLUDED_SOURCE_DIRS = set(proj_doc_config.DEFAULT_EXCLUDE_NAMES)
|
|
112
|
+
CRITICAL_CHECK_IDS = frozenset({1, 4, 5, 8, 9})
|
|
113
|
+
|
|
114
|
+
_TABLE_SEPARATOR_RE = re.compile(r"^:?-{3,}:?$")
|
|
115
|
+
_INVALID_PERCENT_RE = re.compile(r"%(?![0-9A-Fa-f]{2})")
|
|
116
|
+
_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
|
|
117
|
+
_LINK_CELL_RE = re.compile(
|
|
118
|
+
r"^\s*\[([^\]\r\n]*)\]\(\s*"
|
|
119
|
+
r"(<[^>\r\n]*>|[^\s)]+)"
|
|
120
|
+
r"(?:\s+(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|\([^()\r\n]*\)))?\s*\)\s*$"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class _ValidationContext:
|
|
126
|
+
doc_path: Path
|
|
127
|
+
docs_root: Path
|
|
128
|
+
doc_relative: str
|
|
129
|
+
project_root: Path
|
|
130
|
+
source_dir: Path | None
|
|
131
|
+
source_files: tuple[str, ...] | None
|
|
132
|
+
source_subdirs: tuple[str, ...] | None
|
|
133
|
+
profile: str
|
|
134
|
+
profile_mismatch: str | None = None
|
|
135
|
+
virtual_source: bool = False
|
|
136
|
+
is_boundary: bool = False
|
|
137
|
+
project_config: proj_doc_config.ProjectDocConfig = proj_doc_config.DEFAULT_CONFIG
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True)
|
|
141
|
+
class _TableRow:
|
|
142
|
+
cells: tuple[str, ...]
|
|
143
|
+
raw: str
|
|
144
|
+
line_number: int
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class _ManifestRow:
|
|
149
|
+
name: str
|
|
150
|
+
row: _TableRow
|
|
151
|
+
link_target: str | None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _section(content: str, heading: str) -> str | None:
|
|
155
|
+
"""Extract a level-two Markdown section by its exact heading."""
|
|
156
|
+
|
|
157
|
+
pattern = rf"^##[ \t]+{re.escape(heading)}[ \t]*\r?\n(.*?)(?=^##[ \t]+|\Z)"
|
|
158
|
+
match = re.search(pattern, content, re.MULTILINE | re.DOTALL)
|
|
159
|
+
return match.group(1).strip() if match else None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _section_any(content: str, headings: Sequence[str]) -> str | None:
|
|
163
|
+
for heading in headings:
|
|
164
|
+
section_text = _section(content, heading)
|
|
165
|
+
if section_text is not None:
|
|
166
|
+
return section_text
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _strip_markdown(text: str) -> str:
|
|
171
|
+
text = re.sub(r"```.*?```", " ", text, flags=re.DOTALL)
|
|
172
|
+
text = re.sub(r"<!--.*?-->", " ", text, flags=re.DOTALL)
|
|
173
|
+
text = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", text)
|
|
174
|
+
text = re.sub(r"\[([^\]]*)\]\([^)]+\)", r"\1", text)
|
|
175
|
+
text = re.sub(r"`([^`]*)`", r"\1", text)
|
|
176
|
+
text = re.sub(r"^[ \t]*(?:>|[-*+]\s+|\d+[.)]\s+)", "", text, flags=re.MULTILINE)
|
|
177
|
+
text = text.replace("**", "").replace("__", "").replace("~~", "")
|
|
178
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
_ABBREVIATION_DOT_RE = re.compile(
|
|
182
|
+
r"\b(?:e\.g|i\.e|et\s+al|etc|vs|fig|sec|no|dr|mr|mrs|ms|prof|inc|ltd|cf|approx|ref|vol|ch|pp)\.(?=\s|$|[)\)\"\'”’])",
|
|
183
|
+
re.IGNORECASE,
|
|
184
|
+
)
|
|
185
|
+
_INTERNAL_DOT_RE = re.compile(r"(?<=[A-Za-z0-9_])\.(?=[A-Za-z0-9_])")
|
|
186
|
+
_URL_SCHEME_STRIP_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://\S+")
|
|
187
|
+
_WINDOWS_ABS_PATH_RE = re.compile(
|
|
188
|
+
r"(?<![A-Za-z0-9+._-])[A-Za-z]:(?:\\|/(?!/))[^\s`\"'<>|)]*"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _sentence_count(text: str) -> int:
|
|
193
|
+
clean = _strip_markdown(text)
|
|
194
|
+
if not clean:
|
|
195
|
+
return 0
|
|
196
|
+
protected = _ABBREVIATION_DOT_RE.sub(
|
|
197
|
+
lambda m: m.group(0).replace(".", "\uE000"), clean
|
|
198
|
+
)
|
|
199
|
+
protected = _INTERNAL_DOT_RE.sub("\uE000", protected)
|
|
200
|
+
fragments = re.split(r"(?:[。!?!?]+|\.(?=\s|$|[)\)\"\'”’]))", protected)
|
|
201
|
+
return sum(1 for fragment in fragments if re.search(r"[\w㐀-鿿]", fragment))
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _absolute_path_advisories(content: str, *, max_items: int = 5) -> list[dict[str, Any]]:
|
|
205
|
+
"""Detect host-specific Windows drive absolute paths in document body (D1)."""
|
|
206
|
+
|
|
207
|
+
advisories: list[dict[str, Any]] = []
|
|
208
|
+
for line_number, line in enumerate(content.splitlines(), 1):
|
|
209
|
+
stripped = _URL_SCHEME_STRIP_RE.sub(" ", line)
|
|
210
|
+
for match in _WINDOWS_ABS_PATH_RE.finditer(stripped):
|
|
211
|
+
matched = match.group(0)
|
|
212
|
+
advisories.append(
|
|
213
|
+
{
|
|
214
|
+
"code": "absolute-path-in-body",
|
|
215
|
+
"severity": "advisory",
|
|
216
|
+
"line": line_number,
|
|
217
|
+
"match": matched,
|
|
218
|
+
"message": (
|
|
219
|
+
f"文档体第 {line_number} 行包含宿主机绝对路径 {matched!r},"
|
|
220
|
+
"建议改用项目相对路径"
|
|
221
|
+
),
|
|
222
|
+
}
|
|
223
|
+
)
|
|
224
|
+
if len(advisories) >= max_items:
|
|
225
|
+
return advisories
|
|
226
|
+
return advisories
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _split_table_cells(line: str) -> tuple[str, ...] | None:
|
|
230
|
+
stripped = line.strip()
|
|
231
|
+
if not stripped.startswith("|"):
|
|
232
|
+
return None
|
|
233
|
+
if stripped.endswith("|"):
|
|
234
|
+
stripped = stripped[1:-1]
|
|
235
|
+
else:
|
|
236
|
+
stripped = stripped[1:]
|
|
237
|
+
cells = tuple(
|
|
238
|
+
part.replace(r"\|", "|").strip() for part in re.split(r"(?<!\\)\|", stripped)
|
|
239
|
+
)
|
|
240
|
+
return cells if cells else None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _unwrap_formatting(value: str) -> str:
|
|
244
|
+
value = value.strip()
|
|
245
|
+
changed = True
|
|
246
|
+
while changed:
|
|
247
|
+
changed = False
|
|
248
|
+
for marker in ("**", "__"):
|
|
249
|
+
if value.startswith(marker) and value.endswith(marker) and len(value) >= 4:
|
|
250
|
+
value = value[len(marker) : -len(marker)].strip()
|
|
251
|
+
changed = True
|
|
252
|
+
if value.startswith("`") and value.endswith("`") and value.count("`") == 2:
|
|
253
|
+
value = value[1:-1].strip()
|
|
254
|
+
return value
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _cell_label_and_target(cell: str) -> tuple[str, str | None]:
|
|
258
|
+
value = cell.strip()
|
|
259
|
+
for marker in ("**", "__"):
|
|
260
|
+
if value.startswith(marker) and value.endswith(marker):
|
|
261
|
+
value = value[len(marker) : -len(marker)].strip()
|
|
262
|
+
match = _LINK_CELL_RE.fullmatch(value)
|
|
263
|
+
if match is not None:
|
|
264
|
+
return _unwrap_formatting(match.group(1)), match.group(2)
|
|
265
|
+
return _unwrap_formatting(value), None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _table_rows(section_text: str, headers: set[str]) -> list[_TableRow]:
|
|
269
|
+
rows: list[_TableRow] = []
|
|
270
|
+
for line_number, line in enumerate(section_text.splitlines(), 1):
|
|
271
|
+
cells = _split_table_cells(line)
|
|
272
|
+
if not cells:
|
|
273
|
+
continue
|
|
274
|
+
if all(_TABLE_SEPARATOR_RE.fullmatch(cell.replace(" ", "")) for cell in cells):
|
|
275
|
+
continue
|
|
276
|
+
first_label, _ = _cell_label_and_target(cells[0])
|
|
277
|
+
if first_label.strip() in headers:
|
|
278
|
+
continue
|
|
279
|
+
rows.append(_TableRow(cells=cells, raw=line, line_number=line_number))
|
|
280
|
+
return rows
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _manifest_rows(
|
|
284
|
+
section_text: str,
|
|
285
|
+
*,
|
|
286
|
+
kind: str,
|
|
287
|
+
headers: set[str],
|
|
288
|
+
) -> tuple[list[_ManifestRow], list[str]]:
|
|
289
|
+
manifest_rows: list[_ManifestRow] = []
|
|
290
|
+
issues: list[str] = []
|
|
291
|
+
for row in _table_rows(section_text, headers):
|
|
292
|
+
label, target = _cell_label_and_target(row.cells[0])
|
|
293
|
+
if kind == "file":
|
|
294
|
+
if not label or label in {".", ".."} or "/" in label or "\\" in label:
|
|
295
|
+
issues.append(f"表格第 {row.line_number} 行文件名无效: {label!r}")
|
|
296
|
+
continue
|
|
297
|
+
name = label
|
|
298
|
+
else:
|
|
299
|
+
if not label.endswith("/"):
|
|
300
|
+
issues.append(
|
|
301
|
+
f"表格第 {row.line_number} 行子目录必须以 / 结尾: {label!r}"
|
|
302
|
+
)
|
|
303
|
+
continue
|
|
304
|
+
name = label[:-1]
|
|
305
|
+
if not name or name in {".", ".."} or "/" in name or "\\" in name:
|
|
306
|
+
issues.append(f"表格第 {row.line_number} 行子目录名无效: {label!r}")
|
|
307
|
+
continue
|
|
308
|
+
manifest_rows.append(_ManifestRow(name=name, row=row, link_target=target))
|
|
309
|
+
return manifest_rows, issues
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _is_below(path: Path, root: Path) -> bool:
|
|
313
|
+
try:
|
|
314
|
+
path.relative_to(root)
|
|
315
|
+
return True
|
|
316
|
+
except ValueError:
|
|
317
|
+
return False
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _path_text(value: str | os.PathLike[str], label: str) -> str:
|
|
321
|
+
raw = os.fspath(value)
|
|
322
|
+
if not isinstance(raw, str):
|
|
323
|
+
raise PathValidationError(f"{label}必须是文本路径")
|
|
324
|
+
if not raw or "\0" in raw:
|
|
325
|
+
raise PathValidationError(f"{label}为空或包含 NUL")
|
|
326
|
+
return raw
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _resolve_directory(value: str | os.PathLike[str], label: str) -> Path:
|
|
330
|
+
raw = _path_text(value, label)
|
|
331
|
+
try:
|
|
332
|
+
resolved = Path(raw).resolve(strict=True)
|
|
333
|
+
except (OSError, RuntimeError) as exc:
|
|
334
|
+
raise PathValidationError(f"{label}不存在或不可解析: {raw}") from exc
|
|
335
|
+
if not resolved.is_dir():
|
|
336
|
+
raise PathValidationError(f"{label}不是目录: {raw}")
|
|
337
|
+
return resolved
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _entry_is_link_like(entry: os.DirEntry[str]) -> bool:
|
|
341
|
+
"""True when a directory entry may redirect elsewhere (symlink/reparse point).
|
|
342
|
+
|
|
343
|
+
Plain entries inside an already-resolved directory cannot escape the project
|
|
344
|
+
root, so callers may skip the expensive ``resolve(strict=True)`` for them.
|
|
345
|
+
"""
|
|
346
|
+
if entry.is_symlink():
|
|
347
|
+
return True
|
|
348
|
+
try:
|
|
349
|
+
info = entry.stat(follow_symlinks=False)
|
|
350
|
+
except OSError:
|
|
351
|
+
return True # be conservative: an unreadable entry needs the full check
|
|
352
|
+
attributes = getattr(info, "st_file_attributes", 0)
|
|
353
|
+
return bool(attributes & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _infer_docs_root(candidate: Path) -> Path:
|
|
357
|
+
lexical = candidate if candidate.is_absolute() else Path.cwd() / candidate
|
|
358
|
+
lexical = lexical.absolute()
|
|
359
|
+
for parent in lexical.parents:
|
|
360
|
+
if parent.name == "project_docs" and parent.is_dir():
|
|
361
|
+
return parent.resolve(strict=True)
|
|
362
|
+
|
|
363
|
+
default_root = Path.cwd() / "project_docs"
|
|
364
|
+
if default_root.is_dir():
|
|
365
|
+
resolved_default = default_root.resolve(strict=True)
|
|
366
|
+
try:
|
|
367
|
+
candidate.resolve(strict=False).relative_to(resolved_default)
|
|
368
|
+
return resolved_default
|
|
369
|
+
except (OSError, RuntimeError, ValueError):
|
|
370
|
+
pass
|
|
371
|
+
raise PathValidationError(
|
|
372
|
+
"文档必须位于可识别的 project_docs 根目录内;请显式传入 --project-docs"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _candidate_under_root(raw: str, root: Path) -> Path:
|
|
377
|
+
supplied = Path(raw)
|
|
378
|
+
if supplied.is_absolute():
|
|
379
|
+
return supplied
|
|
380
|
+
|
|
381
|
+
cwd_candidate = Path.cwd() / supplied
|
|
382
|
+
try:
|
|
383
|
+
if _is_below(cwd_candidate.resolve(strict=False), root):
|
|
384
|
+
return cwd_candidate
|
|
385
|
+
except (OSError, RuntimeError):
|
|
386
|
+
pass
|
|
387
|
+
|
|
388
|
+
portable = raw.replace("\\", "/")
|
|
389
|
+
pure = PurePosixPath(portable)
|
|
390
|
+
if pure.parts and pure.parts[0] == root.name:
|
|
391
|
+
pure = PurePosixPath(*pure.parts[1:])
|
|
392
|
+
return root.joinpath(*pure.parts)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _resolve_document(
|
|
396
|
+
doc_path: str | os.PathLike[str],
|
|
397
|
+
project_docs_dir: str | os.PathLike[str] | None,
|
|
398
|
+
) -> tuple[Path, Path, str]:
|
|
399
|
+
raw = _path_text(doc_path, "文档路径")
|
|
400
|
+
root = (
|
|
401
|
+
_resolve_directory(project_docs_dir, "project_docs 根目录")
|
|
402
|
+
if project_docs_dir is not None
|
|
403
|
+
else _infer_docs_root(Path(raw))
|
|
404
|
+
)
|
|
405
|
+
candidate = _candidate_under_root(raw, root)
|
|
406
|
+
try:
|
|
407
|
+
lexical_resolved = candidate.resolve(strict=False)
|
|
408
|
+
except (OSError, RuntimeError) as exc:
|
|
409
|
+
raise PathValidationError(f"文档不可解析: {raw}") from exc
|
|
410
|
+
if not _is_below(lexical_resolved, root):
|
|
411
|
+
raise PathValidationError(f"文档路径越界: {raw}")
|
|
412
|
+
try:
|
|
413
|
+
resolved = candidate.resolve(strict=True)
|
|
414
|
+
except FileNotFoundError:
|
|
415
|
+
raise
|
|
416
|
+
except (OSError, RuntimeError) as exc:
|
|
417
|
+
raise PathValidationError(f"文档不可解析: {raw}") from exc
|
|
418
|
+
if not resolved.is_file():
|
|
419
|
+
raise PathValidationError(f"文档不是普通文件: {raw}")
|
|
420
|
+
if not _is_below(resolved, root):
|
|
421
|
+
raise PathValidationError(f"文档路径越界: {raw}")
|
|
422
|
+
relative = resolved.relative_to(root).as_posix()
|
|
423
|
+
validate_manifest_relative_path(relative)
|
|
424
|
+
return resolved, root, relative
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _resolve_source_directory(
|
|
428
|
+
source_dir: str | os.PathLike[str],
|
|
429
|
+
project_root: Path,
|
|
430
|
+
docs_root: Path,
|
|
431
|
+
) -> Path:
|
|
432
|
+
raw = _path_text(source_dir, "源目录")
|
|
433
|
+
supplied = Path(raw)
|
|
434
|
+
candidate = supplied if supplied.is_absolute() else Path.cwd() / supplied
|
|
435
|
+
try:
|
|
436
|
+
cwd_resolved = candidate.resolve(strict=True)
|
|
437
|
+
except (OSError, RuntimeError):
|
|
438
|
+
cwd_resolved = None
|
|
439
|
+
|
|
440
|
+
if supplied.is_absolute():
|
|
441
|
+
try:
|
|
442
|
+
lexical_resolved = supplied.resolve(strict=False)
|
|
443
|
+
except (OSError, RuntimeError) as exc:
|
|
444
|
+
raise PathValidationError(f"源目录不可解析: {raw}") from exc
|
|
445
|
+
if not _is_below(lexical_resolved, project_root):
|
|
446
|
+
raise PathValidationError(f"源目录越过项目根目录: {raw}")
|
|
447
|
+
elif cwd_resolved is None or not _is_below(cwd_resolved, project_root):
|
|
448
|
+
portable = PurePosixPath(raw.replace("\\", "/"))
|
|
449
|
+
if portable.parts and portable.parts[0] == project_root.name:
|
|
450
|
+
portable = PurePosixPath(*portable.parts[1:])
|
|
451
|
+
candidate = project_root.joinpath(*portable.parts)
|
|
452
|
+
|
|
453
|
+
try:
|
|
454
|
+
resolved = candidate.resolve(strict=True)
|
|
455
|
+
except (OSError, RuntimeError) as exc:
|
|
456
|
+
raise PathValidationError(f"源目录不存在或不可解析: {raw}") from exc
|
|
457
|
+
if not resolved.is_dir():
|
|
458
|
+
raise PathValidationError(f"源目录不是目录: {raw}")
|
|
459
|
+
if not _is_below(resolved, project_root):
|
|
460
|
+
raise PathValidationError(f"源目录越过项目根目录: {raw}")
|
|
461
|
+
if _is_below(resolved, docs_root):
|
|
462
|
+
raise PathValidationError(f"源目录不能位于 project_docs 内: {raw}")
|
|
463
|
+
return resolved
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _source_inventory(
|
|
467
|
+
source_dir: Path,
|
|
468
|
+
project_root: Path,
|
|
469
|
+
*,
|
|
470
|
+
config: proj_doc_config.ProjectDocConfig | None = None,
|
|
471
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
|
472
|
+
files: list[str] = []
|
|
473
|
+
subdirs: list[str] = []
|
|
474
|
+
effective_config = (
|
|
475
|
+
config
|
|
476
|
+
if config is not None
|
|
477
|
+
else proj_doc_config.load_project_config(project_root)
|
|
478
|
+
)
|
|
479
|
+
try:
|
|
480
|
+
entries = sorted(source_dir.iterdir(), key=lambda item: item.name)
|
|
481
|
+
except OSError as exc:
|
|
482
|
+
raise PathValidationError(f"无法读取源目录: {source_dir}") from exc
|
|
483
|
+
|
|
484
|
+
for entry in entries:
|
|
485
|
+
name = entry.name
|
|
486
|
+
if name.startswith("."):
|
|
487
|
+
continue
|
|
488
|
+
# ``source_dir`` is already resolved and verified to sit under
|
|
489
|
+
# ``project_root``; a plain entry (neither symlink nor reparse point)
|
|
490
|
+
# therefore cannot escape the project, so the per-entry
|
|
491
|
+
# ``resolve(strict=True)`` syscall is only needed for link-like entries.
|
|
492
|
+
if _entry_is_link_like(entry):
|
|
493
|
+
try:
|
|
494
|
+
resolved = entry.resolve(strict=True)
|
|
495
|
+
except (OSError, RuntimeError) as exc:
|
|
496
|
+
raise PathValidationError(f"源目录项不可解析: {entry}") from exc
|
|
497
|
+
if not _is_below(resolved, project_root):
|
|
498
|
+
raise PathValidationError(f"源目录项越过项目根目录: {entry}")
|
|
499
|
+
is_file = resolved.is_file()
|
|
500
|
+
is_dir = resolved.is_dir()
|
|
501
|
+
else:
|
|
502
|
+
resolved = source_dir / name
|
|
503
|
+
is_file = entry.is_file()
|
|
504
|
+
is_dir = entry.is_dir()
|
|
505
|
+
if is_file:
|
|
506
|
+
if source_dir == project_root and name.casefold() == "claude.md":
|
|
507
|
+
continue
|
|
508
|
+
files.append(name)
|
|
509
|
+
elif is_dir:
|
|
510
|
+
rel_posix = resolved.relative_to(project_root).as_posix()
|
|
511
|
+
if name not in EXCLUDED_SOURCE_DIRS and not proj_doc_config.should_exclude_directory(
|
|
512
|
+
name,
|
|
513
|
+
rel_posix,
|
|
514
|
+
config=effective_config,
|
|
515
|
+
):
|
|
516
|
+
subdirs.append(name)
|
|
517
|
+
return tuple(files), tuple(subdirs)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _content_is_placeholder(content: str) -> bool:
|
|
521
|
+
status = _section(content, "状态") or ""
|
|
522
|
+
return "⬜" in status or "占位目录" in content or "当前为占位" in content
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _source_is_placeholder(
|
|
526
|
+
files: tuple[str, ...] | None,
|
|
527
|
+
subdirs: tuple[str, ...] | None,
|
|
528
|
+
) -> bool | None:
|
|
529
|
+
if files is None or subdirs is None:
|
|
530
|
+
return None
|
|
531
|
+
return proj_doc_config.is_placeholder_directory(files, subdirs)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _select_profile(
|
|
535
|
+
requested: str,
|
|
536
|
+
content: str,
|
|
537
|
+
files: tuple[str, ...] | None,
|
|
538
|
+
subdirs: tuple[str, ...] | None,
|
|
539
|
+
) -> tuple[str, str | None]:
|
|
540
|
+
if requested not in PROFILES:
|
|
541
|
+
raise ValueError(f"未知 profile: {requested!r}")
|
|
542
|
+
source_placeholder = _source_is_placeholder(files, subdirs)
|
|
543
|
+
mismatch: str | None = None
|
|
544
|
+
|
|
545
|
+
if requested == PROFILE_AUTO:
|
|
546
|
+
if source_placeholder is not None:
|
|
547
|
+
profile = PROFILE_PLACEHOLDER if source_placeholder else PROFILE_STANDARD
|
|
548
|
+
else:
|
|
549
|
+
profile = (
|
|
550
|
+
PROFILE_PLACEHOLDER
|
|
551
|
+
if _content_is_placeholder(content)
|
|
552
|
+
else PROFILE_STANDARD
|
|
553
|
+
)
|
|
554
|
+
else:
|
|
555
|
+
profile = requested
|
|
556
|
+
|
|
557
|
+
if profile == PROFILE_PLACEHOLDER and source_placeholder is False:
|
|
558
|
+
mismatch = "placeholder profile 与含实质文件或子目录的源目录不一致"
|
|
559
|
+
return profile, mismatch
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _resolve_virtual_source_directory(
|
|
563
|
+
source_dir: str | os.PathLike[str],
|
|
564
|
+
project_root: Path,
|
|
565
|
+
docs_root: Path,
|
|
566
|
+
) -> Path:
|
|
567
|
+
raw = os.fspath(source_dir)
|
|
568
|
+
if not raw or "\0" in raw:
|
|
569
|
+
raise PathValidationError("源目录为空或包含 NUL 字节")
|
|
570
|
+
supplied = Path(raw)
|
|
571
|
+
if supplied.is_absolute():
|
|
572
|
+
candidate = Path(os.path.normpath(str(supplied)))
|
|
573
|
+
else:
|
|
574
|
+
portable = PurePosixPath(raw.replace("\\", "/"))
|
|
575
|
+
if portable.parts and portable.parts[0] == project_root.name:
|
|
576
|
+
portable = PurePosixPath(*portable.parts[1:])
|
|
577
|
+
candidate = Path(os.path.normpath(str(project_root.joinpath(*portable.parts))))
|
|
578
|
+
if not _is_below(candidate, project_root):
|
|
579
|
+
raise PathValidationError(f"源目录越过项目根目录: {raw}")
|
|
580
|
+
if _is_below(candidate, docs_root):
|
|
581
|
+
raise PathValidationError(f"源目录不能位于 project_docs 内: {raw}")
|
|
582
|
+
return candidate
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _build_context(
|
|
586
|
+
doc_path: str | os.PathLike[str],
|
|
587
|
+
source_dir: str | os.PathLike[str] | None,
|
|
588
|
+
*,
|
|
589
|
+
profile: str,
|
|
590
|
+
project_docs_dir: str | os.PathLike[str] | None,
|
|
591
|
+
project_root: str | os.PathLike[str] | None,
|
|
592
|
+
source_inventory: tuple[Sequence[str], Sequence[str]] | None = None,
|
|
593
|
+
project_config: proj_doc_config.ProjectDocConfig | None = None,
|
|
594
|
+
) -> tuple[_ValidationContext, str]:
|
|
595
|
+
resolved_doc, docs_root, relative_doc = _resolve_document(
|
|
596
|
+
doc_path, project_docs_dir
|
|
597
|
+
)
|
|
598
|
+
content = read_utf8(resolved_doc)
|
|
599
|
+
|
|
600
|
+
resolved_project_root = (
|
|
601
|
+
_resolve_directory(project_root, "项目根目录")
|
|
602
|
+
if project_root is not None
|
|
603
|
+
else docs_root.parent
|
|
604
|
+
)
|
|
605
|
+
if not _is_below(docs_root, resolved_project_root):
|
|
606
|
+
raise PathValidationError("project_docs 根目录越过项目根目录")
|
|
607
|
+
|
|
608
|
+
effective_config = (
|
|
609
|
+
project_config
|
|
610
|
+
if project_config is not None
|
|
611
|
+
else proj_doc_config.load_project_config(resolved_project_root)
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
resolved_source: Path | None = None
|
|
615
|
+
source_files: tuple[str, ...] | None = None
|
|
616
|
+
source_subdirs: tuple[str, ...] | None = None
|
|
617
|
+
virtual_source = False
|
|
618
|
+
raw_source_files: tuple[str, ...] | None = None
|
|
619
|
+
if source_inventory is not None:
|
|
620
|
+
if source_dir is None:
|
|
621
|
+
raise PathValidationError("提供 source_inventory 时必须同时提供 source_dir")
|
|
622
|
+
resolved_source = _resolve_virtual_source_directory(
|
|
623
|
+
source_dir,
|
|
624
|
+
resolved_project_root,
|
|
625
|
+
docs_root,
|
|
626
|
+
)
|
|
627
|
+
raw_source_files = tuple(sorted(str(name) for name in source_inventory[0]))
|
|
628
|
+
is_root_dir = resolved_source == resolved_project_root
|
|
629
|
+
source_files = tuple(
|
|
630
|
+
name
|
|
631
|
+
for name in raw_source_files
|
|
632
|
+
if not name.startswith(".")
|
|
633
|
+
and not (is_root_dir and name.casefold() == "claude.md")
|
|
634
|
+
)
|
|
635
|
+
rel_dir = (
|
|
636
|
+
""
|
|
637
|
+
if is_root_dir
|
|
638
|
+
else resolved_source.relative_to(resolved_project_root).as_posix()
|
|
639
|
+
)
|
|
640
|
+
filtered_subdirs: list[str] = []
|
|
641
|
+
for raw_sub in sorted(str(name) for name in source_inventory[1]):
|
|
642
|
+
if raw_sub.startswith(".") or raw_sub in EXCLUDED_SOURCE_DIRS:
|
|
643
|
+
continue
|
|
644
|
+
child_rel = raw_sub if not rel_dir else f"{rel_dir}/{raw_sub}"
|
|
645
|
+
if proj_doc_config.should_exclude_directory(
|
|
646
|
+
raw_sub,
|
|
647
|
+
child_rel,
|
|
648
|
+
config=effective_config,
|
|
649
|
+
):
|
|
650
|
+
continue
|
|
651
|
+
filtered_subdirs.append(raw_sub)
|
|
652
|
+
source_subdirs = tuple(filtered_subdirs)
|
|
653
|
+
virtual_source = True
|
|
654
|
+
elif source_dir is not None:
|
|
655
|
+
resolved_source = _resolve_source_directory(
|
|
656
|
+
source_dir,
|
|
657
|
+
resolved_project_root,
|
|
658
|
+
docs_root,
|
|
659
|
+
)
|
|
660
|
+
source_files, source_subdirs = _source_inventory(
|
|
661
|
+
resolved_source,
|
|
662
|
+
resolved_project_root,
|
|
663
|
+
config=effective_config,
|
|
664
|
+
)
|
|
665
|
+
raw_source_files = source_files
|
|
666
|
+
|
|
667
|
+
is_boundary = (
|
|
668
|
+
resolved_source is not None
|
|
669
|
+
and resolved_source != resolved_project_root
|
|
670
|
+
and raw_source_files is not None
|
|
671
|
+
and any(name.casefold() == "claude.md" for name in raw_source_files)
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
selected_profile, mismatch = _select_profile(
|
|
675
|
+
profile,
|
|
676
|
+
content,
|
|
677
|
+
source_files,
|
|
678
|
+
source_subdirs,
|
|
679
|
+
)
|
|
680
|
+
return (
|
|
681
|
+
_ValidationContext(
|
|
682
|
+
doc_path=resolved_doc,
|
|
683
|
+
docs_root=docs_root,
|
|
684
|
+
doc_relative=relative_doc,
|
|
685
|
+
project_root=resolved_project_root,
|
|
686
|
+
source_dir=resolved_source,
|
|
687
|
+
source_files=source_files,
|
|
688
|
+
source_subdirs=source_subdirs,
|
|
689
|
+
profile=selected_profile,
|
|
690
|
+
profile_mismatch=mismatch,
|
|
691
|
+
virtual_source=virtual_source,
|
|
692
|
+
is_boundary=is_boundary,
|
|
693
|
+
project_config=effective_config,
|
|
694
|
+
),
|
|
695
|
+
content,
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _legacy_inventory(
|
|
700
|
+
source_dir: str | os.PathLike[str] | None,
|
|
701
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]] | None:
|
|
702
|
+
if source_dir is None:
|
|
703
|
+
return None
|
|
704
|
+
source = _resolve_directory(source_dir, "源目录")
|
|
705
|
+
return _source_inventory(source, source)
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def _inventory_for_check(
|
|
709
|
+
source_dir: str | os.PathLike[str] | None,
|
|
710
|
+
context: _ValidationContext | None,
|
|
711
|
+
) -> tuple[tuple[str, ...], tuple[str, ...]] | None:
|
|
712
|
+
if context is not None:
|
|
713
|
+
if context.source_files is None or context.source_subdirs is None:
|
|
714
|
+
return None
|
|
715
|
+
return context.source_files, context.source_subdirs
|
|
716
|
+
return _legacy_inventory(source_dir)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _duplicates(values: Sequence[str]) -> list[str]:
|
|
720
|
+
seen: set[str] = set()
|
|
721
|
+
duplicates: set[str] = set()
|
|
722
|
+
for value in values:
|
|
723
|
+
if value in seen:
|
|
724
|
+
duplicates.add(value)
|
|
725
|
+
seen.add(value)
|
|
726
|
+
return sorted(duplicates)
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _decode_source_link_target(target: str, context: _ValidationContext) -> Path:
|
|
730
|
+
cleaned = target.strip()
|
|
731
|
+
if cleaned.startswith("<") or cleaned.endswith(">"):
|
|
732
|
+
if not (cleaned.startswith("<") and cleaned.endswith(">")):
|
|
733
|
+
raise PathValidationError("文件链接的尖括号不匹配")
|
|
734
|
+
cleaned = cleaned[1:-1].strip()
|
|
735
|
+
path_text = cleaned.partition("#")[0].partition("?")[0]
|
|
736
|
+
if not path_text or _INVALID_PERCENT_RE.search(path_text):
|
|
737
|
+
raise PathValidationError("文件链接为空或包含非法百分号转义")
|
|
738
|
+
try:
|
|
739
|
+
decoded = unquote(path_text, encoding="utf-8", errors="strict")
|
|
740
|
+
except UnicodeDecodeError as exc:
|
|
741
|
+
raise PathValidationError("文件链接包含非 UTF-8 转义") from exc
|
|
742
|
+
if (
|
|
743
|
+
"\0" in decoded
|
|
744
|
+
or "\\" in decoded
|
|
745
|
+
or decoded.startswith("/")
|
|
746
|
+
or decoded.startswith("//")
|
|
747
|
+
or _URI_SCHEME_RE.match(decoded)
|
|
748
|
+
or PureWindowsPath(decoded).drive
|
|
749
|
+
):
|
|
750
|
+
raise PathValidationError("文件链接不是安全的项目内相对路径")
|
|
751
|
+
if context.virtual_source:
|
|
752
|
+
resolved = Path(
|
|
753
|
+
os.path.normpath(
|
|
754
|
+
str(context.doc_path.parent.joinpath(*PurePosixPath(decoded).parts))
|
|
755
|
+
)
|
|
756
|
+
)
|
|
757
|
+
if not _is_below(resolved, context.project_root):
|
|
758
|
+
raise PathValidationError("文件链接目标越过项目根目录")
|
|
759
|
+
return resolved
|
|
760
|
+
try:
|
|
761
|
+
resolved = context.doc_path.parent.joinpath(
|
|
762
|
+
*PurePosixPath(decoded).parts
|
|
763
|
+
).resolve(strict=True)
|
|
764
|
+
except (OSError, RuntimeError) as exc:
|
|
765
|
+
raise PathValidationError("文件链接目标不存在或不可解析") from exc
|
|
766
|
+
if not _is_below(resolved, context.project_root):
|
|
767
|
+
raise PathValidationError("文件链接目标越过项目根目录")
|
|
768
|
+
return resolved
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def _validate_file_row_links(
|
|
772
|
+
rows: Sequence[_ManifestRow],
|
|
773
|
+
context: _ValidationContext,
|
|
774
|
+
) -> list[str]:
|
|
775
|
+
if context.source_dir is None:
|
|
776
|
+
return []
|
|
777
|
+
issues: list[str] = []
|
|
778
|
+
known_files = set(context.source_files or ())
|
|
779
|
+
for item in rows:
|
|
780
|
+
if item.link_target is None:
|
|
781
|
+
continue
|
|
782
|
+
try:
|
|
783
|
+
actual_target = _decode_source_link_target(item.link_target, context)
|
|
784
|
+
if context.virtual_source:
|
|
785
|
+
if item.name not in known_files:
|
|
786
|
+
raise PathValidationError("文件链接目标不存在或不可解析")
|
|
787
|
+
expected_target = Path(
|
|
788
|
+
os.path.normpath(str(context.source_dir / item.name))
|
|
789
|
+
)
|
|
790
|
+
else:
|
|
791
|
+
expected_target = (context.source_dir / item.name).resolve(strict=True)
|
|
792
|
+
except (OSError, ProjectDocsContractError, ValueError) as exc:
|
|
793
|
+
issues.append(f"文件 {item.name!r} 的链接无效: {exc}")
|
|
794
|
+
continue
|
|
795
|
+
if actual_target != expected_target:
|
|
796
|
+
issues.append(f"文件 {item.name!r} 的链接未指向对应源码文件")
|
|
797
|
+
return issues
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def check_1_file_table(
|
|
801
|
+
content: str,
|
|
802
|
+
source_dir: str | os.PathLike[str] | None,
|
|
803
|
+
*,
|
|
804
|
+
context: _ValidationContext | None = None,
|
|
805
|
+
) -> tuple[bool, str]:
|
|
806
|
+
"""Check that the file manifest exactly matches immediate source files."""
|
|
807
|
+
|
|
808
|
+
section_text = _section(content, "文件清单")
|
|
809
|
+
if section_text is None:
|
|
810
|
+
return False, "缺少 ## 文件清单 段"
|
|
811
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
812
|
+
if inventory is None:
|
|
813
|
+
return False, "未提供源目录,无法精确核验文件清单"
|
|
814
|
+
|
|
815
|
+
rows, issues = _manifest_rows(
|
|
816
|
+
section_text,
|
|
817
|
+
kind="file",
|
|
818
|
+
headers={"文件", "文件名"},
|
|
819
|
+
)
|
|
820
|
+
actual_files = set(inventory[0])
|
|
821
|
+
listed_names = [row.name for row in rows]
|
|
822
|
+
duplicate_names = _duplicates(listed_names)
|
|
823
|
+
missing = sorted(actual_files - set(listed_names))
|
|
824
|
+
extra = sorted(set(listed_names) - actual_files)
|
|
825
|
+
if duplicate_names:
|
|
826
|
+
issues.append(f"重复文件: {', '.join(duplicate_names)}")
|
|
827
|
+
if missing:
|
|
828
|
+
issues.append(f"遗漏文件: {', '.join(missing)}")
|
|
829
|
+
if extra:
|
|
830
|
+
issues.append(f"多余文件: {', '.join(extra)}")
|
|
831
|
+
if context is not None:
|
|
832
|
+
issues.extend(_validate_file_row_links(rows, context))
|
|
833
|
+
if issues:
|
|
834
|
+
return False, "; ".join(issues)
|
|
835
|
+
return True, f"文件清单与源目录精确一致({len(actual_files)} 个文件)"
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def check_2_overview(
|
|
839
|
+
content: str,
|
|
840
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
841
|
+
*,
|
|
842
|
+
context: _ValidationContext | None = None,
|
|
843
|
+
) -> tuple[bool, str]:
|
|
844
|
+
"""Check profile-specific overview requirements."""
|
|
845
|
+
|
|
846
|
+
del source_dir
|
|
847
|
+
section_text = _section(content, "概述")
|
|
848
|
+
if not section_text:
|
|
849
|
+
return False, "缺少 ## 概述 段"
|
|
850
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
851
|
+
sentences = _sentence_count(section_text)
|
|
852
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
853
|
+
if sentences < 1 or "占位" not in _strip_markdown(section_text):
|
|
854
|
+
return False, "placeholder 概述需明确说明占位状态"
|
|
855
|
+
return True, f"placeholder 概述 {sentences} 句话"
|
|
856
|
+
if sentences < 8:
|
|
857
|
+
return False, f"标准概述为 {sentences} 句话(v4.5 起需 ≥8 句)"
|
|
858
|
+
return True, f"标准概述 {sentences} 句话"
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _valid_placeholder_role_link(
|
|
862
|
+
section_text: str,
|
|
863
|
+
context: _ValidationContext | None,
|
|
864
|
+
) -> tuple[bool, str | None]:
|
|
865
|
+
if context is None:
|
|
866
|
+
return False, None
|
|
867
|
+
links = parse_markdown_links(
|
|
868
|
+
section_text,
|
|
869
|
+
source_doc=context.doc_path,
|
|
870
|
+
docs_root=context.docs_root,
|
|
871
|
+
)
|
|
872
|
+
if not links:
|
|
873
|
+
return False, None
|
|
874
|
+
for link in links:
|
|
875
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
876
|
+
return False, f"系统角色链接不安全: {link.raw_target}"
|
|
877
|
+
if link.disposition is LinkDisposition.LOCAL_DOCUMENT and link.exists is False:
|
|
878
|
+
return False, f"系统角色链接不存在: {link.raw_target}"
|
|
879
|
+
return (
|
|
880
|
+
any(
|
|
881
|
+
link.disposition is LinkDisposition.LOCAL_DOCUMENT and link.exists
|
|
882
|
+
for link in links
|
|
883
|
+
),
|
|
884
|
+
None,
|
|
885
|
+
)
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def check_3_system_role(
|
|
889
|
+
content: str,
|
|
890
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
891
|
+
*,
|
|
892
|
+
context: _ValidationContext | None = None,
|
|
893
|
+
) -> tuple[bool, str]:
|
|
894
|
+
"""Check that system-role prose is substantive for its profile."""
|
|
895
|
+
|
|
896
|
+
del source_dir
|
|
897
|
+
section_text = _section(content, "系统角色")
|
|
898
|
+
if not section_text:
|
|
899
|
+
return False, "缺少 ## 系统角色 段"
|
|
900
|
+
clean = _strip_markdown(section_text)
|
|
901
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
902
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
903
|
+
has_valid_link, link_error = _valid_placeholder_role_link(section_text, context)
|
|
904
|
+
if link_error:
|
|
905
|
+
return False, link_error
|
|
906
|
+
if has_valid_link or len(clean) >= 8:
|
|
907
|
+
return True, "placeholder 系统角色已提供简要定位或父文档链接"
|
|
908
|
+
return False, "placeholder 系统角色为空或缺少有效父文档链接"
|
|
909
|
+
|
|
910
|
+
if len(clean) < 50:
|
|
911
|
+
return False, f"系统角色过于简短({len(clean)} 字符,需 >= 50)"
|
|
912
|
+
val_cfg = (
|
|
913
|
+
context.project_config.validation
|
|
914
|
+
if context is not None
|
|
915
|
+
else proj_doc_config.DEFAULT_CONFIG.validation
|
|
916
|
+
)
|
|
917
|
+
architecture_terms = (
|
|
918
|
+
val_cfg.architecture_terms
|
|
919
|
+
if val_cfg.architecture_terms
|
|
920
|
+
else DEFAULT_ARCHITECTURE_TERMS + val_cfg.extra_architecture_terms
|
|
921
|
+
)
|
|
922
|
+
relation_terms = (
|
|
923
|
+
val_cfg.relation_terms
|
|
924
|
+
if val_cfg.relation_terms
|
|
925
|
+
else DEFAULT_RELATION_TERMS + val_cfg.extra_relation_terms
|
|
926
|
+
)
|
|
927
|
+
backtick_entities = set(re.findall(r"`([^`\r\n]+)`", section_text))
|
|
928
|
+
has_arch = any(term in clean for term in architecture_terms) or (
|
|
929
|
+
len(backtick_entities) >= 2
|
|
930
|
+
)
|
|
931
|
+
if not has_arch:
|
|
932
|
+
return False, "系统角色未说明所属子系统、协议层或模块"
|
|
933
|
+
if not any(term in clean for term in relation_terms):
|
|
934
|
+
return False, "系统角色未说明输入输出、依赖或上下游协作关系"
|
|
935
|
+
return True, f"系统角色包含实质架构定位与协作关系({len(clean)} 字符)"
|
|
936
|
+
|
|
937
|
+
|
|
938
|
+
def _expected_child_doc(context: _ValidationContext, child_name: str) -> str:
|
|
939
|
+
if context.doc_relative in ("index.md", ""):
|
|
940
|
+
return f"{child_name}.md"
|
|
941
|
+
current_without_suffix = context.doc_relative[: -len(".md")]
|
|
942
|
+
return PurePosixPath(current_without_suffix, f"{child_name}.md").as_posix()
|
|
943
|
+
|
|
944
|
+
|
|
945
|
+
def _validate_subdir_links(
|
|
946
|
+
rows: Sequence[_ManifestRow],
|
|
947
|
+
context: _ValidationContext,
|
|
948
|
+
) -> list[str]:
|
|
949
|
+
issues: list[str] = []
|
|
950
|
+
for item in rows:
|
|
951
|
+
links = parse_markdown_links(
|
|
952
|
+
item.row.raw,
|
|
953
|
+
source_doc=context.doc_path,
|
|
954
|
+
docs_root=context.docs_root,
|
|
955
|
+
)
|
|
956
|
+
if len(links) != 1:
|
|
957
|
+
issues.append(f"子目录 {item.name!r} 必须且只能有一个 Markdown 文档链接")
|
|
958
|
+
continue
|
|
959
|
+
link = links[0]
|
|
960
|
+
expected = _expected_child_doc(context, item.name)
|
|
961
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
962
|
+
issues.append(f"子目录 {item.name!r} 链接不安全: {link.reason}")
|
|
963
|
+
elif link.disposition is not LinkDisposition.LOCAL_DOCUMENT:
|
|
964
|
+
issues.append(f"子目录 {item.name!r} 未链接本地 Markdown 文档")
|
|
965
|
+
elif link.project_relative_path != expected:
|
|
966
|
+
issues.append(
|
|
967
|
+
f"子目录 {item.name!r} 链接目标错误: "
|
|
968
|
+
f"{link.project_relative_path!r},应为 {expected!r}"
|
|
969
|
+
)
|
|
970
|
+
elif link.exists is not True:
|
|
971
|
+
issues.append(f"子目录 {item.name!r} 文档不存在: {expected}")
|
|
972
|
+
return issues
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
def check_4_subdir_table(
|
|
976
|
+
content: str,
|
|
977
|
+
source_dir: str | os.PathLike[str] | None,
|
|
978
|
+
*,
|
|
979
|
+
context: _ValidationContext | None = None,
|
|
980
|
+
) -> tuple[bool, str]:
|
|
981
|
+
"""Check source subdirectories and their exact Markdown document links."""
|
|
982
|
+
|
|
983
|
+
if context is not None and context.is_boundary:
|
|
984
|
+
return True, "N/A(boundary 目录,子目录不在同步范围)"
|
|
985
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
986
|
+
if inventory is None:
|
|
987
|
+
return False, "未提供源目录,无法精确核验子目录清单"
|
|
988
|
+
actual_subdirs = set(inventory[1])
|
|
989
|
+
section_text = _section_any(content, ("子目录", "子目录清单"))
|
|
990
|
+
if section_text is None:
|
|
991
|
+
if actual_subdirs:
|
|
992
|
+
return False, f"有 {len(actual_subdirs)} 个子目录但缺少 ## 子目录 段"
|
|
993
|
+
return True, "N/A(源目录无子目录)"
|
|
994
|
+
|
|
995
|
+
rows, issues = _manifest_rows(
|
|
996
|
+
section_text,
|
|
997
|
+
kind="subdir",
|
|
998
|
+
headers={"子目录", "目录"},
|
|
999
|
+
)
|
|
1000
|
+
listed_names = [row.name for row in rows]
|
|
1001
|
+
duplicate_names = _duplicates(listed_names)
|
|
1002
|
+
missing = sorted(actual_subdirs - set(listed_names))
|
|
1003
|
+
extra = sorted(set(listed_names) - actual_subdirs)
|
|
1004
|
+
if duplicate_names:
|
|
1005
|
+
issues.append(f"重复子目录: {', '.join(duplicate_names)}")
|
|
1006
|
+
if missing:
|
|
1007
|
+
issues.append(f"遗漏子目录: {', '.join(missing)}")
|
|
1008
|
+
if extra:
|
|
1009
|
+
issues.append(f"多余子目录: {', '.join(extra)}")
|
|
1010
|
+
if context is not None:
|
|
1011
|
+
issues.extend(_validate_subdir_links(rows, context))
|
|
1012
|
+
elif actual_subdirs:
|
|
1013
|
+
issues.append("缺少文档上下文,无法精确核验子目录 Markdown 链接")
|
|
1014
|
+
if issues:
|
|
1015
|
+
return False, "; ".join(issues)
|
|
1016
|
+
if not actual_subdirs:
|
|
1017
|
+
return True, "N/A(源目录无子目录)"
|
|
1018
|
+
return True, f"子目录清单及链接精确一致({len(actual_subdirs)} 个子目录)"
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def check_5_status(
|
|
1022
|
+
content: str,
|
|
1023
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1024
|
+
*,
|
|
1025
|
+
context: _ValidationContext | None = None,
|
|
1026
|
+
) -> tuple[bool, str]:
|
|
1027
|
+
"""Check status marker and profile consistency."""
|
|
1028
|
+
|
|
1029
|
+
del source_dir
|
|
1030
|
+
section_text = _section(content, "状态")
|
|
1031
|
+
if not section_text:
|
|
1032
|
+
return False, "缺少 ## 状态 段"
|
|
1033
|
+
if context is not None and context.profile_mismatch:
|
|
1034
|
+
return False, context.profile_mismatch
|
|
1035
|
+
icons = [icon for icon in STATUS_ICONS if icon in section_text]
|
|
1036
|
+
if len(icons) != 1:
|
|
1037
|
+
return False, f"状态段必须且只能包含一个有效图标({'/'.join(STATUS_ICONS)})"
|
|
1038
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
1039
|
+
icon = icons[0]
|
|
1040
|
+
if profile == PROFILE_PLACEHOLDER and icon != "⬜":
|
|
1041
|
+
return False, "placeholder profile 必须使用 ⬜ 占位状态"
|
|
1042
|
+
if profile == PROFILE_STANDARD and icon == "⬜":
|
|
1043
|
+
return False, "standard profile 不能使用 ⬜ 占位状态"
|
|
1044
|
+
return True, f"状态与 {profile} profile 一致: {icon}"
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def _collect_ast_symbols(
|
|
1048
|
+
stmts: Sequence[ast.stmt],
|
|
1049
|
+
symbols: set[str],
|
|
1050
|
+
*,
|
|
1051
|
+
inside_class: bool = False,
|
|
1052
|
+
) -> None:
|
|
1053
|
+
"""Collect module top-level definitions, class members, and imports without entering function bodies."""
|
|
1054
|
+
|
|
1055
|
+
for node in stmts:
|
|
1056
|
+
if isinstance(node, ast.ClassDef):
|
|
1057
|
+
symbols.add(node.name)
|
|
1058
|
+
_collect_ast_symbols(node.body, symbols, inside_class=True)
|
|
1059
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
1060
|
+
symbols.add(node.name)
|
|
1061
|
+
elif isinstance(node, ast.Assign):
|
|
1062
|
+
for target in node.targets:
|
|
1063
|
+
if isinstance(target, ast.Name):
|
|
1064
|
+
symbols.add(target.id)
|
|
1065
|
+
if not inside_class and target.id == "__all__":
|
|
1066
|
+
if isinstance(node.value, (ast.List, ast.Tuple, ast.Set)):
|
|
1067
|
+
for elt in node.value.elts:
|
|
1068
|
+
if isinstance(elt, ast.Constant) and isinstance(
|
|
1069
|
+
elt.value, str
|
|
1070
|
+
):
|
|
1071
|
+
symbols.add(elt.value)
|
|
1072
|
+
elif isinstance(node, ast.AnnAssign):
|
|
1073
|
+
if isinstance(node.target, ast.Name):
|
|
1074
|
+
symbols.add(node.target.id)
|
|
1075
|
+
elif isinstance(node, ast.Import):
|
|
1076
|
+
for alias in node.names:
|
|
1077
|
+
name = alias.asname or alias.name.split(".")[0]
|
|
1078
|
+
if name and name != "*":
|
|
1079
|
+
symbols.add(name)
|
|
1080
|
+
elif isinstance(node, ast.ImportFrom):
|
|
1081
|
+
for alias in node.names:
|
|
1082
|
+
name = alias.asname or alias.name
|
|
1083
|
+
if name and name != "*":
|
|
1084
|
+
symbols.add(name)
|
|
1085
|
+
elif isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While)):
|
|
1086
|
+
_collect_ast_symbols(node.body, symbols, inside_class=inside_class)
|
|
1087
|
+
_collect_ast_symbols(node.orelse, symbols, inside_class=inside_class)
|
|
1088
|
+
elif isinstance(node, (ast.With, ast.AsyncWith)):
|
|
1089
|
+
_collect_ast_symbols(node.body, symbols, inside_class=inside_class)
|
|
1090
|
+
elif isinstance(node, ast.Try):
|
|
1091
|
+
_collect_ast_symbols(node.body, symbols, inside_class=inside_class)
|
|
1092
|
+
for handler in node.handlers:
|
|
1093
|
+
_collect_ast_symbols(handler.body, symbols, inside_class=inside_class)
|
|
1094
|
+
_collect_ast_symbols(node.orelse, symbols, inside_class=inside_class)
|
|
1095
|
+
_collect_ast_symbols(node.finalbody, symbols, inside_class=inside_class)
|
|
1096
|
+
elif hasattr(ast, "TryStar") and isinstance(node, ast.TryStar):
|
|
1097
|
+
_collect_ast_symbols(node.body, symbols, inside_class=inside_class)
|
|
1098
|
+
for handler in node.handlers:
|
|
1099
|
+
_collect_ast_symbols(handler.body, symbols, inside_class=inside_class)
|
|
1100
|
+
_collect_ast_symbols(node.orelse, symbols, inside_class=inside_class)
|
|
1101
|
+
_collect_ast_symbols(node.finalbody, symbols, inside_class=inside_class)
|
|
1102
|
+
elif hasattr(ast, "Match") and isinstance(node, ast.Match):
|
|
1103
|
+
for case in node.cases:
|
|
1104
|
+
_collect_ast_symbols(case.body, symbols, inside_class=inside_class)
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
@functools.lru_cache(maxsize=2048)
|
|
1108
|
+
def _extract_ast_symbols_cached(
|
|
1109
|
+
path_str: str,
|
|
1110
|
+
mtime_ns: int,
|
|
1111
|
+
size: int,
|
|
1112
|
+
) -> frozenset[str]:
|
|
1113
|
+
del mtime_ns, size
|
|
1114
|
+
try:
|
|
1115
|
+
source_code = Path(path_str).read_text(encoding="utf-8")
|
|
1116
|
+
tree = ast.parse(source_code, filename=path_str)
|
|
1117
|
+
except Exception:
|
|
1118
|
+
return frozenset()
|
|
1119
|
+
symbols: set[str] = set()
|
|
1120
|
+
_collect_ast_symbols(tree.body, symbols)
|
|
1121
|
+
return frozenset(symbols)
|
|
1122
|
+
|
|
1123
|
+
|
|
1124
|
+
def _extract_ast_symbols(source_file: Path) -> set[str]:
|
|
1125
|
+
try:
|
|
1126
|
+
st = source_file.stat()
|
|
1127
|
+
except OSError:
|
|
1128
|
+
return set()
|
|
1129
|
+
return set(_extract_ast_symbols_cached(str(source_file), st.st_mtime_ns, st.st_size))
|
|
1130
|
+
|
|
1131
|
+
|
|
1132
|
+
def _is_pure_reexport_init(source_file: Path) -> bool:
|
|
1133
|
+
"""Return True when ``__init__.py`` has imports/re-exports and no local def/class."""
|
|
1134
|
+
|
|
1135
|
+
try:
|
|
1136
|
+
source_code = source_file.read_text(encoding="utf-8")
|
|
1137
|
+
tree = ast.parse(source_code, filename=str(source_file))
|
|
1138
|
+
except Exception:
|
|
1139
|
+
return False
|
|
1140
|
+
has_import = False
|
|
1141
|
+
for node in tree.body:
|
|
1142
|
+
if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
1143
|
+
return False
|
|
1144
|
+
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
1145
|
+
has_import = True
|
|
1146
|
+
return has_import
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
def check_6_symbol_table(
|
|
1150
|
+
content: str,
|
|
1151
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1152
|
+
*,
|
|
1153
|
+
context: _ValidationContext | None = None,
|
|
1154
|
+
) -> tuple[bool, str]:
|
|
1155
|
+
"""Check key symbols and verify their AST presence in source files."""
|
|
1156
|
+
|
|
1157
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
1158
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
1159
|
+
return True, "N/A(placeholder 不强制关键符号)"
|
|
1160
|
+
|
|
1161
|
+
inventory = _inventory_for_check(source_dir, context)
|
|
1162
|
+
is_python_package = inventory is not None and "__init__.py" in inventory[0]
|
|
1163
|
+
if not is_python_package:
|
|
1164
|
+
return True, "N/A(非 Python 包)"
|
|
1165
|
+
py_files = [name for name in inventory[0] if name.casefold().endswith(".py")]
|
|
1166
|
+
only_init_py = len(py_files) == 1 and py_files[0].casefold() == "__init__.py"
|
|
1167
|
+
pure_reexport = False
|
|
1168
|
+
if only_init_py and context is not None and context.source_dir is not None:
|
|
1169
|
+
if context.virtual_source:
|
|
1170
|
+
pure_reexport = True
|
|
1171
|
+
else:
|
|
1172
|
+
init_file = context.source_dir / py_files[0]
|
|
1173
|
+
if init_file.is_file() and _is_pure_reexport_init(init_file):
|
|
1174
|
+
pure_reexport = True
|
|
1175
|
+
section_text = _section(content, "关键符号")
|
|
1176
|
+
if not section_text:
|
|
1177
|
+
if pure_reexport:
|
|
1178
|
+
return True, "N/A(纯 re-export 包,无本地函数/类定义)"
|
|
1179
|
+
return False, "Python 包目录缺少 ## 关键符号 段"
|
|
1180
|
+
rows = _table_rows(section_text, {"符号", "名称"})
|
|
1181
|
+
symbol_names: list[str] = []
|
|
1182
|
+
issues: list[str] = []
|
|
1183
|
+
|
|
1184
|
+
for row in rows:
|
|
1185
|
+
label, _ = _cell_label_and_target(row.cells[0])
|
|
1186
|
+
if not label:
|
|
1187
|
+
continue
|
|
1188
|
+
symbol_names.append(label)
|
|
1189
|
+
|
|
1190
|
+
# AST-level reality verification when source files are present
|
|
1191
|
+
if (
|
|
1192
|
+
context is not None
|
|
1193
|
+
and context.source_dir is not None
|
|
1194
|
+
and len(row.cells) >= 3
|
|
1195
|
+
):
|
|
1196
|
+
loc = _unwrap_formatting(row.cells[2])
|
|
1197
|
+
file_part = loc.split(":")[0].strip()
|
|
1198
|
+
if file_part.endswith(".py"):
|
|
1199
|
+
if context.virtual_source:
|
|
1200
|
+
if file_part not in (context.source_files or ()):
|
|
1201
|
+
issues.append(f"关键符号定义位置文件 {file_part!r} 在源目录中不存在")
|
|
1202
|
+
else:
|
|
1203
|
+
source_file = context.source_dir / file_part
|
|
1204
|
+
if source_file.is_file():
|
|
1205
|
+
ast_symbols = _extract_ast_symbols(source_file)
|
|
1206
|
+
clean_name = label.split("(")[0].strip()
|
|
1207
|
+
root_name = clean_name.split(".")[0].strip()
|
|
1208
|
+
if (
|
|
1209
|
+
ast_symbols
|
|
1210
|
+
and clean_name not in ast_symbols
|
|
1211
|
+
and root_name not in ast_symbols
|
|
1212
|
+
):
|
|
1213
|
+
issues.append(f"符号 {label!r} 未在 {file_part} 的 AST 定义中找到")
|
|
1214
|
+
else:
|
|
1215
|
+
issues.append(f"关键符号定义位置文件 {file_part!r} 在源目录中不存在")
|
|
1216
|
+
|
|
1217
|
+
if issues:
|
|
1218
|
+
return False, "; ".join(issues)
|
|
1219
|
+
if len(symbol_names) < 3:
|
|
1220
|
+
if pure_reexport:
|
|
1221
|
+
return True, f"N/A(纯 re-export 包,已列出 {len(symbol_names)} 个导出符号)"
|
|
1222
|
+
return False, f"Python 包关键符号仅 {len(symbol_names)} 个(需 >= 3)"
|
|
1223
|
+
return True, f"关键符号 {len(symbol_names)} 个"
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
def check_7_no_banned_words(
|
|
1227
|
+
content: str,
|
|
1228
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1229
|
+
*,
|
|
1230
|
+
context: _ValidationContext | None = None,
|
|
1231
|
+
) -> tuple[bool, str]:
|
|
1232
|
+
"""Check that vague banned terms are absent."""
|
|
1233
|
+
|
|
1234
|
+
del source_dir, context
|
|
1235
|
+
found: list[str] = []
|
|
1236
|
+
lines = content.splitlines()
|
|
1237
|
+
for word in BANNED_WORDS:
|
|
1238
|
+
for line_number, line in enumerate(lines, 1):
|
|
1239
|
+
if word in line:
|
|
1240
|
+
found.append(f"'{word}' (L{line_number})")
|
|
1241
|
+
break
|
|
1242
|
+
if found:
|
|
1243
|
+
return False, f"发现禁止词: {', '.join(found)}"
|
|
1244
|
+
return True, "无禁止词"
|
|
1245
|
+
|
|
1246
|
+
|
|
1247
|
+
def check_8_breadcrumb(
|
|
1248
|
+
content: str,
|
|
1249
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1250
|
+
*,
|
|
1251
|
+
context: _ValidationContext | None = None,
|
|
1252
|
+
) -> tuple[bool, str]:
|
|
1253
|
+
"""Check breadcrumb navigation before the first level-two section."""
|
|
1254
|
+
|
|
1255
|
+
del source_dir, context
|
|
1256
|
+
intro = re.split(r"^##[ \t]+", content, maxsplit=1, flags=re.MULTILINE)[0]
|
|
1257
|
+
if re.search(r"^\s*\*\*导航\*\*\s*:", intro, re.MULTILINE):
|
|
1258
|
+
return True, "面包屑导航存在"
|
|
1259
|
+
if re.search(r"^\s*>?\s*面包屑\s*:", intro, re.MULTILINE):
|
|
1260
|
+
return True, "面包屑导航存在(兼容旧格式)"
|
|
1261
|
+
return False, "缺少文档开头的面包屑导航 (**导航**: ...)"
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
def _dependency_row_issue(
|
|
1265
|
+
row: _TableRow, context: _ValidationContext | None
|
|
1266
|
+
) -> str | None:
|
|
1267
|
+
if len(row.cells) < 3:
|
|
1268
|
+
return f"依赖关系表第 {row.line_number} 行列数不足"
|
|
1269
|
+
direction = _strip_markdown(row.cells[0])
|
|
1270
|
+
if not re.match(r"^(?:⬆|⬇|↔)", direction):
|
|
1271
|
+
return f"依赖关系表第 {row.line_number} 行缺少方向标记"
|
|
1272
|
+
module = _strip_markdown(row.cells[1])
|
|
1273
|
+
relationship = _strip_markdown(row.cells[2])
|
|
1274
|
+
empty_values = {"", "-", "—", "无", "N/A", "n/a", "TODO", "待补充"}
|
|
1275
|
+
if module in empty_values:
|
|
1276
|
+
return f"依赖关系表第 {row.line_number} 行模块名无实质内容"
|
|
1277
|
+
if relationship in empty_values or len(relationship) < 6:
|
|
1278
|
+
return f"依赖关系表第 {row.line_number} 行关系说明不够具体"
|
|
1279
|
+
|
|
1280
|
+
if context is None:
|
|
1281
|
+
if not re.search(r"\[[^\]]+\]\([^)]+\)", row.raw):
|
|
1282
|
+
return f"依赖关系表第 {row.line_number} 行缺少 Markdown 文档链接"
|
|
1283
|
+
return None
|
|
1284
|
+
|
|
1285
|
+
links = parse_markdown_links(
|
|
1286
|
+
row.raw,
|
|
1287
|
+
source_doc=context.doc_path,
|
|
1288
|
+
docs_root=context.docs_root,
|
|
1289
|
+
)
|
|
1290
|
+
invalid = [link for link in links if link.disposition is LinkDisposition.INVALID]
|
|
1291
|
+
if invalid:
|
|
1292
|
+
return f"依赖关系表第 {row.line_number} 行包含不安全链接: {invalid[0].reason}"
|
|
1293
|
+
local_links = [
|
|
1294
|
+
link for link in links if link.disposition is LinkDisposition.LOCAL_DOCUMENT
|
|
1295
|
+
]
|
|
1296
|
+
if len(local_links) != 1:
|
|
1297
|
+
return f"依赖关系表第 {row.line_number} 行必须且只能有一个本地文档链接"
|
|
1298
|
+
link = local_links[0]
|
|
1299
|
+
if link.exists is not True:
|
|
1300
|
+
return f"依赖关系表第 {row.line_number} 行链接目标不存在: {link.raw_target}"
|
|
1301
|
+
if link.project_relative_path == context.doc_relative:
|
|
1302
|
+
return f"依赖关系表第 {row.line_number} 行不能仅链接当前文档"
|
|
1303
|
+
return None
|
|
1304
|
+
|
|
1305
|
+
|
|
1306
|
+
def check_9_dependency_table(
|
|
1307
|
+
content: str,
|
|
1308
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1309
|
+
*,
|
|
1310
|
+
context: _ValidationContext | None = None,
|
|
1311
|
+
) -> tuple[bool, str]:
|
|
1312
|
+
"""Check a substantive dependency table and its safe local document links."""
|
|
1313
|
+
|
|
1314
|
+
del source_dir
|
|
1315
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
1316
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
1317
|
+
return True, "N/A(placeholder 不强制依赖关系表)"
|
|
1318
|
+
section_text = _section(content, "依赖关系")
|
|
1319
|
+
if not section_text:
|
|
1320
|
+
return False, "缺少 ## 依赖关系 段"
|
|
1321
|
+
rows = _table_rows(section_text, {"方向"})
|
|
1322
|
+
if not rows:
|
|
1323
|
+
return False, "依赖关系表为空或不是 Markdown 表格"
|
|
1324
|
+
issues = [
|
|
1325
|
+
issue
|
|
1326
|
+
for row in rows
|
|
1327
|
+
if (issue := _dependency_row_issue(row, context)) is not None
|
|
1328
|
+
]
|
|
1329
|
+
if issues:
|
|
1330
|
+
return False, "; ".join(issues)
|
|
1331
|
+
return True, f"依赖关系 {len(rows)} 条,说明及链接均有效"
|
|
1332
|
+
|
|
1333
|
+
|
|
1334
|
+
def _check_rich_section(
|
|
1335
|
+
content: str,
|
|
1336
|
+
headings: Sequence[str],
|
|
1337
|
+
*,
|
|
1338
|
+
label: str,
|
|
1339
|
+
min_chars: int,
|
|
1340
|
+
context: _ValidationContext | None,
|
|
1341
|
+
) -> tuple[bool, str]:
|
|
1342
|
+
"""Shared v4.5 rule for the three added standard-profile sections.
|
|
1343
|
+
|
|
1344
|
+
A section either carries substantive prose, or explicitly declares
|
|
1345
|
+
``本节不适用`` together with a concrete reason. Placeholder documents are
|
|
1346
|
+
exempt. Missing/empty/filler sections fail as advisory.
|
|
1347
|
+
"""
|
|
1348
|
+
|
|
1349
|
+
profile = context.profile if context is not None else PROFILE_STANDARD
|
|
1350
|
+
if profile == PROFILE_PLACEHOLDER:
|
|
1351
|
+
return True, f"placeholder 无需 ## {label} 段"
|
|
1352
|
+
section_text = _section_any(content, headings)
|
|
1353
|
+
if section_text is None:
|
|
1354
|
+
return False, f"缺少 ## {label} 段(或写「本节不适用:<理由>」)"
|
|
1355
|
+
stripped = _strip_markdown(section_text)
|
|
1356
|
+
if not stripped:
|
|
1357
|
+
return False, f"## {label} 段为空"
|
|
1358
|
+
if "本节不适用" in stripped:
|
|
1359
|
+
reason = stripped.split("本节不适用", 1)[1].strip(" ::—-・·、,,.。;;\n\t")
|
|
1360
|
+
if len(reason) < 6:
|
|
1361
|
+
return False, f"## {label} 声明不适用但未给出具体理由"
|
|
1362
|
+
return True, f"## {label} 已声明不适用(理由 {len(reason)} 字)"
|
|
1363
|
+
if len(stripped) < min_chars:
|
|
1364
|
+
return False, f"## {label} 内容过短({len(stripped)} 字,需 ≥{min_chars})"
|
|
1365
|
+
sentences = _sentence_count(section_text)
|
|
1366
|
+
if sentences < 2:
|
|
1367
|
+
return False, f"## {label} 需至少 2 句实质说明(当前 {sentences} 句)"
|
|
1368
|
+
return True, f"## {label} 内容充实({len(stripped)} 字 / {sentences} 句)"
|
|
1369
|
+
|
|
1370
|
+
|
|
1371
|
+
def check_10_data_state(
|
|
1372
|
+
content: str,
|
|
1373
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1374
|
+
*,
|
|
1375
|
+
context: _ValidationContext | None = None,
|
|
1376
|
+
) -> tuple[bool, str]:
|
|
1377
|
+
"""Check the ``## 数据与状态`` section added in v4.5."""
|
|
1378
|
+
|
|
1379
|
+
del source_dir
|
|
1380
|
+
return _check_rich_section(
|
|
1381
|
+
content,
|
|
1382
|
+
("数据与状态", "数据与状态管理"),
|
|
1383
|
+
label="数据与状态",
|
|
1384
|
+
min_chars=60,
|
|
1385
|
+
context=context,
|
|
1386
|
+
)
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def check_11_perf_resources(
|
|
1390
|
+
content: str,
|
|
1391
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1392
|
+
*,
|
|
1393
|
+
context: _ValidationContext | None = None,
|
|
1394
|
+
) -> tuple[bool, str]:
|
|
1395
|
+
"""Check the ``## 性能与资源特征`` section added in v4.5."""
|
|
1396
|
+
|
|
1397
|
+
del source_dir
|
|
1398
|
+
return _check_rich_section(
|
|
1399
|
+
content,
|
|
1400
|
+
("性能与资源特征", "性能与资源", "性能特征"),
|
|
1401
|
+
label="性能与资源特征",
|
|
1402
|
+
min_chars=60,
|
|
1403
|
+
context=context,
|
|
1404
|
+
)
|
|
1405
|
+
|
|
1406
|
+
|
|
1407
|
+
def check_12_change_migration(
|
|
1408
|
+
content: str,
|
|
1409
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1410
|
+
*,
|
|
1411
|
+
context: _ValidationContext | None = None,
|
|
1412
|
+
) -> tuple[bool, str]:
|
|
1413
|
+
"""Check the ``## 变更与迁移注意`` section added in v4.5."""
|
|
1414
|
+
|
|
1415
|
+
del source_dir
|
|
1416
|
+
return _check_rich_section(
|
|
1417
|
+
content,
|
|
1418
|
+
("变更与迁移注意", "变更与迁移", "迁移注意"),
|
|
1419
|
+
label="变更与迁移注意",
|
|
1420
|
+
min_chars=60,
|
|
1421
|
+
context=context,
|
|
1422
|
+
)
|
|
1423
|
+
|
|
1424
|
+
|
|
1425
|
+
CHECKS = [
|
|
1426
|
+
(1, "file_manifest_table", "文件清单表格", check_1_file_table),
|
|
1427
|
+
(2, "overview_min_8", "概述 ≥8 句", check_2_overview),
|
|
1428
|
+
(3, "system_role", "系统角色段", check_3_system_role),
|
|
1429
|
+
(4, "subdir_table", "子目录表", check_4_subdir_table),
|
|
1430
|
+
(5, "status_marker", "状态标记", check_5_status),
|
|
1431
|
+
(6, "symbol_table", "关键符号表", check_6_symbol_table),
|
|
1432
|
+
(7, "no_banned_words", "无禁止词", check_7_no_banned_words),
|
|
1433
|
+
(8, "breadcrumb", "面包屑导航", check_8_breadcrumb),
|
|
1434
|
+
(9, "dependency_table", "依赖关系表", check_9_dependency_table),
|
|
1435
|
+
(10, "data_state", "数据与状态", check_10_data_state),
|
|
1436
|
+
(11, "perf_resources", "性能与资源特征", check_11_perf_resources),
|
|
1437
|
+
(12, "change_migration", "变更与迁移注意", check_12_change_migration),
|
|
1438
|
+
]
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def _display_path(value: str | os.PathLike[str] | None) -> str | None:
|
|
1442
|
+
if value is None:
|
|
1443
|
+
return None
|
|
1444
|
+
try:
|
|
1445
|
+
return os.fspath(value)
|
|
1446
|
+
except TypeError:
|
|
1447
|
+
return repr(value)
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def _not_run_checks(reason: str) -> list[dict[str, Any]]:
|
|
1451
|
+
return [
|
|
1452
|
+
{
|
|
1453
|
+
"id": check_id,
|
|
1454
|
+
"name": name,
|
|
1455
|
+
"label": label,
|
|
1456
|
+
"severity": "critical" if check_id in CRITICAL_CHECK_IDS else "advisory",
|
|
1457
|
+
"result": "N/A",
|
|
1458
|
+
"detail": f"未执行: {reason}",
|
|
1459
|
+
}
|
|
1460
|
+
for check_id, name, label, _ in CHECKS
|
|
1461
|
+
]
|
|
1462
|
+
|
|
1463
|
+
|
|
1464
|
+
def _critical_result(
|
|
1465
|
+
doc_path: str | os.PathLike[str],
|
|
1466
|
+
source_dir: str | os.PathLike[str] | None,
|
|
1467
|
+
requested_profile: str,
|
|
1468
|
+
*,
|
|
1469
|
+
error_code: str,
|
|
1470
|
+
message: str,
|
|
1471
|
+
) -> dict[str, Any]:
|
|
1472
|
+
profile = (
|
|
1473
|
+
requested_profile
|
|
1474
|
+
if requested_profile in {PROFILE_STANDARD, PROFILE_PLACEHOLDER}
|
|
1475
|
+
else None
|
|
1476
|
+
)
|
|
1477
|
+
checks = _not_run_checks(message)
|
|
1478
|
+
return {
|
|
1479
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1480
|
+
"file": _display_path(doc_path),
|
|
1481
|
+
"source_dir": _display_path(source_dir),
|
|
1482
|
+
"requested_profile": requested_profile,
|
|
1483
|
+
"profile": profile,
|
|
1484
|
+
"checks": checks,
|
|
1485
|
+
"passed": 0,
|
|
1486
|
+
"failed": 0,
|
|
1487
|
+
"na": len(checks),
|
|
1488
|
+
"known_issue_count": 0,
|
|
1489
|
+
"known_issues": [],
|
|
1490
|
+
"advisories": [],
|
|
1491
|
+
"critical_failed": 1,
|
|
1492
|
+
"critical": True,
|
|
1493
|
+
"qualified": False,
|
|
1494
|
+
"ok": False,
|
|
1495
|
+
"error_code": error_code,
|
|
1496
|
+
"error": message,
|
|
1497
|
+
"errors": [message],
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
def _invalid_link_errors(content: str, context: _ValidationContext) -> list[str]:
|
|
1502
|
+
errors: list[str] = []
|
|
1503
|
+
for link in parse_markdown_links(
|
|
1504
|
+
content,
|
|
1505
|
+
source_doc=context.doc_path,
|
|
1506
|
+
docs_root=context.docs_root,
|
|
1507
|
+
):
|
|
1508
|
+
if link.disposition is LinkDisposition.INVALID:
|
|
1509
|
+
errors.append(f"不安全 Markdown 链接 {link.raw_target!r}: {link.reason}")
|
|
1510
|
+
return sorted(set(errors))
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def validate_doc(
|
|
1514
|
+
doc_path: str | os.PathLike[str],
|
|
1515
|
+
source_dir: str | os.PathLike[str] | None = None,
|
|
1516
|
+
*,
|
|
1517
|
+
profile: str = PROFILE_AUTO,
|
|
1518
|
+
project_docs_dir: str | os.PathLike[str] | None = None,
|
|
1519
|
+
project_root: str | os.PathLike[str] | None = None,
|
|
1520
|
+
source_inventory: tuple[Sequence[str], Sequence[str]] | None = None,
|
|
1521
|
+
project_config: proj_doc_config.ProjectDocConfig | None = None,
|
|
1522
|
+
) -> dict[str, Any]:
|
|
1523
|
+
"""Run all checks and always return the same complete result structure."""
|
|
1524
|
+
|
|
1525
|
+
try:
|
|
1526
|
+
context, content = _build_context(
|
|
1527
|
+
doc_path,
|
|
1528
|
+
source_dir,
|
|
1529
|
+
profile=profile,
|
|
1530
|
+
project_docs_dir=project_docs_dir,
|
|
1531
|
+
project_root=project_root,
|
|
1532
|
+
source_inventory=source_inventory,
|
|
1533
|
+
project_config=project_config,
|
|
1534
|
+
)
|
|
1535
|
+
except FileNotFoundError:
|
|
1536
|
+
return _critical_result(
|
|
1537
|
+
doc_path,
|
|
1538
|
+
source_dir,
|
|
1539
|
+
profile,
|
|
1540
|
+
error_code="document-not-found",
|
|
1541
|
+
message="file not found",
|
|
1542
|
+
)
|
|
1543
|
+
except StrictUtf8Error as exc:
|
|
1544
|
+
return _critical_result(
|
|
1545
|
+
doc_path,
|
|
1546
|
+
source_dir,
|
|
1547
|
+
profile,
|
|
1548
|
+
error_code="invalid-utf8",
|
|
1549
|
+
message=str(exc),
|
|
1550
|
+
)
|
|
1551
|
+
except (OSError, ValueError, ProjectDocsContractError) as exc:
|
|
1552
|
+
return _critical_result(
|
|
1553
|
+
doc_path,
|
|
1554
|
+
source_dir,
|
|
1555
|
+
profile,
|
|
1556
|
+
error_code="path-or-input-error",
|
|
1557
|
+
message=str(exc),
|
|
1558
|
+
)
|
|
1559
|
+
|
|
1560
|
+
critical_errors = _invalid_link_errors(content, context)
|
|
1561
|
+
advisories = _absolute_path_advisories(content)
|
|
1562
|
+
expected_rules = context.project_config.validation.expected_failures
|
|
1563
|
+
doc_rel_folded = context.doc_relative.casefold()
|
|
1564
|
+
results: list[dict[str, Any]] = []
|
|
1565
|
+
known_issues: list[dict[str, Any]] = []
|
|
1566
|
+
for check_id, name, label, function in CHECKS:
|
|
1567
|
+
try:
|
|
1568
|
+
passed, detail = function(content, source_dir, context=context)
|
|
1569
|
+
except (
|
|
1570
|
+
Exception
|
|
1571
|
+
) as exc: # A broken check must be reported, never hide the rest.
|
|
1572
|
+
passed = False
|
|
1573
|
+
detail = f"检查异常: {type(exc).__name__}: {exc}"
|
|
1574
|
+
status = (
|
|
1575
|
+
"N/A"
|
|
1576
|
+
if passed and detail.startswith("N/A")
|
|
1577
|
+
else ("PASS" if passed else "FAIL")
|
|
1578
|
+
)
|
|
1579
|
+
matched_rule = None
|
|
1580
|
+
if status == "FAIL" and expected_rules:
|
|
1581
|
+
for rule in expected_rules:
|
|
1582
|
+
if (
|
|
1583
|
+
rule.path.casefold() == doc_rel_folded
|
|
1584
|
+
and rule.check_id == check_id
|
|
1585
|
+
):
|
|
1586
|
+
matched_rule = rule
|
|
1587
|
+
break
|
|
1588
|
+
if matched_rule is not None:
|
|
1589
|
+
status = "KNOWN_ISSUE"
|
|
1590
|
+
known_issues.append(
|
|
1591
|
+
{
|
|
1592
|
+
"path": context.doc_relative,
|
|
1593
|
+
"check_id": check_id,
|
|
1594
|
+
"name": name,
|
|
1595
|
+
"label": label,
|
|
1596
|
+
"detail": detail,
|
|
1597
|
+
"reason": matched_rule.reason,
|
|
1598
|
+
"review_date": matched_rule.review_date,
|
|
1599
|
+
}
|
|
1600
|
+
)
|
|
1601
|
+
detail = f"已知预期失败 ({matched_rule.reason}): {detail}"
|
|
1602
|
+
results.append(
|
|
1603
|
+
{
|
|
1604
|
+
"id": check_id,
|
|
1605
|
+
"name": name,
|
|
1606
|
+
"label": label,
|
|
1607
|
+
"severity": (
|
|
1608
|
+
"critical" if check_id in CRITICAL_CHECK_IDS else "advisory"
|
|
1609
|
+
),
|
|
1610
|
+
"result": status,
|
|
1611
|
+
"detail": detail,
|
|
1612
|
+
}
|
|
1613
|
+
)
|
|
1614
|
+
|
|
1615
|
+
passed_count = sum(result["result"] == "PASS" for result in results)
|
|
1616
|
+
failed_count = sum(result["result"] == "FAIL" for result in results)
|
|
1617
|
+
na_count = sum(result["result"] == "N/A" for result in results)
|
|
1618
|
+
known_issue_count = len(known_issues)
|
|
1619
|
+
critical_check_failures = sum(
|
|
1620
|
+
result["result"] == "FAIL" and result["severity"] == "critical"
|
|
1621
|
+
for result in results
|
|
1622
|
+
)
|
|
1623
|
+
critical_failed = critical_check_failures + len(critical_errors)
|
|
1624
|
+
qualified = failed_count == 0 and not critical_errors
|
|
1625
|
+
|
|
1626
|
+
return {
|
|
1627
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1628
|
+
"file": _display_path(doc_path),
|
|
1629
|
+
"source_dir": _display_path(source_dir),
|
|
1630
|
+
"requested_profile": profile,
|
|
1631
|
+
"profile": context.profile,
|
|
1632
|
+
"checks": results,
|
|
1633
|
+
"passed": passed_count,
|
|
1634
|
+
"failed": failed_count,
|
|
1635
|
+
"na": na_count,
|
|
1636
|
+
"known_issue_count": known_issue_count,
|
|
1637
|
+
"known_issues": known_issues,
|
|
1638
|
+
"advisories": advisories,
|
|
1639
|
+
"critical_failed": critical_failed,
|
|
1640
|
+
"critical": critical_failed > 0,
|
|
1641
|
+
"qualified": qualified,
|
|
1642
|
+
"ok": qualified,
|
|
1643
|
+
"error_code": "unsafe-markdown-link" if critical_errors else None,
|
|
1644
|
+
"error": critical_errors[0] if critical_errors else None,
|
|
1645
|
+
"errors": critical_errors,
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
|
|
1649
|
+
def _audit_single_doc_inventory(
|
|
1650
|
+
rel_path: str,
|
|
1651
|
+
root: Path,
|
|
1652
|
+
docs_root: Path,
|
|
1653
|
+
project_config: proj_doc_config.ProjectDocConfig,
|
|
1654
|
+
) -> dict[str, Any] | None:
|
|
1655
|
+
"""Compare one document's ``## 文件清单`` entries against direct disk files."""
|
|
1656
|
+
|
|
1657
|
+
pure = PurePosixPath(rel_path)
|
|
1658
|
+
if pure.name == "index.md" or pure.name.startswith("_"):
|
|
1659
|
+
return None
|
|
1660
|
+
src_rel = pure.with_suffix("").as_posix()
|
|
1661
|
+
src_dir = root / pure.with_suffix("")
|
|
1662
|
+
try:
|
|
1663
|
+
src_stat = src_dir.lstat()
|
|
1664
|
+
except OSError:
|
|
1665
|
+
return None
|
|
1666
|
+
if os.path.islink(src_dir) or not os.path.isdir(src_dir):
|
|
1667
|
+
return None
|
|
1668
|
+
reparse_flag = 0x400
|
|
1669
|
+
if bool(getattr(src_stat, "st_file_attributes", 0) & reparse_flag):
|
|
1670
|
+
return None
|
|
1671
|
+
if proj_doc_config.should_exclude_directory(
|
|
1672
|
+
src_dir.name, src_rel, config=project_config
|
|
1673
|
+
):
|
|
1674
|
+
return None
|
|
1675
|
+
|
|
1676
|
+
disk_files = sorted(
|
|
1677
|
+
entry.name
|
|
1678
|
+
for entry in os.scandir(src_dir)
|
|
1679
|
+
if not entry.name.startswith(".") and entry.is_file(follow_symlinks=False)
|
|
1680
|
+
)
|
|
1681
|
+
disk_set = set(disk_files)
|
|
1682
|
+
|
|
1683
|
+
content = read_utf8(docs_root / pure)
|
|
1684
|
+
section_text = _section_any(content, ("文件清单",))
|
|
1685
|
+
if section_text is not None:
|
|
1686
|
+
rows, _issues = _manifest_rows(
|
|
1687
|
+
section_text,
|
|
1688
|
+
kind="file",
|
|
1689
|
+
headers={"文件", "文件名"},
|
|
1690
|
+
)
|
|
1691
|
+
doc_set = {row.name for row in rows}
|
|
1692
|
+
else:
|
|
1693
|
+
doc_set = set()
|
|
1694
|
+
|
|
1695
|
+
missing = sorted(disk_set - doc_set)
|
|
1696
|
+
extra = sorted(doc_set - disk_set)
|
|
1697
|
+
if not missing and not extra:
|
|
1698
|
+
return {"audited": True, "issue": None}
|
|
1699
|
+
return {
|
|
1700
|
+
"audited": True,
|
|
1701
|
+
"issue": {
|
|
1702
|
+
"doc": rel_path,
|
|
1703
|
+
"source_dir": src_rel,
|
|
1704
|
+
"disk_count": len(disk_files),
|
|
1705
|
+
"doc_count": len(doc_set),
|
|
1706
|
+
"missing": missing,
|
|
1707
|
+
"extra": extra,
|
|
1708
|
+
},
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
|
|
1712
|
+
def audit_inventory(
|
|
1713
|
+
project_root: str | os.PathLike[str],
|
|
1714
|
+
*,
|
|
1715
|
+
project_docs_dir: str | os.PathLike[str] | None = None,
|
|
1716
|
+
) -> dict[str, Any]:
|
|
1717
|
+
"""Audit ``## 文件清单`` of every active project_docs document against disk."""
|
|
1718
|
+
|
|
1719
|
+
root = Path(project_root).resolve(strict=True)
|
|
1720
|
+
docs_root = (
|
|
1721
|
+
Path(project_docs_dir).resolve(strict=True)
|
|
1722
|
+
if project_docs_dir is not None
|
|
1723
|
+
else (root / "project_docs").resolve(strict=True)
|
|
1724
|
+
)
|
|
1725
|
+
project_config = proj_doc_config.load_project_config(root)
|
|
1726
|
+
active_paths = discover_active_markdown_paths(docs_root)
|
|
1727
|
+
candidates = [
|
|
1728
|
+
rel
|
|
1729
|
+
for rel in active_paths
|
|
1730
|
+
if PurePosixPath(rel).name != "index.md"
|
|
1731
|
+
and not PurePosixPath(rel).name.startswith("_")
|
|
1732
|
+
]
|
|
1733
|
+
|
|
1734
|
+
audited_docs = 0
|
|
1735
|
+
issues: list[dict[str, Any]] = []
|
|
1736
|
+
if candidates:
|
|
1737
|
+
max_workers = min(32, (os.cpu_count() or 4) * 4)
|
|
1738
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
|
1739
|
+
results = list(
|
|
1740
|
+
executor.map(
|
|
1741
|
+
lambda rel: _audit_single_doc_inventory(
|
|
1742
|
+
rel, root, docs_root, project_config
|
|
1743
|
+
),
|
|
1744
|
+
candidates,
|
|
1745
|
+
)
|
|
1746
|
+
)
|
|
1747
|
+
for item in results:
|
|
1748
|
+
if item is None:
|
|
1749
|
+
continue
|
|
1750
|
+
audited_docs += 1
|
|
1751
|
+
if item["issue"] is not None:
|
|
1752
|
+
issues.append(item["issue"])
|
|
1753
|
+
|
|
1754
|
+
issues.sort(key=lambda entry: (entry["doc"].casefold(), entry["doc"]))
|
|
1755
|
+
return {
|
|
1756
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1757
|
+
"project_root": root.as_posix(),
|
|
1758
|
+
"project_docs": docs_root.as_posix(),
|
|
1759
|
+
"audited_docs": audited_docs,
|
|
1760
|
+
"issue_count": len(issues),
|
|
1761
|
+
"ok": len(issues) == 0,
|
|
1762
|
+
"issues": issues,
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
|
|
1766
|
+
def _parser() -> argparse.ArgumentParser:
|
|
1767
|
+
parser = argparse.ArgumentParser(
|
|
1768
|
+
description="Validate a project_docs document against its source directory"
|
|
1769
|
+
)
|
|
1770
|
+
parser.add_argument(
|
|
1771
|
+
"doc",
|
|
1772
|
+
nargs="?",
|
|
1773
|
+
help="Path to the .md document to validate (omit when using --audit-inventory)",
|
|
1774
|
+
)
|
|
1775
|
+
parser.add_argument(
|
|
1776
|
+
"--audit-inventory",
|
|
1777
|
+
metavar="PROJECT_ROOT",
|
|
1778
|
+
dest="audit_inventory",
|
|
1779
|
+
help="Batch-audit ## 文件清单 of all active project_docs against disk in parallel",
|
|
1780
|
+
)
|
|
1781
|
+
parser.add_argument(
|
|
1782
|
+
"--source-dir",
|
|
1783
|
+
"--source_dir",
|
|
1784
|
+
"-s",
|
|
1785
|
+
dest="source_dir",
|
|
1786
|
+
help="Corresponding source directory for exact inventory comparison",
|
|
1787
|
+
)
|
|
1788
|
+
parser.add_argument(
|
|
1789
|
+
"--project-docs",
|
|
1790
|
+
"--docs-root",
|
|
1791
|
+
dest="project_docs",
|
|
1792
|
+
help="Trusted project_docs root (otherwise inferred from the document path)",
|
|
1793
|
+
)
|
|
1794
|
+
parser.add_argument(
|
|
1795
|
+
"--project-root",
|
|
1796
|
+
help="Trusted project root used to bound the source directory",
|
|
1797
|
+
)
|
|
1798
|
+
parser.add_argument(
|
|
1799
|
+
"--profile",
|
|
1800
|
+
choices=PROFILES,
|
|
1801
|
+
default=PROFILE_AUTO,
|
|
1802
|
+
help="Validation profile (default: auto)",
|
|
1803
|
+
)
|
|
1804
|
+
parser.add_argument(
|
|
1805
|
+
"--strict",
|
|
1806
|
+
action="store_true",
|
|
1807
|
+
help="Exit non-zero for advisory as well as critical check failures",
|
|
1808
|
+
)
|
|
1809
|
+
parser.add_argument("--json", action="store_true", help="Write only JSON to stdout")
|
|
1810
|
+
return parser
|
|
1811
|
+
|
|
1812
|
+
|
|
1813
|
+
def _result_exit_code(result: dict[str, Any], *, strict: bool) -> int:
|
|
1814
|
+
if result["error_code"] is not None:
|
|
1815
|
+
return EXIT_CRITICAL_ERROR
|
|
1816
|
+
if result["critical_failed"]:
|
|
1817
|
+
return EXIT_VALIDATION_FAILED
|
|
1818
|
+
if strict and result["failed"]:
|
|
1819
|
+
return EXIT_VALIDATION_FAILED
|
|
1820
|
+
return EXIT_OK
|
|
1821
|
+
|
|
1822
|
+
|
|
1823
|
+
def _configure_stdout_utf8() -> None:
|
|
1824
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
1825
|
+
if callable(reconfigure):
|
|
1826
|
+
reconfigure(encoding="utf-8", errors="strict")
|
|
1827
|
+
|
|
1828
|
+
|
|
1829
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
1830
|
+
parser = _parser()
|
|
1831
|
+
args = parser.parse_args(argv)
|
|
1832
|
+
_configure_stdout_utf8()
|
|
1833
|
+
|
|
1834
|
+
if args.audit_inventory is not None:
|
|
1835
|
+
try:
|
|
1836
|
+
report = audit_inventory(
|
|
1837
|
+
args.audit_inventory,
|
|
1838
|
+
project_docs_dir=args.project_docs,
|
|
1839
|
+
)
|
|
1840
|
+
except (
|
|
1841
|
+
OSError,
|
|
1842
|
+
ValueError,
|
|
1843
|
+
ProjectDocsContractError,
|
|
1844
|
+
proj_doc_config.ConfigError,
|
|
1845
|
+
) as exc:
|
|
1846
|
+
error_payload = {
|
|
1847
|
+
"schema_version": RESULT_SCHEMA_VERSION,
|
|
1848
|
+
"ok": False,
|
|
1849
|
+
"error_code": "audit-error",
|
|
1850
|
+
"error": str(exc),
|
|
1851
|
+
"issues": [],
|
|
1852
|
+
}
|
|
1853
|
+
if args.json:
|
|
1854
|
+
print(stable_json_dumps(error_payload), end="")
|
|
1855
|
+
else:
|
|
1856
|
+
print(f"ERROR [audit-error]: {exc}", file=sys.stderr)
|
|
1857
|
+
return EXIT_CRITICAL_ERROR
|
|
1858
|
+
|
|
1859
|
+
if args.json:
|
|
1860
|
+
print(stable_json_dumps(report), end="")
|
|
1861
|
+
elif report["ok"]:
|
|
1862
|
+
print(
|
|
1863
|
+
f"所有 {report['audited_docs']} 份文档文件清单与磁盘一致 ✅"
|
|
1864
|
+
)
|
|
1865
|
+
else:
|
|
1866
|
+
print(
|
|
1867
|
+
f"审计 {report['audited_docs']} 份文档,发现 {report['issue_count']} 份存在文件清单差异:"
|
|
1868
|
+
)
|
|
1869
|
+
for issue in report["issues"]:
|
|
1870
|
+
print(
|
|
1871
|
+
f" {issue['doc']}: 磁盘 {issue['disk_count']} / 文档 {issue['doc_count']}"
|
|
1872
|
+
)
|
|
1873
|
+
if issue["missing"]:
|
|
1874
|
+
print(f" 漏文件: {issue['missing']}")
|
|
1875
|
+
if issue["extra"]:
|
|
1876
|
+
print(f" 幽灵条目: {issue['extra']}")
|
|
1877
|
+
return EXIT_OK if report["ok"] else EXIT_VALIDATION_FAILED
|
|
1878
|
+
|
|
1879
|
+
if not args.doc:
|
|
1880
|
+
parser.error("the following arguments are required: doc")
|
|
1881
|
+
|
|
1882
|
+
result = validate_doc(
|
|
1883
|
+
args.doc,
|
|
1884
|
+
args.source_dir,
|
|
1885
|
+
profile=args.profile,
|
|
1886
|
+
project_docs_dir=args.project_docs,
|
|
1887
|
+
project_root=args.project_root,
|
|
1888
|
+
)
|
|
1889
|
+
exit_code = _result_exit_code(result, strict=args.strict)
|
|
1890
|
+
|
|
1891
|
+
if args.json:
|
|
1892
|
+
print(stable_json_dumps(result), end="")
|
|
1893
|
+
return exit_code
|
|
1894
|
+
|
|
1895
|
+
print(f"=== {result['file']} ===")
|
|
1896
|
+
if result["error"]:
|
|
1897
|
+
print(f"ERROR [{result['error_code']}]: {result['error']}", file=sys.stderr)
|
|
1898
|
+
for check in result["checks"]:
|
|
1899
|
+
icon = {"PASS": "✅", "FAIL": "❌", "N/A": "⬜"}[check["result"]]
|
|
1900
|
+
print(f" {icon} #{check['id']} {check['label']}: {check['detail']}")
|
|
1901
|
+
print(" ---")
|
|
1902
|
+
print(
|
|
1903
|
+
f" PASS: {result['passed']} FAIL: {result['failed']} "
|
|
1904
|
+
f"N/A: {result['na']} CRITICAL: {result['critical_failed']}"
|
|
1905
|
+
)
|
|
1906
|
+
print(f" Profile: {result['profile']} Qualified: {result['qualified']}")
|
|
1907
|
+
return exit_code
|
|
1908
|
+
|
|
1909
|
+
|
|
1910
|
+
if __name__ == "__main__":
|
|
1911
|
+
raise SystemExit(main())
|