@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,2735 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Safe, fingerprint-based Phase 1 directory scanner.
3
+
4
+ A scan produces a schema-v2 *candidate* state. The committed baseline is only
5
+ replaced by :func:`commit_candidate_state` (or ``--commit``), after the caller
6
+ has successfully processed the candidate. This prevents a failed docs sync
7
+ from losing the previous incremental baseline.
8
+
9
+ The legacy command-line flags remain accepted. New callers should pass
10
+ ``--state`` for the committed baseline and ``--candidate`` (or ``--output``)
11
+ for the candidate file.
12
+ """
13
+
14
+ from __future__ import annotations
15
+ import sys as _bootstrap_sys
16
+ from pathlib import Path as _bootstrap_path
17
+ _bootstrap_sys.dont_write_bytecode = True
18
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parents[1]))
19
+ import _paths # noqa: E402
20
+ _paths.install()
21
+
22
+ import argparse
23
+ import concurrent.futures
24
+ import copy
25
+ import hashlib
26
+ import hmac
27
+ import os
28
+ import re
29
+ import stat
30
+ import sys
31
+ from dataclasses import dataclass
32
+ from datetime import datetime, timezone
33
+ from enum import Enum
34
+ from pathlib import Path, PurePosixPath
35
+ from typing import Any, Mapping, Sequence
36
+
37
+ import proj_doc_config
38
+ import project_docs_contract as contract
39
+
40
+ EXCLUDE_NAMES = set(proj_doc_config.DEFAULT_EXCLUDE_NAMES)
41
+
42
+ MAX_DEPTH = 8
43
+ SCAN_STATE_SCHEMA_VERSION = 2
44
+ SCANNER_VERSION = "2.3"
45
+ SCAN_STATE_KIND = "proj-doc-builder-directory-scan"
46
+ SCAN_STATE_PRODUCER = {"name": "proj-doc-builder.scan_dirs", "version": "2.1"}
47
+ DEFAULT_STATE_RELATIVE_PATH = Path("project_docs") / "_scan_state.json"
48
+ _COMMIT_GENERATED = "__generated_candidate__"
49
+ _SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
50
+ _PORTABLE_ROOT = "."
51
+ _PROJECT_ID_DOMAIN = b"proj-doc-builder-project-root-v1\0"
52
+ _STATE_LOCK_DOMAIN = b"proj-doc-builder-scan-state-target-v1\0"
53
+ _FILE_HASH_CHUNK_SIZE = 1024 * 1024
54
+ _STABLE_SCAN_MAX_PASSES = 4
55
+ _EXCLUDE_NAMES_CASEFOLD = frozenset(name.casefold() for name in EXCLUDE_NAMES)
56
+
57
+
58
+ class ScanError(RuntimeError):
59
+ """A directory tree cannot be scanned without an unsafe or partial result."""
60
+
61
+
62
+ class ScanStateError(ValueError):
63
+ """A persisted scan state does not satisfy the scanner contract."""
64
+
65
+
66
+ class BaselineConflict(ScanStateError):
67
+ """The committed baseline no longer matches the candidate precondition."""
68
+
69
+
70
+ class CommitDisposition(str, Enum):
71
+ """Observable result after a candidate commit operation raises."""
72
+
73
+ INSTALLED = "installed"
74
+ NOT_INSTALLED = "not-installed"
75
+ UNKNOWN = "unknown"
76
+
77
+
78
+ class CandidateCommitError(ScanStateError):
79
+ """Candidate publication failed with an explicit installed-state verdict."""
80
+
81
+ def __init__(
82
+ self,
83
+ message: str,
84
+ *,
85
+ disposition: CommitDisposition,
86
+ durability_confirmed: bool,
87
+ ) -> None:
88
+ super().__init__(message)
89
+ self.disposition = disposition
90
+ self.durability_confirmed = durability_confirmed
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class BaselinePrecondition:
95
+ """Exact committed-state preimage used to classify a candidate."""
96
+
97
+ exists: bool
98
+ sha256: str | None
99
+ generation_id: str | None
100
+
101
+
102
+ def should_prune(
103
+ name: str,
104
+ relative_path: str | None = None,
105
+ *,
106
+ config: proj_doc_config.ProjectDocConfig | None = None,
107
+ ) -> bool:
108
+ """Return whether a directory name or relative path is outside the documentation scan."""
109
+
110
+ return proj_doc_config.should_exclude_directory(
111
+ name, relative_path, config=config
112
+ )
113
+
114
+
115
+ def _now_iso() -> str:
116
+ return datetime.now(timezone.utc).isoformat()
117
+
118
+
119
+ def _resolved_root(root: str | os.PathLike[str]) -> Path:
120
+ candidate = Path(root)
121
+ try:
122
+ lexical = Path(os.path.abspath(candidate))
123
+ lexical_state = lexical.lstat()
124
+ resolved = lexical.resolve(strict=True)
125
+ except (OSError, RuntimeError) as exc:
126
+ raise ScanError(
127
+ f"root directory cannot be resolved: {candidate}: {exc}"
128
+ ) from exc
129
+ if (
130
+ lexical.is_symlink()
131
+ or _is_reparse(lexical_state)
132
+ or os.path.normcase(os.path.normpath(str(lexical)))
133
+ != os.path.normcase(os.path.normpath(str(resolved)))
134
+ ):
135
+ raise ScanError(f"root directory must not use an indirect path: {candidate}")
136
+ if not stat.S_ISDIR(lexical_state.st_mode) or not resolved.is_dir():
137
+ raise ScanError(f"root path is not a directory: {resolved}")
138
+ return resolved
139
+
140
+
141
+ def _validate_relative_directory_path(relative_path: str) -> str:
142
+ if relative_path == "":
143
+ return ""
144
+ # Reuse the shared portable path contract by validating a synthetic document
145
+ # below the directory. This rejects absolute, drive-qualified, traversal,
146
+ # backslash, empty-segment, and NUL-containing paths consistently.
147
+ try:
148
+ contract.validate_manifest_relative_path(
149
+ f"{relative_path}/__scan_directory__.md"
150
+ )
151
+ except contract.PathValidationError as exc:
152
+ raise ScanStateError(
153
+ f"invalid scan directory path {relative_path!r}: {exc}"
154
+ ) from exc
155
+ return relative_path
156
+
157
+
158
+ def _join_relative(parent: str, name: str) -> str:
159
+ if not name or "/" in name or "\\" in name or "\0" in name:
160
+ raise ScanError(f"directory entry has a non-portable name: {name!r}")
161
+ relative = f"{parent}/{name}" if parent else name
162
+ return _validate_relative_directory_path(relative)
163
+
164
+
165
+ def _is_within_root(candidate: Path, root: Path) -> bool:
166
+ try:
167
+ candidate.relative_to(root)
168
+ return True
169
+ except ValueError:
170
+ return False
171
+
172
+
173
+ def _is_reparse(stat_result: os.stat_result) -> bool:
174
+ attributes = getattr(stat_result, "st_file_attributes", 0)
175
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
176
+ return bool(attributes & reparse_flag)
177
+
178
+
179
+ def _project_identity_from_path(root: Path) -> str:
180
+ """Return an opaque, stable identity without persisting the absolute root."""
181
+
182
+ normalized = os.path.normpath(str(root.resolve(strict=False)))
183
+ if os.name == "nt":
184
+ normalized = normalized.replace("\\", "/").casefold()
185
+ return hashlib.sha256(
186
+ _PROJECT_ID_DOMAIN + normalized.encode("utf-8", errors="strict")
187
+ ).hexdigest()
188
+
189
+
190
+ def _project_identity(root: Path) -> str:
191
+ return _project_identity_from_path(root.resolve(strict=True))
192
+
193
+
194
+ def _mtime_ns(stat_result: os.stat_result) -> int:
195
+ return getattr(
196
+ stat_result,
197
+ "st_mtime_ns",
198
+ int(stat_result.st_mtime * 1_000_000_000),
199
+ )
200
+
201
+
202
+ def _stat_identity(stat_result: os.stat_result) -> tuple[int, int]:
203
+ return (int(stat_result.st_dev), int(stat_result.st_ino))
204
+
205
+
206
+ def _same_file_identity(first: os.stat_result, second: os.stat_result) -> bool:
207
+ first_id = _stat_identity(first)
208
+ second_id = _stat_identity(second)
209
+ if first_id != (0, 0) and second_id != (0, 0):
210
+ return first_id == second_id
211
+ return (
212
+ stat.S_IFMT(first.st_mode) == stat.S_IFMT(second.st_mode)
213
+ and first.st_size == second.st_size
214
+ and getattr(first, "st_ctime_ns", None) == getattr(second, "st_ctime_ns", None)
215
+ )
216
+
217
+
218
+ def _assert_scan_entry_casefold_unique(
219
+ entries: Sequence[os.DirEntry[str]], directory: Path
220
+ ) -> None:
221
+ seen: dict[str, str] = {}
222
+ for entry in entries:
223
+ folded = entry.name.casefold()
224
+ prior = seen.get(folded)
225
+ if prior is not None and prior != entry.name:
226
+ raise ScanError(
227
+ "directory contains Unicode-casefold-colliding entries: "
228
+ f"{directory}: {prior!r} and {entry.name!r}"
229
+ )
230
+ seen[folded] = entry.name
231
+
232
+
233
+ def _entry_directory_details(entry: os.DirEntry[str]) -> tuple[bool, bool, bool]:
234
+ """Return ``(is_directory, is_symlink, is_reparse)`` without recursion."""
235
+
236
+ try:
237
+ lstat_result = entry.stat(follow_symlinks=False)
238
+ is_symlink = entry.is_symlink()
239
+ is_reparse = _is_reparse(lstat_result)
240
+ is_directory = stat.S_ISDIR(lstat_result.st_mode)
241
+ if is_symlink or is_reparse:
242
+ try:
243
+ is_directory = is_directory or entry.is_dir(follow_symlinks=True)
244
+ except OSError:
245
+ # An unresolvable reparse entry is reported as skipped below if its
246
+ # own metadata identifies it as a directory. A broken file link is
247
+ # treated as a direct file and never followed.
248
+ pass
249
+ return is_directory, is_symlink, is_reparse
250
+ except OSError as exc:
251
+ raise ScanError(f"cannot inspect directory entry {entry.path}: {exc}") from exc
252
+
253
+
254
+ def _file_snapshot(
255
+ entry: os.DirEntry[str],
256
+ root: Path,
257
+ *,
258
+ rel_dir: str = "",
259
+ mtime_cache: Mapping[tuple[str, str], tuple[int, int, str]] | None = None,
260
+ ) -> dict[str, Any]:
261
+ """Hash one verified direct regular file without following a reparse entry."""
262
+
263
+ path = Path(entry.path)
264
+ try:
265
+ # ``DirEntry.stat`` reports zero file IDs on some Windows/Python builds;
266
+ # path.lstat supplies the handle-comparable identity without following.
267
+ before = path.lstat()
268
+ except OSError as exc:
269
+ raise ScanError(f"cannot stat direct file {entry.path}: {exc}") from exc
270
+ if stat.S_ISLNK(before.st_mode) or _is_reparse(before):
271
+ raise ScanError(f"direct file is a symlink or reparse point: {entry.path}")
272
+ if not stat.S_ISREG(before.st_mode):
273
+ raise ScanError(f"direct entry is not a regular file: {entry.path}")
274
+
275
+ if mtime_cache is not None:
276
+ cached = mtime_cache.get((rel_dir, entry.name))
277
+ if cached is not None:
278
+ cached_size, cached_mtime_ns, cached_sha256 = cached
279
+ if (
280
+ int(before.st_size) == cached_size
281
+ and _mtime_ns(before) == cached_mtime_ns
282
+ ):
283
+ # Cache hit: bytes are identical to a previously hashed copy.
284
+ # A non-reparse regular file physically inside a directory the
285
+ # walker already verified cannot escape the scan root, so the
286
+ # expensive ``resolve(strict=True)`` is unnecessary here.
287
+ return {
288
+ "name": entry.name,
289
+ "path": entry.name,
290
+ "file_type": "regular",
291
+ "size": cached_size,
292
+ "mtime_ns": cached_mtime_ns,
293
+ "sha256": cached_sha256,
294
+ }
295
+
296
+ try:
297
+ resolved_before = path.resolve(strict=True)
298
+ except (OSError, RuntimeError) as exc:
299
+ raise ScanError(f"cannot resolve direct file {entry.path}: {exc}") from exc
300
+ if not _is_within_root(resolved_before, root):
301
+ raise ScanError(f"direct file resolves outside the scan root: {entry.path}")
302
+
303
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
304
+ try:
305
+ descriptor = os.open(path, flags)
306
+ except OSError as exc:
307
+ raise ScanError(f"cannot safely open direct file {entry.path}: {exc}") from exc
308
+
309
+ try:
310
+ opened = os.fstat(descriptor)
311
+ try:
312
+ after_open = path.lstat()
313
+ resolved_after = path.resolve(strict=True)
314
+ except (OSError, RuntimeError) as exc:
315
+ raise ScanError(
316
+ f"direct file changed while opening {entry.path}: {exc}"
317
+ ) from exc
318
+ if (
319
+ not stat.S_ISREG(opened.st_mode)
320
+ or not stat.S_ISREG(after_open.st_mode)
321
+ or _is_reparse(opened)
322
+ or _is_reparse(after_open)
323
+ or not _same_file_identity(before, opened)
324
+ or not _same_file_identity(opened, after_open)
325
+ or not _is_within_root(resolved_after, root)
326
+ ):
327
+ raise ScanError(
328
+ f"direct file changed identity or escaped root: {entry.path}"
329
+ )
330
+
331
+ digest = hashlib.sha256()
332
+ while True:
333
+ chunk = os.read(descriptor, _FILE_HASH_CHUNK_SIZE)
334
+ if not chunk:
335
+ break
336
+ digest.update(chunk)
337
+ finished = os.fstat(descriptor)
338
+ try:
339
+ final_path_state = path.lstat()
340
+ resolved_final = path.resolve(strict=True)
341
+ except (OSError, RuntimeError) as exc:
342
+ raise ScanError(
343
+ f"direct file changed after hashing {entry.path}: {exc}"
344
+ ) from exc
345
+ if (
346
+ not _same_file_identity(opened, finished)
347
+ or not _same_file_identity(finished, final_path_state)
348
+ or _is_reparse(final_path_state)
349
+ or stat.S_ISLNK(final_path_state.st_mode)
350
+ or not _is_within_root(resolved_final, root)
351
+ or opened.st_size != finished.st_size
352
+ or _mtime_ns(opened) != _mtime_ns(finished)
353
+ ):
354
+ raise ScanError(f"direct file changed while hashing: {entry.path}")
355
+ finally:
356
+ os.close(descriptor)
357
+
358
+ return {
359
+ "name": entry.name,
360
+ "path": entry.name,
361
+ "file_type": "regular",
362
+ "size": int(opened.st_size),
363
+ "mtime_ns": _mtime_ns(opened),
364
+ "sha256": digest.hexdigest(),
365
+ }
366
+
367
+
368
+ def _fingerprint(value: Any) -> str:
369
+ payload = contract.stable_json_dumps(value).encode("utf-8")
370
+ return contract.sha256_bytes(payload)
371
+
372
+
373
+ def _content_only_payload(snapshot: Mapping[str, Any]) -> dict[str, Any]:
374
+ """Content-only canonical payload for directory fingerprints.
375
+
376
+ Excludes ``mtime_ns``/``path``/``file_type`` so that ``touch`` (an mtime-only
377
+ change with identical bytes and sha256) keeps the fingerprint unchanged.
378
+ """
379
+ files = []
380
+ for info in snapshot.get("files", []) or []:
381
+ if not isinstance(info, Mapping):
382
+ continue
383
+ files.append(
384
+ {
385
+ "name": str(info.get("name", "")),
386
+ "size": int(info.get("size", 0) or 0),
387
+ "sha256": str(info.get("sha256", "")),
388
+ }
389
+ )
390
+ files.sort(key=lambda value: (value["name"].casefold(), value["name"]))
391
+ skipped = []
392
+ for entry in snapshot.get("skipped_directories", []) or []:
393
+ if isinstance(entry, Mapping):
394
+ skipped.append(
395
+ {
396
+ "name": str(entry.get("name", "")),
397
+ "kind": str(entry.get("kind", "")),
398
+ "reason": str(entry.get("reason", "")),
399
+ "target": str(entry.get("target", "")),
400
+ }
401
+ )
402
+ skipped.sort(key=lambda value: (value["name"].casefold(), value["name"]))
403
+ child_directories = sorted(
404
+ str(name) for name in (snapshot.get("child_directories", []) or [])
405
+ )
406
+ return {
407
+ "files": files,
408
+ "child_directories": child_directories,
409
+ "is_boundary": bool(snapshot.get("is_boundary", False)),
410
+ "skipped_directories": skipped,
411
+ }
412
+
413
+
414
+ def _directory_fingerprint(snapshot: Mapping[str, Any]) -> str:
415
+ """Content-only directory fingerprint (G7).
416
+
417
+ A legacy full-snapshot fingerprint is still accepted by the state validator
418
+ when reading previously committed states, so existing states migrate without
419
+ a forced re-scan.
420
+ """
421
+ return _fingerprint(_content_only_payload(snapshot))
422
+
423
+
424
+ def _directory_sort_key(record: Mapping[str, Any]) -> tuple[int, str, str]:
425
+ path = str(record["path"])
426
+ return (-int(record.get("depth", 0)), path.casefold(), path)
427
+
428
+
429
+ def _add_unknown_scope(
430
+ scopes: list[dict[str, str]],
431
+ *,
432
+ path: str,
433
+ reason: str,
434
+ scope: str,
435
+ ) -> None:
436
+ record = {"path": path, "reason": reason, "scope": scope}
437
+ if record not in scopes:
438
+ scopes.append(record)
439
+
440
+
441
+ def _skipped_directory(
442
+ entry: os.DirEntry[str],
443
+ *,
444
+ relative_path: str,
445
+ root: Path,
446
+ is_symlink: bool,
447
+ is_reparse: bool,
448
+ ) -> tuple[dict[str, str], None]:
449
+ try:
450
+ resolved = Path(entry.path).resolve(strict=True)
451
+ outside = not _is_within_root(resolved, root)
452
+ if outside:
453
+ target = "<outside-root>"
454
+ reason = "outside-root"
455
+ else:
456
+ relative_target = resolved.relative_to(root).as_posix()
457
+ target = relative_target if relative_target != "." else "<project-root>"
458
+ reason = "reparse-directory"
459
+ except (OSError, RuntimeError):
460
+ target = "<unresolvable>"
461
+ reason = "unresolvable-reparse-directory"
462
+
463
+ kind = "symlink" if is_symlink else "reparse" if is_reparse else "directory"
464
+ return (
465
+ {
466
+ "path": relative_path,
467
+ "kind": kind,
468
+ "reason": reason,
469
+ "target": target,
470
+ },
471
+ None,
472
+ )
473
+
474
+
475
+ def _validated_directory_state(path: Path, root: Path) -> os.stat_result:
476
+ try:
477
+ state = path.lstat()
478
+ resolved = path.resolve(strict=True)
479
+ except (OSError, RuntimeError) as exc:
480
+ raise ScanError(f"cannot validate directory {path}: {exc}") from exc
481
+ if stat.S_ISLNK(state.st_mode) or _is_reparse(state) or not stat.S_ISDIR(state.st_mode):
482
+ raise ScanError(
483
+ f"directory became a link, reparse point, or non-directory: {path}"
484
+ )
485
+ if not _is_within_root(resolved, root):
486
+ raise ScanError(f"directory escaped the scan root: {path}")
487
+ return state
488
+
489
+
490
+ def _scan_tree_once(
491
+ root: str | os.PathLike[str],
492
+ *,
493
+ executor: concurrent.futures.ThreadPoolExecutor | None = None,
494
+ mtime_cache: Mapping[tuple[str, str], tuple[int, int, str]] | None = None,
495
+ ) -> dict[str, Any]:
496
+ """Return one complete safe snapshot plus skipped/unknown subtree reports."""
497
+
498
+ resolved_root = _resolved_root(root)
499
+ try:
500
+ project_config = proj_doc_config.load_project_config(resolved_root)
501
+ except proj_doc_config.ConfigError as exc:
502
+ raise ScanError(str(exc)) from exc
503
+ effective_max_depth = min(project_config.scan.max_depth, MAX_DEPTH)
504
+ active_mtime_cache = mtime_cache if project_config.scan.use_mtime_cache else None
505
+ directories: list[dict[str, Any]] = []
506
+ skipped: list[dict[str, str]] = []
507
+ unknown_scopes: list[dict[str, str]] = []
508
+ visited = {os.path.normcase(str(resolved_root))}
509
+
510
+ def inspect_child(
511
+ entry: os.DirEntry[str],
512
+ parent_relative: str,
513
+ ) -> tuple[str, Path | None, dict[str, str] | None]:
514
+ relative = _join_relative(parent_relative, entry.name)
515
+ is_directory, is_symlink, is_reparse = _entry_directory_details(entry)
516
+ if not is_directory:
517
+ return relative, None, None
518
+
519
+ if is_symlink or is_reparse:
520
+ skipped_record, _ = _skipped_directory(
521
+ entry,
522
+ relative_path=relative,
523
+ root=resolved_root,
524
+ is_symlink=is_symlink,
525
+ is_reparse=is_reparse,
526
+ )
527
+ skipped.append(skipped_record)
528
+ _add_unknown_scope(
529
+ unknown_scopes,
530
+ path=relative,
531
+ reason=skipped_record["reason"],
532
+ scope="subtree",
533
+ )
534
+ return relative, None, skipped_record
535
+
536
+ try:
537
+ resolved = Path(entry.path).resolve(strict=True)
538
+ except (OSError, RuntimeError) as exc:
539
+ raise ScanError(f"cannot resolve directory {entry.path}: {exc}") from exc
540
+ if not _is_within_root(resolved, resolved_root):
541
+ skipped_record = {
542
+ "path": relative,
543
+ "kind": "directory",
544
+ "reason": "outside-root",
545
+ "target": "<outside-root>",
546
+ }
547
+ skipped.append(skipped_record)
548
+ _add_unknown_scope(
549
+ unknown_scopes,
550
+ path=relative,
551
+ reason="outside-root",
552
+ scope="subtree",
553
+ )
554
+ return relative, None, skipped_record
555
+
556
+ identity = os.path.normcase(str(resolved))
557
+ if identity in visited:
558
+ relative_target = resolved.relative_to(resolved_root).as_posix()
559
+ skipped_record = {
560
+ "path": relative,
561
+ "kind": "directory",
562
+ "reason": "directory-cycle-or-alias",
563
+ "target": (
564
+ relative_target if relative_target != "." else "<project-root>"
565
+ ),
566
+ }
567
+ skipped.append(skipped_record)
568
+ _add_unknown_scope(
569
+ unknown_scopes,
570
+ path=relative,
571
+ reason="directory-cycle-or-alias",
572
+ scope="subtree",
573
+ )
574
+ return relative, None, skipped_record
575
+ visited.add(identity)
576
+ return relative, resolved, None
577
+
578
+ def list_entries(path: Path) -> list[os.DirEntry[str]]:
579
+ before = _validated_directory_state(path, resolved_root)
580
+ try:
581
+ with os.scandir(path) as iterator:
582
+ entries = list(iterator)
583
+ except OSError as exc:
584
+ raise ScanError(f"cannot enumerate directory {path}: {exc}") from exc
585
+ after = _validated_directory_state(path, resolved_root)
586
+ if not _same_file_identity(before, after):
587
+ raise ScanError(f"directory changed identity while enumerating: {path}")
588
+ _assert_scan_entry_casefold_unique(entries, path)
589
+ return sorted(entries, key=lambda item: (item.name.casefold(), item.name))
590
+
591
+ def visit(path: Path, relative: str, depth: int) -> None:
592
+ entries = list_entries(path)
593
+ files: list[dict[str, Any]] = []
594
+ child_names: list[str] = []
595
+ child_paths: list[tuple[Path, str]] = []
596
+ local_skipped: list[dict[str, str]] = []
597
+
598
+ candidate_files: list[os.DirEntry[str]] = []
599
+ for entry in entries:
600
+ is_directory, _, _ = _entry_directory_details(entry)
601
+ if is_directory:
602
+ child_rel_candidate = (
603
+ f"{relative}/{entry.name}" if relative else entry.name
604
+ )
605
+ if should_prune(
606
+ entry.name,
607
+ child_rel_candidate,
608
+ config=project_config,
609
+ ):
610
+ continue
611
+ child_names.append(entry.name)
612
+ child_relative, child_path, skipped_record = inspect_child(
613
+ entry, relative
614
+ )
615
+ if skipped_record is not None:
616
+ local_skipped.append(
617
+ {
618
+ "name": entry.name,
619
+ "kind": skipped_record["kind"],
620
+ "reason": skipped_record["reason"],
621
+ "target": skipped_record["target"],
622
+ }
623
+ )
624
+ elif child_path is not None:
625
+ child_paths.append((child_path, child_relative))
626
+ continue
627
+
628
+ if entry.name.startswith("."):
629
+ continue
630
+ if depth == 0 and entry.name.casefold() == "claude.md":
631
+ continue
632
+ candidate_files.append(entry)
633
+
634
+ if active_mtime_cache is not None:
635
+ def _snapshot_entry(item: os.DirEntry[str]) -> dict[str, Any]:
636
+ return _file_snapshot(
637
+ item,
638
+ resolved_root,
639
+ rel_dir=relative,
640
+ mtime_cache=active_mtime_cache,
641
+ )
642
+ else:
643
+ def _snapshot_entry(item: os.DirEntry[str]) -> dict[str, Any]:
644
+ return _file_snapshot(item, resolved_root)
645
+
646
+ if executor is not None and len(candidate_files) > 1:
647
+ files = list(executor.map(_snapshot_entry, candidate_files))
648
+ else:
649
+ files = [_snapshot_entry(entry) for entry in candidate_files]
650
+
651
+ child_names.sort(key=lambda value: (value.casefold(), value))
652
+ files.sort(key=lambda value: (value["name"].casefold(), value["name"]))
653
+ local_skipped.sort(key=lambda value: (value["name"].casefold(), value["name"]))
654
+ is_boundary = depth > 0 and any(
655
+ file_info["name"].casefold() == "claude.md" for file_info in files
656
+ )
657
+ snapshot = {
658
+ "files": files,
659
+ "child_directories": child_names,
660
+ "is_boundary": is_boundary,
661
+ "skipped_directories": local_skipped,
662
+ }
663
+ visible_names = {file_info["name"].casefold() for file_info in files}
664
+ file_count = len(files)
665
+ record = {
666
+ "path": relative,
667
+ "depth": depth,
668
+ "is_boundary": is_boundary,
669
+ "file_count": file_count,
670
+ "py_file_count": sum(
671
+ 1 for file_info in files if file_info["name"].casefold().endswith(".py")
672
+ ),
673
+ "has_init_py": "__init__.py" in visible_names,
674
+ "has_readme": "readme.md" in visible_names,
675
+ "is_empty": file_count == 0
676
+ or (file_count == 1 and "__init__.py" in visible_names),
677
+ "snapshot": snapshot,
678
+ "fingerprint": _directory_fingerprint(snapshot),
679
+ }
680
+ directories.append(record)
681
+
682
+ if is_boundary:
683
+ _add_unknown_scope(
684
+ unknown_scopes,
685
+ path=relative,
686
+ reason="boundary",
687
+ scope="descendants",
688
+ )
689
+ return
690
+ if depth >= effective_max_depth:
691
+ if child_names:
692
+ _add_unknown_scope(
693
+ unknown_scopes,
694
+ path=relative,
695
+ reason="max-depth",
696
+ scope="descendants",
697
+ )
698
+ return
699
+ for child_path, child_relative in child_paths:
700
+ visit(child_path, child_relative, depth + 1)
701
+
702
+ # The project root itself has depth 0 and generates the top-level index.md
703
+ # document. Root's own CLAUDE.md is the central instruction file and does
704
+ # not form a boundary; nested visits proceed to depth 1.
705
+ visit(resolved_root, "", 0)
706
+
707
+ directories.sort(key=_directory_sort_key)
708
+ skipped.sort(key=lambda value: (value["path"].casefold(), value["path"]))
709
+ unknown_scopes.sort(
710
+ key=lambda value: (value["path"].casefold(), value["path"], value["reason"])
711
+ )
712
+ return {
713
+ "root": resolved_root.as_posix(),
714
+ "directories": directories,
715
+ "skipped_directories": skipped,
716
+ "unknown_scopes": unknown_scopes,
717
+ }
718
+
719
+
720
+ def _scan_fault(point: str, root: Path) -> None:
721
+ """测试故障注入点;生产运行不执行任何操作。"""
722
+
723
+ return None
724
+
725
+
726
+ def _stable_scan_payload(scan: Mapping[str, Any]) -> dict[str, Any]:
727
+ return {
728
+ "directories": copy.deepcopy(scan["directories"]),
729
+ "skipped_directories": copy.deepcopy(scan["skipped_directories"]),
730
+ "unknown_scopes": copy.deepcopy(scan["unknown_scopes"]),
731
+ }
732
+
733
+
734
+ def _extract_mtime_cache(
735
+ previous: Mapping[str, Any] | None,
736
+ ) -> dict[tuple[str, str], tuple[int, int, str]] | None:
737
+ """Build an optional ``(rel_dir, name) -> (size, mtime_ns, sha256)`` cache."""
738
+
739
+ if not isinstance(previous, Mapping):
740
+ return None
741
+ snapshot = previous.get("snapshot")
742
+ if not isinstance(snapshot, Mapping):
743
+ return None
744
+ directories = snapshot.get("directories")
745
+ if not isinstance(directories, list):
746
+ return None
747
+ cache: dict[tuple[str, str], tuple[int, int, str]] = {}
748
+ for record in directories:
749
+ if not isinstance(record, Mapping):
750
+ continue
751
+ rel_dir = record.get("path")
752
+ dir_snap = record.get("snapshot")
753
+ if not isinstance(rel_dir, str) or not isinstance(dir_snap, Mapping):
754
+ continue
755
+ files = dir_snap.get("files")
756
+ if not isinstance(files, list):
757
+ continue
758
+ for file_info in files:
759
+ if not isinstance(file_info, Mapping):
760
+ continue
761
+ name = file_info.get("name")
762
+ size = file_info.get("size")
763
+ mtime_ns = file_info.get("mtime_ns")
764
+ sha256 = file_info.get("sha256")
765
+ if (
766
+ isinstance(name, str)
767
+ and type(size) is int
768
+ and type(mtime_ns) is int
769
+ and isinstance(sha256, str)
770
+ and _SHA256_RE.match(sha256)
771
+ ):
772
+ cache[(rel_dir, name)] = (size, mtime_ns, sha256)
773
+ return cache or None
774
+
775
+
776
+ def _scan_result_mtime_cache(
777
+ scan: Mapping[str, Any],
778
+ ) -> dict[tuple[str, str], tuple[int, int, str]]:
779
+ """Build a ``(rel_dir, name) -> (size, mtime_ns, sha256)`` cache from a scan
780
+ result so the next pass can reuse sha256 for unchanged files (G6).
781
+ """
782
+ cache: dict[tuple[str, str], tuple[int, int, str]] = {}
783
+ for record in scan.get("directories", []) or []:
784
+ if not isinstance(record, Mapping):
785
+ continue
786
+ rel_dir = record.get("path")
787
+ snapshot = record.get("snapshot")
788
+ if not isinstance(rel_dir, str) or not isinstance(snapshot, Mapping):
789
+ continue
790
+ for file_info in snapshot.get("files", []) or []:
791
+ if not isinstance(file_info, Mapping):
792
+ continue
793
+ name = file_info.get("name")
794
+ size = file_info.get("size")
795
+ mtime_ns = file_info.get("mtime_ns")
796
+ sha256 = file_info.get("sha256")
797
+ if (
798
+ isinstance(name, str)
799
+ and type(size) is int
800
+ and type(mtime_ns) is int
801
+ and isinstance(sha256, str)
802
+ and _SHA256_RE.match(sha256)
803
+ ):
804
+ cache[(rel_dir, name)] = (size, mtime_ns, sha256)
805
+ return cache or {}
806
+
807
+
808
+ def _content_sha256(entry: Mapping[str, Any]) -> str:
809
+ """Content identity of one snapshot file entry (mtime-independent)."""
810
+
811
+ return str(entry.get("sha256") or "")
812
+
813
+
814
+ def _scan_drift_summary(previous: Mapping[str, Any], current: Mapping[str, Any]) -> str:
815
+ """Human-readable diff between two scan results for unstable-tree errors (G9)."""
816
+ prev_dirs = {
817
+ str(r.get("path", "")): r
818
+ for r in (previous.get("directories", []) or [])
819
+ if isinstance(r, Mapping)
820
+ }
821
+ curr_dirs = {
822
+ str(r.get("path", "")): r
823
+ for r in (current.get("directories", []) or [])
824
+ if isinstance(r, Mapping)
825
+ }
826
+ notes: list[str] = []
827
+ for path in sorted(set(curr_dirs) - set(prev_dirs)):
828
+ notes.append(f"+{path}")
829
+ if len(notes) >= 5:
830
+ break
831
+ for path in sorted(set(prev_dirs) - set(curr_dirs)):
832
+ notes.append(f"-{path}")
833
+ if len(notes) >= 5:
834
+ break
835
+ for path in sorted(set(prev_dirs) & set(curr_dirs)):
836
+ if notes and len(notes) >= 5:
837
+ break
838
+ prev_files = {
839
+ str(f.get("name", "")): f
840
+ for f in (prev_dirs[path].get("snapshot", {}) or {}).get("files", []) or []
841
+ if isinstance(f, Mapping) and isinstance(f.get("name"), str)
842
+ }
843
+ curr_files = {
844
+ str(f.get("name", "")): f
845
+ for f in (curr_dirs[path].get("snapshot", {}) or {}).get("files", []) or []
846
+ if isinstance(f, Mapping) and isinstance(f.get("name"), str)
847
+ }
848
+ added = sorted(set(curr_files) - set(prev_files))
849
+ removed = sorted(set(prev_files) - set(curr_files))
850
+ changed = sorted(
851
+ name
852
+ for name in (set(prev_files) & set(curr_files))
853
+ if _content_sha256(prev_files[name]) != _content_sha256(curr_files[name])
854
+ )
855
+ if added or removed or changed:
856
+ parts: list[str] = []
857
+ if added:
858
+ parts.append(f"added: {','.join(added)}")
859
+ if removed:
860
+ parts.append(f"removed: {','.join(removed)}")
861
+ if changed:
862
+ parts.append(f"changed: {','.join(changed)}")
863
+ notes.append(f"~{path} ({'; '.join(parts)})")
864
+ return "; ".join(notes) if notes else "no directory-level diff detected"
865
+
866
+
867
+ def _scan_stability_view(scan: Mapping[str, Any]) -> tuple[Any, Any, Any]:
868
+ """Content-only view used to decide whether two passes agree (G7/G9).
869
+
870
+ Comparing raw records would include ``mtime_ns``, so a file merely touched
871
+ between the two passes (editor save, ``svn update``, a build tool rewriting
872
+ an identical file) would make the tree look unstable forever. Only content
873
+ identity may decide stability; genuine content changes still differ here and
874
+ are reported by :func:`_scan_drift_summary`.
875
+ """
876
+
877
+ directories = []
878
+ for record in scan.get("directories", []) or []:
879
+ if not isinstance(record, Mapping):
880
+ continue
881
+ snapshot = record.get("snapshot")
882
+ payload = _content_only_payload(snapshot) if isinstance(snapshot, Mapping) else None
883
+ directories.append((str(record.get("path", "")), _fingerprint(payload)))
884
+ directories.sort()
885
+ return (
886
+ directories,
887
+ sorted(str(item) for item in (scan.get("skipped_directories") or [])),
888
+ sorted(
889
+ (str(item.get("path", "")), str(item.get("reason", "")))
890
+ for item in (scan.get("unknown_scopes") or [])
891
+ if isinstance(item, Mapping)
892
+ ),
893
+ )
894
+
895
+
896
+ def _scan_tree(
897
+ root: str | os.PathLike[str],
898
+ *,
899
+ mtime_cache: Mapping[tuple[str, str], tuple[int, int, str]] | None = None,
900
+ ) -> dict[str, Any]:
901
+ """Require two consecutive equal full scans or fail after bounded retries.
902
+
903
+ Pass *N+1* reuses the mtime cache built from pass *N* so unchanged files
904
+ skip sha256 hashing (G6). When the tree never stabilises, the error includes
905
+ a directory-level diff between the final two passes (G9).
906
+ """
907
+ resolved_root = _resolved_root(root)
908
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
909
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
910
+ previous: dict[str, Any] | None = None
911
+ active_cache = mtime_cache
912
+ drift = ""
913
+ for pass_index in range(_STABLE_SCAN_MAX_PASSES):
914
+ current = _scan_tree_once(
915
+ resolved_root,
916
+ executor=executor,
917
+ mtime_cache=active_cache,
918
+ )
919
+ if previous is not None:
920
+ if _scan_stability_view(previous) == _scan_stability_view(current):
921
+ return current
922
+ # Keep the diff of the final two passes: the loop rebinds
923
+ # ``previous`` below, so computing this after the loop would
924
+ # compare a scan with itself and always report "no diff".
925
+ drift = _scan_drift_summary(previous, current)
926
+ previous = current
927
+ active_cache = _scan_result_mtime_cache(current)
928
+ _scan_fault(f"after-pass-{pass_index + 1}", resolved_root)
929
+ detail = f"; drifting: {drift}" if drift else ""
930
+ raise ScanError(
931
+ f"source tree did not reach a stable two-pass snapshot after "
932
+ f"{_STABLE_SCAN_MAX_PASSES} passes{detail}"
933
+ )
934
+
935
+
936
+ def scan_directories(root: str | os.PathLike[str]) -> list[dict[str, Any]]:
937
+ """Compatibility API returning the complete deepest-first directory list."""
938
+
939
+ return _scan_tree(root)["directories"]
940
+
941
+
942
+ def compute_mtime(path: str | os.PathLike[str]) -> float:
943
+ """Legacy non-recursive maximum file mtime helper."""
944
+
945
+ directory = Path(path)
946
+ try:
947
+ mtimes = [
948
+ entry.stat(follow_symlinks=False).st_mtime
949
+ for entry in os.scandir(directory)
950
+ if not entry.is_dir(follow_symlinks=False)
951
+ ]
952
+ except OSError:
953
+ return 0.0
954
+ return max(mtimes, default=0.0)
955
+
956
+
957
+ def _require_mapping(value: Any, field: str) -> Mapping[str, Any]:
958
+ if not isinstance(value, Mapping):
959
+ raise ScanStateError(f"{field} must be a JSON object")
960
+ return value
961
+
962
+
963
+ def _require_list(value: Any, field: str) -> list[Any]:
964
+ if not isinstance(value, list):
965
+ raise ScanStateError(f"{field} must be a JSON array")
966
+ return value
967
+
968
+
969
+ def _require_exact_keys(
970
+ value: Mapping[str, Any],
971
+ required: set[str],
972
+ field: str,
973
+ *,
974
+ optional: set[str] | None = None,
975
+ ) -> None:
976
+ actual = set(value)
977
+ allowed = required | (optional or set())
978
+ missing = sorted(required - actual)
979
+ extra = sorted(actual - allowed)
980
+ if missing or extra:
981
+ raise ScanStateError(
982
+ f"{field} has invalid fields (missing={missing}, extra={extra})"
983
+ )
984
+
985
+
986
+ def _require_non_negative_int(value: Any, field: str) -> int:
987
+ if type(value) is not int or value < 0:
988
+ raise ScanStateError(f"{field} must be a non-negative integer")
989
+ return value
990
+
991
+
992
+ def _require_sha256(value: Any, field: str) -> str:
993
+ if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None:
994
+ raise ScanStateError(f"{field} must be a lowercase SHA-256 hex digest")
995
+ return value
996
+
997
+
998
+ def _validate_entry_name(name: Any, field: str) -> str:
999
+ if (
1000
+ not isinstance(name, str)
1001
+ or not name
1002
+ or name in (".", "..")
1003
+ or "/" in name
1004
+ or "\\" in name
1005
+ or "\0" in name
1006
+ ):
1007
+ raise ScanStateError(f"{field} is not a portable direct-entry name")
1008
+ try:
1009
+ contract.validate_manifest_relative_path(f"_scan_entries/{name}/__entry__.md")
1010
+ except contract.PathValidationError as exc:
1011
+ raise ScanStateError(f"{field} is not portable: {exc}") from exc
1012
+ return name
1013
+
1014
+
1015
+ def _ensure_casefold_unique(values: Sequence[str], field: str) -> None:
1016
+ seen: dict[str, str] = {}
1017
+ for value in values:
1018
+ folded = value.casefold()
1019
+ prior = seen.get(folded)
1020
+ if prior is not None:
1021
+ raise ScanStateError(
1022
+ f"{field} contains Unicode-casefold collision: {prior!r} and {value!r}"
1023
+ )
1024
+ seen[folded] = value
1025
+
1026
+
1027
+ def _validate_timestamp(value: Any, field: str) -> str:
1028
+ if not isinstance(value, str):
1029
+ raise ScanStateError(f"{field} must be an ISO-8601 timestamp")
1030
+ try:
1031
+ parsed = datetime.fromisoformat(value)
1032
+ except ValueError as exc:
1033
+ raise ScanStateError(f"{field} must be an ISO-8601 timestamp") from exc
1034
+ if parsed.tzinfo is None:
1035
+ raise ScanStateError(f"{field} must include a timezone")
1036
+ return value
1037
+
1038
+
1039
+ def _validate_portable_state_path(value: Any) -> str:
1040
+ if not isinstance(value, str) or not value or "\\" in value or "\0" in value:
1041
+ raise ScanStateError("state_path must be a portable relative path")
1042
+ path = PurePosixPath(value)
1043
+ if path.is_absolute() or any(part in ("", ".", "..") for part in path.parts):
1044
+ raise ScanStateError("state_path must be a portable relative path")
1045
+ try:
1046
+ contract.validate_manifest_relative_path(f"_scan_state_paths/{value}.md")
1047
+ except contract.PathValidationError as exc:
1048
+ raise ScanStateError(f"state_path is not portable: {exc}") from exc
1049
+ return value
1050
+
1051
+
1052
+ def _validate_directory_snapshot(record: Mapping[str, Any], field: str) -> str:
1053
+ required_record_fields = {
1054
+ "path",
1055
+ "depth",
1056
+ "is_boundary",
1057
+ "file_count",
1058
+ "py_file_count",
1059
+ "has_init_py",
1060
+ "has_readme",
1061
+ "is_empty",
1062
+ "snapshot",
1063
+ "fingerprint",
1064
+ }
1065
+ _require_exact_keys(record, required_record_fields, field)
1066
+ path = record.get("path")
1067
+ if not isinstance(path, str):
1068
+ raise ScanStateError(f"{field}.path must be a string")
1069
+ _validate_relative_directory_path(path)
1070
+
1071
+ depth = _require_non_negative_int(record.get("depth"), f"{field}.depth")
1072
+ expected_depth = len(PurePosixPath(path).parts)
1073
+ if depth != expected_depth or depth < 0 or depth > MAX_DEPTH:
1074
+ raise ScanStateError(f"{field}.depth does not match its relative path")
1075
+
1076
+ snapshot = _require_mapping(record.get("snapshot"), f"{field}.snapshot")
1077
+ _require_exact_keys(
1078
+ snapshot,
1079
+ {"files", "child_directories", "is_boundary", "skipped_directories"},
1080
+ f"{field}.snapshot",
1081
+ )
1082
+ files = _require_list(snapshot.get("files"), f"{field}.snapshot.files")
1083
+ file_names: list[str] = []
1084
+ for index, file_info_value in enumerate(files):
1085
+ file_field = f"{field}.snapshot.files[{index}]"
1086
+ file_info = _require_mapping(file_info_value, file_field)
1087
+ _require_exact_keys(
1088
+ file_info,
1089
+ {"name", "path", "file_type", "size", "mtime_ns", "sha256"},
1090
+ file_field,
1091
+ )
1092
+ name = _validate_entry_name(file_info.get("name"), f"{file_field}.name")
1093
+ if file_info.get("path") != name:
1094
+ raise ScanStateError(f"{file_field}.path must equal its direct file name")
1095
+ if file_info.get("file_type") != "regular":
1096
+ raise ScanStateError(f"{file_field}.file_type must be 'regular'")
1097
+ _require_non_negative_int(file_info.get("size"), f"{file_field}.size")
1098
+ _require_non_negative_int(file_info.get("mtime_ns"), f"{file_field}.mtime_ns")
1099
+ _require_sha256(file_info.get("sha256"), f"{file_field}.sha256")
1100
+ file_names.append(name)
1101
+ if files != sorted(
1102
+ files,
1103
+ key=lambda value: (str(value["name"]).casefold(), str(value["name"])),
1104
+ ):
1105
+ raise ScanStateError(f"{field}.snapshot.files must use canonical order")
1106
+
1107
+ child_values = _require_list(
1108
+ snapshot.get("child_directories"),
1109
+ f"{field}.snapshot.child_directories",
1110
+ )
1111
+ child_names = [
1112
+ _validate_entry_name(value, f"{field}.snapshot.child_directories[{index}]")
1113
+ for index, value in enumerate(child_values)
1114
+ ]
1115
+ if child_names != sorted(child_names, key=lambda value: (value.casefold(), value)):
1116
+ raise ScanStateError(
1117
+ f"{field}.snapshot.child_directories must use canonical order"
1118
+ )
1119
+ _ensure_casefold_unique(file_names + child_names, f"{field}.snapshot entries")
1120
+
1121
+ skipped_values = _require_list(
1122
+ snapshot.get("skipped_directories"),
1123
+ f"{field}.snapshot.skipped_directories",
1124
+ )
1125
+ skipped_names: list[str] = []
1126
+ for index, skipped_value in enumerate(skipped_values):
1127
+ skipped_field = f"{field}.snapshot.skipped_directories[{index}]"
1128
+ skipped = _require_mapping(skipped_value, skipped_field)
1129
+ _require_exact_keys(
1130
+ skipped, {"name", "kind", "reason", "target"}, skipped_field
1131
+ )
1132
+ name = _validate_entry_name(skipped.get("name"), f"{skipped_field}.name")
1133
+ if name not in child_names:
1134
+ raise ScanStateError(f"{skipped_field}.name is not a child directory")
1135
+ if skipped.get("kind") not in ("symlink", "reparse", "directory"):
1136
+ raise ScanStateError(f"{skipped_field}.kind is invalid")
1137
+ if skipped.get("reason") not in (
1138
+ "outside-root",
1139
+ "reparse-directory",
1140
+ "unresolvable-reparse-directory",
1141
+ "directory-cycle-or-alias",
1142
+ ):
1143
+ raise ScanStateError(f"{skipped_field}.reason is invalid")
1144
+ target = skipped.get("target")
1145
+ if target not in ("<outside-root>", "<unresolvable>", "<project-root>"):
1146
+ if not isinstance(target, str):
1147
+ raise ScanStateError(f"{skipped_field}.target is invalid")
1148
+ _validate_relative_directory_path(target)
1149
+ skipped_names.append(name)
1150
+ _ensure_casefold_unique(skipped_names, f"{field}.snapshot.skipped_directories")
1151
+ if skipped_values != sorted(
1152
+ skipped_values,
1153
+ key=lambda value: (str(value["name"]).casefold(), str(value["name"])),
1154
+ ):
1155
+ raise ScanStateError(
1156
+ f"{field}.snapshot.skipped_directories must use canonical order"
1157
+ )
1158
+
1159
+ is_boundary = snapshot.get("is_boundary")
1160
+ if type(is_boundary) is not bool:
1161
+ raise ScanStateError(f"{field}.snapshot.is_boundary must be boolean")
1162
+ expected_boundary = depth > 0 and any(
1163
+ name.casefold() == "claude.md" for name in file_names
1164
+ )
1165
+ if (
1166
+ is_boundary != expected_boundary
1167
+ or record.get("is_boundary") != expected_boundary
1168
+ ):
1169
+ raise ScanStateError(f"{field}.is_boundary is inconsistent with direct files")
1170
+
1171
+ visible_names = {name.casefold() for name in file_names}
1172
+ _require_non_negative_int(record.get("file_count"), f"{field}.file_count")
1173
+ _require_non_negative_int(record.get("py_file_count"), f"{field}.py_file_count")
1174
+ for boolean_field in ("is_boundary", "has_init_py", "has_readme", "is_empty"):
1175
+ if type(record.get(boolean_field)) is not bool:
1176
+ raise ScanStateError(f"{field}.{boolean_field} must be boolean")
1177
+ expected_values = {
1178
+ "file_count": len(files),
1179
+ "py_file_count": sum(name.casefold().endswith(".py") for name in file_names),
1180
+ "has_init_py": "__init__.py" in visible_names,
1181
+ "has_readme": "readme.md" in visible_names,
1182
+ "is_empty": len(files) == 0
1183
+ or (len(files) == 1 and "__init__.py" in visible_names),
1184
+ }
1185
+ for derived_field, expected_value in expected_values.items():
1186
+ if record.get(derived_field) != expected_value:
1187
+ raise ScanStateError(
1188
+ f"{field}.{derived_field} is inconsistent with snapshot"
1189
+ )
1190
+
1191
+ fingerprint = _require_sha256(record.get("fingerprint"), f"{field}.fingerprint")
1192
+ if fingerprint not in (
1193
+ _directory_fingerprint(dict(snapshot)),
1194
+ _fingerprint(dict(snapshot)),
1195
+ ):
1196
+ raise ScanStateError(f"{field}.fingerprint does not match its snapshot")
1197
+ return path
1198
+
1199
+
1200
+ def _validate_skipped_directory(record: Mapping[str, Any], field: str) -> str:
1201
+ _require_exact_keys(record, {"path", "kind", "reason", "target"}, field)
1202
+ path = record.get("path")
1203
+ if not isinstance(path, str):
1204
+ raise ScanStateError(f"{field}.path must be a string")
1205
+ _validate_relative_directory_path(path)
1206
+ if record.get("kind") not in ("symlink", "reparse", "directory"):
1207
+ raise ScanStateError(f"{field}.kind is invalid")
1208
+ if record.get("reason") not in (
1209
+ "outside-root",
1210
+ "reparse-directory",
1211
+ "unresolvable-reparse-directory",
1212
+ "directory-cycle-or-alias",
1213
+ ):
1214
+ raise ScanStateError(f"{field}.reason is invalid")
1215
+ target = record.get("target")
1216
+ if target not in ("<outside-root>", "<unresolvable>", "<project-root>"):
1217
+ if not isinstance(target, str):
1218
+ raise ScanStateError(f"{field}.target is invalid")
1219
+ _validate_relative_directory_path(target)
1220
+ return path
1221
+
1222
+
1223
+ def _validate_unknown_scope(record: Mapping[str, Any], field: str) -> str:
1224
+ _require_exact_keys(record, {"path", "reason", "scope"}, field)
1225
+ path = record.get("path")
1226
+ if not isinstance(path, str):
1227
+ raise ScanStateError(f"{field}.path must be a string")
1228
+ _validate_relative_directory_path(path)
1229
+ if record.get("reason") not in (
1230
+ "boundary",
1231
+ "max-depth",
1232
+ "outside-root",
1233
+ "reparse-directory",
1234
+ "unresolvable-reparse-directory",
1235
+ "directory-cycle-or-alias",
1236
+ ):
1237
+ raise ScanStateError(f"{field}.reason is invalid")
1238
+ if record.get("scope") not in ("descendants", "subtree"):
1239
+ raise ScanStateError(f"{field}.scope is invalid")
1240
+ return path
1241
+
1242
+
1243
+ def _ensure_unique_directory_paths(paths: Sequence[str], field: str) -> None:
1244
+ try:
1245
+ contract.ensure_unique_manifest_paths(
1246
+ [f"{path}/__scan_directory__.md" if path else "index.md" for path in paths]
1247
+ )
1248
+ except contract.PathValidationError as exc:
1249
+ raise ScanStateError(f"{field} contains conflicting paths: {exc}") from exc
1250
+
1251
+
1252
+ def _validate_complete_snapshot(
1253
+ snapshot_value: Any,
1254
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
1255
+ snapshot = dict(_require_mapping(snapshot_value, "snapshot"))
1256
+ _require_exact_keys(
1257
+ snapshot,
1258
+ {"directories", "skipped_directories", "unknown_scopes"},
1259
+ "snapshot",
1260
+ )
1261
+ record_values = _require_list(snapshot.get("directories"), "snapshot.directories")
1262
+ records: list[dict[str, Any]] = []
1263
+ paths: list[str] = []
1264
+ for index, record_value in enumerate(record_values):
1265
+ field = f"snapshot.directories[{index}]"
1266
+ record = dict(_require_mapping(record_value, field))
1267
+ paths.append(_validate_directory_snapshot(record, field))
1268
+ records.append(record)
1269
+ _ensure_unique_directory_paths(paths, "snapshot.directories")
1270
+ if records != sorted(records, key=_directory_sort_key):
1271
+ raise ScanStateError(
1272
+ "snapshot.directories must use canonical deepest-first order"
1273
+ )
1274
+
1275
+ skipped_values = _require_list(
1276
+ snapshot.get("skipped_directories"), "snapshot.skipped_directories"
1277
+ )
1278
+ skipped_paths = [
1279
+ _validate_skipped_directory(
1280
+ _require_mapping(value, f"snapshot.skipped_directories[{index}]"),
1281
+ f"snapshot.skipped_directories[{index}]",
1282
+ )
1283
+ for index, value in enumerate(skipped_values)
1284
+ ]
1285
+ _ensure_unique_directory_paths(skipped_paths, "snapshot.skipped_directories")
1286
+ if skipped_values != sorted(
1287
+ skipped_values,
1288
+ key=lambda value: (str(value["path"]).casefold(), str(value["path"])),
1289
+ ):
1290
+ raise ScanStateError("snapshot.skipped_directories must use canonical order")
1291
+
1292
+ scope_values = _require_list(
1293
+ snapshot.get("unknown_scopes"), "snapshot.unknown_scopes"
1294
+ )
1295
+ scope_paths = [
1296
+ _validate_unknown_scope(
1297
+ _require_mapping(value, f"snapshot.unknown_scopes[{index}]"),
1298
+ f"snapshot.unknown_scopes[{index}]",
1299
+ )
1300
+ for index, value in enumerate(scope_values)
1301
+ ]
1302
+ _ensure_unique_directory_paths(scope_paths, "snapshot.unknown_scopes")
1303
+ if scope_values != sorted(
1304
+ scope_values,
1305
+ key=lambda value: (
1306
+ str(value["path"]).casefold(),
1307
+ str(value["path"]),
1308
+ str(value["reason"]),
1309
+ ),
1310
+ ):
1311
+ raise ScanStateError("snapshot.unknown_scopes must use canonical order")
1312
+ return snapshot, records
1313
+
1314
+
1315
+ def _validate_changes(value: Any, current_paths: Sequence[str]) -> dict[str, list[str]]:
1316
+ changes_value = _require_mapping(value, "changes")
1317
+ names = ("new", "modified", "deleted", "unchanged", "unknown")
1318
+ _require_exact_keys(changes_value, set(names), "changes")
1319
+ changes: dict[str, list[str]] = {}
1320
+ all_paths: list[str] = []
1321
+ for name in names:
1322
+ paths = _require_list(changes_value.get(name), f"changes.{name}")
1323
+ validated: list[str] = []
1324
+ for index, path in enumerate(paths):
1325
+ if not isinstance(path, str):
1326
+ raise ScanStateError(f"changes.{name}[{index}] must be a string")
1327
+ validated.append(_validate_relative_directory_path(path))
1328
+ if validated != sorted(validated, key=lambda item: (item.casefold(), item)):
1329
+ raise ScanStateError(f"changes.{name} must use canonical order")
1330
+ changes[name] = validated
1331
+ all_paths.extend(validated)
1332
+ _ensure_unique_directory_paths(all_paths, "changes")
1333
+
1334
+ current_by_fold = {path.casefold(): path for path in current_paths}
1335
+ classified_current = changes["new"] + changes["modified"] + changes["unchanged"]
1336
+ if {path.casefold() for path in classified_current} != set(current_by_fold):
1337
+ raise ScanStateError(
1338
+ "changes.new/modified/unchanged must partition snapshot.directories"
1339
+ )
1340
+ for path in classified_current:
1341
+ if current_by_fold.get(path.casefold()) != path:
1342
+ raise ScanStateError(
1343
+ "changes must preserve canonical snapshot path spelling"
1344
+ )
1345
+ for path in changes["deleted"] + changes["unknown"]:
1346
+ if path.casefold() in current_by_fold:
1347
+ raise ScanStateError(
1348
+ "deleted/unknown changes must not exist in the snapshot"
1349
+ )
1350
+ return changes
1351
+
1352
+
1353
+ def _candidate_worklist(
1354
+ data: Mapping[str, Any],
1355
+ records: Sequence[Mapping[str, Any]],
1356
+ changes: Mapping[str, Sequence[str]],
1357
+ ) -> list[dict[str, Any]]:
1358
+ change_by_fold = {
1359
+ path.casefold(): name
1360
+ for name in ("new", "modified", "unchanged")
1361
+ for path in changes[name]
1362
+ }
1363
+ if data.get("mode") == "incremental":
1364
+ selected = {path.casefold() for path in changes["new"] + changes["modified"]}
1365
+ else:
1366
+ selected = {str(record["path"]).casefold() for record in records}
1367
+ worklist: list[dict[str, Any]] = []
1368
+ for record in records:
1369
+ path = str(record["path"])
1370
+ if path.casefold() not in selected:
1371
+ continue
1372
+ annotated = copy.deepcopy(dict(record))
1373
+ annotated["change"] = change_by_fold[path.casefold()]
1374
+ worklist.append(annotated)
1375
+ return worklist
1376
+
1377
+
1378
+ def _candidate_generation_payload(data: Mapping[str, Any]) -> dict[str, Any]:
1379
+ payload = copy.deepcopy(dict(data))
1380
+ payload.pop("candidate_generation_id", None)
1381
+ payload.pop("committed_at", None)
1382
+ payload.pop("state_path", None)
1383
+ payload.pop("manifest_generation_id", None)
1384
+ payload.pop("doc_hash_cache", None)
1385
+ if payload.get("state_role") == "committed":
1386
+ snapshot = _require_mapping(payload.get("snapshot"), "snapshot")
1387
+ records = _require_list(snapshot.get("directories"), "snapshot.directories")
1388
+ changes = _require_mapping(payload.get("changes"), "changes")
1389
+ payload["state_role"] = "candidate"
1390
+ payload["directories"] = _candidate_worklist(payload, records, changes)
1391
+ payload["total"] = len(payload["directories"])
1392
+ return payload
1393
+
1394
+
1395
+ def _candidate_generation_id(data: Mapping[str, Any]) -> str:
1396
+ return _fingerprint(_candidate_generation_payload(data))
1397
+
1398
+
1399
+ def validate_scan_state_v2(state: Mapping[str, Any]) -> dict[str, Any]:
1400
+ """Strictly validate every redundant v2 field and its candidate binding."""
1401
+
1402
+ data = copy.deepcopy(dict(_require_mapping(state, "scan state")))
1403
+ role = data.get("state_role")
1404
+ base_fields = {
1405
+ "schema_version",
1406
+ "kind",
1407
+ "state_role",
1408
+ "producer",
1409
+ "root",
1410
+ "project_identity",
1411
+ "scan_time",
1412
+ "mode",
1413
+ "baseline",
1414
+ "directories",
1415
+ "deleted_directories",
1416
+ "unknown_directories",
1417
+ "changes",
1418
+ "change_counts",
1419
+ "total",
1420
+ "full_total",
1421
+ "skipped_unchanged",
1422
+ "max_depth",
1423
+ "boundary_count",
1424
+ "skipped_directory_count",
1425
+ "snapshot",
1426
+ "snapshot_fingerprint",
1427
+ "candidate_generation_id",
1428
+ }
1429
+ if role == "candidate":
1430
+ _require_exact_keys(
1431
+ data,
1432
+ base_fields,
1433
+ "candidate scan state",
1434
+ optional={"baseline_precondition", "scanner_version"},
1435
+ )
1436
+ elif role == "committed":
1437
+ _require_exact_keys(
1438
+ data,
1439
+ base_fields | {"committed_at"},
1440
+ "committed scan state",
1441
+ optional={
1442
+ "state_path",
1443
+ "baseline_precondition",
1444
+ "manifest_generation_id",
1445
+ "scanner_version",
1446
+ "doc_hash_cache",
1447
+ },
1448
+ )
1449
+ else:
1450
+ raise ScanStateError("state_role must be 'candidate' or 'committed'")
1451
+
1452
+ if "scanner_version" in data:
1453
+ scanner_ver = data["scanner_version"]
1454
+ if not isinstance(scanner_ver, str) or not scanner_ver.strip():
1455
+ raise ScanStateError("scanner_version must be a non-empty string")
1456
+ if "doc_hash_cache" in data:
1457
+ cache_obj = _require_mapping(data["doc_hash_cache"], "doc_hash_cache")
1458
+ for doc_key, doc_hash in cache_obj.items():
1459
+ if not isinstance(doc_key, str) or not doc_key:
1460
+ raise ScanStateError("doc_hash_cache keys must be non-empty strings")
1461
+ _require_sha256(doc_hash, f"doc_hash_cache[{doc_key!r}]")
1462
+
1463
+ schema_version = data.get("schema_version")
1464
+ if type(schema_version) is not int or schema_version != SCAN_STATE_SCHEMA_VERSION:
1465
+ raise ScanStateError(
1466
+ f"expected schema_version={SCAN_STATE_SCHEMA_VERSION}, got {schema_version!r}"
1467
+ )
1468
+ if data.get("kind") != SCAN_STATE_KIND:
1469
+ raise ScanStateError(f"scan state kind must be {SCAN_STATE_KIND!r}")
1470
+ if data.get("producer") != SCAN_STATE_PRODUCER:
1471
+ raise ScanStateError("producer does not match this scan-state contract")
1472
+ if data.get("root") != _PORTABLE_ROOT:
1473
+ raise ScanStateError("v2 root must be the portable project-relative value '.'")
1474
+ _require_sha256(data.get("project_identity"), "project_identity")
1475
+ _validate_timestamp(data.get("scan_time"), "scan_time")
1476
+ if role == "committed":
1477
+ _validate_timestamp(data.get("committed_at"), "committed_at")
1478
+ if "state_path" in data:
1479
+ _validate_portable_state_path(data["state_path"])
1480
+ if "manifest_generation_id" in data:
1481
+ _require_sha256(
1482
+ data.get("manifest_generation_id"),
1483
+ "manifest_generation_id",
1484
+ )
1485
+
1486
+ mode = data.get("mode")
1487
+ if mode not in ("incremental", "full"):
1488
+ raise ScanStateError("mode must be 'incremental' or 'full'")
1489
+ baseline = _require_mapping(data.get("baseline"), "baseline")
1490
+ _require_exact_keys(
1491
+ baseline,
1492
+ {
1493
+ "available",
1494
+ "schema_version",
1495
+ "snapshot_fingerprint",
1496
+ "candidate_generation_id",
1497
+ "force_full",
1498
+ },
1499
+ "baseline",
1500
+ )
1501
+ if type(baseline.get("available")) is not bool:
1502
+ raise ScanStateError("baseline.available must be boolean")
1503
+ if type(baseline.get("force_full")) is not bool:
1504
+ raise ScanStateError("baseline.force_full must be boolean")
1505
+ if baseline["force_full"]:
1506
+ if mode != "full" or baseline["available"]:
1507
+ raise ScanStateError(
1508
+ "force_full must use full mode and ignore the baseline"
1509
+ )
1510
+ if baseline["available"]:
1511
+ baseline_schema = baseline.get("schema_version")
1512
+ if type(baseline_schema) is not int or baseline_schema not in (1, 2):
1513
+ raise ScanStateError("baseline.schema_version must be 1 or 2")
1514
+ if baseline_schema == 2:
1515
+ _require_sha256(
1516
+ baseline.get("snapshot_fingerprint"),
1517
+ "baseline.snapshot_fingerprint",
1518
+ )
1519
+ _require_sha256(
1520
+ baseline.get("candidate_generation_id"),
1521
+ "baseline.candidate_generation_id",
1522
+ )
1523
+ elif (
1524
+ baseline.get("snapshot_fingerprint") is not None
1525
+ or baseline.get("candidate_generation_id") is not None
1526
+ ):
1527
+ raise ScanStateError("legacy baseline fingerprints must be null")
1528
+ elif any(
1529
+ baseline.get(name) is not None
1530
+ for name in (
1531
+ "schema_version",
1532
+ "snapshot_fingerprint",
1533
+ "candidate_generation_id",
1534
+ )
1535
+ ):
1536
+ raise ScanStateError("unavailable baseline metadata must be null")
1537
+
1538
+ if "baseline_precondition" in data:
1539
+ precondition = _require_mapping(
1540
+ data.get("baseline_precondition"),
1541
+ "baseline_precondition",
1542
+ )
1543
+ _require_exact_keys(
1544
+ precondition,
1545
+ {"exists", "sha256", "generation_id"},
1546
+ "baseline_precondition",
1547
+ )
1548
+ if type(precondition.get("exists")) is not bool:
1549
+ raise ScanStateError("baseline_precondition.exists must be boolean")
1550
+ if precondition["exists"]:
1551
+ _require_sha256(
1552
+ precondition.get("sha256"),
1553
+ "baseline_precondition.sha256",
1554
+ )
1555
+ if precondition.get("generation_id") is not None:
1556
+ _require_sha256(
1557
+ precondition.get("generation_id"),
1558
+ "baseline_precondition.generation_id",
1559
+ )
1560
+ elif (
1561
+ precondition.get("sha256") is not None
1562
+ or precondition.get("generation_id") is not None
1563
+ ):
1564
+ raise ScanStateError("absent baseline_precondition cannot carry hashes")
1565
+ if not baseline["force_full"]:
1566
+ if precondition["exists"] != baseline["available"]:
1567
+ raise ScanStateError(
1568
+ "baseline_precondition existence disagrees with baseline"
1569
+ )
1570
+ if (
1571
+ baseline["available"]
1572
+ and baseline["schema_version"] == SCAN_STATE_SCHEMA_VERSION
1573
+ and precondition.get("generation_id")
1574
+ != baseline["candidate_generation_id"]
1575
+ ):
1576
+ raise ScanStateError(
1577
+ "baseline_precondition generation disagrees with baseline"
1578
+ )
1579
+
1580
+ snapshot, records = _validate_complete_snapshot(data.get("snapshot"))
1581
+ snapshot_fingerprint = _require_sha256(
1582
+ data.get("snapshot_fingerprint"), "snapshot_fingerprint"
1583
+ )
1584
+ if snapshot_fingerprint != _fingerprint(snapshot):
1585
+ raise ScanStateError("snapshot_fingerprint does not match snapshot")
1586
+ current_paths = [str(record["path"]) for record in records]
1587
+ changes = _validate_changes(data.get("changes"), current_paths)
1588
+
1589
+ if baseline["force_full"]:
1590
+ expected_new = sorted(current_paths, key=lambda item: (item.casefold(), item))
1591
+ if changes["new"] != expected_new or any(
1592
+ changes[name] for name in ("modified", "deleted", "unchanged", "unknown")
1593
+ ):
1594
+ raise ScanStateError(
1595
+ "force_full must classify every current directory as new"
1596
+ )
1597
+
1598
+ counts_value = _require_mapping(data.get("change_counts"), "change_counts")
1599
+ _require_exact_keys(counts_value, set(changes), "change_counts")
1600
+ expected_counts = {name: len(paths) for name, paths in changes.items()}
1601
+ for name in expected_counts:
1602
+ _require_non_negative_int(counts_value.get(name), f"change_counts.{name}")
1603
+ if dict(counts_value) != expected_counts:
1604
+ raise ScanStateError("change_counts does not match changes")
1605
+
1606
+ expected_worklist = _candidate_worklist(data, records, changes)
1607
+ directory_values = _require_list(data.get("directories"), "directories")
1608
+ expected_directories: Sequence[Mapping[str, Any]] = (
1609
+ expected_worklist if role == "candidate" else records
1610
+ )
1611
+ if directory_values != list(expected_directories):
1612
+ raise ScanStateError("directories does not match mode, changes, and snapshot")
1613
+
1614
+ expected_deleted = [
1615
+ {"path": path, "change": "deleted"} for path in changes["deleted"]
1616
+ ]
1617
+ expected_unknown = [
1618
+ {"path": path, "change": "unknown"} for path in changes["unknown"]
1619
+ ]
1620
+ if (
1621
+ _require_list(data.get("deleted_directories"), "deleted_directories")
1622
+ != expected_deleted
1623
+ ):
1624
+ raise ScanStateError("deleted_directories does not match changes.deleted")
1625
+ if (
1626
+ _require_list(data.get("unknown_directories"), "unknown_directories")
1627
+ != expected_unknown
1628
+ ):
1629
+ raise ScanStateError("unknown_directories does not match changes.unknown")
1630
+
1631
+ full_total = _require_non_negative_int(data.get("full_total"), "full_total")
1632
+ if full_total != len(records):
1633
+ raise ScanStateError("full_total does not match snapshot.directories")
1634
+ total = _require_non_negative_int(data.get("total"), "total")
1635
+ expected_total = len(expected_worklist) if role == "candidate" else full_total
1636
+ if total != expected_total:
1637
+ raise ScanStateError("total does not match directories")
1638
+ skipped_unchanged = _require_non_negative_int(
1639
+ data.get("skipped_unchanged"), "skipped_unchanged"
1640
+ )
1641
+ expected_skipped = len(changes["unchanged"]) if mode == "incremental" else 0
1642
+ if skipped_unchanged != expected_skipped:
1643
+ raise ScanStateError("skipped_unchanged is inconsistent with mode and changes")
1644
+
1645
+ max_depth = _require_non_negative_int(data.get("max_depth"), "max_depth")
1646
+ if max_depth != max((int(record["depth"]) for record in records), default=0):
1647
+ raise ScanStateError("max_depth does not match snapshot.directories")
1648
+ boundary_count = _require_non_negative_int(
1649
+ data.get("boundary_count"), "boundary_count"
1650
+ )
1651
+ if boundary_count != sum(bool(record["is_boundary"]) for record in records):
1652
+ raise ScanStateError("boundary_count does not match snapshot.directories")
1653
+ skipped_count = _require_non_negative_int(
1654
+ data.get("skipped_directory_count"), "skipped_directory_count"
1655
+ )
1656
+ if skipped_count != len(snapshot["skipped_directories"]):
1657
+ raise ScanStateError("skipped_directory_count does not match snapshot")
1658
+
1659
+ generation = _require_sha256(
1660
+ data.get("candidate_generation_id"), "candidate_generation_id"
1661
+ )
1662
+ if not hmac.compare_digest(generation, _candidate_generation_id(data)):
1663
+ raise ScanStateError(
1664
+ "candidate_generation_id does not cover the complete candidate"
1665
+ )
1666
+ return data
1667
+
1668
+
1669
+ def _legacy_state_from_paths(
1670
+ paths: Sequence[str], project_identity: str | None = None
1671
+ ) -> dict[str, Any]:
1672
+ validated = [_validate_relative_directory_path(path) for path in paths]
1673
+ _ensure_unique_directory_paths(validated, "legacy directories")
1674
+ normalized: dict[str, Any] = {
1675
+ "schema_version": 1,
1676
+ "directories": [
1677
+ {"path": path}
1678
+ for path in sorted(validated, key=lambda item: (item.casefold(), item))
1679
+ ],
1680
+ }
1681
+ if project_identity is not None:
1682
+ normalized["legacy_project_identity"] = _require_sha256(
1683
+ project_identity, "legacy_project_identity"
1684
+ )
1685
+ return normalized
1686
+
1687
+
1688
+ def _validate_legacy_state(state: Mapping[str, Any]) -> dict[str, Any]:
1689
+ data = copy.deepcopy(dict(state))
1690
+ directories = _require_list(data.get("directories"), "legacy directories")
1691
+ paths: list[str] = []
1692
+ for index, value in enumerate(directories):
1693
+ record = _require_mapping(value, f"legacy directories[{index}]")
1694
+ path = record.get("path")
1695
+ if not isinstance(path, str):
1696
+ raise ScanStateError(f"legacy directories[{index}].path must be a string")
1697
+ paths.append(path)
1698
+
1699
+ identity: str | None = None
1700
+ if "legacy_project_identity" in data:
1701
+ identity = _require_sha256(
1702
+ data.get("legacy_project_identity"), "legacy_project_identity"
1703
+ )
1704
+ legacy_root = data.get("root")
1705
+ if legacy_root is not None:
1706
+ if not isinstance(legacy_root, str) or not Path(legacy_root).is_absolute():
1707
+ raise ScanStateError("legacy root must be an absolute path")
1708
+ root_identity = _project_identity_from_path(Path(legacy_root))
1709
+ if identity is not None and not hmac.compare_digest(identity, root_identity):
1710
+ raise ScanStateError("legacy root and project identity disagree")
1711
+ identity = root_identity
1712
+ return _legacy_state_from_paths(paths, identity)
1713
+
1714
+
1715
+ def _migrate_legacy_v2_state(
1716
+ state: Mapping[str, Any], *, require_committed: bool
1717
+ ) -> dict[str, Any]:
1718
+ """Reduce the former absolute-root v2 state to a conservative v1 baseline."""
1719
+
1720
+ data = copy.deepcopy(dict(state))
1721
+ if data.get("schema_version") != SCAN_STATE_SCHEMA_VERSION:
1722
+ raise ScanStateError("legacy v2 state has an invalid schema version")
1723
+ if require_committed and data.get("state_role") != "committed":
1724
+ raise ScanStateError("only committed state can be used as a baseline")
1725
+ root = data.get("root")
1726
+ if not isinstance(root, str) or not Path(root).is_absolute():
1727
+ raise ScanStateError("legacy v2 root must be an absolute path")
1728
+
1729
+ snapshot = _require_mapping(data.get("snapshot"), "legacy v2 snapshot")
1730
+ records = _require_list(
1731
+ snapshot.get("directories"), "legacy v2 snapshot.directories"
1732
+ )
1733
+ paths: list[str] = []
1734
+ for index, value in enumerate(records):
1735
+ field = f"legacy v2 snapshot.directories[{index}]"
1736
+ record = _require_mapping(value, field)
1737
+ path = record.get("path")
1738
+ if not isinstance(path, str):
1739
+ raise ScanStateError(f"{field}.path must be a string")
1740
+ paths.append(_validate_relative_directory_path(path))
1741
+ record_snapshot = record.get("snapshot")
1742
+ record_fingerprint = record.get("fingerprint")
1743
+ if record_snapshot is not None or record_fingerprint is not None:
1744
+ if not isinstance(record_snapshot, Mapping):
1745
+ raise ScanStateError(f"{field}.snapshot must be an object")
1746
+ if record_fingerprint not in (
1747
+ _directory_fingerprint(dict(record_snapshot)),
1748
+ _fingerprint(dict(record_snapshot)),
1749
+ ):
1750
+ raise ScanStateError(f"{field}.fingerprint does not match snapshot")
1751
+ if data.get("snapshot_fingerprint") != _fingerprint(dict(snapshot)):
1752
+ raise ScanStateError("legacy v2 snapshot_fingerprint does not match snapshot")
1753
+ return _legacy_state_from_paths(paths, _project_identity_from_path(Path(root)))
1754
+
1755
+
1756
+ def parse_previous_state_bytes(
1757
+ raw_bytes: bytes | None,
1758
+ *,
1759
+ source: str = "<scan-state-bytes>",
1760
+ ) -> dict[str, Any] | None:
1761
+ """Parse one captured byte snapshot into the committed baseline it represents."""
1762
+
1763
+ if raw_bytes is None:
1764
+ return None
1765
+ try:
1766
+ text = raw_bytes.decode("utf-8", errors="strict")
1767
+ except UnicodeDecodeError as exc:
1768
+ raise ScanStateError(
1769
+ f"scan state is not strict UTF-8: {source}: {exc}"
1770
+ ) from exc
1771
+ value = contract.parse_json_strict(text, source=source)
1772
+ mapping = _require_mapping(value, "scan state")
1773
+ if "schema_version" not in mapping or mapping.get("schema_version") == 1:
1774
+ return _validate_legacy_state(mapping)
1775
+ if mapping.get("schema_version") != SCAN_STATE_SCHEMA_VERSION:
1776
+ raise ScanStateError("unsupported scan-state schema version")
1777
+ if (
1778
+ mapping.get("root") != _PORTABLE_ROOT
1779
+ or "project_identity" not in mapping
1780
+ or "candidate_generation_id" not in mapping
1781
+ ):
1782
+ return _migrate_legacy_v2_state(mapping, require_committed=True)
1783
+ validated = validate_scan_state_v2(mapping)
1784
+ if validated["state_role"] != "committed":
1785
+ raise ScanStateError("only committed state can be used as a baseline")
1786
+ return validated
1787
+
1788
+
1789
+ def _read_optional_regular_bytes(path: Path, label: str) -> bytes | None:
1790
+ lexical = Path(os.path.abspath(path))
1791
+ if not os.path.lexists(lexical):
1792
+ return None
1793
+ try:
1794
+ before = lexical.lstat()
1795
+ resolved_before = lexical.resolve(strict=True)
1796
+ except (OSError, RuntimeError) as exc:
1797
+ raise ScanStateError(f"cannot inspect {label} {path}: {exc}") from exc
1798
+ if (
1799
+ lexical.is_symlink()
1800
+ or _is_reparse(before)
1801
+ or not stat.S_ISREG(before.st_mode)
1802
+ or os.path.normcase(os.path.normpath(str(lexical)))
1803
+ != os.path.normcase(os.path.normpath(str(resolved_before)))
1804
+ ):
1805
+ raise ScanStateError(
1806
+ f"{label} must be a direct regular non-reparse file: {path}"
1807
+ )
1808
+
1809
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
1810
+ try:
1811
+ descriptor = os.open(lexical, flags)
1812
+ except OSError as exc:
1813
+ raise ScanStateError(f"cannot safely open {label} {path}: {exc}") from exc
1814
+ try:
1815
+ opened = os.fstat(descriptor)
1816
+ after_open = lexical.lstat()
1817
+ if (
1818
+ not stat.S_ISREG(opened.st_mode)
1819
+ or not stat.S_ISREG(after_open.st_mode)
1820
+ or _is_reparse(opened)
1821
+ or _is_reparse(after_open)
1822
+ or lexical.is_symlink()
1823
+ or not _same_file_identity(before, opened)
1824
+ or not _same_file_identity(opened, after_open)
1825
+ ):
1826
+ raise ScanStateError(f"{label} changed identity while opening: {path}")
1827
+ chunks: list[bytes] = []
1828
+ while True:
1829
+ chunk = os.read(descriptor, _FILE_HASH_CHUNK_SIZE)
1830
+ if not chunk:
1831
+ break
1832
+ chunks.append(chunk)
1833
+ finished = os.fstat(descriptor)
1834
+ final_path_state = lexical.lstat()
1835
+ resolved_final = lexical.resolve(strict=True)
1836
+ if (
1837
+ not _same_file_identity(opened, finished)
1838
+ or not _same_file_identity(finished, final_path_state)
1839
+ or _is_reparse(final_path_state)
1840
+ or lexical.is_symlink()
1841
+ or os.path.normcase(os.path.normpath(str(lexical)))
1842
+ != os.path.normcase(os.path.normpath(str(resolved_final)))
1843
+ or opened.st_size != finished.st_size
1844
+ or _mtime_ns(opened) != _mtime_ns(finished)
1845
+ ):
1846
+ raise ScanStateError(f"{label} changed while reading: {path}")
1847
+ except (OSError, RuntimeError) as exc:
1848
+ raise ScanStateError(f"cannot safely read {label} {path}: {exc}") from exc
1849
+ finally:
1850
+ os.close(descriptor)
1851
+ return b"".join(chunks)
1852
+
1853
+
1854
+ def baseline_precondition_from_bytes(
1855
+ raw_bytes: bytes | None,
1856
+ *,
1857
+ source: str = "<scan-state-bytes>",
1858
+ ) -> BaselinePrecondition:
1859
+ state = parse_previous_state_bytes(raw_bytes, source=source)
1860
+ generation = None
1861
+ if state is not None and state.get("schema_version") == SCAN_STATE_SCHEMA_VERSION:
1862
+ value = state.get("candidate_generation_id")
1863
+ generation = value if isinstance(value, str) else None
1864
+ return BaselinePrecondition(
1865
+ exists=raw_bytes is not None,
1866
+ sha256=contract.sha256_bytes(raw_bytes) if raw_bytes is not None else None,
1867
+ generation_id=generation,
1868
+ )
1869
+
1870
+
1871
+ def load_previous_state_with_precondition(
1872
+ state_path: str | os.PathLike[str],
1873
+ ) -> tuple[dict[str, Any] | None, BaselinePrecondition, bytes | None]:
1874
+ path = Path(state_path)
1875
+ raw_bytes = _read_optional_regular_bytes(path, "scan state")
1876
+ state = parse_previous_state_bytes(raw_bytes, source=str(path))
1877
+ generation = None
1878
+ if state is not None and state.get("schema_version") == SCAN_STATE_SCHEMA_VERSION:
1879
+ value = state.get("candidate_generation_id")
1880
+ generation = value if isinstance(value, str) else None
1881
+ precondition = BaselinePrecondition(
1882
+ exists=raw_bytes is not None,
1883
+ sha256=contract.sha256_bytes(raw_bytes) if raw_bytes is not None else None,
1884
+ generation_id=generation,
1885
+ )
1886
+ return state, precondition, raw_bytes
1887
+
1888
+
1889
+ def load_previous_state(
1890
+ state_path: str | os.PathLike[str],
1891
+ ) -> dict[str, Any] | None:
1892
+ """Strictly load a committed v2 baseline or conservatively migrate legacy state."""
1893
+
1894
+ state, _, _ = load_previous_state_with_precondition(state_path)
1895
+ return state
1896
+
1897
+
1898
+ def _state_records(state: Mapping[str, Any] | None) -> list[dict[str, Any]]:
1899
+ if state is None:
1900
+ return []
1901
+ if state.get("schema_version") == SCAN_STATE_SCHEMA_VERSION:
1902
+ snapshot = _require_mapping(state.get("snapshot"), "snapshot")
1903
+ return [
1904
+ copy.deepcopy(dict(_require_mapping(record, "snapshot directory")))
1905
+ for record in _require_list(
1906
+ snapshot.get("directories"), "snapshot.directories"
1907
+ )
1908
+ ]
1909
+ # Legacy records deliberately carry paths only, so every surviving directory
1910
+ # is classified modified until a content-hash v2 baseline is committed.
1911
+ return [
1912
+ {"path": str(_require_mapping(record, "legacy directory")["path"])}
1913
+ for record in _require_list(state.get("directories"), "legacy directories")
1914
+ ]
1915
+
1916
+
1917
+ def _scope_covers(path: str, scope: Mapping[str, str]) -> bool:
1918
+ scope_parts = tuple(part.casefold() for part in PurePosixPath(scope["path"]).parts)
1919
+ candidate_parts = tuple(part.casefold() for part in PurePosixPath(path).parts)
1920
+ if candidate_parts[: len(scope_parts)] != scope_parts:
1921
+ return False
1922
+ if scope.get("scope") == "subtree":
1923
+ return True
1924
+ return len(candidate_parts) > len(scope_parts)
1925
+
1926
+
1927
+ def _previous_fingerprint(record: Mapping[str, Any]) -> str | None:
1928
+ """Recompute a baseline directory fingerprint with the current algorithm (G7).
1929
+
1930
+ Legacy states stored a fingerprint that included ``mtime_ns``. Recomputing
1931
+ from the stored snapshot keeps content-identical directories ``unchanged``
1932
+ across a scanner upgrade instead of flagging the whole tree as modified.
1933
+ """
1934
+ snapshot = record.get("snapshot")
1935
+ if isinstance(snapshot, Mapping) and isinstance(snapshot.get("files"), list):
1936
+ try:
1937
+ return _directory_fingerprint(snapshot)
1938
+ except Exception: # pragma: no cover - defensive fallback to stored value
1939
+ pass
1940
+ stored = record.get("fingerprint")
1941
+ return stored if isinstance(stored, str) else None
1942
+
1943
+
1944
+ def _classify(
1945
+ current: Sequence[Mapping[str, Any]],
1946
+ previous: Sequence[Mapping[str, Any]],
1947
+ unknown_scopes: Sequence[Mapping[str, str]],
1948
+ *,
1949
+ content_only_compare: bool = True,
1950
+ ) -> tuple[dict[str, list[str]], dict[str, dict[str, Any]]]:
1951
+ current_map = {
1952
+ str(record["path"]).casefold(): (str(record["path"]), record)
1953
+ for record in current
1954
+ }
1955
+ previous_map = {
1956
+ str(record["path"]).casefold(): (str(record["path"]), record)
1957
+ for record in previous
1958
+ }
1959
+ changes = {
1960
+ "new": [],
1961
+ "modified": [],
1962
+ "deleted": [],
1963
+ "unchanged": [],
1964
+ "unknown": [],
1965
+ }
1966
+ records_by_path: dict[str, dict[str, Any]] = {}
1967
+
1968
+ for folded, (path, record) in current_map.items():
1969
+ previous_entry = previous_map.get(folded)
1970
+ old_path, old = previous_entry if previous_entry is not None else (None, None)
1971
+ if old is None:
1972
+ change = "new"
1973
+ elif (
1974
+ old_path == path
1975
+ and (
1976
+ (_previous_fingerprint(old) if content_only_compare else old.get("fingerprint"))
1977
+ == record.get("fingerprint")
1978
+ )
1979
+ ):
1980
+ change = "unchanged"
1981
+ else:
1982
+ # Legacy path-only records and spelling-only path changes both require
1983
+ # processing; a complete matching v2 fingerprint is needed to skip.
1984
+ change = "modified"
1985
+ changes[change].append(path)
1986
+ changed_record = copy.deepcopy(dict(record))
1987
+ changed_record["change"] = change
1988
+ records_by_path[path] = changed_record
1989
+
1990
+ for folded, (path, _old) in previous_map.items():
1991
+ if folded in current_map:
1992
+ continue
1993
+ change = (
1994
+ "unknown"
1995
+ if any(_scope_covers(path, scope) for scope in unknown_scopes)
1996
+ else "deleted"
1997
+ )
1998
+ changes[change].append(path)
1999
+ records_by_path[path] = {"path": path, "change": change}
2000
+
2001
+ for paths in changes.values():
2002
+ paths.sort(key=lambda value: (value.casefold(), value))
2003
+ return changes, records_by_path
2004
+
2005
+
2006
+ def build_candidate_state(
2007
+ root: str | os.PathLike[str],
2008
+ previous: Mapping[str, Any] | None = None,
2009
+ *,
2010
+ incremental: bool = False,
2011
+ force_full: bool = False,
2012
+ baseline_precondition: BaselinePrecondition | None = None,
2013
+ ) -> dict[str, Any]:
2014
+ """Scan ``root`` and build a complete, root-bound schema-v2 candidate."""
2015
+
2016
+ mtime_cache = (
2017
+ None if (previous is None or force_full) else _extract_mtime_cache(previous)
2018
+ )
2019
+ scan = _scan_tree(root, mtime_cache=mtime_cache)
2020
+ resolved_root = Path(scan["root"])
2021
+ identity = _project_identity(resolved_root)
2022
+ normalized_previous: Mapping[str, Any] | None = None
2023
+ # A forced full scan is deliberately independent of baseline validity and
2024
+ # classification. It still emits a fresh root-bound candidate.
2025
+ if previous is not None and not force_full:
2026
+ if previous.get("schema_version") == SCAN_STATE_SCHEMA_VERSION:
2027
+ if (
2028
+ previous.get("root") == _PORTABLE_ROOT
2029
+ and "project_identity" in previous
2030
+ and "candidate_generation_id" in previous
2031
+ ):
2032
+ normalized_previous = validate_scan_state_v2(previous)
2033
+ else:
2034
+ normalized_previous = _migrate_legacy_v2_state(
2035
+ previous, require_committed=False
2036
+ )
2037
+ else:
2038
+ normalized_previous = _validate_legacy_state(previous)
2039
+ previous_identity = normalized_previous.get(
2040
+ "project_identity",
2041
+ normalized_previous.get("legacy_project_identity"),
2042
+ )
2043
+ if previous_identity is not None and not hmac.compare_digest(
2044
+ str(previous_identity), identity
2045
+ ):
2046
+ raise ScanStateError(
2047
+ "committed scan state belongs to a different project root "
2048
+ "(identity mismatch). This happens after cloning, moving, or "
2049
+ "renaming the project directory. Remedy: re-run with --full "
2050
+ "--apply to rebind the scan state to this root, or delete "
2051
+ "project_docs/_scan_state.json and re-run as first-run."
2052
+ )
2053
+
2054
+ comparison_previous = None if force_full else normalized_previous
2055
+ previous_records = _state_records(comparison_previous)
2056
+ # Legacy/migrated states are re-audited on purpose: their fingerprints were
2057
+ # produced by an older contract, so a content-only comparison would silently
2058
+ # mark them unchanged and skip the refresh the migration is meant to force.
2059
+ content_only_compare = (
2060
+ comparison_previous is not None
2061
+ and comparison_previous.get("schema_version") == SCAN_STATE_SCHEMA_VERSION
2062
+ )
2063
+ changes, classified = _classify(
2064
+ scan["directories"],
2065
+ previous_records,
2066
+ scan["unknown_scopes"],
2067
+ content_only_compare=content_only_compare,
2068
+ )
2069
+ mode = "incremental" if incremental and not force_full else "full"
2070
+ if mode == "incremental":
2071
+ selected_paths = set(changes["new"] + changes["modified"])
2072
+ else:
2073
+ selected_paths = {str(record["path"]) for record in scan["directories"]}
2074
+
2075
+ directories = [
2076
+ copy.deepcopy(classified[str(record["path"])])
2077
+ for record in scan["directories"]
2078
+ if str(record["path"]) in selected_paths
2079
+ ]
2080
+ deleted_directories = [
2081
+ copy.deepcopy(classified[path]) for path in changes["deleted"]
2082
+ ]
2083
+ unknown_directories = [
2084
+ copy.deepcopy(classified[path]) for path in changes["unknown"]
2085
+ ]
2086
+ snapshot = {
2087
+ "directories": copy.deepcopy(scan["directories"]),
2088
+ "skipped_directories": copy.deepcopy(scan["skipped_directories"]),
2089
+ "unknown_scopes": copy.deepcopy(scan["unknown_scopes"]),
2090
+ }
2091
+ change_counts = {name: len(paths) for name, paths in changes.items()}
2092
+ if comparison_previous is None:
2093
+ baseline_schema = None
2094
+ baseline_snapshot_fingerprint = None
2095
+ baseline_generation = None
2096
+ else:
2097
+ baseline_schema = int(comparison_previous.get("schema_version", 1))
2098
+ baseline_snapshot_fingerprint = (
2099
+ comparison_previous.get("snapshot_fingerprint")
2100
+ if baseline_schema == SCAN_STATE_SCHEMA_VERSION
2101
+ else None
2102
+ )
2103
+ baseline_generation = (
2104
+ comparison_previous.get("candidate_generation_id")
2105
+ if baseline_schema == SCAN_STATE_SCHEMA_VERSION
2106
+ else None
2107
+ )
2108
+
2109
+ bound_precondition: BaselinePrecondition | None = None
2110
+ if baseline_precondition is not None:
2111
+ bound_precondition = _validate_baseline_precondition(baseline_precondition)
2112
+ if not force_full:
2113
+ if bound_precondition.exists != (comparison_previous is not None):
2114
+ raise ScanStateError(
2115
+ "captured baseline existence disagrees with parsed baseline"
2116
+ )
2117
+ if bound_precondition.generation_id != baseline_generation:
2118
+ raise ScanStateError(
2119
+ "captured baseline generation disagrees with parsed baseline"
2120
+ )
2121
+
2122
+ candidate = {
2123
+ "schema_version": SCAN_STATE_SCHEMA_VERSION,
2124
+ "scanner_version": SCANNER_VERSION,
2125
+ "kind": SCAN_STATE_KIND,
2126
+ "state_role": "candidate",
2127
+ "producer": copy.deepcopy(SCAN_STATE_PRODUCER),
2128
+ "root": _PORTABLE_ROOT,
2129
+ "project_identity": identity,
2130
+ "scan_time": _now_iso(),
2131
+ "mode": mode,
2132
+ "baseline": {
2133
+ "available": comparison_previous is not None,
2134
+ "schema_version": baseline_schema,
2135
+ "snapshot_fingerprint": baseline_snapshot_fingerprint,
2136
+ "candidate_generation_id": baseline_generation,
2137
+ "force_full": bool(force_full),
2138
+ },
2139
+ "directories": directories,
2140
+ "deleted_directories": deleted_directories,
2141
+ "unknown_directories": unknown_directories,
2142
+ "changes": changes,
2143
+ "change_counts": change_counts,
2144
+ "total": len(directories),
2145
+ "full_total": len(scan["directories"]),
2146
+ "skipped_unchanged": change_counts["unchanged"] if mode == "incremental" else 0,
2147
+ "max_depth": max(
2148
+ (int(record["depth"]) for record in scan["directories"]),
2149
+ default=0,
2150
+ ),
2151
+ "boundary_count": sum(
2152
+ 1 for record in scan["directories"] if record["is_boundary"]
2153
+ ),
2154
+ "skipped_directory_count": len(scan["skipped_directories"]),
2155
+ "snapshot": snapshot,
2156
+ "snapshot_fingerprint": _fingerprint(snapshot),
2157
+ }
2158
+ if bound_precondition is not None:
2159
+ candidate["baseline_precondition"] = {
2160
+ "exists": bound_precondition.exists,
2161
+ "sha256": bound_precondition.sha256,
2162
+ "generation_id": bound_precondition.generation_id,
2163
+ }
2164
+ candidate["candidate_generation_id"] = _candidate_generation_id(candidate)
2165
+ return validate_scan_state_v2(candidate)
2166
+
2167
+
2168
+ def incremental_scan(
2169
+ root: str | os.PathLike[str],
2170
+ previous: Mapping[str, Any],
2171
+ ) -> dict[str, Any]:
2172
+ """Compatibility API for an incremental schema-v2 candidate scan."""
2173
+
2174
+ return build_candidate_state(root, previous, incremental=True)
2175
+
2176
+
2177
+ def _ensure_output_parent(path: Path) -> None:
2178
+ # ``Path('state.json').parent`` is ``Path('.')`` rather than the empty string
2179
+ # that caused the historical ``os.makedirs('')`` failure. Missing parents are
2180
+ # rejected instead of recursively created: creating first and validating later
2181
+ # can traverse a symlink/junction and leave directories outside the intended tree.
2182
+ lexical_parent = Path(os.path.abspath(path.parent))
2183
+ try:
2184
+ parent_state = lexical_parent.lstat()
2185
+ resolved_parent = lexical_parent.resolve(strict=True)
2186
+ except (OSError, RuntimeError) as exc:
2187
+ raise ScanStateError(
2188
+ f"cannot validate existing output parent directory {path.parent}: {exc}"
2189
+ ) from exc
2190
+ if (
2191
+ lexical_parent.is_symlink()
2192
+ or _is_reparse(parent_state)
2193
+ or not stat.S_ISDIR(parent_state.st_mode)
2194
+ or os.path.normcase(os.path.normpath(str(lexical_parent)))
2195
+ != os.path.normcase(os.path.normpath(str(resolved_parent)))
2196
+ ):
2197
+ raise ScanStateError(
2198
+ f"output parent must be a direct real directory: {path.parent}"
2199
+ )
2200
+
2201
+
2202
+ def _state_commit_lock_path(root: Path, destination: Path) -> Path:
2203
+ """Return one cross-project lock for a physical scan-state target path."""
2204
+
2205
+ lexical = Path(os.path.abspath(destination))
2206
+ normalized = os.path.normcase(os.path.normpath(str(lexical))).encode("utf-8")
2207
+ digest = hashlib.sha256(_STATE_LOCK_DOMAIN + normalized).hexdigest()
2208
+ lock_parent = contract.project_sync_lock_path(root).parent
2209
+ return lock_parent / f"scan-state-{digest}.lock"
2210
+
2211
+
2212
+ def write_candidate_state(
2213
+ candidate_path: str | os.PathLike[str],
2214
+ candidate: Mapping[str, Any],
2215
+ ) -> Path:
2216
+ """Atomically write a validated candidate without touching the baseline."""
2217
+
2218
+ data = validate_scan_state_v2(candidate)
2219
+ if data["state_role"] != "candidate":
2220
+ raise ScanStateError("write_candidate_state requires a candidate state")
2221
+ destination = Path(candidate_path)
2222
+ _ensure_output_parent(destination)
2223
+ _read_optional_regular_bytes(destination, "candidate state")
2224
+ return contract.atomic_write_json(destination, data)
2225
+
2226
+
2227
+ def _same_location(first: Path, second: Path) -> bool:
2228
+ return os.path.normcase(str(first.resolve(strict=False))) == os.path.normcase(
2229
+ str(second.resolve(strict=False))
2230
+ )
2231
+
2232
+
2233
+ def _validate_baseline_precondition(
2234
+ value: BaselinePrecondition,
2235
+ ) -> BaselinePrecondition:
2236
+ if not isinstance(value, BaselinePrecondition):
2237
+ raise ScanStateError("commit requires an exact BaselinePrecondition")
2238
+ if value.exists:
2239
+ if value.sha256 is None:
2240
+ raise ScanStateError("existing baseline precondition requires sha256")
2241
+ _require_sha256(value.sha256, "expected_baseline.sha256")
2242
+ if value.generation_id is not None:
2243
+ _require_sha256(
2244
+ value.generation_id,
2245
+ "expected_baseline.generation_id",
2246
+ )
2247
+ elif value.sha256 is not None or value.generation_id is not None:
2248
+ raise ScanStateError("absent baseline precondition cannot carry hashes")
2249
+ return value
2250
+
2251
+
2252
+ def _baseline_matches_bytes(
2253
+ expected: BaselinePrecondition,
2254
+ current: bytes | None,
2255
+ ) -> bool:
2256
+ if expected.exists != (current is not None):
2257
+ return False
2258
+ if current is None:
2259
+ return True
2260
+ return hmac.compare_digest(contract.sha256_bytes(current), expected.sha256 or "")
2261
+
2262
+
2263
+ def _baseline_precondition_mapping(
2264
+ value: BaselinePrecondition,
2265
+ ) -> dict[str, Any]:
2266
+ return {
2267
+ "exists": value.exists,
2268
+ "sha256": value.sha256,
2269
+ "generation_id": value.generation_id,
2270
+ }
2271
+
2272
+
2273
+ def _verify_current_baseline_identity(
2274
+ current: bytes | None,
2275
+ expected: BaselinePrecondition,
2276
+ root: Path,
2277
+ *,
2278
+ source: str,
2279
+ ) -> None:
2280
+ if current is None:
2281
+ return
2282
+ state = parse_previous_state_bytes(current, source=source)
2283
+ if state is None: # pragma: no cover - guarded by current is not None
2284
+ raise BaselineConflict("existing baseline parsed as absent")
2285
+ actual_generation = None
2286
+ if state.get("schema_version") == SCAN_STATE_SCHEMA_VERSION:
2287
+ value = state.get("candidate_generation_id")
2288
+ actual_generation = value if isinstance(value, str) else None
2289
+ if actual_generation != expected.generation_id:
2290
+ raise BaselineConflict(
2291
+ "committed scan-state generation changed before candidate promotion"
2292
+ )
2293
+ state_identity = state.get(
2294
+ "project_identity",
2295
+ state.get("legacy_project_identity"),
2296
+ )
2297
+ if state_identity is not None and not hmac.compare_digest(
2298
+ str(state_identity),
2299
+ _project_identity(root),
2300
+ ):
2301
+ raise BaselineConflict("committed scan state belongs to another project")
2302
+
2303
+
2304
+ def commit_candidate_state(
2305
+ candidate_path: str | os.PathLike[str],
2306
+ state_path: str | os.PathLike[str],
2307
+ *,
2308
+ project_root: str | os.PathLike[str],
2309
+ expected_baseline: BaselinePrecondition,
2310
+ expected_candidate_generation_id: str | None = None,
2311
+ ) -> dict[str, Any]:
2312
+ """Promote one candidate only if its project and baseline preimage still match."""
2313
+
2314
+ if expected_candidate_generation_id is None:
2315
+ raise ScanStateError("commit requires expected_candidate_generation_id")
2316
+ expected_generation = _require_sha256(
2317
+ expected_candidate_generation_id,
2318
+ "expected_candidate_generation_id",
2319
+ )
2320
+ baseline = _validate_baseline_precondition(expected_baseline)
2321
+ root = _resolved_root(project_root)
2322
+ candidate_file = Path(candidate_path)
2323
+ destination = Path(state_path)
2324
+ if _same_location(candidate_file, destination):
2325
+ raise ScanStateError("candidate and committed state paths must be different")
2326
+ candidate_bytes = _read_optional_regular_bytes(candidate_file, "candidate state")
2327
+ if candidate_bytes is None:
2328
+ raise ScanStateError(f"candidate state does not exist: {candidate_file}")
2329
+ try:
2330
+ candidate_text = candidate_bytes.decode("utf-8", errors="strict")
2331
+ except UnicodeDecodeError as exc:
2332
+ raise ScanStateError(f"candidate state is not strict UTF-8: {exc}") from exc
2333
+ value = contract.parse_json_strict(candidate_text, source=str(candidate_file))
2334
+ candidate = validate_scan_state_v2(_require_mapping(value, "candidate scan state"))
2335
+ if candidate["state_role"] != "candidate":
2336
+ raise ScanStateError("only a candidate state can be committed")
2337
+ if not hmac.compare_digest(
2338
+ candidate["candidate_generation_id"], expected_generation
2339
+ ):
2340
+ raise ScanStateError(
2341
+ "candidate generation does not match the accepted worklist"
2342
+ )
2343
+ if not hmac.compare_digest(candidate["project_identity"], _project_identity(root)):
2344
+ raise ScanStateError("candidate belongs to a different project root")
2345
+ if "baseline_precondition" not in candidate:
2346
+ raise ScanStateError(
2347
+ "candidate is not bound to an exact committed-state preimage"
2348
+ )
2349
+ if candidate["baseline_precondition"] != _baseline_precondition_mapping(baseline):
2350
+ raise BaselineConflict(
2351
+ "candidate baseline precondition does not match the accepted preimage"
2352
+ )
2353
+
2354
+ committed = copy.deepcopy(candidate)
2355
+ committed["state_role"] = "committed"
2356
+ committed["committed_at"] = _now_iso()
2357
+ # Committed consumers receive the complete snapshot. Validation reconstructs
2358
+ # the selected candidate worklist before checking candidate_generation_id.
2359
+ committed["directories"] = copy.deepcopy(candidate["snapshot"]["directories"])
2360
+ committed["total"] = committed["full_total"]
2361
+ committed["state_path"] = destination.name
2362
+ committed = validate_scan_state_v2(committed)
2363
+ expected_bytes = contract.stable_json_dumps(committed).encode("utf-8")
2364
+
2365
+ _ensure_output_parent(destination)
2366
+ target_lock = _state_commit_lock_path(root, destination)
2367
+ # The project lock serializes normal writers for one root. A separate lock
2368
+ # derived from the physical destination closes the cross-project case where
2369
+ # two roots intentionally or accidentally share an external state file.
2370
+ with contract.exclusive_file_lock(target_lock):
2371
+ with contract.project_sync_lock(root):
2372
+ _ensure_output_parent(destination)
2373
+ current_bytes = _read_optional_regular_bytes(destination, "scan state")
2374
+ if not _baseline_matches_bytes(baseline, current_bytes):
2375
+ raise BaselineConflict(
2376
+ "committed scan-state baseline changed before candidate promotion"
2377
+ )
2378
+ _verify_current_baseline_identity(
2379
+ current_bytes,
2380
+ baseline,
2381
+ root,
2382
+ source=str(destination),
2383
+ )
2384
+ durability_confirmed = False
2385
+ try:
2386
+ contract.atomic_write_json(destination, committed)
2387
+ durability_confirmed = True
2388
+ installed = _read_optional_regular_bytes(destination, "scan state")
2389
+ if installed != expected_bytes:
2390
+ raise ScanStateError("committed scan state failed exact readback")
2391
+ except BaseException as exc:
2392
+ try:
2393
+ observed = _read_optional_regular_bytes(destination, "scan state")
2394
+ except BaseException:
2395
+ disposition = CommitDisposition.UNKNOWN
2396
+ else:
2397
+ if observed == expected_bytes:
2398
+ disposition = CommitDisposition.INSTALLED
2399
+ elif observed == current_bytes and not durability_confirmed:
2400
+ disposition = CommitDisposition.NOT_INSTALLED
2401
+ else:
2402
+ # Once the atomic writer returned successfully, observing the
2403
+ # preimage again is an A→B→A supersession, not evidence that B
2404
+ # was never installed.
2405
+ disposition = CommitDisposition.UNKNOWN
2406
+ raise CandidateCommitError(
2407
+ f"candidate commit failed ({disposition.value}): {exc}",
2408
+ disposition=disposition,
2409
+ durability_confirmed=durability_confirmed,
2410
+ ) from exc
2411
+ return committed
2412
+
2413
+
2414
+ def commit_candidate(
2415
+ candidate_path: str | os.PathLike[str],
2416
+ state_path: str | os.PathLike[str],
2417
+ *,
2418
+ project_root: str | os.PathLike[str],
2419
+ expected_baseline: BaselinePrecondition,
2420
+ expected_candidate_generation_id: str | None = None,
2421
+ ) -> dict[str, Any]:
2422
+ """Short alias retained for callers using the approved commit terminology."""
2423
+
2424
+ return commit_candidate_state(
2425
+ candidate_path,
2426
+ state_path,
2427
+ project_root=project_root,
2428
+ expected_baseline=expected_baseline,
2429
+ expected_candidate_generation_id=expected_candidate_generation_id,
2430
+ )
2431
+
2432
+
2433
+ def save_state(
2434
+ state_path: str | os.PathLike[str],
2435
+ dirs: Sequence[Mapping[str, Any]],
2436
+ root: str | os.PathLike[str],
2437
+ ) -> None:
2438
+ """Legacy writer: create a candidate at ``state_path`` instead of committing.
2439
+
2440
+ ``dirs`` is retained in the signature for source compatibility. A fresh scan
2441
+ is used so the saved candidate always contains complete schema-v2 snapshots.
2442
+ """
2443
+
2444
+ del dirs
2445
+ write_candidate_state(state_path, build_candidate_state(root))
2446
+
2447
+
2448
+ def _candidate_path_for(state_path: Path) -> Path:
2449
+ suffix = state_path.suffix or ".json"
2450
+ stem = state_path.stem if state_path.suffix else state_path.name
2451
+ return state_path.with_name(f"{stem}.candidate{suffix}")
2452
+
2453
+
2454
+ def _looks_like_committed_state(path: Path) -> bool:
2455
+ if not path.is_file():
2456
+ return False
2457
+ try:
2458
+ value = contract.read_json_strict(path)
2459
+ except (OSError, contract.ProjectDocsContractError):
2460
+ # Existing unknown content is protected as a presumed baseline.
2461
+ return True
2462
+ return not (
2463
+ isinstance(value, Mapping)
2464
+ and value.get("schema_version") == SCAN_STATE_SCHEMA_VERSION
2465
+ and value.get("state_role") == "candidate"
2466
+ )
2467
+
2468
+
2469
+ def _cli_paths(
2470
+ args: argparse.Namespace,
2471
+ root: Path,
2472
+ *,
2473
+ commit_generated: bool,
2474
+ ) -> tuple[Path, Path]:
2475
+ default_state = root / DEFAULT_STATE_RELATIVE_PATH
2476
+ explicit_state = Path(args.state) if args.state else None
2477
+ explicit_candidate = Path(args.candidate) if args.candidate else None
2478
+ legacy_output = Path(args.output) if args.output else None
2479
+
2480
+ if explicit_state is not None:
2481
+ state_path = explicit_state
2482
+ candidate_path = (
2483
+ explicit_candidate or legacy_output or _candidate_path_for(state_path)
2484
+ )
2485
+ elif explicit_candidate is not None:
2486
+ candidate_path = explicit_candidate
2487
+ state_path = legacy_output or default_state
2488
+ elif legacy_output is not None:
2489
+ # Protect an existing legacy/committed --output file. For a new path,
2490
+ # --output serves as the candidate destination, which is the least
2491
+ # surprising behavior for new callers and fixes bare-filename output.
2492
+ if commit_generated or _looks_like_committed_state(legacy_output):
2493
+ state_path = legacy_output
2494
+ candidate_path = _candidate_path_for(state_path)
2495
+ else:
2496
+ state_path = default_state
2497
+ candidate_path = legacy_output
2498
+ else:
2499
+ state_path = default_state
2500
+ candidate_path = _candidate_path_for(state_path)
2501
+
2502
+ if _same_location(candidate_path, state_path):
2503
+ raise ScanStateError("candidate and committed state paths must be different")
2504
+ return state_path, candidate_path
2505
+
2506
+
2507
+ def _configure_stdout_utf8() -> None:
2508
+ reconfigure = getattr(sys.stdout, "reconfigure", None)
2509
+ if callable(reconfigure):
2510
+ reconfigure(encoding="utf-8")
2511
+
2512
+
2513
+ def _build_parser() -> argparse.ArgumentParser:
2514
+ parser = argparse.ArgumentParser(
2515
+ description="Scan project directories and produce a schema-v2 candidate state"
2516
+ )
2517
+ parser.add_argument("root", nargs="?", help="Project root directory")
2518
+ parser.add_argument(
2519
+ "--output",
2520
+ "-o",
2521
+ help=(
2522
+ "Candidate output for new callers; an existing legacy state is "
2523
+ "protected and gets a sibling .candidate.json"
2524
+ ),
2525
+ )
2526
+ parser.add_argument(
2527
+ "--state",
2528
+ "--state-file",
2529
+ dest="state",
2530
+ help="Committed baseline path (never replaced unless --commit is explicit)",
2531
+ )
2532
+ parser.add_argument(
2533
+ "--candidate",
2534
+ "--candidate-output",
2535
+ dest="candidate",
2536
+ help="Explicit candidate state path",
2537
+ )
2538
+ parser.add_argument(
2539
+ "--incremental",
2540
+ "-i",
2541
+ action="store_true",
2542
+ help="Return only new/modified work items while snapshotting the full tree",
2543
+ )
2544
+ parser.add_argument(
2545
+ "--full",
2546
+ "-f",
2547
+ action="store_true",
2548
+ help="Force a full scan and ignore the committed baseline",
2549
+ )
2550
+ parser.add_argument(
2551
+ "--json",
2552
+ action="store_true",
2553
+ help="Emit strict JSON only (JSON remains the legacy default as well)",
2554
+ )
2555
+ parser.add_argument(
2556
+ "--commit",
2557
+ nargs="?",
2558
+ const=_COMMIT_GENERATED,
2559
+ metavar="CANDIDATE",
2560
+ help=(
2561
+ "Atomically commit the generated candidate, or commit the supplied "
2562
+ "candidate path without scanning"
2563
+ ),
2564
+ )
2565
+ parser.add_argument(
2566
+ "--commit-state",
2567
+ action="store_true",
2568
+ help="Alias for --commit with the generated candidate",
2569
+ )
2570
+ parser.add_argument(
2571
+ "--commit-candidate",
2572
+ metavar="CANDIDATE",
2573
+ help="Commit an existing candidate without scanning",
2574
+ )
2575
+ parser.add_argument(
2576
+ "--expected-candidate-generation-id",
2577
+ metavar="SHA256",
2578
+ help=(
2579
+ "Required when committing an existing candidate; binds publication "
2580
+ "to the candidate generation already processed by the caller"
2581
+ ),
2582
+ )
2583
+ baseline_group = parser.add_mutually_exclusive_group()
2584
+ baseline_group.add_argument(
2585
+ "--expected-baseline-sha256",
2586
+ metavar="SHA256",
2587
+ help=(
2588
+ "Required for an existing baseline when committing an existing "
2589
+ "candidate; this is the preimage hash captured before processing"
2590
+ ),
2591
+ )
2592
+ baseline_group.add_argument(
2593
+ "--expected-baseline-absent",
2594
+ action="store_true",
2595
+ help=(
2596
+ "Declare that no committed baseline existed when the existing "
2597
+ "candidate was generated"
2598
+ ),
2599
+ )
2600
+ parser.add_argument(
2601
+ "--expected-baseline-generation-id",
2602
+ metavar="SHA256",
2603
+ help="Generation ID captured with --expected-baseline-sha256",
2604
+ )
2605
+ return parser
2606
+
2607
+
2608
+ def _emit_json(value: Mapping[str, Any]) -> None:
2609
+ sys.stdout.write(contract.stable_json_dumps(dict(value)))
2610
+
2611
+
2612
+ def _expected_baseline_from_cli(args: argparse.Namespace) -> BaselinePrecondition:
2613
+ if args.expected_baseline_absent:
2614
+ if args.expected_baseline_generation_id is not None:
2615
+ raise ScanStateError(
2616
+ "--expected-baseline-generation-id cannot accompany "
2617
+ "--expected-baseline-absent"
2618
+ )
2619
+ return BaselinePrecondition(False, None, None)
2620
+ if args.expected_baseline_sha256 is None:
2621
+ raise ScanStateError(
2622
+ "committing an existing candidate requires either "
2623
+ "--expected-baseline-sha256 or --expected-baseline-absent"
2624
+ )
2625
+ sha256 = _require_sha256(
2626
+ args.expected_baseline_sha256,
2627
+ "expected_baseline_sha256",
2628
+ )
2629
+ generation = args.expected_baseline_generation_id
2630
+ if generation is not None:
2631
+ generation = _require_sha256(
2632
+ generation,
2633
+ "expected_baseline_generation_id",
2634
+ )
2635
+ return BaselinePrecondition(True, sha256, generation)
2636
+
2637
+
2638
+ def main(argv: Sequence[str] | None = None) -> int:
2639
+ _configure_stdout_utf8()
2640
+ parser = _build_parser()
2641
+ args = parser.parse_args(argv)
2642
+
2643
+ try:
2644
+ commit_existing = args.commit_candidate
2645
+ if args.commit not in (None, _COMMIT_GENERATED):
2646
+ if commit_existing is not None:
2647
+ raise ScanStateError(
2648
+ "--commit CANDIDATE and --commit-candidate are mutually exclusive"
2649
+ )
2650
+ commit_existing = args.commit
2651
+
2652
+ if commit_existing is not None:
2653
+ if not args.root:
2654
+ raise ScanStateError(
2655
+ "committing an existing candidate requires the project root"
2656
+ )
2657
+ state_argument = args.state or args.output
2658
+ if not state_argument:
2659
+ raise ScanStateError(
2660
+ "committing an existing candidate requires --state (or legacy --output)"
2661
+ )
2662
+ committed = commit_candidate_state(
2663
+ commit_existing,
2664
+ state_argument,
2665
+ project_root=args.root,
2666
+ expected_baseline=_expected_baseline_from_cli(args),
2667
+ expected_candidate_generation_id=args.expected_candidate_generation_id,
2668
+ )
2669
+ _emit_json(committed)
2670
+ return 0
2671
+
2672
+ if args.expected_baseline_sha256 is not None or args.expected_baseline_absent:
2673
+ raise ScanStateError(
2674
+ "expected-baseline options apply only when committing an existing candidate"
2675
+ )
2676
+ if args.expected_baseline_generation_id is not None:
2677
+ raise ScanStateError(
2678
+ "--expected-baseline-generation-id requires an existing-candidate commit"
2679
+ )
2680
+ if not args.root:
2681
+ parser.error("the following arguments are required: root")
2682
+ root = _resolved_root(args.root)
2683
+ commit_generated = args.commit == _COMMIT_GENERATED or args.commit_state
2684
+ state_path, candidate_path = _cli_paths(
2685
+ args,
2686
+ root,
2687
+ commit_generated=commit_generated,
2688
+ )
2689
+
2690
+ incremental = args.incremental and not args.full
2691
+ captured_previous, baseline_precondition, _ = (
2692
+ load_previous_state_with_precondition(state_path)
2693
+ )
2694
+ previous = None if args.full else captured_previous
2695
+ candidate = build_candidate_state(
2696
+ root,
2697
+ previous,
2698
+ incremental=incremental,
2699
+ force_full=args.full,
2700
+ baseline_precondition=baseline_precondition,
2701
+ )
2702
+ write_candidate_state(candidate_path, candidate)
2703
+
2704
+ output = copy.deepcopy(candidate)
2705
+ output["commit"] = {"performed": False}
2706
+ if commit_generated:
2707
+ expected_generation = (
2708
+ args.expected_candidate_generation_id
2709
+ or candidate["candidate_generation_id"]
2710
+ )
2711
+ committed = commit_candidate_state(
2712
+ candidate_path,
2713
+ state_path,
2714
+ project_root=root,
2715
+ expected_baseline=baseline_precondition,
2716
+ expected_candidate_generation_id=expected_generation,
2717
+ )
2718
+ output["commit"] = {
2719
+ "performed": True,
2720
+ "state_path": committed["state_path"],
2721
+ }
2722
+ _emit_json(output)
2723
+ return 0
2724
+ except (
2725
+ OSError,
2726
+ RuntimeError,
2727
+ ValueError,
2728
+ contract.ProjectDocsContractError,
2729
+ ) as exc:
2730
+ print(f"ERROR: {exc}", file=sys.stderr)
2731
+ return 1
2732
+
2733
+
2734
+ if __name__ == "__main__":
2735
+ raise SystemExit(main())