@walvka-code/proj-doc-builder 4.0.0 → 4.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +290 -272
  2. package/README.zh-CN.md +258 -240
  3. package/package.json +6 -2
  4. package/skills/proj-doc-builder/SKILL.md +97 -35
  5. package/skills/proj-doc-builder/references/audit_script.md +103 -96
  6. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  7. package/skills/proj-doc-builder/references/checklist.md +20 -10
  8. package/skills/proj-doc-builder/references/exclusions.md +1 -1
  9. package/skills/proj-doc-builder/references/linking.md +83 -83
  10. package/skills/proj-doc-builder/references/templates.md +57 -17
  11. package/skills/proj-doc-builder/tests/claims.json +76 -0
  12. package/skills/proj-doc-builder/tests/conftest.py +17 -5
  13. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  14. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  15. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -248
  16. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +32 -1
  17. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1 -1
  18. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  19. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -2169
  20. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  21. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  22. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  23. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  24. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  25. package/skills/proj-doc-builder/tests/test_validate_doc.py +172 -15
  26. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  27. package/skills/proj-doc-builder/tools/{claude_doc_index.py → core/claude_doc_index.py} +504 -298
  28. package/skills/proj-doc-builder/tools/{compute_link.py → core/compute_link.py} +239 -233
  29. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  30. package/skills/proj-doc-builder/tools/{project_docs_contract.py → core/project_docs_contract.py} +460 -53
  31. package/skills/proj-doc-builder/tools/phase4/__init__.py +31 -6
  32. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +11 -4
  33. package/skills/proj-doc-builder/tools/phase4/engine.py +17 -2
  34. package/skills/proj-doc-builder/tools/phase4/journal.py +15 -8
  35. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +12 -5
  36. package/skills/proj-doc-builder/tools/phase4_exit.py +153 -47
  37. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  38. package/skills/proj-doc-builder/tools/{sync_project_docs.py → pipeline/sync_project_docs.py} +5531 -3639
  39. package/skills/proj-doc-builder/tools/{load_docs.py → reader/load_docs.py} +654 -380
  40. package/skills/proj-doc-builder/tools/{link_check.py → scan/link_check.py} +203 -152
  41. package/skills/proj-doc-builder/tools/{normalize_markers.py → scan/normalize_markers.py} +211 -205
  42. package/skills/proj-doc-builder/tools/{scan_dirs.py → scan/scan_dirs.py} +2735 -2405
  43. package/skills/proj-doc-builder/tools/{validate_doc.py → validate/validate_doc.py} +1911 -1299
  44. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  45. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  46. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  47. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  48. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  49. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  50. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  51. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  52. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  53. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  54. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  55. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  56. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  57. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  58. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  59. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  60. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  61. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
@@ -11,12 +11,14 @@ from __future__ import annotations
11
11
  import concurrent.futures
12
12
  import copy
13
13
  import errno
14
+ import functools
14
15
  import hashlib
15
16
  import json
16
17
  import math
17
18
  import os
18
19
  import posixpath
19
20
  import re
21
+ import shutil
20
22
  import stat
21
23
  import sys
22
24
  import tempfile
@@ -31,8 +33,9 @@ from typing import Any, Iterable, Iterator, Mapping, Sequence
31
33
  from urllib.parse import unquote
32
34
 
33
35
  MANIFEST_SCHEMA_VERSION = 2
36
+ DOC_CONTRACT_VERSION = "4.2"
34
37
  DEFAULT_PRODUCER_NAME = "proj-doc-builder"
35
- DEFAULT_PRODUCER_VERSION = "4.0"
38
+ DEFAULT_PRODUCER_VERSION = "4.5.2"
36
39
  MANIFEST_FILENAME = "_manifest.json"
37
40
  QUARANTINE_DIRNAME = ".quarantine"
38
41
  COORDINATOR_JOURNAL_SUFFIX = ".publish-transaction.json"
@@ -236,6 +239,16 @@ class MarkdownLinkResult:
236
239
  return self.disposition is LinkDisposition.LOCAL_DOCUMENT
237
240
 
238
241
 
242
+ def _is_stat_link_or_reparse(info: os.stat_result) -> bool:
243
+ """Return whether an ``lstat`` result represents a symlink or reparse point."""
244
+
245
+ if stat.S_ISLNK(info.st_mode):
246
+ return True
247
+ attributes = getattr(info, "st_file_attributes", 0)
248
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
249
+ return bool(attributes & reparse_flag)
250
+
251
+
239
252
  def _is_link_or_reparse_path(path: Path) -> bool:
240
253
  """Return whether an existing path is a link, junction, or reparse point."""
241
254
 
@@ -243,14 +256,7 @@ def _is_link_or_reparse_path(path: Path) -> bool:
243
256
  info = path.lstat()
244
257
  except FileNotFoundError:
245
258
  return False
246
- attributes = getattr(info, "st_file_attributes", 0)
247
- reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
248
- is_junction = getattr(path, "is_junction", None)
249
- try:
250
- junction = bool(callable(is_junction) and is_junction())
251
- except OSError as exc:
252
- raise LockError(f"cannot inspect lock path {path}: {exc}") from exc
253
- return stat.S_ISLNK(info.st_mode) or junction or bool(attributes & reparse_flag)
259
+ return _is_stat_link_or_reparse(info)
254
260
 
255
261
 
256
262
  def _same_file_identity(first: os.stat_result, second: os.stat_result) -> bool:
@@ -267,6 +273,68 @@ def _same_file_identity(first: os.stat_result, second: os.stat_result) -> bool:
267
273
  )
268
274
 
269
275
 
276
+ def _lock_fd(fd: int) -> None:
277
+ """Non-blocking cross-process exclusive lock on a pre-opened file descriptor."""
278
+
279
+ os.lseek(fd, 0, os.SEEK_SET)
280
+ if os.name == "nt":
281
+ import msvcrt
282
+
283
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
284
+ elif os.name == "posix":
285
+ import fcntl
286
+
287
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
288
+ else: # pragma: no cover - supported deployment platforms are nt/posix
289
+ raise LockError(f"unsupported lock platform: {os.name}")
290
+
291
+
292
+ def _unlock_fd(fd: int) -> None:
293
+ """Release the cross-process exclusive lock acquired by :func:`_lock_fd`."""
294
+
295
+ os.lseek(fd, 0, os.SEEK_SET)
296
+ if os.name == "nt":
297
+ import msvcrt
298
+
299
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
300
+ elif os.name == "posix":
301
+ import fcntl
302
+
303
+ fcntl.flock(fd, fcntl.LOCK_UN)
304
+
305
+
306
+ def lock_file_is_free(path: Path) -> bool:
307
+ """Return whether ``path`` is an unheld advisory lock that a process may delete.
308
+
309
+ Used by lock-domain retention to distinguish an orphaned lock file (a leftover
310
+ from a crashed or finished run) from one currently held by a live process. A free
311
+ file is safe to delete: the next writer re-creates it with ``O_CREAT | O_EXCL``.
312
+ """
313
+
314
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
315
+ try:
316
+ fd = os.open(path, os.O_RDWR | nofollow)
317
+ except OSError:
318
+ return False
319
+ try:
320
+ _lock_fd(fd)
321
+ except (OSError, LockError):
322
+ return False
323
+ else:
324
+ try:
325
+ _unlock_fd(fd)
326
+ except OSError:
327
+ pass
328
+ finally:
329
+ # The handle must be closed before the caller can unlink the file on Windows,
330
+ # and closing also releases the advisory lock taken above.
331
+ try:
332
+ os.close(fd)
333
+ except OSError:
334
+ pass
335
+ return True
336
+
337
+
270
338
  class ExclusiveFileLock:
271
339
  """Small cross-process exclusive lock using verified regular files."""
272
340
 
@@ -287,28 +355,10 @@ class ExclusiveFileLock:
287
355
  self._fd: int | None = None
288
356
 
289
357
  def _try_lock(self, fd: int) -> None:
290
- os.lseek(fd, 0, os.SEEK_SET)
291
- if os.name == "nt":
292
- import msvcrt
293
-
294
- msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
295
- elif os.name == "posix":
296
- import fcntl
297
-
298
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
299
- else: # pragma: no cover - supported deployment platforms are nt/posix
300
- raise LockError(f"unsupported lock platform: {os.name}")
358
+ _lock_fd(fd)
301
359
 
302
360
  def _unlock(self, fd: int) -> None:
303
- os.lseek(fd, 0, os.SEEK_SET)
304
- if os.name == "nt":
305
- import msvcrt
306
-
307
- msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
308
- elif os.name == "posix":
309
- import fcntl
310
-
311
- fcntl.flock(fd, fcntl.LOCK_UN)
361
+ _unlock_fd(fd)
312
362
 
313
363
  def acquire(self) -> "ExclusiveFileLock":
314
364
  """Acquire the lock, waiting until timeout when another process owns it."""
@@ -582,6 +632,159 @@ def coordinator_pending_publish_status(
582
632
  return {"required": True, "entries": blocking}
583
633
 
584
634
 
635
+ # --------------------------------------------------------------------------- lock-domain retention
636
+
637
+ LOCK_DOMAIN_DIRNAME = "proj-doc-builder-locks"
638
+ LOCK_DOMAIN_STALE_LOCK_HOURS = 1.0 # unheld .lock files older than this are leftovers
639
+ LOCK_DOMAIN_MAX_AGE_HOURS = 168.0 # journals / artifact dirs survive a week (--recover window)
640
+ LOCK_DOMAIN_HISTORY_KEEP = 20
641
+
642
+
643
+ def lock_domain_root() -> Path:
644
+ """Return the shared lock directory used by every proj-doc-builder writer."""
645
+
646
+ return Path(tempfile.gettempdir()) / LOCK_DOMAIN_DIRNAME
647
+
648
+
649
+ def prune_lock_domain(
650
+ project_root: PathLike,
651
+ *,
652
+ stale_lock_hours: float | None = None,
653
+ max_age_hours: float | None = None,
654
+ history_keep: int | None = None,
655
+ lock_parent: Path | None = None,
656
+ dry_run: bool = False,
657
+ ) -> dict[str, Any]:
658
+ """Drop stale entries in the shared lock domain.
659
+
660
+ The lock domain lives outside the project tree so that locking does not pollute
661
+ ``git status`` / ``svn status``. Its entries are keyed by digests of *every*
662
+ project root and staging target ever seen on the machine, so they accumulate for
663
+ the lifetime of the machine: thousands of entries made directory listings slow and
664
+ wasted temp space. Retention rules:
665
+
666
+ * ``<digest>.publish-history-*.json`` — keep the newest ``history_keep`` per digest.
667
+ * ``*.lock`` — removed once *unheld* and older than ``stale_lock_hours``. An unheld
668
+ lock file is a leftover: writers re-create it with ``O_CREAT | O_EXCL``. Held
669
+ locks are never touched.
670
+ * ``<digest>.publish-transaction.json`` and
671
+ ``<digest>.publish-transaction.publish-artifacts-*`` — removed once older than
672
+ ``max_age_hours`` unless they belong to the *current* project (a pending journal
673
+ must be resolved with ``--recover`` instead of being deleted silently).
674
+ * anything else is left alone.
675
+
676
+ Deletion failures (a lock taken between the probe and the unlink, permission
677
+ errors) are recorded in ``skipped`` and the run continues.
678
+ """
679
+
680
+ keep_history = LOCK_DOMAIN_HISTORY_KEEP if history_keep is None else max(1, int(history_keep))
681
+ stale_hours = (
682
+ LOCK_DOMAIN_STALE_LOCK_HOURS if stale_lock_hours is None else float(stale_lock_hours)
683
+ )
684
+ max_age = LOCK_DOMAIN_MAX_AGE_HOURS if max_age_hours is None else float(max_age_hours)
685
+ parent = Path(lock_parent) if lock_parent is not None else lock_domain_root()
686
+ summary: dict[str, Any] = {
687
+ "lock_domain": str(parent),
688
+ "scanned": 0,
689
+ "kept": 0,
690
+ "in_use": 0,
691
+ "removed": {},
692
+ "protected": [],
693
+ "skipped": [],
694
+ "history_keep": keep_history,
695
+ "stale_lock_hours": stale_hours,
696
+ "max_age_hours": max_age,
697
+ }
698
+ if not parent.is_dir() or _is_link_or_reparse_path(parent):
699
+ return summary
700
+ current = project_sync_lock_path(project_root)
701
+ current_digest = current.stem
702
+ protected = {current.name}
703
+ protected.update(path.name for path in coordinator_publish_journal_paths(project_root).values())
704
+ now = time.time()
705
+ lock_cutoff = now - stale_hours * 3600.0
706
+ cutoff = now - max_age * 3600.0
707
+ histories: dict[str, list[tuple[float, Path]]] = {}
708
+ removable: list[tuple[str, Path, bool]] = []
709
+ try:
710
+ entries = sorted(parent.iterdir())
711
+ except OSError as exc:
712
+ summary["skipped"].append(f"{parent}: {exc}")
713
+ return summary
714
+ for entry in entries:
715
+ name = entry.name
716
+ if name in protected:
717
+ summary["protected"].append(name)
718
+ summary["kept"] += 1
719
+ continue
720
+ if _is_link_or_reparse_path(entry):
721
+ summary["kept"] += 1
722
+ continue
723
+ summary["scanned"] += 1
724
+ digest = name.split(".", 1)[0]
725
+ if COORDINATOR_HISTORY_MARKER in name:
726
+ try:
727
+ mtime = entry.lstat().st_mtime
728
+ except OSError:
729
+ summary["kept"] += 1
730
+ continue
731
+ histories.setdefault(digest, []).append((mtime, entry))
732
+ continue
733
+ if digest == current_digest:
734
+ summary["kept"] += 1
735
+ continue
736
+ try:
737
+ mtime = entry.lstat().st_mtime
738
+ except OSError:
739
+ summary["kept"] += 1
740
+ continue
741
+ if name.endswith(".lock"):
742
+ # Probe the advisory lock first: a *held* lock is authoritative evidence of a
743
+ # live process, while a free one is a leftover whatever its age. Only free
744
+ # locks are candidates, and only once they are older than the stale window.
745
+ if not lock_file_is_free(entry):
746
+ summary["in_use"] += 1
747
+ summary["kept"] += 1
748
+ continue
749
+ if mtime >= lock_cutoff:
750
+ summary["kept"] += 1
751
+ continue
752
+ removable.append(("lock", entry, False))
753
+ continue
754
+ if mtime >= cutoff:
755
+ summary["kept"] += 1
756
+ continue
757
+ if COORDINATOR_ARTIFACT_ROOT_MARKER in name:
758
+ removable.append(("artifact", entry, entry.is_dir()))
759
+ elif name.endswith(COORDINATOR_JOURNAL_SUFFIX):
760
+ removable.append(("journal", entry, False))
761
+ else:
762
+ summary["kept"] += 1
763
+ for digest, items in histories.items():
764
+ items.sort(key=lambda pair: pair[0], reverse=True)
765
+ for _, path in items[:keep_history]:
766
+ summary["kept"] += 1
767
+ for _, path in items[keep_history:]:
768
+ removable.append(("history", path, False))
769
+ removed: dict[str, int] = {}
770
+ for kind, path, is_dir in removable:
771
+ if dry_run:
772
+ removed[kind] = removed.get(kind, 0) + 1
773
+ continue
774
+ try:
775
+ if is_dir:
776
+ shutil.rmtree(path)
777
+ else:
778
+ path.unlink()
779
+ except OSError as exc:
780
+ summary["skipped"].append(f"{path.name}: {exc}")
781
+ continue
782
+ removed[kind] = removed.get(kind, 0) + 1
783
+ summary["removed"] = removed
784
+ summary["dry_run"] = dry_run
785
+ return summary
786
+
787
+
585
788
  @contextmanager
586
789
  def project_sync_lock(
587
790
  project_root: PathLike,
@@ -650,6 +853,7 @@ def _parse_json_float(value: str) -> float:
650
853
  return parsed
651
854
 
652
855
 
856
+ @functools.lru_cache(maxsize=8192)
653
857
  def _contains_surrogate(value: str) -> bool:
654
858
  return any(0xD800 <= ord(character) <= 0xDFFF for character in value)
655
859
 
@@ -791,6 +995,24 @@ def _atomic_write_bytes(path: PathLike, payload: bytes) -> Path:
791
995
  file_obj.write(payload)
792
996
  file_obj.flush()
793
997
  os.fsync(file_obj.fileno())
998
+ # Preserve the destination's permission bits when replacing an existing
999
+ # file so that a shared repository keeps 0644 docs readable by other
1000
+ # users; for brand-new files, apply umask-correct 0666 (mkstemp alone
1001
+ # yields 0600, which silently makes docs owner-only on POSIX).
1002
+ target_mode: int | None = None
1003
+ try:
1004
+ target_mode = os.stat(destination).st_mode & 0o777
1005
+ except FileNotFoundError:
1006
+ current_umask = os.umask(0)
1007
+ os.umask(current_umask)
1008
+ target_mode = 0o666 & ~current_umask
1009
+ except OSError:
1010
+ target_mode = None
1011
+ if target_mode is not None:
1012
+ try:
1013
+ os.chmod(temporary, target_mode)
1014
+ except OSError:
1015
+ pass
794
1016
  os.replace(temporary, destination)
795
1017
  replaced = True
796
1018
  _fsync_parent_directory(parent)
@@ -823,6 +1045,7 @@ def atomic_write_json(path: PathLike, value: Any) -> Path:
823
1045
  return atomic_write_utf8(path, stable_json_dumps(value))
824
1046
 
825
1047
 
1048
+ @functools.lru_cache(maxsize=8192)
826
1049
  def _validate_portable_path_segment(segment: str, path: str) -> None:
827
1050
  if any(
828
1051
  ord(character) < 32 or character in _WINDOWS_FORBIDDEN_CHARS
@@ -842,6 +1065,7 @@ def _validate_portable_path_segment(segment: str, path: str) -> None:
842
1065
  )
843
1066
 
844
1067
 
1068
+ @functools.lru_cache(maxsize=16384)
845
1069
  def validate_manifest_relative_path(
846
1070
  relative_path: str | PurePosixPath,
847
1071
  ) -> PurePosixPath:
@@ -1010,13 +1234,13 @@ def _is_reparse_point(path: Path) -> bool:
1010
1234
  return bool(attributes & marker)
1011
1235
 
1012
1236
 
1013
- def _is_directory_link_or_junction(path: Path) -> bool:
1014
- junction_check = getattr(path, "is_junction", None)
1015
- return bool(
1016
- path.is_symlink()
1017
- or _is_reparse_point(path)
1018
- or (junction_check is not None and junction_check())
1019
- )
1237
+ def _is_directory_link_or_junction(
1238
+ path: Path,
1239
+ *,
1240
+ stat_result: os.stat_result | None = None,
1241
+ ) -> bool:
1242
+ info = stat_result if stat_result is not None else path.lstat()
1243
+ return _is_stat_link_or_reparse(info)
1020
1244
 
1021
1245
 
1022
1246
  def _read_checked_document_fd(root: Path, pure_path: PurePosixPath) -> bytes:
@@ -1025,7 +1249,7 @@ def _read_checked_document_fd(root: Path, pure_path: PurePosixPath) -> bytes:
1025
1249
  for index, segment in enumerate(pure_path.parts):
1026
1250
  current = current / segment
1027
1251
  current_stat = current.lstat()
1028
- if current.is_symlink() or _is_reparse_point(current):
1252
+ if _is_stat_link_or_reparse(current_stat):
1029
1253
  raise PathValidationError(
1030
1254
  f"document path contains a symlink or reparse point: {pure_path.as_posix()}"
1031
1255
  )
@@ -1053,7 +1277,7 @@ def _read_checked_document_fd(root: Path, pure_path: PurePosixPath) -> bytes:
1053
1277
  raise PathValidationError(
1054
1278
  f"document changed while it was being opened: {pure_path.as_posix()}"
1055
1279
  )
1056
- if _is_reparse_point(lexical) or not stat.S_ISREG(opened.st_mode):
1280
+ if _is_stat_link_or_reparse(after) or not stat.S_ISREG(opened.st_mode):
1057
1281
  raise PathValidationError(
1058
1282
  f"document is not a stable regular file: {pure_path.as_posix()}"
1059
1283
  )
@@ -1721,9 +1945,7 @@ def discover_active_markdown_paths(docs_root: PathLike) -> list[str]:
1721
1945
  def visit(directory: Path) -> None:
1722
1946
  try:
1723
1947
  before = directory.lstat()
1724
- if _is_directory_link_or_junction(directory) or not stat.S_ISDIR(
1725
- before.st_mode
1726
- ):
1948
+ if _is_stat_link_or_reparse(before) or not stat.S_ISDIR(before.st_mode):
1727
1949
  raise PathValidationError(
1728
1950
  f"active document directory is indirect or invalid: {directory}"
1729
1951
  )
@@ -1740,7 +1962,7 @@ def discover_active_markdown_paths(docs_root: PathLike) -> list[str]:
1740
1962
  f"cannot securely enumerate active documents: {directory}"
1741
1963
  ) from exc
1742
1964
 
1743
- if _is_directory_link_or_junction(directory) or not _same_file_identity(
1965
+ if _is_stat_link_or_reparse(after) or not _same_file_identity(
1744
1966
  before,
1745
1967
  after,
1746
1968
  ):
@@ -1751,8 +1973,8 @@ def discover_active_markdown_paths(docs_root: PathLike) -> list[str]:
1751
1973
  for item in entries:
1752
1974
  path = Path(item.path)
1753
1975
  try:
1754
- item_stat = path.lstat()
1755
- indirect = _is_directory_link_or_junction(path)
1976
+ item_stat = item.stat(follow_symlinks=False)
1977
+ indirect = _is_stat_link_or_reparse(item_stat)
1756
1978
  except OSError as exc:
1757
1979
  raise PathValidationError(
1758
1980
  f"active document path changed while scanning: {path}"
@@ -1821,6 +2043,9 @@ def _document_record(
1821
2043
  relative_path: str,
1822
2044
  *,
1823
2045
  fallback_synced_at: str,
2046
+ doc_contract_version: str | None = DOC_CONTRACT_VERSION,
2047
+ generator: str | None = None,
2048
+ previous_entry: Mapping[str, Any] | None = None,
1824
2049
  ) -> dict[str, Any]:
1825
2050
  safe_path, raw, content = _read_project_document_bytes(root, relative_path)
1826
2051
  metadata = parse_document_metadata(
@@ -1832,15 +2057,32 @@ def _document_record(
1832
2057
  metadata.synced_at,
1833
2058
  f"file {relative_path!r} synced_at",
1834
2059
  )
1835
- return {
2060
+ file_sha256 = sha256_bytes(raw)
2061
+ record: dict[str, Any] = {
1836
2062
  "path": relative_path,
1837
2063
  "depth": safe_path.depth,
1838
2064
  "title": metadata.title,
1839
2065
  "status": metadata.status,
1840
2066
  "bytes": len(raw),
1841
- "sha256": sha256_bytes(raw),
2067
+ "sha256": file_sha256,
1842
2068
  "synced_at": synced_at,
1843
2069
  }
2070
+ if (
2071
+ isinstance(previous_entry, Mapping)
2072
+ and previous_entry.get("sha256") == file_sha256
2073
+ ):
2074
+ prev_ver = previous_entry.get("doc_contract_version")
2075
+ if isinstance(prev_ver, str) and prev_ver:
2076
+ record["doc_contract_version"] = prev_ver
2077
+ prev_gen = previous_entry.get("generator")
2078
+ if isinstance(prev_gen, str) and prev_gen:
2079
+ record["generator"] = prev_gen
2080
+ else:
2081
+ if doc_contract_version is not None:
2082
+ record["doc_contract_version"] = doc_contract_version
2083
+ if generator is not None:
2084
+ record["generator"] = generator
2085
+ return record
1844
2086
 
1845
2087
 
1846
2088
  def build_manifest(
@@ -1849,6 +2091,9 @@ def build_manifest(
1849
2091
  producer: Mapping[str, str] | None = None,
1850
2092
  last_synced: str | None = None,
1851
2093
  docs_root_label: str | None = None,
2094
+ doc_contract_version: str | None = DOC_CONTRACT_VERSION,
2095
+ generator: str | None = None,
2096
+ previous_manifest: Mapping[str, Any] | None = None,
1852
2097
  ) -> dict[str, Any]:
1853
2098
  """Build a deterministic-order schema-v2 manifest from strict UTF-8 docs."""
1854
2099
 
@@ -1865,6 +2110,11 @@ def build_manifest(
1865
2110
  raise ManifestValidationError(
1866
2111
  f"producer.{field} must be a non-empty string"
1867
2112
  )
2113
+ effective_generator = (
2114
+ generator
2115
+ if generator is not None
2116
+ else f"{producer_value['name']}/{producer_value['version']}"
2117
+ )
1868
2118
 
1869
2119
  synced_at = _parse_timestamp(last_synced or _utc_now_iso(), "last_synced")
1870
2120
  label = docs_root_label if docs_root_label is not None else root.name
@@ -1873,10 +2123,43 @@ def build_manifest(
1873
2123
  "docs_root label must be a non-empty NUL-free string"
1874
2124
  )
1875
2125
 
1876
- files = [
1877
- _document_record(root, relative_path, fallback_synced_at=synced_at)
1878
- for relative_path in discover_active_markdown_paths(root)
1879
- ]
2126
+ prev_by_path: dict[str, Mapping[str, Any]] = {}
2127
+ if isinstance(previous_manifest, Mapping):
2128
+ prev_files = previous_manifest.get("files")
2129
+ if isinstance(prev_files, list):
2130
+ for entry in prev_files:
2131
+ if isinstance(entry, Mapping) and isinstance(entry.get("path"), str):
2132
+ prev_by_path[entry["path"]] = entry
2133
+
2134
+ active_paths = discover_active_markdown_paths(root)
2135
+ if len(active_paths) > 1:
2136
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
2137
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
2138
+ files = list(
2139
+ executor.map(
2140
+ lambda rel: _document_record(
2141
+ root,
2142
+ rel,
2143
+ fallback_synced_at=synced_at,
2144
+ doc_contract_version=doc_contract_version,
2145
+ generator=effective_generator,
2146
+ previous_entry=prev_by_path.get(rel),
2147
+ ),
2148
+ active_paths,
2149
+ )
2150
+ )
2151
+ else:
2152
+ files = [
2153
+ _document_record(
2154
+ root,
2155
+ relative_path,
2156
+ fallback_synced_at=synced_at,
2157
+ doc_contract_version=doc_contract_version,
2158
+ generator=effective_generator,
2159
+ previous_entry=prev_by_path.get(relative_path),
2160
+ )
2161
+ for relative_path in active_paths
2162
+ ]
1880
2163
  files.sort(key=lambda entry: entry["path"])
1881
2164
  manifest = {
1882
2165
  "schema_version": MANIFEST_SCHEMA_VERSION,
@@ -1888,7 +2171,12 @@ def build_manifest(
1888
2171
  "depth_counts": _depth_counts(files),
1889
2172
  "last_synced": synced_at,
1890
2173
  }
1891
- return validate_manifest_v2(manifest, root, verify_files=True)
2174
+ return validate_manifest_v2(
2175
+ manifest,
2176
+ root,
2177
+ verify_files=False,
2178
+ verify_complete_set=False,
2179
+ )
1892
2180
 
1893
2181
 
1894
2182
  def _require_mapping(value: Any, field: str) -> Mapping[str, Any]:
@@ -1972,6 +2260,7 @@ def validate_manifest_v2(
1972
2260
  *,
1973
2261
  verify_files: bool = True,
1974
2262
  verify_complete_set: bool = True,
2263
+ target_paths: Iterable[str] | None = None,
1975
2264
  ) -> dict[str, Any]:
1976
2265
  """Strictly validate a schema-v2 manifest and return an isolated copy."""
1977
2266
 
@@ -2000,6 +2289,11 @@ def validate_manifest_v2(
2000
2289
  files: list[dict[str, Any]] = []
2001
2290
  paths: list[str] = []
2002
2291
  root = _resolved_docs_root(docs_root)
2292
+ target_set: set[str] | None = (
2293
+ {validate_manifest_relative_path(item).as_posix() for item in target_paths}
2294
+ if target_paths is not None
2295
+ else None
2296
+ )
2003
2297
 
2004
2298
  verify_tasks: list[tuple[str, int, str, str, str, str, Path, str]] = []
2005
2299
  for index, raw_entry in enumerate(files_value):
@@ -2030,12 +2324,22 @@ def validate_manifest_v2(
2030
2324
  entry.get("synced_at"),
2031
2325
  f"files[{index}].synced_at",
2032
2326
  )
2327
+ if "doc_contract_version" in entry and entry["doc_contract_version"] is not None:
2328
+ _require_nonempty_string(
2329
+ entry["doc_contract_version"],
2330
+ f"files[{index}].doc_contract_version",
2331
+ )
2332
+ if "generator" in entry and entry["generator"] is not None:
2333
+ _require_nonempty_string(
2334
+ entry["generator"],
2335
+ f"files[{index}].generator",
2336
+ )
2033
2337
 
2034
- if verify_files:
2338
+ if verify_files and (target_set is None or path in target_set):
2035
2339
  verify_tasks.append(
2036
2340
  (path, byte_count, digest, synced_at, title, status, root, manifest_synced_at)
2037
2341
  )
2038
- else:
2342
+ elif target_set is None:
2039
2343
  resolve_manifest_document(root, path, must_exist=False)
2040
2344
  files.append(entry)
2041
2345
 
@@ -2142,6 +2446,7 @@ def validate_manifest(
2142
2446
  *,
2143
2447
  verify_files: bool = True,
2144
2448
  verify_complete_set: bool = True,
2449
+ target_paths: Iterable[str] | None = None,
2145
2450
  ) -> dict[str, Any]:
2146
2451
  """Validate v2 or normalize legacy v1 without writing it back."""
2147
2452
 
@@ -2166,6 +2471,7 @@ def validate_manifest(
2166
2471
  docs_root,
2167
2472
  verify_files=verify_files,
2168
2473
  verify_complete_set=verify_complete_set,
2474
+ target_paths=target_paths,
2169
2475
  )
2170
2476
  raise ManifestSchemaError(
2171
2477
  f"unsupported manifest schema_version: {schema_version!r}"
@@ -2192,6 +2498,7 @@ def load_manifest(
2192
2498
  docs_root: PathLike | None = None,
2193
2499
  verify_files: bool = True,
2194
2500
  verify_complete_set: bool = True,
2501
+ target_paths: Iterable[str] | None = None,
2195
2502
  ) -> dict[str, Any]:
2196
2503
  """Strictly load and validate ``_manifest.json`` or a supplied JSON path."""
2197
2504
 
@@ -2204,6 +2511,7 @@ def load_manifest(
2204
2511
  root,
2205
2512
  verify_files=verify_files,
2206
2513
  verify_complete_set=verify_complete_set,
2514
+ target_paths=target_paths,
2207
2515
  )
2208
2516
 
2209
2517
 
@@ -2254,10 +2562,108 @@ def build_and_write_manifest(
2254
2562
  return manifest
2255
2563
 
2256
2564
 
2565
+ def migrate_manifest(
2566
+ docs_root: PathLike,
2567
+ *,
2568
+ manifest_path: PathLike | None = None,
2569
+ doc_contract_version: str = DOC_CONTRACT_VERSION,
2570
+ generator: str | None = None,
2571
+ dry_run: bool = False,
2572
+ timeout: float | None = 10.0,
2573
+ ) -> dict[str, Any]:
2574
+ """Migrate a v1 or older v2 manifest in-place without rescanning source dirs.
2575
+
2576
+ Preserves existing document hashes/metadata for v2 entries and fills missing
2577
+ ``doc_contract_version`` / ``generator`` fields; upgrades v1 entries to v2.
2578
+ """
2579
+
2580
+ supplied = Path(manifest_path or Path(docs_root) / MANIFEST_FILENAME)
2581
+ destination, root = _manifest_location(supplied, docs_root)
2582
+ raw = read_json_strict(destination)
2583
+ if not isinstance(raw, Mapping):
2584
+ raise ManifestSchemaError("manifest JSON root must be an object")
2585
+ loaded = validate_manifest(
2586
+ raw,
2587
+ root,
2588
+ verify_files=False,
2589
+ verify_complete_set=False,
2590
+ )
2591
+ previous_schema = loaded.get("schema_version")
2592
+ producer = loaded.get("producer")
2593
+ if not isinstance(producer, Mapping) or not producer.get("name") or not producer.get("version"):
2594
+ producer_value = {
2595
+ "name": DEFAULT_PRODUCER_NAME,
2596
+ "version": DEFAULT_PRODUCER_VERSION,
2597
+ }
2598
+ else:
2599
+ producer_value = {
2600
+ "name": str(producer["name"]),
2601
+ "version": str(producer["version"]),
2602
+ }
2603
+ effective_generator = (
2604
+ generator
2605
+ if generator is not None
2606
+ else f"{producer_value['name']}/{producer_value['version']}"
2607
+ )
2608
+ synced_at = (
2609
+ loaded.get("last_synced")
2610
+ if isinstance(loaded.get("last_synced"), str) and loaded.get("last_synced")
2611
+ else _utc_now_iso()
2612
+ )
2613
+ updated_entries = 0
2614
+ migrated_files: list[dict[str, Any]] = []
2615
+ for raw_entry in loaded["files"]:
2616
+ entry = copy.deepcopy(dict(raw_entry))
2617
+ changed = False
2618
+ if not entry.get("doc_contract_version"):
2619
+ entry["doc_contract_version"] = doc_contract_version
2620
+ changed = True
2621
+ if not entry.get("generator"):
2622
+ entry["generator"] = effective_generator
2623
+ changed = True
2624
+ if changed:
2625
+ updated_entries += 1
2626
+ migrated_files.append(entry)
2627
+ migrated_files.sort(key=lambda item: item["path"])
2628
+ migrated = {
2629
+ "schema_version": MANIFEST_SCHEMA_VERSION,
2630
+ "producer": producer_value,
2631
+ "generation_id": compute_generation_id(migrated_files),
2632
+ "docs_root": str(loaded.get("docs_root") or root.name),
2633
+ "files": migrated_files,
2634
+ "total": len(migrated_files),
2635
+ "depth_counts": _depth_counts(migrated_files),
2636
+ "last_synced": _parse_timestamp(synced_at, "last_synced"),
2637
+ }
2638
+ validated = validate_manifest_v2(
2639
+ migrated,
2640
+ root,
2641
+ verify_files=False,
2642
+ verify_complete_set=False,
2643
+ )
2644
+ wrote = False
2645
+ if not dry_run:
2646
+ write_manifest(destination, validated, timeout=timeout, use_lock=True)
2647
+ wrote = True
2648
+ return {
2649
+ "ok": True,
2650
+ "dry_run": dry_run,
2651
+ "wrote": wrote,
2652
+ "manifest_path": str(destination),
2653
+ "previous_schema_version": previous_schema,
2654
+ "schema_version": MANIFEST_SCHEMA_VERSION,
2655
+ "total_files": len(migrated_files),
2656
+ "updated_entries": updated_entries,
2657
+ "doc_contract_version": doc_contract_version,
2658
+ "generation_id": validated["generation_id"],
2659
+ }
2660
+
2661
+
2257
2662
  __all__ = [
2258
2663
  "AtomicWriteError",
2259
2664
  "DEFAULT_PRODUCER_NAME",
2260
2665
  "DEFAULT_PRODUCER_VERSION",
2666
+ "DOC_CONTRACT_VERSION",
2261
2667
  "DocumentMetadata",
2262
2668
  "ExclusiveFileLock",
2263
2669
  "JsonContractError",
@@ -2294,6 +2700,7 @@ __all__ = [
2294
2700
  "iter_local_document_links",
2295
2701
  "load_manifest",
2296
2702
  "manifest_path_depth",
2703
+ "migrate_manifest",
2297
2704
  "parse_document_metadata",
2298
2705
  "parse_json_strict",
2299
2706
  "parse_last_synced_marker",