@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,361 @@
1
+ # -*- coding: utf-8 -*-
2
+ """v4.4 upgrades: lock-domain retention + root-directory role wording.
3
+
4
+ Two long-standing annoyances this covers:
5
+
6
+ * ``%TEMP%/proj-doc-builder-locks`` grew forever — one ``<digest>.lock`` per lock
7
+ target ever seen on the machine, plus one publish-history file per apply. Nothing
8
+ removed them, so directory listings got slow and temp space leaked. The fix adds
9
+ ``prune_lock_domain`` (unheld + old locks, capped history, aged journals) and a
10
+ ``--prune-locks`` mode, plus automatic housekeeping after a successful ``--apply``.
11
+ * the repository root described itself as, for example, "Python 脚本目录(1 个脚本)"
12
+ because the role was derived from whatever stray script happened to sit in the root,
13
+ which then read as "仓库根 是 Python 脚本目录" in the very document meant to explain
14
+ the whole project.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+
27
+ TOOLS = Path(__file__).resolve().parents[1] / "tools"
28
+ if str(TOOLS) not in sys.path:
29
+ sys.path.insert(0, str(TOOLS))
30
+
31
+ import _paths # noqa: E402
32
+
33
+ _paths.install(TOOLS)
34
+
35
+ import gen_docs_from_scaffold as doc_gen # noqa: E402
36
+ import project_docs_contract as contract # noqa: E402
37
+ import sync_project_docs # noqa: E402
38
+
39
+ TEST_PROJECT = Path(__file__).resolve().parents[3]
40
+
41
+
42
+ def _age(path: Path, hours: float) -> None:
43
+ stamp = time.time() - hours * 3600.0
44
+ os.utime(path, (stamp, stamp))
45
+
46
+
47
+ def _lock_domain(tmp_path: Path) -> Path:
48
+ parent = tmp_path / "locks"
49
+ parent.mkdir()
50
+ return parent
51
+
52
+
53
+ def _project_lock(domain: Path, root: Path) -> Path:
54
+ digest = contract.project_sync_lock_path(root).stem
55
+ path = domain / f"{digest}.lock"
56
+ path.write_text("", encoding="utf-8")
57
+ return path
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # lock-domain retention
62
+ # ---------------------------------------------------------------------------
63
+
64
+
65
+ def test_prune_drops_unheld_old_locks_and_keeps_fresh_ones(tmp_path: Path) -> None:
66
+ root = tmp_path / "project"
67
+ root.mkdir()
68
+ domain = _lock_domain(tmp_path)
69
+ stale = domain / "aa11bb22.lock"
70
+ fresh = domain / "cc33dd44.lock"
71
+ for path in (stale, fresh):
72
+ path.write_text("", encoding="utf-8")
73
+ _age(stale, 5)
74
+ protected = _project_lock(domain, root)
75
+
76
+ summary = contract.prune_lock_domain(root, lock_parent=domain, history_keep=20)
77
+
78
+ assert not stale.exists(), "unheld lock older than the stale window must be dropped"
79
+ assert fresh.exists(), "a lock created just now must survive"
80
+ assert protected.exists(), "the current project's own lock is never pruned"
81
+ assert summary["removed"] == {"lock": 1}
82
+ assert summary["protected"] == [protected.name]
83
+ assert summary["in_use"] == 0
84
+
85
+
86
+ def test_prune_counts_held_lock_as_in_use(tmp_path: Path) -> None:
87
+ root = tmp_path / "project"
88
+ root.mkdir()
89
+ domain = _lock_domain(tmp_path)
90
+ held = domain / "ee55ff66.lock"
91
+ held.write_text("", encoding="utf-8")
92
+ _age(held, 5)
93
+
94
+ # A live holder must be a *separate process*: advisory locks are per-process on
95
+ # Windows, so re-locking from this process would look "free" and prove nothing.
96
+ child = subprocess.Popen(
97
+ [
98
+ sys.executable,
99
+ "-c",
100
+ (
101
+ "import sys, time\n"
102
+ f"sys.path.insert(0, {str(TOOLS / 'core')!r})\n"
103
+ "import project_docs_contract as c\n"
104
+ f"lock = c.ExclusiveFileLock({str(held)!r})\n"
105
+ "lock.acquire()\n"
106
+ "print('locked', flush=True)\n"
107
+ "time.sleep(60)\n"
108
+ ),
109
+ ],
110
+ stdout=subprocess.PIPE,
111
+ text=True,
112
+ encoding="utf-8",
113
+ )
114
+ try:
115
+ assert child.stdout is not None
116
+ assert child.stdout.readline().strip() == "locked"
117
+
118
+ summary = contract.prune_lock_domain(root, lock_parent=domain)
119
+ assert held.exists(), "a lock held by a live process must never be removed"
120
+ assert summary["in_use"] == 1
121
+ assert summary["removed"] == {}
122
+ finally:
123
+ child.kill()
124
+ child.wait(timeout=30)
125
+
126
+ # once the holder is gone the orphan becomes prunable
127
+ _age(held, 5)
128
+ summary = contract.prune_lock_domain(root, lock_parent=domain)
129
+ assert summary["removed"] == {"lock": 1}
130
+ assert not held.exists()
131
+
132
+
133
+ def test_prune_caps_publish_history_per_digest(tmp_path: Path) -> None:
134
+ root = tmp_path / "project"
135
+ root.mkdir()
136
+ domain = _lock_domain(tmp_path)
137
+ digest = "abc123"
138
+ for index in range(5):
139
+ path = domain / f"{digest}{contract.COORDINATOR_HISTORY_MARKER}{index}-committed.json"
140
+ path.write_text("{}", encoding="utf-8")
141
+ _age(path, 5 - index) # index 4 is the newest
142
+ other = domain / f"fff999{contract.COORDINATOR_HISTORY_MARKER}0-committed.json"
143
+ other.write_text("{}", encoding="utf-8")
144
+
145
+ summary = contract.prune_lock_domain(root, lock_parent=domain, history_keep=2)
146
+
147
+ remaining = sorted(
148
+ p.name for p in domain.iterdir() if contract.COORDINATOR_HISTORY_MARKER in p.name
149
+ )
150
+ assert summary["removed"] == {"history": 3}
151
+ assert len(remaining) == 3, f"two for the busy digest plus one for the other, got {remaining}"
152
+ assert f"{digest}{contract.COORDINATOR_HISTORY_MARKER}4-committed.json" in remaining
153
+ assert f"{digest}{contract.COORDINATOR_HISTORY_MARKER}3-committed.json" in remaining
154
+
155
+
156
+ def test_prune_keeps_recent_journal_but_drops_aged_one(tmp_path: Path) -> None:
157
+ root = tmp_path / "project"
158
+ root.mkdir()
159
+ domain = _lock_domain(tmp_path)
160
+ recent = domain / f"aaa111{contract.COORDINATOR_JOURNAL_SUFFIX}"
161
+ aged = domain / f"bbb222{contract.COORDINATOR_JOURNAL_SUFFIX}"
162
+ recent.write_text("{}", encoding="utf-8")
163
+ aged.write_text("{}", encoding="utf-8")
164
+ _age(aged, 24 * 30)
165
+
166
+ summary = contract.prune_lock_domain(root, lock_parent=domain)
167
+
168
+ assert recent.exists(), "a journal inside the recovery window must survive"
169
+ assert not aged.exists(), "a month-old journal is dead weight"
170
+ assert summary["removed"] == {"journal": 1}
171
+
172
+
173
+ def test_prune_never_touches_current_project_journal(tmp_path: Path) -> None:
174
+ root = tmp_path / "project"
175
+ root.mkdir()
176
+ domain = _lock_domain(tmp_path)
177
+ slots = contract.coordinator_publish_journal_paths(root)
178
+ path = next(iter(slots.values()))
179
+ local = domain / path.name
180
+ local.write_text("{}", encoding="utf-8")
181
+ _age(local, 24 * 30)
182
+
183
+ summary = contract.prune_lock_domain(root, lock_parent=domain)
184
+
185
+ assert local.exists(), "a pending journal of this project must be resolved, not deleted"
186
+ assert local.name in summary["protected"]
187
+
188
+
189
+ def test_prune_dry_run_reports_without_deleting(tmp_path: Path) -> None:
190
+ root = tmp_path / "project"
191
+ root.mkdir()
192
+ domain = _lock_domain(tmp_path)
193
+ stale = domain / "dead.lock"
194
+ stale.write_text("", encoding="utf-8")
195
+ _age(stale, 5)
196
+
197
+ summary = contract.prune_lock_domain(root, lock_parent=domain, dry_run=True)
198
+
199
+ assert stale.exists()
200
+ assert summary["removed"] == {"lock": 1}
201
+ assert summary["dry_run"] is True
202
+
203
+
204
+ def test_prune_missing_domain_is_a_noop(tmp_path: Path) -> None:
205
+ summary = contract.prune_lock_domain(
206
+ tmp_path, lock_parent=tmp_path / "does-not-exist"
207
+ )
208
+ assert summary["scanned"] == 0
209
+ assert summary["removed"] == {}
210
+
211
+
212
+ def test_prune_locks_project_reports_mode(tmp_path: Path) -> None:
213
+ root = tmp_path / "project"
214
+ root.mkdir()
215
+ report, code = sync_project_docs.prune_locks_project(root, dry_run=True)
216
+ assert code == 0
217
+ assert report["mode"] == "prune-locks"
218
+ assert report["ok"] is True
219
+ assert "lock_domain" in report
220
+
221
+
222
+ def test_prune_locks_cli_dry_run(tmp_path: Path) -> None:
223
+ root = tmp_path / "project"
224
+ root.mkdir()
225
+ completed = subprocess.run(
226
+ [
227
+ sys.executable,
228
+ str(TOOLS / "pipeline" / "sync_project_docs.py"),
229
+ str(root),
230
+ "--prune-locks",
231
+ "--dry-run",
232
+ "--json",
233
+ ],
234
+ capture_output=True,
235
+ text=True,
236
+ encoding="utf-8",
237
+ timeout=180,
238
+ )
239
+ assert completed.returncode == 0, completed.stderr
240
+ payload = json.loads(completed.stdout)
241
+ assert payload["mode"] == "prune-locks"
242
+ assert payload["dry_run"] is True
243
+
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # root-directory wording
247
+ # ---------------------------------------------------------------------------
248
+
249
+
250
+ def test_directory_role_names_the_repository_root() -> None:
251
+ role = doc_gen._directory_role(
252
+ ["cx3322a.py"],
253
+ ["python_side", "firmware_side", "tools"],
254
+ is_boundary=False,
255
+ is_archive=False,
256
+ profile="standard",
257
+ is_root=True,
258
+ )
259
+ assert role.startswith("仓库根")
260
+ assert "1 个直接文件" in role
261
+ assert "3 个顶层子目录" in role
262
+ assert "Python" not in role, "the root role must not be derived from a stray script"
263
+
264
+
265
+ def test_directory_role_ignores_root_flag_for_nested_directories() -> None:
266
+ role = doc_gen._directory_role(
267
+ ["gen_config_package.py"],
268
+ [],
269
+ is_boundary=False,
270
+ is_archive=False,
271
+ profile="standard",
272
+ )
273
+ assert "仓库根" not in role
274
+
275
+
276
+ def test_root_document_overview_avoids_self_reference(tmp_path: Path) -> None:
277
+ root = tmp_path / "proj"
278
+ (root / "src").mkdir(parents=True)
279
+ (root / "cx3322a.py").write_text("VALUE = 1\n", encoding="utf-8")
280
+ scaffold_item = {
281
+ "path": "",
282
+ "doc_path": "project_docs/index.md",
283
+ "change": "new",
284
+ "direct_files": [{"name": "cx3322a.py", "size": 10, "is_py": True}],
285
+ "inventory_files": ["cx3322a.py"],
286
+ "inventory_subdirs": ["src"],
287
+ "direct_subdirectories": ["src"],
288
+ "is_boundary": False,
289
+ "recommended_profile": "standard",
290
+ "profile_basis": "files=1,subdirs=1",
291
+ "precomputed_links": {
292
+ "parent": None,
293
+ "children": [
294
+ {"path": "src", "doc_path": "project_docs/src.md", "relative_link": "src.md"},
295
+ ],
296
+ "tests": None,
297
+ },
298
+ }
299
+ text = doc_gen.generate_document_from_scaffold(scaffold_item, project_root=root)
300
+ overview = text.split("## 概述", 1)[1].split("## 文件清单", 1)[0]
301
+ assert text.splitlines()[0].startswith("# ")
302
+ assert "仓库根" in text.splitlines()[0]
303
+ assert "是项目源码树中的仓库根" not in text
304
+ assert "是项目总入口" in overview
305
+ assert "上游无父模块" in overview
306
+
307
+
308
+ def test_generated_root_document_uses_root_role(tmp_path: Path) -> None:
309
+ """End-to-end: a scaffold whose only root file is a script still says 仓库根."""
310
+
311
+ root = tmp_path / "proj"
312
+ (root / "project_docs").mkdir(parents=True)
313
+ (root / "src").mkdir()
314
+ (root / "cx3322a.py").write_text("VALUE = 1\n", encoding="utf-8")
315
+ (root / "src" / "alpha.py").write_text("def compute(x):\n return x + 1\n", encoding="utf-8")
316
+ scaffold_path = tmp_path / "scaffold.json"
317
+ scaffold_path.write_text(
318
+ json.dumps(
319
+ {
320
+ "schema_version": 1,
321
+ "facts_enabled": False,
322
+ "scaffold": [
323
+ {
324
+ "path": "",
325
+ "doc_path": "project_docs/index.md",
326
+ "change": "new",
327
+ "direct_files": [{"name": "cx3322a.py", "size": 10, "is_py": True}],
328
+ "inventory_files": ["cx3322a.py"],
329
+ "inventory_subdirs": ["src"],
330
+ "direct_subdirectories": ["src"],
331
+ "is_boundary": False,
332
+ "recommended_profile": "standard",
333
+ "profile_basis": "files=1,subdirs=1",
334
+ "precomputed_links": {
335
+ "parent": None,
336
+ "children": [
337
+ {
338
+ "path": "src",
339
+ "doc_path": "project_docs/src.md",
340
+ "relative_link": "src.md",
341
+ }
342
+ ],
343
+ "tests": None,
344
+ },
345
+ }
346
+ ],
347
+ },
348
+ ensure_ascii=False,
349
+ ),
350
+ encoding="utf-8",
351
+ )
352
+
353
+ summary = doc_gen.generate_from_scaffold_file(
354
+ scaffold_path,
355
+ project_root=root,
356
+ overwrite=True,
357
+ )
358
+ assert summary.get("ok", False) is True, summary
359
+ first_line = (root / "project_docs" / "index.md").read_text(encoding="utf-8").splitlines()[0]
360
+ assert "仓库根" in first_line
361
+ assert "Python 脚本目录" not in first_line
@@ -0,0 +1,212 @@
1
+ # -*- coding: utf-8 -*-
2
+ """v4.5.2 upgrades: ``--full`` really is the final gate, honest ``first_run``,
3
+ and an actionable message for a relocated project.
4
+
5
+ Three defects this locks down (found by the review loop after 4.5.1):
6
+
7
+ * ``--full`` cleared ``comparison_previous``, so ``strict_paths`` was empty and the
8
+ advertised "发布前的终审档位" blocked nothing while validating every document
9
+ purely advisorily. Now, when a committed v2 baseline exists, critical check
10
+ failures on *any* document block under ``--full``; advisory richness checks stay
11
+ advisory so an in-progress migration is not deadlocked.
12
+ * ``first_run`` was derived from the candidate's own ``baseline.schema_version``,
13
+ which ``--full`` deliberately clears — so every ``--full`` run of an established
14
+ project printed "本轮为首轮同步(baseline.schema_version != 2)" and told the user
15
+ to "use --full" while already using it.
16
+ * a committed ``_scan_state.json`` is bound to the absolute project path, so a clone
17
+ or rename failed with a bare "belongs to a different project root" and no remedy.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ import shutil
24
+ from pathlib import Path
25
+
26
+ import pytest
27
+
28
+ import scan_dirs
29
+ import sync_project_docs
30
+
31
+ SYNCED = "2026-11-28T00:00:00Z"
32
+
33
+
34
+ def _write(path: Path, text: str) -> Path:
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ path.write_text(text, encoding="utf-8")
37
+ return path
38
+
39
+
40
+ def _make_valid_claude_md() -> str:
41
+ sections = [
42
+ ("doc-tree-instruction", "## 文档树索引\n\n- [index.md](project_docs/index.md)\n"),
43
+ ("project-overview", "## 项目概览\n\n测试项目。\n"),
44
+ ("common-commands", "## 常用命令\n\n```bash\npytest\n```\n"),
45
+ ("architecture", "## 架构说明\n\n核心模块。\n"),
46
+ ("test-structure", "## 测试结构\n\n单元测试。\n"),
47
+ ("dependencies", "## 依赖关系\n\n无额外依赖。\n"),
48
+ ]
49
+ parts = ["# CLAUDE.md\n"]
50
+ for name, body in sections:
51
+ parts.append(
52
+ f"<!-- AUTO-GENERATED v3.0: {name} START -->\n"
53
+ f"{body}"
54
+ f"<!-- AUTO-GENERATED v3.0: {name} END -->\n"
55
+ )
56
+ return "\n".join(parts)
57
+
58
+
59
+ def _setup_mini_project(tmp_path: Path) -> Path:
60
+ root = tmp_path / "proj"
61
+ root.mkdir()
62
+ _write(root / "CLAUDE.md", _make_valid_claude_md())
63
+ _write(root / "src" / "alpha.py", '"""Alpha module."""\n\ndef compute(x):\n return x + 1\n')
64
+ _write(root / "src" / "beta.py", '"""Beta module."""\n\nclass Runner:\n pass\n')
65
+ (root / "project_docs").mkdir()
66
+ return root
67
+
68
+
69
+ def _generate_and_apply(root: Path) -> None:
70
+ scaffold_file = root / "scaffold.json"
71
+ _, code = sync_project_docs.synchronize_project(
72
+ root, apply=False, force_full=True, scaffold_dump=scaffold_file
73
+ )
74
+ assert code in (sync_project_docs.EXIT_OK, sync_project_docs.EXIT_GATE_FAILED)
75
+ import gen_docs_from_scaffold as doc_gen
76
+
77
+ doc_gen.generate_from_scaffold_file(
78
+ scaffold_file, root, overwrite=True, timestamp=SYNCED
79
+ )
80
+ scaffold_file.unlink(missing_ok=True)
81
+ report, code = sync_project_docs.synchronize_project(root, apply=True)
82
+ assert code == sync_project_docs.EXIT_OK, report.get("errors")
83
+
84
+
85
+ def _drop_section(doc: Path, heading: str) -> None:
86
+ text = doc.read_text(encoding="utf-8")
87
+ pruned = re.sub(
88
+ rf"## {re.escape(heading)}.*?(?=\n## )", "", text, count=1, flags=re.S
89
+ )
90
+ assert pruned != text, f"section {heading} not found in {doc}"
91
+ doc.write_text(pruned, encoding="utf-8")
92
+
93
+
94
+ # ---------------------------------------------------------------------------
95
+ # 1. --full blocks a critical failure on an *unchanged* document
96
+ # ---------------------------------------------------------------------------
97
+ def test_full_blocks_critical_failure_on_unchanged_document(tmp_path: Path) -> None:
98
+ root = _setup_mini_project(tmp_path)
99
+ _generate_and_apply(root)
100
+
101
+ # 文件清单 is critical check 4; the source directory itself is untouched.
102
+ _drop_section(root / "project_docs" / "src.md", "文件清单")
103
+ refresh, code = sync_project_docs.synchronize_project(root, apply=True)
104
+ assert code == sync_project_docs.EXIT_OK, refresh.get("errors")
105
+
106
+ incremental, inc_code = sync_project_docs.synchronize_project(root, apply=False)
107
+ assert inc_code == sync_project_docs.EXIT_OK
108
+ assert incremental["validation"]["blocking_failure_count"] == 0
109
+ assert incremental["validation"]["strict_all_critical"] is False
110
+
111
+ full, full_code = sync_project_docs.synchronize_project(
112
+ root, apply=False, force_full=True
113
+ )
114
+ assert full_code == sync_project_docs.EXIT_GATE_FAILED
115
+ validation = full["validation"]
116
+ assert validation["strict_all_critical"] is True
117
+ assert validation["blocking_failure_count"] == 1
118
+ blocked = validation["blocking_failures"][0]
119
+ assert blocked["path"] == "src.md"
120
+ assert blocked["strict_scope"] == "full-critical"
121
+ assert blocked["critical_failed"] == 1
122
+ messages = [error["message"] for error in full["errors"]]
123
+ assert "src.md failed strict full-scope critical validation" in messages
124
+
125
+
126
+ def test_full_keeps_advisory_failures_advisory(tmp_path: Path) -> None:
127
+ root = _setup_mini_project(tmp_path)
128
+ _generate_and_apply(root)
129
+
130
+ # A deprecated extra section is advisory only (unknown/extra heading is not a
131
+ # critical check) — it must not block, and neither must an advisory failure.
132
+ doc = root / "project_docs" / "src.md"
133
+ doc.write_text(
134
+ doc.read_text(encoding="utf-8") + "\n## 技术债\n\n无。\n", encoding="utf-8"
135
+ )
136
+ refresh, code = sync_project_docs.synchronize_project(root, apply=True)
137
+ assert code == sync_project_docs.EXIT_OK, refresh.get("errors")
138
+
139
+ full, full_code = sync_project_docs.synchronize_project(
140
+ root, apply=False, force_full=True
141
+ )
142
+ assert full_code == sync_project_docs.EXIT_OK, full.get("errors")
143
+ assert full["validation"]["strict_all_critical"] is True
144
+ assert full["validation"]["blocking_failure_count"] == 0
145
+
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # 2. first_run must not be faked by --full on an established project
149
+ # ---------------------------------------------------------------------------
150
+ def test_full_reports_first_run_false_on_established_project(tmp_path: Path) -> None:
151
+ root = _setup_mini_project(tmp_path)
152
+ _generate_and_apply(root)
153
+
154
+ full, code = sync_project_docs.synchronize_project(
155
+ root, apply=False, force_full=True
156
+ )
157
+ assert code in (sync_project_docs.EXIT_OK, sync_project_docs.EXIT_GATE_FAILED)
158
+ assert full["first_run"] is False
159
+ assert "first_run_notice" not in full
160
+ assert "full_scope_note" in full
161
+ assert "--full" in full["full_scope_note"]
162
+
163
+
164
+ def test_first_run_still_reported_without_committed_state(tmp_path: Path) -> None:
165
+ root = _setup_mini_project(tmp_path)
166
+ report, code = sync_project_docs.synchronize_project(
167
+ root, apply=False, force_full=True
168
+ )
169
+ assert code in (sync_project_docs.EXIT_OK, sync_project_docs.EXIT_GATE_FAILED)
170
+ assert report["first_run"] is True
171
+ assert "first_run_notice" in report
172
+ # No committed baseline: --full must not invent strict blocking.
173
+ assert report["validation"]["strict_all_critical"] is False
174
+ assert report["validation"]["blocking_failure_count"] == 0
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # 3. a relocated project explains itself and offers a remedy
179
+ # ---------------------------------------------------------------------------
180
+ def test_relocated_project_error_names_the_remedy(tmp_path: Path) -> None:
181
+ root = _setup_mini_project(tmp_path)
182
+ _generate_and_apply(root)
183
+
184
+ moved = tmp_path / "moved"
185
+ shutil.copytree(root, moved)
186
+
187
+ # ``synchronize_project`` raises on a scanner/contract input error; the CLI
188
+ # ``main`` wrapper catches it and emits an ``input-or-operational-error``
189
+ # result with the same message. The library-level test asserts the message
190
+ # carries the actionable remedy so a clone or rename no longer dead-ends.
191
+ with pytest.raises(scan_dirs.ScanStateError) as exc_info:
192
+ sync_project_docs.synchronize_project(moved, apply=False)
193
+ message = str(exc_info.value)
194
+ assert "different project root" in message
195
+ assert "--full" in message
196
+ assert "_scan_state.json" in message
197
+
198
+
199
+ def test_full_rebinds_a_relocated_project(tmp_path: Path) -> None:
200
+ root = _setup_mini_project(tmp_path)
201
+ _generate_and_apply(root)
202
+
203
+ moved = tmp_path / "moved"
204
+ shutil.copytree(root, moved)
205
+
206
+ rebind, code = sync_project_docs.synchronize_project(
207
+ moved, apply=True, force_full=True
208
+ )
209
+ assert code == sync_project_docs.EXIT_OK, rebind.get("errors")
210
+
211
+ after, after_code = sync_project_docs.synchronize_project(moved, apply=False)
212
+ assert after_code == sync_project_docs.EXIT_OK, after.get("errors")