@walvka-code/proj-doc-builder 0.0.0-stage → 4.0.0

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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +271 -2
  3. package/README.zh-CN.md +240 -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 +55 -4
  10. package/skills/proj-doc-builder/SKILL.md +350 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +96 -0
  12. package/skills/proj-doc-builder/references/checklist.md +80 -0
  13. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  14. package/skills/proj-doc-builder/references/linking.md +83 -0
  15. package/skills/proj-doc-builder/references/migration.md +32 -0
  16. package/skills/proj-doc-builder/references/phase4.md +200 -0
  17. package/skills/proj-doc-builder/references/templates.md +172 -0
  18. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  19. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  20. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  21. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  22. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  23. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  24. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  25. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  26. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  27. package/skills/proj-doc-builder/tests/conftest.py +11 -0
  28. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  29. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  30. package/skills/proj-doc-builder/tests/test_load_docs.py +248 -0
  31. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  32. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  33. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +781 -0
  34. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  35. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  36. package/skills/proj-doc-builder/tests/test_validate_doc.py +555 -0
  37. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  38. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  39. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  40. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  41. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  42. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  43. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  44. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  45. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
  46. package/skills/proj-doc-builder/tools/claude_doc_index.py +298 -0
  47. package/skills/proj-doc-builder/tools/compute_link.py +233 -0
  48. package/skills/proj-doc-builder/tools/link_check.py +152 -0
  49. package/skills/proj-doc-builder/tools/load_docs.py +380 -0
  50. package/skills/proj-doc-builder/tools/normalize_markers.py +205 -0
  51. package/skills/proj-doc-builder/tools/phase4/__init__.py +57 -0
  52. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +18 -0
  53. package/skills/proj-doc-builder/tools/phase4/engine.py +20 -0
  54. package/skills/proj-doc-builder/tools/phase4/journal.py +22 -0
  55. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +20 -0
  56. package/skills/proj-doc-builder/tools/phase4_exit.py +8459 -0
  57. package/skills/proj-doc-builder/tools/project_docs_contract.py +2318 -0
  58. package/skills/proj-doc-builder/tools/scan_dirs.py +2405 -0
  59. package/skills/proj-doc-builder/tools/sync_project_docs.py +3639 -0
  60. package/skills/proj-doc-builder/tools/validate_doc.py +1299 -0
@@ -0,0 +1,1159 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Focused contract tests for the schema-v2 directory scanner."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import copy
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+
16
+ import project_docs_contract as contract
17
+ import scan_dirs
18
+
19
+
20
+ def _mkdir_with_file(path: Path, name: str = "data.txt", text: str = "data") -> Path:
21
+ path.mkdir(parents=True, exist_ok=True)
22
+ file_path = path / name
23
+ file_path.write_text(text, encoding="utf-8")
24
+ return file_path
25
+
26
+
27
+ def _snapshot_map(state: dict) -> dict[str, dict]:
28
+ return {entry["path"]: entry for entry in state["snapshot"]["directories"]}
29
+
30
+
31
+ def _tamper_candidate(candidate: dict, field: str) -> dict:
32
+ tampered = copy.deepcopy(candidate)
33
+ if field == "directories":
34
+ tampered["directories"] = []
35
+ elif field == "deleted_directories":
36
+ tampered["deleted_directories"] = [{"path": "phantom", "change": "deleted"}]
37
+ elif field == "unknown_directories":
38
+ tampered["unknown_directories"] = [{"path": "phantom", "change": "unknown"}]
39
+ elif field == "changes":
40
+ tampered["changes"]["new"] = []
41
+ elif field == "change_counts":
42
+ tampered["change_counts"]["new"] = 0
43
+ elif field in (
44
+ "total",
45
+ "full_total",
46
+ "max_depth",
47
+ "boundary_count",
48
+ "skipped_directory_count",
49
+ ):
50
+ tampered[field] = int(tampered[field]) + 1
51
+ elif field == "mode":
52
+ tampered["mode"] = "incremental"
53
+ else: # pragma: no cover - protects the test helper itself
54
+ raise AssertionError(field)
55
+ return tampered
56
+
57
+
58
+ def test_source_starts_with_utf8_cookie() -> None:
59
+ source = Path(scan_dirs.__file__).read_text(encoding="utf-8")
60
+ assert source.splitlines()[0] == "# -*- coding: utf-8 -*-"
61
+
62
+
63
+ def test_v2_snapshot_fingerprint_covers_direct_metadata_and_structure(
64
+ tmp_path: Path,
65
+ ) -> None:
66
+ root = tmp_path / "project"
67
+ root.mkdir()
68
+ (root / "CLAUDE.md").write_text("root is not a boundary", encoding="utf-8")
69
+ package = root / "package"
70
+ direct_file = _mkdir_with_file(package, "module.py", "print('ok')\n")
71
+ (package / "child").mkdir()
72
+ fixed_mtime_ns = 1_700_000_000_123_456_700
73
+ os.utime(direct_file, ns=(fixed_mtime_ns, fixed_mtime_ns))
74
+
75
+ candidate = scan_dirs.build_candidate_state(root)
76
+ records = _snapshot_map(candidate)
77
+
78
+ assert candidate["schema_version"] == 2
79
+ assert candidate["state_role"] == "candidate"
80
+ assert {"package", "package/child"} <= records.keys()
81
+ package_record = records["package"]
82
+ assert package_record["snapshot"]["files"] == [
83
+ {
84
+ "name": "module.py",
85
+ "path": "module.py",
86
+ "file_type": "regular",
87
+ "size": direct_file.stat().st_size,
88
+ "mtime_ns": direct_file.stat().st_mtime_ns,
89
+ "sha256": hashlib.sha256(direct_file.read_bytes()).hexdigest(),
90
+ }
91
+ ]
92
+ assert package_record["snapshot"]["child_directories"] == ["child"]
93
+ assert package_record["snapshot"]["is_boundary"] is False
94
+ assert len(package_record["fingerprint"]) == 64
95
+
96
+ old_fingerprint = package_record["fingerprint"]
97
+ (package / "second_child").mkdir()
98
+ rescanned = scan_dirs.build_candidate_state(root, candidate, incremental=True)
99
+ assert _snapshot_map(rescanned)["package"]["fingerprint"] != old_fingerprint
100
+ assert "package" in rescanned["changes"]["modified"]
101
+ assert "package/second_child" in rescanned["changes"]["new"]
102
+
103
+
104
+ def test_same_size_and_mtime_content_change_is_modified(tmp_path: Path) -> None:
105
+ root = tmp_path / "project"
106
+ root.mkdir()
107
+ direct_file = _mkdir_with_file(root / "package", "payload.bin", "AAAA")
108
+ baseline = scan_dirs.build_candidate_state(root)
109
+ original_stat = direct_file.stat()
110
+ original_sha = _snapshot_map(baseline)["package"]["snapshot"]["files"][0]["sha256"]
111
+
112
+ direct_file.write_text("BBBB", encoding="utf-8")
113
+ os.utime(
114
+ direct_file,
115
+ ns=(original_stat.st_atime_ns, original_stat.st_mtime_ns),
116
+ )
117
+ candidate = scan_dirs.build_candidate_state(root, baseline, incremental=True)
118
+
119
+ assert direct_file.stat().st_size == original_stat.st_size
120
+ assert direct_file.stat().st_mtime_ns == original_stat.st_mtime_ns
121
+ assert candidate["changes"]["modified"] == ["package"]
122
+ assert (
123
+ _snapshot_map(candidate)["package"]["snapshot"]["files"][0]["sha256"]
124
+ != original_sha
125
+ )
126
+
127
+
128
+ def test_direct_file_symlink_is_rejected_without_following_outside_root(
129
+ tmp_path: Path,
130
+ ) -> None:
131
+ root = tmp_path / "project"
132
+ package = root / "package"
133
+ package.mkdir(parents=True)
134
+ outside = tmp_path / "outside.txt"
135
+ outside.write_text("secret", encoding="utf-8")
136
+ link = package / "linked.txt"
137
+ try:
138
+ link.symlink_to(outside)
139
+ except (NotImplementedError, OSError) as exc:
140
+ pytest.skip(f"file symlink creation is unavailable: {exc}")
141
+
142
+ with pytest.raises(scan_dirs.ScanError, match="symlink or reparse"):
143
+ scan_dirs.build_candidate_state(root)
144
+
145
+
146
+ def test_exclusions_use_unicode_casefold(tmp_path: Path) -> None:
147
+ root = tmp_path / "project"
148
+ root.mkdir()
149
+ _mkdir_with_file(root / "NoDe_MoDuLeS" / "dependency")
150
+ _mkdir_with_file(root / "PrOjEcT_DoCs" / "generated")
151
+ _mkdir_with_file(root / "visible")
152
+
153
+ paths = set(_snapshot_map(scan_dirs.build_candidate_state(root)))
154
+
155
+ assert paths == {"", "visible"}
156
+
157
+
158
+ def test_unicode_casefold_collision_is_rejected(tmp_path: Path) -> None:
159
+ root = tmp_path / "project"
160
+ package = root / "package"
161
+ package.mkdir(parents=True)
162
+ (package / "Straße.txt").write_text("one", encoding="utf-8")
163
+ (package / "STRASSE.txt").write_text("two", encoding="utf-8")
164
+ if len(list(package.iterdir())) != 2:
165
+ pytest.skip("filesystem does not permit the Unicode collision fixture")
166
+
167
+ with pytest.raises(scan_dirs.ScanError, match="casefold-colliding"):
168
+ scan_dirs.build_candidate_state(root)
169
+
170
+
171
+ def test_incremental_classifies_new_modified_deleted_renamed_and_unchanged(
172
+ tmp_path: Path,
173
+ ) -> None:
174
+ root = tmp_path / "project"
175
+ root.mkdir()
176
+ _mkdir_with_file(root / "stable")
177
+ changed_file = _mkdir_with_file(root / "changed")
178
+ _mkdir_with_file(root / "gone")
179
+ _mkdir_with_file(root / "container" / "old")
180
+
181
+ baseline = scan_dirs.build_candidate_state(root)
182
+ changed_file.write_text("different length", encoding="utf-8")
183
+ (root / "gone" / "data.txt").unlink()
184
+ (root / "gone").rmdir()
185
+ (root / "container" / "old").rename(root / "container" / "new")
186
+ _mkdir_with_file(root / "added")
187
+
188
+ candidate = scan_dirs.build_candidate_state(root, baseline, incremental=True)
189
+
190
+ assert candidate["mode"] == "incremental"
191
+ assert set(candidate["changes"]["new"]) == {"added", "container/new"}
192
+ assert {"changed", "container"} <= set(candidate["changes"]["modified"])
193
+ assert set(candidate["changes"]["deleted"]) == {"container/old", "gone"}
194
+ assert "stable" in candidate["changes"]["unchanged"]
195
+ assert candidate["changes"]["unknown"] == []
196
+ assert {entry["path"] for entry in candidate["directories"]} == {
197
+ "",
198
+ "added",
199
+ "changed",
200
+ "container",
201
+ "container/new",
202
+ }
203
+ assert {entry["path"] for entry in candidate["deleted_directories"]} == {
204
+ "container/old",
205
+ "gone",
206
+ }
207
+
208
+
209
+ def test_nested_claude_boundary_stops_recursion_and_descendants_become_unknown(
210
+ tmp_path: Path,
211
+ ) -> None:
212
+ root = tmp_path / "project"
213
+ root.mkdir()
214
+ (root / "CLAUDE.md").write_text("root boundary must be ignored", encoding="utf-8")
215
+ _mkdir_with_file(root / "open" / "deep")
216
+ _mkdir_with_file(root / "bounded" / "deep")
217
+
218
+ baseline = scan_dirs.build_candidate_state(root)
219
+ baseline_paths = _snapshot_map(baseline)
220
+ assert "open/deep" in baseline_paths
221
+ assert "bounded/deep" in baseline_paths
222
+
223
+ (root / "bounded" / "cLaUdE.Md").write_text(
224
+ "nested boundary",
225
+ encoding="utf-8",
226
+ )
227
+ candidate = scan_dirs.build_candidate_state(root, baseline, incremental=True)
228
+ records = _snapshot_map(candidate)
229
+
230
+ assert "open/deep" in records
231
+ assert records["bounded"]["is_boundary"] is True
232
+ assert "bounded/deep" not in records
233
+ assert "bounded/deep" in candidate["changes"]["unknown"]
234
+ assert "bounded/deep" not in candidate["changes"]["deleted"]
235
+ assert {
236
+ "path": "bounded",
237
+ "reason": "boundary",
238
+ "scope": "descendants",
239
+ } in candidate["snapshot"]["unknown_scopes"]
240
+
241
+
242
+ def test_outside_root_directory_symlink_is_skipped_and_reported(tmp_path: Path) -> None:
243
+ root = tmp_path / "project"
244
+ root.mkdir()
245
+ _mkdir_with_file(root / "inside")
246
+ outside = tmp_path / "outside"
247
+ _mkdir_with_file(outside / "secret")
248
+ link = root / "escape"
249
+ try:
250
+ link.symlink_to(outside, target_is_directory=True)
251
+ except (NotImplementedError, OSError) as exc:
252
+ pytest.skip(f"directory symlink creation is unavailable: {exc}")
253
+
254
+ candidate = scan_dirs.build_candidate_state(root)
255
+ paths = _snapshot_map(candidate)
256
+
257
+ assert "inside" in paths
258
+ assert "escape" not in paths
259
+ assert "escape/secret" not in paths
260
+ assert candidate["skipped_directory_count"] == 1
261
+ skipped = candidate["snapshot"]["skipped_directories"][0]
262
+ assert skipped["path"] == "escape"
263
+ assert skipped["reason"] == "outside-root"
264
+ assert skipped["kind"] == "symlink"
265
+ assert skipped["target"] == "<outside-root>"
266
+ assert {
267
+ "path": "escape",
268
+ "reason": "outside-root",
269
+ "scope": "subtree",
270
+ } in candidate["snapshot"]["unknown_scopes"]
271
+
272
+
273
+ def test_candidate_does_not_replace_state_commit_is_atomic_and_zero_change_is_valid(
274
+ tmp_path: Path,
275
+ monkeypatch: pytest.MonkeyPatch,
276
+ ) -> None:
277
+ root = tmp_path / "project"
278
+ root.mkdir()
279
+ _mkdir_with_file(root / "package")
280
+ state_path = tmp_path / "state.json"
281
+ candidate_path = tmp_path / "candidate.json"
282
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
283
+
284
+ replace_calls: list[tuple[Path, Path]] = []
285
+ real_replace = contract.os.replace
286
+
287
+ def recording_replace(source: str | Path, target: str | Path) -> None:
288
+ replace_calls.append((Path(source), Path(target)))
289
+ real_replace(source, target)
290
+
291
+ monkeypatch.setattr(contract.os, "replace", recording_replace)
292
+ first = scan_dirs.build_candidate_state(
293
+ root,
294
+ baseline_precondition=absent,
295
+ )
296
+ scan_dirs.write_candidate_state(candidate_path, first)
297
+
298
+ state_path.write_text('{"sentinel": true}\n', encoding="utf-8")
299
+ with pytest.raises(scan_dirs.BaselineConflict, match="baseline changed"):
300
+ scan_dirs.commit_candidate_state(
301
+ candidate_path,
302
+ state_path,
303
+ project_root=root,
304
+ expected_baseline=absent,
305
+ expected_candidate_generation_id=first["candidate_generation_id"],
306
+ )
307
+ assert contract.read_json_strict(state_path) == {"sentinel": True}
308
+ assert contract.read_json_strict(candidate_path)["state_role"] == "candidate"
309
+
310
+ state_path.unlink()
311
+ first = scan_dirs.build_candidate_state(
312
+ root,
313
+ baseline_precondition=absent,
314
+ )
315
+ scan_dirs.write_candidate_state(candidate_path, first)
316
+ committed = scan_dirs.commit_candidate_state(
317
+ candidate_path,
318
+ state_path,
319
+ project_root=root,
320
+ expected_baseline=absent,
321
+ expected_candidate_generation_id=first["candidate_generation_id"],
322
+ )
323
+ assert committed["state_role"] == "committed"
324
+ assert contract.read_json_strict(state_path)["state_role"] == "committed"
325
+ assert contract.read_json_strict(candidate_path)["state_role"] == "candidate"
326
+ assert all(source.parent == target.parent for source, target in replace_calls)
327
+
328
+ baseline_bytes = state_path.read_bytes()
329
+ previous = scan_dirs.load_previous_state(state_path)
330
+ zero_change = scan_dirs.build_candidate_state(root, previous, incremental=True)
331
+ assert zero_change["directories"] == []
332
+ assert zero_change["total"] == 0
333
+ assert zero_change["change_counts"] == {
334
+ "new": 0,
335
+ "modified": 0,
336
+ "deleted": 0,
337
+ "unchanged": 2,
338
+ "unknown": 0,
339
+ }
340
+ assert zero_change["snapshot"]["directories"]
341
+
342
+ monkeypatch.chdir(tmp_path)
343
+ scan_dirs.write_candidate_state("bare-candidate.json", zero_change)
344
+ assert (tmp_path / "bare-candidate.json").is_file()
345
+ assert state_path.read_bytes() == baseline_bytes
346
+
347
+
348
+ @pytest.mark.parametrize(
349
+ "field",
350
+ [
351
+ "directories",
352
+ "deleted_directories",
353
+ "unknown_directories",
354
+ "changes",
355
+ "change_counts",
356
+ "total",
357
+ "full_total",
358
+ "max_depth",
359
+ "boundary_count",
360
+ "skipped_directory_count",
361
+ "mode",
362
+ ],
363
+ )
364
+ def test_v2_validator_rejects_redundant_field_tampering(
365
+ tmp_path: Path,
366
+ field: str,
367
+ ) -> None:
368
+ root = tmp_path / "project"
369
+ root.mkdir()
370
+ _mkdir_with_file(root / "package")
371
+ candidate = scan_dirs.build_candidate_state(root)
372
+
373
+ with pytest.raises(scan_dirs.ScanStateError):
374
+ scan_dirs.validate_scan_state_v2(_tamper_candidate(candidate, field))
375
+
376
+
377
+ def test_candidate_generation_covers_non_snapshot_candidate_fields(
378
+ tmp_path: Path,
379
+ ) -> None:
380
+ root = tmp_path / "project"
381
+ root.mkdir()
382
+ _mkdir_with_file(root / "package")
383
+ candidate = scan_dirs.build_candidate_state(root)
384
+ tampered = copy.deepcopy(candidate)
385
+ tampered["scan_time"] = "2030-01-01T00:00:00+00:00"
386
+
387
+ with pytest.raises(scan_dirs.ScanStateError, match="candidate_generation_id"):
388
+ scan_dirs.validate_scan_state_v2(tampered)
389
+
390
+
391
+ def test_tampered_or_substituted_candidate_cannot_advance_baseline(
392
+ tmp_path: Path,
393
+ ) -> None:
394
+ root = tmp_path / "project"
395
+ root.mkdir()
396
+ direct_file = _mkdir_with_file(root / "package", text="AAAA")
397
+ candidate_path = tmp_path / "candidate.json"
398
+ state_path = tmp_path / "state.json"
399
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
400
+ accepted = scan_dirs.build_candidate_state(
401
+ root,
402
+ baseline_precondition=absent,
403
+ )
404
+ state_path.write_text('{"sentinel": true}\n', encoding="utf-8")
405
+
406
+ tampered = _tamper_candidate(accepted, "directories")
407
+ with pytest.raises(scan_dirs.ScanStateError):
408
+ scan_dirs.write_candidate_state(candidate_path, tampered)
409
+ contract.atomic_write_json(candidate_path, tampered)
410
+ with pytest.raises(scan_dirs.ScanStateError):
411
+ scan_dirs.commit_candidate_state(
412
+ candidate_path,
413
+ state_path,
414
+ project_root=root,
415
+ expected_baseline=absent,
416
+ expected_candidate_generation_id=accepted["candidate_generation_id"],
417
+ )
418
+ assert contract.read_json_strict(state_path) == {"sentinel": True}
419
+
420
+ direct_file.write_text("BBBB", encoding="utf-8")
421
+ replacement = scan_dirs.build_candidate_state(root)
422
+ scan_dirs.write_candidate_state(candidate_path, replacement)
423
+ with pytest.raises(scan_dirs.ScanStateError, match="accepted worklist"):
424
+ scan_dirs.commit_candidate_state(
425
+ candidate_path,
426
+ state_path,
427
+ project_root=root,
428
+ expected_baseline=absent,
429
+ expected_candidate_generation_id=accepted["candidate_generation_id"],
430
+ )
431
+ assert contract.read_json_strict(state_path) == {"sentinel": True}
432
+
433
+
434
+ def test_committed_state_is_portable_and_rejects_another_project(
435
+ tmp_path: Path,
436
+ ) -> None:
437
+ first_root = tmp_path / "first-project"
438
+ first_root.mkdir()
439
+ _mkdir_with_file(first_root / "package")
440
+ candidate_path = tmp_path / "candidate.json"
441
+ state_path = tmp_path / "state.json"
442
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
443
+ candidate = scan_dirs.build_candidate_state(
444
+ first_root,
445
+ baseline_precondition=absent,
446
+ )
447
+ scan_dirs.write_candidate_state(candidate_path, candidate)
448
+
449
+ committed = scan_dirs.commit_candidate_state(
450
+ candidate_path,
451
+ state_path,
452
+ project_root=first_root,
453
+ expected_baseline=absent,
454
+ expected_candidate_generation_id=candidate["candidate_generation_id"],
455
+ )
456
+ persisted_text = state_path.read_text(encoding="utf-8")
457
+
458
+ assert committed["root"] == "."
459
+ assert len(committed["project_identity"]) == 64
460
+ assert "candidate_path" not in committed
461
+ assert committed["state_path"] == state_path.name
462
+ assert not Path(committed["state_path"]).is_absolute()
463
+ assert first_root.resolve().as_posix() not in persisted_text.replace("\\", "/")
464
+
465
+ second_root = tmp_path / "second-project"
466
+ second_root.mkdir()
467
+ _mkdir_with_file(second_root / "package")
468
+ previous = scan_dirs.load_previous_state(state_path)
469
+ with pytest.raises(scan_dirs.ScanStateError, match="different project root"):
470
+ scan_dirs.build_candidate_state(second_root, previous, incremental=True)
471
+
472
+
473
+ def test_committed_validator_rejects_worklist_and_absolute_path_tampering(
474
+ tmp_path: Path,
475
+ ) -> None:
476
+ root = tmp_path / "project"
477
+ root.mkdir()
478
+ _mkdir_with_file(root / "package")
479
+ state_path = tmp_path / "state.json"
480
+ candidate_path = tmp_path / "candidate.json"
481
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
482
+ first = scan_dirs.build_candidate_state(
483
+ root,
484
+ baseline_precondition=absent,
485
+ )
486
+ scan_dirs.write_candidate_state(candidate_path, first)
487
+ scan_dirs.commit_candidate_state(
488
+ candidate_path,
489
+ state_path,
490
+ project_root=root,
491
+ expected_baseline=absent,
492
+ expected_candidate_generation_id=first["candidate_generation_id"],
493
+ )
494
+ previous, baseline, _ = scan_dirs.load_previous_state_with_precondition(state_path)
495
+ zero_change = scan_dirs.build_candidate_state(
496
+ root,
497
+ previous,
498
+ incremental=True,
499
+ baseline_precondition=baseline,
500
+ )
501
+ scan_dirs.write_candidate_state(candidate_path, zero_change)
502
+ committed = scan_dirs.commit_candidate_state(
503
+ candidate_path,
504
+ state_path,
505
+ project_root=root,
506
+ expected_baseline=baseline,
507
+ expected_candidate_generation_id=zero_change["candidate_generation_id"],
508
+ )
509
+ assert zero_change["directories"] == []
510
+ assert committed["directories"] == committed["snapshot"]["directories"]
511
+
512
+ bad_worklist = copy.deepcopy(committed)
513
+ bad_worklist["directories"] = []
514
+ bad_worklist["total"] = 0
515
+ with pytest.raises(scan_dirs.ScanStateError, match="directories"):
516
+ scan_dirs.validate_scan_state_v2(bad_worklist)
517
+
518
+ for field, value in (
519
+ ("root", root.resolve().as_posix()),
520
+ ("state_path", state_path.resolve().as_posix()),
521
+ ("candidate_path", candidate_path.resolve().as_posix()),
522
+ ):
523
+ tampered = copy.deepcopy(committed)
524
+ tampered[field] = value
525
+ with pytest.raises(scan_dirs.ScanStateError):
526
+ scan_dirs.validate_scan_state_v2(tampered)
527
+
528
+
529
+ def test_legacy_absolute_root_v2_migrates_without_persisting_the_path(
530
+ tmp_path: Path,
531
+ ) -> None:
532
+ root = tmp_path / "project"
533
+ root.mkdir()
534
+ _mkdir_with_file(root / "package")
535
+ candidate = scan_dirs.build_candidate_state(root)
536
+ legacy = copy.deepcopy(candidate)
537
+ legacy["state_role"] = "committed"
538
+ legacy["committed_at"] = "2026-07-29T00:00:00+00:00"
539
+ legacy["directories"] = copy.deepcopy(legacy["snapshot"]["directories"])
540
+ legacy["total"] = legacy["full_total"]
541
+ legacy["root"] = root.resolve().as_posix()
542
+ legacy.pop("project_identity")
543
+ legacy.pop("candidate_generation_id")
544
+ legacy_path = tmp_path / "legacy-v2.json"
545
+ contract.atomic_write_json(legacy_path, legacy)
546
+
547
+ migrated = scan_dirs.load_previous_state(legacy_path)
548
+ assert migrated["schema_version"] == 1
549
+ assert "root" not in migrated
550
+ same_project = scan_dirs.build_candidate_state(root, migrated, incremental=True)
551
+ assert same_project["changes"]["modified"] == ["", "package"]
552
+ assert same_project["root"] == "."
553
+
554
+ other_root = tmp_path / "other-project"
555
+ other_root.mkdir()
556
+ _mkdir_with_file(other_root / "package")
557
+ with pytest.raises(scan_dirs.ScanStateError, match="different project root"):
558
+ scan_dirs.build_candidate_state(other_root, migrated, incremental=True)
559
+
560
+
561
+ def test_force_full_ignores_previous_classification(tmp_path: Path) -> None:
562
+ root = tmp_path / "project"
563
+ root.mkdir()
564
+ changed_file = _mkdir_with_file(root / "stable", text="before")
565
+ _mkdir_with_file(root / "gone")
566
+ baseline = scan_dirs.build_candidate_state(root)
567
+ changed_file.write_text("after", encoding="utf-8")
568
+ (root / "gone" / "data.txt").unlink()
569
+ (root / "gone").rmdir()
570
+ _mkdir_with_file(root / "added")
571
+
572
+ candidate = scan_dirs.build_candidate_state(
573
+ root,
574
+ baseline,
575
+ incremental=True,
576
+ force_full=True,
577
+ )
578
+
579
+ assert candidate["mode"] == "full"
580
+ assert candidate["baseline"] == {
581
+ "available": False,
582
+ "schema_version": None,
583
+ "snapshot_fingerprint": None,
584
+ "candidate_generation_id": None,
585
+ "force_full": True,
586
+ }
587
+ assert candidate["changes"] == {
588
+ "new": ["", "added", "stable"],
589
+ "modified": [],
590
+ "deleted": [],
591
+ "unchanged": [],
592
+ "unknown": [],
593
+ }
594
+ assert {record["path"] for record in candidate["directories"]} == {
595
+ "",
596
+ "added",
597
+ "stable",
598
+ }
599
+ ignored_invalid_baseline = scan_dirs.build_candidate_state(
600
+ root,
601
+ {"schema_version": 999, "directories": "invalid"},
602
+ incremental=True,
603
+ force_full=True,
604
+ )
605
+ assert ignored_invalid_baseline["changes"] == candidate["changes"]
606
+
607
+
608
+ def test_legacy_mtime_state_is_accepted_but_migrated_conservatively(
609
+ tmp_path: Path,
610
+ ) -> None:
611
+ root = tmp_path / "project"
612
+ root.mkdir()
613
+ _mkdir_with_file(root / "package")
614
+ legacy_path = tmp_path / "legacy.json"
615
+ legacy_path.write_text(
616
+ json.dumps(
617
+ {
618
+ "last_scan": "2026-07-29T00:00:00+08:00",
619
+ "total": 1,
620
+ "directories": [{"path": "package", "src_mtime": 0}],
621
+ }
622
+ ),
623
+ encoding="utf-8",
624
+ )
625
+
626
+ legacy = scan_dirs.load_previous_state(legacy_path)
627
+ candidate = scan_dirs.incremental_scan(root, legacy)
628
+
629
+ assert candidate["baseline"] == {
630
+ "available": True,
631
+ "schema_version": 1,
632
+ "snapshot_fingerprint": None,
633
+ "candidate_generation_id": None,
634
+ "force_full": False,
635
+ }
636
+ assert candidate["changes"]["modified"] == ["package"]
637
+ assert candidate["schema_version"] == 2
638
+
639
+
640
+ def test_cli_json_is_clean_bare_output_works_and_errors_are_nonzero(
641
+ tmp_path: Path,
642
+ ) -> None:
643
+ root = tmp_path / "project"
644
+ root.mkdir()
645
+ _mkdir_with_file(root / "package")
646
+ script = Path(scan_dirs.__file__).resolve()
647
+ environment = dict(os.environ)
648
+ environment["PYTHONIOENCODING"] = "utf-8"
649
+
650
+ success = subprocess.run(
651
+ [
652
+ sys.executable,
653
+ str(script),
654
+ str(root),
655
+ "--incremental",
656
+ "--state",
657
+ "committed.json",
658
+ "--output",
659
+ "candidate.json",
660
+ "--json",
661
+ ],
662
+ cwd=tmp_path,
663
+ env=environment,
664
+ capture_output=True,
665
+ text=True,
666
+ encoding="utf-8",
667
+ check=False,
668
+ )
669
+
670
+ assert success.returncode == 0, success.stderr
671
+ payload = json.loads(success.stdout)
672
+ assert payload["schema_version"] == 2
673
+ assert payload["state_role"] == "candidate"
674
+ assert success.stderr == ""
675
+ assert (tmp_path / "candidate.json").is_file()
676
+ assert not (tmp_path / "committed.json").exists()
677
+
678
+ failure = subprocess.run(
679
+ [sys.executable, str(script), str(tmp_path / "missing"), "--json"],
680
+ cwd=tmp_path,
681
+ env=environment,
682
+ capture_output=True,
683
+ text=True,
684
+ encoding="utf-8",
685
+ check=False,
686
+ )
687
+ assert failure.returncode != 0
688
+ assert failure.stdout == ""
689
+ assert "ERROR:" in failure.stderr
690
+
691
+
692
+ def test_cli_explicit_commit_promotes_generated_candidate(tmp_path: Path) -> None:
693
+ root = tmp_path / "project"
694
+ root.mkdir()
695
+ _mkdir_with_file(root / "package")
696
+ script = Path(scan_dirs.__file__).resolve()
697
+ environment = dict(os.environ)
698
+ environment["PYTHONIOENCODING"] = "utf-8"
699
+ state_path = tmp_path / "state.json"
700
+ candidate_path = tmp_path / "candidate.json"
701
+
702
+ completed = subprocess.run(
703
+ [
704
+ sys.executable,
705
+ str(script),
706
+ str(root),
707
+ "--state",
708
+ str(state_path),
709
+ "--candidate",
710
+ str(candidate_path),
711
+ "--commit",
712
+ "--json",
713
+ ],
714
+ env=environment,
715
+ capture_output=True,
716
+ text=True,
717
+ encoding="utf-8",
718
+ check=False,
719
+ )
720
+
721
+ assert completed.returncode == 0, completed.stderr
722
+ output = json.loads(completed.stdout)
723
+ assert output["commit"]["performed"] is True
724
+ assert contract.read_json_strict(candidate_path)["state_role"] == "candidate"
725
+ assert contract.read_json_strict(state_path)["state_role"] == "committed"
726
+
727
+
728
+ def test_stable_scan_retries_when_file_appears_after_first_pass(
729
+ tmp_path: Path,
730
+ monkeypatch: pytest.MonkeyPatch,
731
+ ) -> None:
732
+ root = tmp_path / "project"
733
+ root.mkdir()
734
+ package = root / "package"
735
+ _mkdir_with_file(package, "first.txt", "first")
736
+
737
+ def add_file_after_first_pass(point: str, _root: Path) -> None:
738
+ if point == "after-pass-1":
739
+ (package / "late.txt").write_text("late", encoding="utf-8")
740
+
741
+ monkeypatch.setattr(scan_dirs, "_scan_fault", add_file_after_first_pass)
742
+ candidate = scan_dirs.build_candidate_state(root)
743
+ files = _snapshot_map(candidate)["package"]["snapshot"]["files"]
744
+
745
+ assert [item["name"] for item in files] == ["first.txt", "late.txt"]
746
+
747
+
748
+ def test_stable_scan_rejects_mixed_sibling_snapshot_and_retries(
749
+ tmp_path: Path,
750
+ monkeypatch: pytest.MonkeyPatch,
751
+ ) -> None:
752
+ root = tmp_path / "project"
753
+ root.mkdir()
754
+ package = root / "package"
755
+ first = _mkdir_with_file(package, "a.txt", "AAAA")
756
+ (package / "b.txt").write_text("BBBB", encoding="utf-8")
757
+ changed = False
758
+
759
+ def mutate_between_passes(point: str, scan_root: Path) -> None:
760
+ nonlocal changed
761
+ if point == "after-pass-1" and not changed:
762
+ changed = True
763
+ first.write_text("CCCC", encoding="utf-8")
764
+
765
+ # 注入点必须在两遍扫描之间(单线程),不能在另一个文件的快照钩子里改兄弟文件:
766
+ # 同一目录下多文件走并发快照,那个写法会与并发读竞争,导致偶发的
767
+ # "direct file changed while hashing" 而不是"混合快照 → 重试"。
768
+ monkeypatch.setattr(scan_dirs, "_scan_fault", mutate_between_passes)
769
+ candidate = scan_dirs.build_candidate_state(root)
770
+ files = _snapshot_map(candidate)["package"]["snapshot"]["files"]
771
+ by_name = {item["name"]: item for item in files}
772
+
773
+ assert changed is True
774
+ assert by_name["a.txt"]["sha256"] == hashlib.sha256(b"CCCC").hexdigest()
775
+
776
+
777
+ def test_stable_scan_detects_path_replacement_after_hash(
778
+ tmp_path: Path,
779
+ monkeypatch: pytest.MonkeyPatch,
780
+ ) -> None:
781
+ root = tmp_path / "project"
782
+ root.mkdir()
783
+ package = root / "package"
784
+ payload = _mkdir_with_file(package, "payload.bin", "AAAA")
785
+ original_snapshot = scan_dirs._file_snapshot
786
+ replaced = False
787
+
788
+ def replace_after_hash(entry, scan_root):
789
+ nonlocal replaced
790
+ snapshot = original_snapshot(entry, scan_root)
791
+ if entry.name == "payload.bin" and not replaced:
792
+ replaced = True
793
+ replacement = package / "replacement.bin"
794
+ replacement.write_text("BBBB", encoding="utf-8")
795
+ os.replace(replacement, payload)
796
+ return snapshot
797
+
798
+ monkeypatch.setattr(scan_dirs, "_file_snapshot", replace_after_hash)
799
+ candidate = scan_dirs.build_candidate_state(root)
800
+ file_info = _snapshot_map(candidate)["package"]["snapshot"]["files"][0]
801
+
802
+ assert replaced is True
803
+ assert file_info["sha256"] == hashlib.sha256(b"BBBB").hexdigest()
804
+
805
+
806
+ def test_stable_scan_fails_after_bounded_continuous_changes(
807
+ tmp_path: Path,
808
+ monkeypatch: pytest.MonkeyPatch,
809
+ ) -> None:
810
+ root = tmp_path / "project"
811
+ root.mkdir()
812
+ payload = _mkdir_with_file(root / "package", "payload.txt", "0")
813
+ passes: list[str] = []
814
+
815
+ def mutate_after_every_pass(point: str, _root: Path) -> None:
816
+ passes.append(point)
817
+ payload.write_text(str(len(passes)), encoding="utf-8")
818
+
819
+ monkeypatch.setattr(scan_dirs, "_scan_fault", mutate_after_every_pass)
820
+
821
+ with pytest.raises(scan_dirs.ScanError, match="stable two-pass snapshot"):
822
+ scan_dirs.build_candidate_state(root)
823
+ assert passes == [
824
+ "after-pass-1",
825
+ "after-pass-2",
826
+ "after-pass-3",
827
+ "after-pass-4",
828
+ ]
829
+
830
+
831
+ def test_candidate_commit_rejects_unbound_and_cross_project_candidates(
832
+ tmp_path: Path,
833
+ ) -> None:
834
+ first_root = tmp_path / "first"
835
+ second_root = tmp_path / "second"
836
+ first_root.mkdir()
837
+ second_root.mkdir()
838
+ _mkdir_with_file(first_root / "package")
839
+ _mkdir_with_file(second_root / "package")
840
+ candidate_path = tmp_path / "candidate.json"
841
+ state_path = tmp_path / "state.json"
842
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
843
+
844
+ unbound = scan_dirs.build_candidate_state(first_root)
845
+ scan_dirs.write_candidate_state(candidate_path, unbound)
846
+ with pytest.raises(scan_dirs.ScanStateError, match="not bound"):
847
+ scan_dirs.commit_candidate_state(
848
+ candidate_path,
849
+ state_path,
850
+ project_root=first_root,
851
+ expected_baseline=absent,
852
+ expected_candidate_generation_id=unbound["candidate_generation_id"],
853
+ )
854
+
855
+ bound = scan_dirs.build_candidate_state(
856
+ first_root,
857
+ baseline_precondition=absent,
858
+ )
859
+ scan_dirs.write_candidate_state(candidate_path, bound)
860
+ with pytest.raises(scan_dirs.ScanStateError, match="different project root"):
861
+ scan_dirs.commit_candidate_state(
862
+ candidate_path,
863
+ state_path,
864
+ project_root=second_root,
865
+ expected_baseline=absent,
866
+ expected_candidate_generation_id=bound["candidate_generation_id"],
867
+ )
868
+ assert not state_path.exists()
869
+
870
+
871
+ def test_force_full_candidate_still_compares_exact_baseline_preimage(
872
+ tmp_path: Path,
873
+ ) -> None:
874
+ root = tmp_path / "project"
875
+ root.mkdir()
876
+ _mkdir_with_file(root / "package")
877
+ state_path = tmp_path / "state.json"
878
+ candidate_path = tmp_path / "candidate.json"
879
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
880
+ initial = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
881
+ scan_dirs.write_candidate_state(candidate_path, initial)
882
+ scan_dirs.commit_candidate_state(
883
+ candidate_path,
884
+ state_path,
885
+ project_root=root,
886
+ expected_baseline=absent,
887
+ expected_candidate_generation_id=initial["candidate_generation_id"],
888
+ )
889
+ previous, baseline, _ = scan_dirs.load_previous_state_with_precondition(state_path)
890
+ force_full = scan_dirs.build_candidate_state(
891
+ root,
892
+ previous,
893
+ force_full=True,
894
+ baseline_precondition=baseline,
895
+ )
896
+ scan_dirs.write_candidate_state(candidate_path, force_full)
897
+ foreign = b'{"foreign":"replacement"}\n'
898
+ state_path.write_bytes(foreign)
899
+
900
+ with pytest.raises(scan_dirs.BaselineConflict, match="baseline changed"):
901
+ scan_dirs.commit_candidate_state(
902
+ candidate_path,
903
+ state_path,
904
+ project_root=root,
905
+ expected_baseline=baseline,
906
+ expected_candidate_generation_id=force_full["candidate_generation_id"],
907
+ )
908
+ assert state_path.read_bytes() == foreign
909
+
910
+
911
+ def test_candidate_commit_classifies_not_installed_failure(
912
+ tmp_path: Path,
913
+ monkeypatch: pytest.MonkeyPatch,
914
+ ) -> None:
915
+ root = tmp_path / "project"
916
+ root.mkdir()
917
+ _mkdir_with_file(root / "package")
918
+ state_path = tmp_path / "state.json"
919
+ candidate_path = tmp_path / "candidate.json"
920
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
921
+ candidate = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
922
+ scan_dirs.write_candidate_state(candidate_path, candidate)
923
+
924
+ def fail_before_install(_path: Path, _value: dict) -> Path:
925
+ raise OSError("before-install")
926
+
927
+ monkeypatch.setattr(contract, "atomic_write_json", fail_before_install)
928
+ with pytest.raises(scan_dirs.CandidateCommitError) as caught:
929
+ scan_dirs.commit_candidate_state(
930
+ candidate_path,
931
+ state_path,
932
+ project_root=root,
933
+ expected_baseline=absent,
934
+ expected_candidate_generation_id=candidate["candidate_generation_id"],
935
+ )
936
+
937
+ assert caught.value.disposition is scan_dirs.CommitDisposition.NOT_INSTALLED
938
+ assert caught.value.durability_confirmed is False
939
+ assert not state_path.exists()
940
+
941
+
942
+ def test_candidate_commit_classifies_installed_post_replace_failure(
943
+ tmp_path: Path,
944
+ monkeypatch: pytest.MonkeyPatch,
945
+ ) -> None:
946
+ root = tmp_path / "project"
947
+ root.mkdir()
948
+ _mkdir_with_file(root / "package")
949
+ state_path = tmp_path / "state.json"
950
+ candidate_path = tmp_path / "candidate.json"
951
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
952
+ candidate = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
953
+ scan_dirs.write_candidate_state(candidate_path, candidate)
954
+ real_atomic_write = contract.atomic_write_json
955
+
956
+ def interrupt_after_install(path: Path, value: dict) -> Path:
957
+ installed = real_atomic_write(path, value)
958
+ raise KeyboardInterrupt("after-install")
959
+
960
+ monkeypatch.setattr(contract, "atomic_write_json", interrupt_after_install)
961
+ with pytest.raises(scan_dirs.CandidateCommitError) as caught:
962
+ scan_dirs.commit_candidate_state(
963
+ candidate_path,
964
+ state_path,
965
+ project_root=root,
966
+ expected_baseline=absent,
967
+ expected_candidate_generation_id=candidate["candidate_generation_id"],
968
+ )
969
+
970
+ assert caught.value.disposition is scan_dirs.CommitDisposition.INSTALLED
971
+ assert caught.value.durability_confirmed is False
972
+ assert scan_dirs.load_previous_state(state_path) is not None
973
+
974
+
975
+ def test_candidate_commit_classifies_post_success_aba_as_unknown(
976
+ tmp_path: Path,
977
+ monkeypatch: pytest.MonkeyPatch,
978
+ ) -> None:
979
+ root = tmp_path / "project"
980
+ root.mkdir()
981
+ _mkdir_with_file(root / "package")
982
+ state_path = tmp_path / "state.json"
983
+ candidate_path = tmp_path / "candidate.json"
984
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
985
+ candidate = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
986
+ scan_dirs.write_candidate_state(candidate_path, candidate)
987
+ real_atomic_write = contract.atomic_write_json
988
+
989
+ def install_then_restore_absent(path: Path, value: dict) -> Path:
990
+ installed = real_atomic_write(path, value)
991
+ path.unlink()
992
+ return installed
993
+
994
+ monkeypatch.setattr(contract, "atomic_write_json", install_then_restore_absent)
995
+ with pytest.raises(scan_dirs.CandidateCommitError) as caught:
996
+ scan_dirs.commit_candidate_state(
997
+ candidate_path,
998
+ state_path,
999
+ project_root=root,
1000
+ expected_baseline=absent,
1001
+ expected_candidate_generation_id=candidate["candidate_generation_id"],
1002
+ )
1003
+
1004
+ assert caught.value.disposition is scan_dirs.CommitDisposition.UNKNOWN
1005
+ assert caught.value.durability_confirmed is True
1006
+ assert not state_path.exists()
1007
+
1008
+
1009
+ def test_candidate_commit_classifies_foreign_bytes_as_unknown(
1010
+ tmp_path: Path,
1011
+ monkeypatch: pytest.MonkeyPatch,
1012
+ ) -> None:
1013
+ root = tmp_path / "project"
1014
+ root.mkdir()
1015
+ _mkdir_with_file(root / "package")
1016
+ state_path = tmp_path / "state.json"
1017
+ candidate_path = tmp_path / "candidate.json"
1018
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
1019
+ candidate = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
1020
+ scan_dirs.write_candidate_state(candidate_path, candidate)
1021
+ foreign = b'{"foreign":true}\n'
1022
+
1023
+ def install_foreign_then_fail(path: Path, _value: dict) -> Path:
1024
+ path.write_bytes(foreign)
1025
+ raise OSError("foreign-install")
1026
+
1027
+ monkeypatch.setattr(contract, "atomic_write_json", install_foreign_then_fail)
1028
+ with pytest.raises(scan_dirs.CandidateCommitError) as caught:
1029
+ scan_dirs.commit_candidate_state(
1030
+ candidate_path,
1031
+ state_path,
1032
+ project_root=root,
1033
+ expected_baseline=absent,
1034
+ expected_candidate_generation_id=candidate["candidate_generation_id"],
1035
+ )
1036
+
1037
+ assert caught.value.disposition is scan_dirs.CommitDisposition.UNKNOWN
1038
+ assert caught.value.durability_confirmed is False
1039
+ assert state_path.read_bytes() == foreign
1040
+
1041
+
1042
+ def test_scanner_rejects_indirect_root_and_output_parent(
1043
+ tmp_path: Path,
1044
+ ) -> None:
1045
+ real_root = tmp_path / "real-project"
1046
+ real_root.mkdir()
1047
+ _mkdir_with_file(real_root / "package")
1048
+ root_link = tmp_path / "project-link"
1049
+ try:
1050
+ root_link.symlink_to(real_root, target_is_directory=True)
1051
+ except (NotImplementedError, OSError) as exc:
1052
+ pytest.skip(f"directory symlink creation is unavailable: {exc}")
1053
+
1054
+ with pytest.raises(scan_dirs.ScanError, match="indirect path"):
1055
+ scan_dirs.build_candidate_state(root_link)
1056
+
1057
+ candidate = scan_dirs.build_candidate_state(real_root)
1058
+ real_output = tmp_path / "real-output"
1059
+ real_output.mkdir()
1060
+ output_link = tmp_path / "output-link"
1061
+ output_link.symlink_to(real_output, target_is_directory=True)
1062
+ with pytest.raises(scan_dirs.ScanStateError, match="direct real directory"):
1063
+ scan_dirs.write_candidate_state(output_link / "candidate.json", candidate)
1064
+
1065
+
1066
+ def test_output_parent_is_not_created_through_an_indirect_ancestor(
1067
+ tmp_path: Path,
1068
+ ) -> None:
1069
+ root = tmp_path / "project"
1070
+ root.mkdir()
1071
+ _mkdir_with_file(root / "package")
1072
+ candidate = scan_dirs.build_candidate_state(root)
1073
+ real_output = tmp_path / "real-output"
1074
+ real_output.mkdir()
1075
+ output_link = tmp_path / "output-link"
1076
+ try:
1077
+ output_link.symlink_to(real_output, target_is_directory=True)
1078
+ except (NotImplementedError, OSError) as exc:
1079
+ pytest.skip(f"directory symlink creation is unavailable: {exc}")
1080
+
1081
+ escaped_parent = real_output / "new" / "nested"
1082
+ with pytest.raises(scan_dirs.ScanStateError, match="existing output parent"):
1083
+ scan_dirs.write_candidate_state(
1084
+ output_link / "new" / "nested" / "candidate.json",
1085
+ candidate,
1086
+ )
1087
+
1088
+ assert not escaped_parent.exists()
1089
+
1090
+
1091
+ def test_state_target_lock_is_shared_across_project_roots(tmp_path: Path) -> None:
1092
+ first_root = tmp_path / "first"
1093
+ second_root = tmp_path / "second"
1094
+ first_root.mkdir()
1095
+ second_root.mkdir()
1096
+ state_path = tmp_path / "shared-state.json"
1097
+
1098
+ first_lock = scan_dirs._state_commit_lock_path(first_root, state_path)
1099
+ second_lock = scan_dirs._state_commit_lock_path(second_root, state_path)
1100
+ other_lock = scan_dirs._state_commit_lock_path(
1101
+ first_root,
1102
+ tmp_path / "other-state.json",
1103
+ )
1104
+
1105
+ assert first_lock == second_lock
1106
+ assert first_lock != other_lock
1107
+ assert first_lock.parent == contract.project_sync_lock_path(first_root).parent
1108
+
1109
+
1110
+ def test_cli_existing_candidate_requires_and_uses_explicit_baseline_preimage(
1111
+ tmp_path: Path,
1112
+ ) -> None:
1113
+ root = tmp_path / "project"
1114
+ root.mkdir()
1115
+ _mkdir_with_file(root / "package")
1116
+ script = Path(scan_dirs.__file__).resolve()
1117
+ environment = dict(os.environ)
1118
+ environment["PYTHONIOENCODING"] = "utf-8"
1119
+ candidate_path = tmp_path / "candidate.json"
1120
+ state_path = tmp_path / "state.json"
1121
+ absent = scan_dirs.BaselinePrecondition(False, None, None)
1122
+ candidate = scan_dirs.build_candidate_state(root, baseline_precondition=absent)
1123
+ scan_dirs.write_candidate_state(candidate_path, candidate)
1124
+ base_command = [
1125
+ sys.executable,
1126
+ str(script),
1127
+ str(root),
1128
+ "--state",
1129
+ str(state_path),
1130
+ "--commit-candidate",
1131
+ str(candidate_path),
1132
+ "--expected-candidate-generation-id",
1133
+ candidate["candidate_generation_id"],
1134
+ "--json",
1135
+ ]
1136
+
1137
+ missing_preimage = subprocess.run(
1138
+ base_command,
1139
+ env=environment,
1140
+ capture_output=True,
1141
+ text=True,
1142
+ encoding="utf-8",
1143
+ check=False,
1144
+ )
1145
+ assert missing_preimage.returncode != 0
1146
+ assert "expected-baseline" in missing_preimage.stderr
1147
+ assert not state_path.exists()
1148
+
1149
+ committed = subprocess.run(
1150
+ [*base_command, "--expected-baseline-absent"],
1151
+ env=environment,
1152
+ capture_output=True,
1153
+ text=True,
1154
+ encoding="utf-8",
1155
+ check=False,
1156
+ )
1157
+ assert committed.returncode == 0, committed.stderr
1158
+ assert json.loads(committed.stdout)["state_role"] == "committed"
1159
+ assert scan_dirs.load_previous_state(state_path) is not None