@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,203 @@
1
+ # -*- coding: utf-8 -*-
2
+ """严格校验 ``project_docs`` 内的 Markdown 文档链接。
3
+
4
+ 本工具只校验和报告,不生成或写入 manifest。manifest 发布由
5
+ ``sync_project_docs.py`` 的最终协调阶段负责。
6
+ """
7
+
8
+ from __future__ import annotations
9
+ import sys as _bootstrap_sys
10
+ from pathlib import Path as _bootstrap_path
11
+ _bootstrap_sys.dont_write_bytecode = True
12
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
13
+ import _paths # noqa: E402
14
+ _paths.install()
15
+
16
+ import argparse
17
+ import concurrent.futures
18
+ import os
19
+ import sys
20
+ from pathlib import Path, PurePosixPath
21
+ from typing import Any, Sequence
22
+
23
+ from project_docs_contract import (
24
+ LinkDisposition,
25
+ PathConflictError,
26
+ PathValidationError, # noqa: F401 — re-exported; callers raise/catch via link_check
27
+ ProjectDocsContractError,
28
+ configure_stdio_utf8,
29
+ discover_active_markdown_paths,
30
+ read_markdown_links,
31
+ resolve_docs_root,
32
+ stable_json_dumps,
33
+ )
34
+
35
+
36
+ def discover_documents(project_docs: str | os.PathLike[str]) -> list[tuple[str, Path]]:
37
+ """使用共享契约确定性枚举完整活动 Markdown 集合。"""
38
+
39
+ root = resolve_docs_root(project_docs)
40
+ return [
41
+ (relative, root.joinpath(*PurePosixPath(relative).parts))
42
+ for relative in discover_active_markdown_paths(root)
43
+ ]
44
+
45
+
46
+ def _is_quarantine_relative(relative_path: str) -> bool:
47
+ parts = PurePosixPath(relative_path).parts
48
+ return bool(parts) and parts[0].casefold() == ".quarantine"
49
+
50
+
51
+ def check_links_with_graph(
52
+ project_docs: str | os.PathLike[str],
53
+ ) -> tuple[int, list[dict[str, Any]], dict[str, set[str]], list[dict[str, str]]]:
54
+ """一次遍历完成链接校验并构建入链图,供下游 ``phase4_exit`` 复用。
55
+
56
+ 返回 ``(问题数, 问题详情, inbound_sources, invalid_links)``。
57
+ """
58
+
59
+ root = resolve_docs_root(project_docs)
60
+ docs = discover_documents(root)
61
+ issues: list[dict[str, Any]] = []
62
+ inbound: dict[str, set[str]] = {doc_rel: set() for doc_rel, _ in docs}
63
+ invalid_links: list[dict[str, str]] = []
64
+
65
+ def _check_doc(
66
+ doc_rel: str,
67
+ ) -> tuple[list[dict[str, Any]], list[str], list[dict[str, str]]]:
68
+ doc_issues: list[dict[str, Any]] = []
69
+ targets: list[str] = []
70
+ doc_invalid: list[dict[str, str]] = []
71
+ for link in read_markdown_links(doc_rel, root):
72
+ if link.disposition is LinkDisposition.SKIPPED:
73
+ continue
74
+ if link.disposition is LinkDisposition.INVALID:
75
+ reason = link.reason or "invalid-local-target"
76
+ doc_issues.append(
77
+ {
78
+ "doc": doc_rel,
79
+ "text": link.text,
80
+ "target": link.raw_target,
81
+ "resolved": link.normalized_target,
82
+ "kind": "invalid",
83
+ "reason": link.reason,
84
+ }
85
+ )
86
+ doc_invalid.append(
87
+ {
88
+ "source": doc_rel,
89
+ "target": link.raw_target,
90
+ "reason": reason,
91
+ }
92
+ )
93
+ else:
94
+ if link.exists is False:
95
+ doc_issues.append(
96
+ {
97
+ "doc": doc_rel,
98
+ "text": link.text,
99
+ "target": link.raw_target,
100
+ "resolved": link.project_relative_path,
101
+ "kind": "missing",
102
+ "reason": link.reason,
103
+ }
104
+ )
105
+ if link.is_local_document and link.project_relative_path is not None:
106
+ target = link.project_relative_path
107
+ if not _is_quarantine_relative(target) and target != doc_rel:
108
+ targets.append(target)
109
+ return doc_issues, targets, doc_invalid
110
+
111
+ if len(docs) > 1:
112
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
113
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
114
+ doc_rels = [doc_rel for doc_rel, _ in docs]
115
+ for doc_rel, (doc_issues, targets, doc_invalid) in zip(
116
+ doc_rels, executor.map(_check_doc, doc_rels)
117
+ ):
118
+ issues.extend(doc_issues)
119
+ invalid_links.extend(doc_invalid)
120
+ for target in targets:
121
+ inbound.setdefault(target, set()).add(doc_rel)
122
+ else:
123
+ for doc_rel, _ in docs:
124
+ doc_issues, targets, doc_invalid = _check_doc(doc_rel)
125
+ issues.extend(doc_issues)
126
+ invalid_links.extend(doc_invalid)
127
+ for target in targets:
128
+ inbound.setdefault(target, set()).add(doc_rel)
129
+
130
+ return len(issues), issues, inbound, invalid_links
131
+
132
+
133
+ def check_links(
134
+ project_docs: str | os.PathLike[str],
135
+ ) -> tuple[int, list[dict[str, Any]]]:
136
+ """检查全部本地文档链接,返回 ``(问题数, 详情)``。"""
137
+
138
+ issue_count, issues, _, _ = check_links_with_graph(project_docs)
139
+ return issue_count, issues
140
+
141
+
142
+ def _parser() -> argparse.ArgumentParser:
143
+ parser = argparse.ArgumentParser(description="校验 project_docs Markdown 链接")
144
+ parser.add_argument(
145
+ "--project-docs",
146
+ default="project_docs",
147
+ help="project_docs 目录(默认: project_docs)",
148
+ )
149
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
150
+ parser.add_argument(
151
+ "--check-only",
152
+ action="store_true",
153
+ help="兼容旧参数;当前工具始终只执行链接检查",
154
+ )
155
+ parser.add_argument(
156
+ "--manifest-only",
157
+ action="store_true",
158
+ help="已废弃;manifest 只能由同步协调器发布",
159
+ )
160
+ return parser
161
+
162
+
163
+ def main(argv: Sequence[str] | None = None) -> int:
164
+ configure_stdio_utf8()
165
+ args = _parser().parse_args(argv)
166
+ if args.manifest_only:
167
+ message = "--manifest-only 已废弃;请使用 sync_project_docs.py 构建 manifest"
168
+ if args.json:
169
+ print(stable_json_dumps({"error": message, "ok": False}), end="")
170
+ else:
171
+ print(f"ERROR: {message}", file=sys.stderr)
172
+ return 2
173
+
174
+ try:
175
+ issue_count, issues = check_links(args.project_docs)
176
+ result = {
177
+ "ok": issue_count == 0,
178
+ "broken_count": issue_count,
179
+ "broken": issues,
180
+ "manifest_written": False,
181
+ }
182
+ if args.json:
183
+ print(stable_json_dumps(result), end="")
184
+ elif issue_count:
185
+ print(f"发现 {issue_count} 条无效或断开的文档链接:")
186
+ for issue in issues:
187
+ print(
188
+ f" {issue['doc']} -> {issue['target']} "
189
+ f"({issue['kind']}: {issue['reason']})"
190
+ )
191
+ else:
192
+ print("文档链接校验通过:0 条断链。")
193
+ return 1 if issue_count else 0
194
+ except (OSError, ProjectDocsContractError, PathConflictError) as exc:
195
+ if args.json:
196
+ print(stable_json_dumps({"error": str(exc), "ok": False}), end="")
197
+ else:
198
+ print(f"ERROR: {exc}", file=sys.stderr)
199
+ return 2
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())
@@ -0,0 +1,211 @@
1
+ # -*- coding: utf-8 -*-
2
+ """机械规范化可精确识别的历史 ``Last synced`` 损坏尾缀。"""
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 re
14
+ import sys
15
+ from dataclasses import dataclass
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import Sequence
18
+
19
+ from link_check import discover_documents
20
+ from project_docs_contract import (
21
+ ProjectDocsContractError,
22
+ atomic_write_utf8,
23
+ configure_stdio_utf8,
24
+ parse_last_synced_marker,
25
+ project_sync_lock,
26
+ read_project_document,
27
+ resolve_docs_root,
28
+ stable_json_dumps,
29
+ )
30
+
31
+ # 历史迁移 bug 只会在完整 marker 后追加字面量 `` v3.1 -->``。
32
+ # 使用逐行锚定,避免“修复”任何其他自由文本或不完整注释。
33
+ _DUPLICATE_V31_TAIL_RE = re.compile(
34
+ r"^(?P<marker><!--[ \t]*Last[ \t]+synced[ \t]*:[^\r\n]*?-->)[ \t]+"
35
+ r"v3\.1[ \t]*-->[ \t]*(?=\r?$)",
36
+ re.IGNORECASE | re.MULTILINE,
37
+ )
38
+
39
+
40
+ class MarkerNormalizationError(ValueError):
41
+ """marker 候选不满足可机械修复的精确前置条件。"""
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class MarkerChange:
46
+ path: str
47
+ line: int
48
+ before: str
49
+ after: str
50
+ original_content: str
51
+ normalized_content: str
52
+
53
+
54
+ def normalize_marker_content(
55
+ content: str, *, path: str = "<memory>"
56
+ ) -> tuple[str, list[dict]]:
57
+ """只移除精确的重复 v3.1 尾缀,保留原 marker 时间值。"""
58
+
59
+ changes: list[dict] = []
60
+
61
+ def replace(match: re.Match[str]) -> str:
62
+ marker = match.group("marker")
63
+ if parse_last_synced_marker(marker) is None:
64
+ raise MarkerNormalizationError(f"无法解析 Last synced marker: {path}")
65
+ line = content.count("\n", 0, match.start()) + 1
66
+ changes.append(
67
+ {
68
+ "path": path,
69
+ "line": line,
70
+ "before": match.group(0),
71
+ "after": marker,
72
+ }
73
+ )
74
+ return marker
75
+
76
+ normalized = _DUPLICATE_V31_TAIL_RE.sub(replace, content)
77
+ return normalized, changes
78
+
79
+
80
+ def collect_marker_changes(project_docs: str | Path) -> list[MarkerChange]:
81
+ """安全枚举文档并收集全部候选,不执行写入。"""
82
+
83
+ root = resolve_docs_root(project_docs)
84
+ collected: list[MarkerChange] = []
85
+ for relative, _ in discover_documents(root):
86
+ original = read_project_document(root, relative)
87
+ normalized, changes = normalize_marker_content(original, path=relative)
88
+ for item in changes:
89
+ collected.append(
90
+ MarkerChange(
91
+ path=relative,
92
+ line=item["line"],
93
+ before=item["before"],
94
+ after=item["after"],
95
+ original_content=original,
96
+ normalized_content=normalized,
97
+ )
98
+ )
99
+ collected.sort(key=lambda item: (item.path, item.line))
100
+ return collected
101
+
102
+
103
+ def _unique_file_changes(changes: Sequence[MarkerChange]) -> list[MarkerChange]:
104
+ unique: dict[str, MarkerChange] = {}
105
+ for change in changes:
106
+ previous = unique.get(change.path)
107
+ if (
108
+ previous is not None
109
+ and previous.normalized_content != change.normalized_content
110
+ ):
111
+ raise MarkerNormalizationError(
112
+ f"同一文档产生不一致的 marker 候选: {change.path}"
113
+ )
114
+ unique[change.path] = change
115
+ return [unique[path] for path in sorted(unique)]
116
+
117
+
118
+ def apply_marker_changes(
119
+ project_docs: str | Path,
120
+ changes: Sequence[MarkerChange],
121
+ *,
122
+ lock_timeout: float = 10.0,
123
+ ) -> list[str]:
124
+ """在单一锁下发布;失败时尽力逐文件回滚。"""
125
+
126
+ root = resolve_docs_root(project_docs)
127
+ files = _unique_file_changes(changes)
128
+ applied: list[MarkerChange] = []
129
+ with project_sync_lock(root.parent, timeout=lock_timeout):
130
+ try:
131
+ for change in files:
132
+ pure_path = PurePosixPath(change.path)
133
+ target = root.joinpath(*pure_path.parts)
134
+ if read_project_document(root, change.path) != change.original_content:
135
+ raise MarkerNormalizationError(
136
+ f"发布前文档已变化,拒绝覆盖: {change.path}"
137
+ )
138
+ atomic_write_utf8(target, change.normalized_content)
139
+ applied.append(change)
140
+ except BaseException as exc:
141
+ rollback_errors: list[str] = []
142
+ for change in reversed(applied):
143
+ target = root.joinpath(*PurePosixPath(change.path).parts)
144
+ try:
145
+ current = read_project_document(root, change.path)
146
+ if current != change.normalized_content:
147
+ rollback_errors.append(
148
+ f"{change.path}: 回滚冲突,文件已被并发修改"
149
+ )
150
+ continue
151
+ atomic_write_utf8(target, change.original_content)
152
+ except Exception as rollback_exc: # pragma: no cover - 双重 I/O 故障
153
+ rollback_errors.append(f"{change.path}: {rollback_exc}")
154
+ if rollback_errors:
155
+ raise MarkerNormalizationError(
156
+ f"marker 发布失败且回滚不完整: {exc}; " + "; ".join(rollback_errors)
157
+ ) from exc
158
+ raise
159
+ return [change.path for change in files]
160
+
161
+
162
+ def _parser() -> argparse.ArgumentParser:
163
+ parser = argparse.ArgumentParser(description="规范化历史 Last synced marker 尾缀")
164
+ parser.add_argument("--project-docs", default="project_docs")
165
+ parser.add_argument("--apply", action="store_true", help="原子写入候选修改")
166
+ parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
167
+ return parser
168
+
169
+
170
+ def main(argv: Sequence[str] | None = None) -> int:
171
+ configure_stdio_utf8()
172
+ args = _parser().parse_args(argv)
173
+ try:
174
+ changes = collect_marker_changes(args.project_docs)
175
+ applied_paths: list[str] = []
176
+ if args.apply and changes:
177
+ applied_paths = apply_marker_changes(args.project_docs, changes)
178
+ result = {
179
+ "ok": True,
180
+ "candidate_count": len(changes),
181
+ "candidate_file_count": len({change.path for change in changes}),
182
+ "applied": bool(args.apply and changes),
183
+ "applied_paths": applied_paths,
184
+ "changes": [
185
+ {
186
+ "path": change.path,
187
+ "line": change.line,
188
+ "before": change.before,
189
+ "after": change.after,
190
+ }
191
+ for change in changes
192
+ ],
193
+ }
194
+ if args.json:
195
+ print(stable_json_dumps(result), end="")
196
+ else:
197
+ action = "已规范化" if args.apply else "待规范化"
198
+ print(
199
+ f"{action}: {len(changes)} 处 / {len(set(c.path for c in changes))} 个文件"
200
+ )
201
+ return 0
202
+ except (OSError, MarkerNormalizationError, ProjectDocsContractError) as exc:
203
+ if args.json:
204
+ print(stable_json_dumps({"ok": False, "error": str(exc)}), end="")
205
+ else:
206
+ print(f"ERROR: {exc}", file=sys.stderr)
207
+ return 2
208
+
209
+
210
+ if __name__ == "__main__":
211
+ raise SystemExit(main())