@walvka-code/proj-doc-builder 4.0.0 → 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 (61) hide show
  1. package/README.md +290 -272
  2. package/README.zh-CN.md +258 -240
  3. package/package.json +6 -2
  4. package/skills/proj-doc-builder/SKILL.md +97 -35
  5. package/skills/proj-doc-builder/references/audit_script.md +103 -96
  6. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  7. package/skills/proj-doc-builder/references/checklist.md +20 -10
  8. package/skills/proj-doc-builder/references/exclusions.md +1 -1
  9. package/skills/proj-doc-builder/references/linking.md +83 -83
  10. package/skills/proj-doc-builder/references/templates.md +57 -17
  11. package/skills/proj-doc-builder/tests/claims.json +76 -0
  12. package/skills/proj-doc-builder/tests/conftest.py +17 -5
  13. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  14. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  15. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -248
  16. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +32 -1
  17. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1 -1
  18. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  19. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -2169
  20. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  21. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  22. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  23. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  24. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  25. package/skills/proj-doc-builder/tests/test_validate_doc.py +172 -15
  26. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  27. package/skills/proj-doc-builder/tools/{claude_doc_index.py → core/claude_doc_index.py} +504 -298
  28. package/skills/proj-doc-builder/tools/{compute_link.py → core/compute_link.py} +239 -233
  29. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  30. package/skills/proj-doc-builder/tools/{project_docs_contract.py → core/project_docs_contract.py} +460 -53
  31. package/skills/proj-doc-builder/tools/phase4/__init__.py +31 -6
  32. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +11 -4
  33. package/skills/proj-doc-builder/tools/phase4/engine.py +17 -2
  34. package/skills/proj-doc-builder/tools/phase4/journal.py +15 -8
  35. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +12 -5
  36. package/skills/proj-doc-builder/tools/phase4_exit.py +153 -47
  37. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  38. package/skills/proj-doc-builder/tools/{sync_project_docs.py → pipeline/sync_project_docs.py} +5531 -3639
  39. package/skills/proj-doc-builder/tools/{load_docs.py → reader/load_docs.py} +654 -380
  40. package/skills/proj-doc-builder/tools/{link_check.py → scan/link_check.py} +203 -152
  41. package/skills/proj-doc-builder/tools/{normalize_markers.py → scan/normalize_markers.py} +211 -205
  42. package/skills/proj-doc-builder/tools/{scan_dirs.py → scan/scan_dirs.py} +2735 -2405
  43. package/skills/proj-doc-builder/tools/{validate_doc.py → validate/validate_doc.py} +1911 -1299
  44. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  45. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  46. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  47. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  48. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  49. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  50. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  51. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  52. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  53. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  54. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  55. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  56. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  57. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  58. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  59. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  60. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  61. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
@@ -1,205 +1,211 @@
1
- # -*- coding: utf-8 -*-
2
- """机械规范化可精确识别的历史 ``Last synced`` 损坏尾缀。"""
3
-
4
- from __future__ import annotations
5
-
6
- import argparse
7
- import re
8
- import sys
9
- from dataclasses import dataclass
10
- from pathlib import Path, PurePosixPath
11
- from typing import Sequence
12
-
13
- from link_check import discover_documents
14
- from project_docs_contract import (
15
- ProjectDocsContractError,
16
- atomic_write_utf8,
17
- configure_stdio_utf8,
18
- parse_last_synced_marker,
19
- project_sync_lock,
20
- read_project_document,
21
- resolve_docs_root,
22
- stable_json_dumps,
23
- )
24
-
25
- # 历史迁移 bug 只会在完整 marker 后追加字面量 `` v3.1 -->``。
26
- # 使用逐行锚定,避免“修复”任何其他自由文本或不完整注释。
27
- _DUPLICATE_V31_TAIL_RE = re.compile(
28
- r"^(?P<marker><!--[ \t]*Last[ \t]+synced[ \t]*:[^\r\n]*?-->)[ \t]+"
29
- r"v3\.1[ \t]*-->[ \t]*(?=\r?$)",
30
- re.IGNORECASE | re.MULTILINE,
31
- )
32
-
33
-
34
- class MarkerNormalizationError(ValueError):
35
- """marker 候选不满足可机械修复的精确前置条件。"""
36
-
37
-
38
- @dataclass(frozen=True)
39
- class MarkerChange:
40
- path: str
41
- line: int
42
- before: str
43
- after: str
44
- original_content: str
45
- normalized_content: str
46
-
47
-
48
- def normalize_marker_content(
49
- content: str, *, path: str = "<memory>"
50
- ) -> tuple[str, list[dict]]:
51
- """只移除精确的重复 v3.1 尾缀,保留原 marker 时间值。"""
52
-
53
- changes: list[dict] = []
54
-
55
- def replace(match: re.Match[str]) -> str:
56
- marker = match.group("marker")
57
- if parse_last_synced_marker(marker) is None:
58
- raise MarkerNormalizationError(f"无法解析 Last synced marker: {path}")
59
- line = content.count("\n", 0, match.start()) + 1
60
- changes.append(
61
- {
62
- "path": path,
63
- "line": line,
64
- "before": match.group(0),
65
- "after": marker,
66
- }
67
- )
68
- return marker
69
-
70
- normalized = _DUPLICATE_V31_TAIL_RE.sub(replace, content)
71
- return normalized, changes
72
-
73
-
74
- def collect_marker_changes(project_docs: str | Path) -> list[MarkerChange]:
75
- """安全枚举文档并收集全部候选,不执行写入。"""
76
-
77
- root = resolve_docs_root(project_docs)
78
- collected: list[MarkerChange] = []
79
- for relative, _ in discover_documents(root):
80
- original = read_project_document(root, relative)
81
- normalized, changes = normalize_marker_content(original, path=relative)
82
- for item in changes:
83
- collected.append(
84
- MarkerChange(
85
- path=relative,
86
- line=item["line"],
87
- before=item["before"],
88
- after=item["after"],
89
- original_content=original,
90
- normalized_content=normalized,
91
- )
92
- )
93
- collected.sort(key=lambda item: (item.path, item.line))
94
- return collected
95
-
96
-
97
- def _unique_file_changes(changes: Sequence[MarkerChange]) -> list[MarkerChange]:
98
- unique: dict[str, MarkerChange] = {}
99
- for change in changes:
100
- previous = unique.get(change.path)
101
- if (
102
- previous is not None
103
- and previous.normalized_content != change.normalized_content
104
- ):
105
- raise MarkerNormalizationError(
106
- f"同一文档产生不一致的 marker 候选: {change.path}"
107
- )
108
- unique[change.path] = change
109
- return [unique[path] for path in sorted(unique)]
110
-
111
-
112
- def apply_marker_changes(
113
- project_docs: str | Path,
114
- changes: Sequence[MarkerChange],
115
- *,
116
- lock_timeout: float = 10.0,
117
- ) -> list[str]:
118
- """在单一锁下发布;失败时尽力逐文件回滚。"""
119
-
120
- root = resolve_docs_root(project_docs)
121
- files = _unique_file_changes(changes)
122
- applied: list[MarkerChange] = []
123
- with project_sync_lock(root.parent, timeout=lock_timeout):
124
- try:
125
- for change in files:
126
- pure_path = PurePosixPath(change.path)
127
- target = root.joinpath(*pure_path.parts)
128
- if read_project_document(root, change.path) != change.original_content:
129
- raise MarkerNormalizationError(
130
- f"发布前文档已变化,拒绝覆盖: {change.path}"
131
- )
132
- atomic_write_utf8(target, change.normalized_content)
133
- applied.append(change)
134
- except BaseException as exc:
135
- rollback_errors: list[str] = []
136
- for change in reversed(applied):
137
- target = root.joinpath(*PurePosixPath(change.path).parts)
138
- try:
139
- current = read_project_document(root, change.path)
140
- if current != change.normalized_content:
141
- rollback_errors.append(
142
- f"{change.path}: 回滚冲突,文件已被并发修改"
143
- )
144
- continue
145
- atomic_write_utf8(target, change.original_content)
146
- except Exception as rollback_exc: # pragma: no cover - 双重 I/O 故障
147
- rollback_errors.append(f"{change.path}: {rollback_exc}")
148
- if rollback_errors:
149
- raise MarkerNormalizationError(
150
- f"marker 发布失败且回滚不完整: {exc}; " + "; ".join(rollback_errors)
151
- ) from exc
152
- raise
153
- return [change.path for change in files]
154
-
155
-
156
- def _parser() -> argparse.ArgumentParser:
157
- parser = argparse.ArgumentParser(description="规范化历史 Last synced marker 尾缀")
158
- parser.add_argument("--project-docs", default="project_docs")
159
- parser.add_argument("--apply", action="store_true", help="原子写入候选修改")
160
- parser.add_argument("--json", action="store_true", help="stdout 仅输出 JSON")
161
- return parser
162
-
163
-
164
- def main(argv: Sequence[str] | None = None) -> int:
165
- configure_stdio_utf8()
166
- args = _parser().parse_args(argv)
167
- try:
168
- changes = collect_marker_changes(args.project_docs)
169
- applied_paths: list[str] = []
170
- if args.apply and changes:
171
- applied_paths = apply_marker_changes(args.project_docs, changes)
172
- result = {
173
- "ok": True,
174
- "candidate_count": len(changes),
175
- "candidate_file_count": len({change.path for change in changes}),
176
- "applied": bool(args.apply and changes),
177
- "applied_paths": applied_paths,
178
- "changes": [
179
- {
180
- "path": change.path,
181
- "line": change.line,
182
- "before": change.before,
183
- "after": change.after,
184
- }
185
- for change in changes
186
- ],
187
- }
188
- if args.json:
189
- print(stable_json_dumps(result), end="")
190
- else:
191
- action = "已规范化" if args.apply else "待规范化"
192
- print(
193
- f"{action}: {len(changes)} 处 / {len(set(c.path for c in changes))} 个文件"
194
- )
195
- return 0
196
- except (OSError, MarkerNormalizationError, ProjectDocsContractError) as exc:
197
- if args.json:
198
- print(stable_json_dumps({"ok": False, "error": str(exc)}), end="")
199
- else:
200
- print(f"ERROR: {exc}", file=sys.stderr)
201
- return 2
202
-
203
-
204
- if __name__ == "__main__":
205
- raise SystemExit(main())
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())