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

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