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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -3
  3. package/README.zh-CN.md +258 -0
  4. package/cordis.patch.yml +8 -0
  5. package/icon.svg +11 -0
  6. package/index.js +164 -0
  7. package/locale/en.json +6 -0
  8. package/locale/zh.json +6 -0
  9. package/package.json +59 -4
  10. package/skills/proj-doc-builder/SKILL.md +412 -0
  11. package/skills/proj-doc-builder/references/audit_script.md +103 -0
  12. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  13. package/skills/proj-doc-builder/references/checklist.md +90 -0
  14. package/skills/proj-doc-builder/references/exclusions.md +79 -0
  15. package/skills/proj-doc-builder/references/linking.md +83 -0
  16. package/skills/proj-doc-builder/references/migration.md +32 -0
  17. package/skills/proj-doc-builder/references/phase4.md +200 -0
  18. package/skills/proj-doc-builder/references/templates.md +212 -0
  19. package/skills/proj-doc-builder/tests/claims.json +76 -0
  20. package/skills/proj-doc-builder/tests/conftest.py +23 -0
  21. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  22. package/skills/proj-doc-builder/tests/test_claude_doc_index.py +157 -0
  23. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  24. package/skills/proj-doc-builder/tests/test_link_tools.py +279 -0
  25. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -0
  26. package/skills/proj-doc-builder/tests/test_normalize_markers.py +120 -0
  27. package/skills/proj-doc-builder/tests/test_phase4_exit.py +3895 -0
  28. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +812 -0
  29. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1159 -0
  30. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  31. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -0
  32. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  33. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  34. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  35. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  36. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  37. package/skills/proj-doc-builder/tests/test_validate_doc.py +712 -0
  38. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  39. package/skills/proj-doc-builder/tools/core/claude_doc_index.py +504 -0
  40. package/skills/proj-doc-builder/tools/core/compute_link.py +239 -0
  41. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  42. package/skills/proj-doc-builder/tools/core/project_docs_contract.py +2725 -0
  43. package/skills/proj-doc-builder/tools/phase4/__init__.py +82 -0
  44. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +25 -0
  45. package/skills/proj-doc-builder/tools/phase4/engine.py +35 -0
  46. package/skills/proj-doc-builder/tools/phase4/journal.py +29 -0
  47. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +27 -0
  48. package/skills/proj-doc-builder/tools/phase4_exit.py +8565 -0
  49. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  50. package/skills/proj-doc-builder/tools/pipeline/sync_project_docs.py +5531 -0
  51. package/skills/proj-doc-builder/tools/reader/load_docs.py +654 -0
  52. package/skills/proj-doc-builder/tools/scan/link_check.py +203 -0
  53. package/skills/proj-doc-builder/tools/scan/normalize_markers.py +211 -0
  54. package/skills/proj-doc-builder/tools/scan/scan_dirs.py +2735 -0
  55. package/skills/proj-doc-builder/tools/validate/validate_doc.py +1911 -0
@@ -0,0 +1,2725 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Shared, security-sensitive contracts for ``project_docs`` tooling.
3
+
4
+ The module intentionally has no dependency on the other proj-doc-builder tools so
5
+ that writers (the coordinator) and any reader can import the same path, link, JSON,
6
+ locking, and manifest rules.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import concurrent.futures
12
+ import copy
13
+ import errno
14
+ import functools
15
+ import hashlib
16
+ import json
17
+ import math
18
+ import os
19
+ import posixpath
20
+ import re
21
+ import shutil
22
+ import stat
23
+ import sys
24
+ import tempfile
25
+ import time
26
+ import warnings
27
+ from contextlib import contextmanager
28
+ from dataclasses import dataclass, replace
29
+ from datetime import datetime, timezone
30
+ from enum import Enum
31
+ from pathlib import Path, PurePosixPath, PureWindowsPath
32
+ from typing import Any, Iterable, Iterator, Mapping, Sequence
33
+ from urllib.parse import unquote
34
+
35
+ MANIFEST_SCHEMA_VERSION = 2
36
+ DOC_CONTRACT_VERSION = "4.2"
37
+ DEFAULT_PRODUCER_NAME = "proj-doc-builder"
38
+ DEFAULT_PRODUCER_VERSION = "4.5.2"
39
+ MANIFEST_FILENAME = "_manifest.json"
40
+ QUARANTINE_DIRNAME = ".quarantine"
41
+ COORDINATOR_JOURNAL_SUFFIX = ".publish-transaction.json"
42
+ COORDINATOR_COMMITTED_SUFFIX = ".publish-transaction.committed.json"
43
+ COORDINATOR_ROLLED_BACK_SUFFIX = ".publish-transaction.rolled-back.json"
44
+ COORDINATOR_TEMP_MARKER = ".publish-"
45
+ COORDINATOR_ARTIFACT_ROOT_MARKER = ".publish-artifacts-"
46
+ COORDINATOR_RETAINED_ARTIFACT_MARKER = ".publish-retained-"
47
+ COORDINATOR_HISTORY_MARKER = ".publish-history-"
48
+
49
+ SOURCE_FILE_EXTENSIONS = frozenset(
50
+ {
51
+ ".asm",
52
+ ".bash",
53
+ ".bat",
54
+ ".c",
55
+ ".cc",
56
+ ".cfg",
57
+ ".cmake",
58
+ ".cmd",
59
+ ".conf",
60
+ ".cpp",
61
+ ".css",
62
+ ".csv",
63
+ ".cxx",
64
+ ".go",
65
+ ".h",
66
+ ".hh",
67
+ ".hpp",
68
+ ".html",
69
+ ".ini",
70
+ ".java",
71
+ ".js",
72
+ ".json",
73
+ ".jsx",
74
+ ".kt",
75
+ ".kts",
76
+ ".mk",
77
+ ".ps1",
78
+ ".py",
79
+ ".pyi",
80
+ ".pyx",
81
+ ".rs",
82
+ ".scss",
83
+ ".sh",
84
+ ".s",
85
+ ".toml",
86
+ ".ts",
87
+ ".tsx",
88
+ ".txt",
89
+ ".xml",
90
+ ".yaml",
91
+ ".yml",
92
+ }
93
+ )
94
+
95
+ _STATUS_MARKERS = ("✅", "🔶", "⬜", "📦", "❓")
96
+ _SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
97
+ _WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
98
+ _URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
99
+ _INVALID_PERCENT_RE = re.compile(r"%(?![0-9A-Fa-f]{2})")
100
+ _WINDOWS_FORBIDDEN_CHARS = frozenset('<>:"|?*')
101
+ _WINDOWS_RESERVED_NAME_RE = re.compile(
102
+ r"^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$",
103
+ re.IGNORECASE,
104
+ )
105
+ _TITLE_RE = re.compile(r"^#(?!#)[ \t]+(.+?)[ \t]*$", re.MULTILINE)
106
+ _STATUS_SECTION_RE = re.compile(
107
+ r"^##[ \t]+状态[ \t]*\r?\n(.*?)(?=^#{1,6}[ \t]+|\Z)",
108
+ re.MULTILINE | re.DOTALL,
109
+ )
110
+ _LAST_SYNCED_RE = re.compile(
111
+ r"<!--\s*Last\s+synced\s*:\s*(.*?)\s*-->",
112
+ re.IGNORECASE | re.DOTALL,
113
+ )
114
+ _MARKDOWN_LINK_RE = re.compile(
115
+ r"(?<!!)\[([^\]\r\n]*)\]\(\s*"
116
+ r"(<[^>\r\n]*>|[^\s)]+)"
117
+ r"(?:\s+(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|\([^()\r\n]*\)))?\s*\)"
118
+ )
119
+ _MARKDOWN_REFERENCE_DEFINITION_RE = re.compile(
120
+ r"^[ \t]{0,3}\[([^\]\r\n]+)\]:[ \t]*"
121
+ r"(<[^>\r\n]*>|[^\s<>]+)"
122
+ r"(?:[ \t]+(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|\([^()\r\n]*\)))?[ \t]*(?:\r?$)",
123
+ re.MULTILINE,
124
+ )
125
+ _MARKDOWN_REFERENCE_LINK_RE = re.compile(r"(?<!!)\[([^\]\r\n]+)\]\[([^\]\r\n]*)\]")
126
+ _MARKDOWN_SHORTCUT_REFERENCE_RE = re.compile(r"(?<!!)\[([^\]\r\n]+)\](?![ \t]*[\[(])")
127
+ _HTML_HREF_RE = re.compile(
128
+ r"<a\b[^>]*?\bhref[ \t]*=[ \t]*(?:\"([^\"\r\n]*)\"|'([^'\r\n]*)')",
129
+ re.IGNORECASE,
130
+ )
131
+
132
+ PathLike = str | os.PathLike[str]
133
+
134
+
135
+ class ProjectDocsContractError(Exception):
136
+ """Base class for all explicit contract failures."""
137
+
138
+
139
+ class StrictUtf8Error(ProjectDocsContractError, UnicodeError):
140
+ """A file or value is not valid strict UTF-8."""
141
+
142
+
143
+ class JsonContractError(ProjectDocsContractError, ValueError):
144
+ """JSON is malformed, non-standard, or contains duplicate object keys."""
145
+
146
+
147
+ class PathValidationError(ProjectDocsContractError, ValueError):
148
+ """A document path violates the portable project_docs path contract."""
149
+
150
+
151
+ class PathConflictError(PathValidationError):
152
+ """Two manifest paths are equal after Unicode case folding."""
153
+
154
+
155
+ class LinkResolutionError(ProjectDocsContractError, ValueError):
156
+ """A source document cannot be safely placed below project_docs."""
157
+
158
+
159
+ class AtomicWriteError(ProjectDocsContractError, OSError):
160
+ """An atomic UTF-8 or JSON write failed."""
161
+
162
+
163
+ class LockError(ProjectDocsContractError, OSError):
164
+ """A cross-process lock could not be acquired or released."""
165
+
166
+
167
+ class LockTimeoutError(LockError, TimeoutError):
168
+ """An exclusive lock was not acquired before its deadline."""
169
+
170
+
171
+ class ManifestError(ProjectDocsContractError, ValueError):
172
+ """Base class for manifest failures."""
173
+
174
+
175
+ class ManifestSchemaError(ManifestError):
176
+ """A manifest uses an unsupported schema or malformed schema fields."""
177
+
178
+
179
+ class ManifestValidationError(ManifestError):
180
+ """A supported manifest is internally inconsistent."""
181
+
182
+
183
+ class ManifestFileMismatchError(ManifestValidationError):
184
+ """Manifest bytes or digest metadata does not match a document file."""
185
+
186
+
187
+ class LegacyManifestWarning(UserWarning):
188
+ """A v1 manifest was accepted with untrusted fields recomputed in memory."""
189
+
190
+
191
+ @dataclass(frozen=True)
192
+ class SafeManifestPath:
193
+ """A validated manifest path and its resolved location."""
194
+
195
+ relative_path: str
196
+ pure_path: PurePosixPath
197
+ resolved_path: Path
198
+ depth: int
199
+
200
+
201
+ @dataclass(frozen=True)
202
+ class DocumentMetadata:
203
+ """Metadata parsed from one Markdown document."""
204
+
205
+ title: str
206
+ status: str
207
+ synced_at: str | None
208
+
209
+
210
+ class LinkDisposition(str, Enum):
211
+ """Classification returned for every parsed Markdown link."""
212
+
213
+ LOCAL_DOCUMENT = "local_document"
214
+ SKIPPED = "skipped"
215
+ INVALID = "invalid"
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class MarkdownLinkResult:
220
+ """Structured Markdown link parse and resolution result."""
221
+
222
+ text: str
223
+ raw_target: str
224
+ disposition: LinkDisposition
225
+ source_path: Path
226
+ normalized_target: str | None = None
227
+ project_relative_path: str | None = None
228
+ resolved_path: Path | None = None
229
+ exists: bool | None = None
230
+ reason: str | None = None
231
+ query: str | None = None
232
+ fragment: str | None = None
233
+ span: tuple[int, int] | None = None
234
+
235
+ @property
236
+ def is_local_document(self) -> bool:
237
+ """Whether this result names a safe local Markdown document."""
238
+
239
+ return self.disposition is LinkDisposition.LOCAL_DOCUMENT
240
+
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
+
252
+ def _is_link_or_reparse_path(path: Path) -> bool:
253
+ """Return whether an existing path is a link, junction, or reparse point."""
254
+
255
+ try:
256
+ info = path.lstat()
257
+ except FileNotFoundError:
258
+ return False
259
+ return _is_stat_link_or_reparse(info)
260
+
261
+
262
+ def _same_file_identity(first: os.stat_result, second: os.stat_result) -> bool:
263
+ """Compare stable filesystem identity fields after a no-follow open."""
264
+
265
+ first_identity = (getattr(first, "st_dev", 0), getattr(first, "st_ino", 0))
266
+ second_identity = (getattr(second, "st_dev", 0), getattr(second, "st_ino", 0))
267
+ if first_identity != (0, 0) and second_identity != (0, 0):
268
+ return first_identity == second_identity
269
+ return (
270
+ stat.S_IFMT(first.st_mode) == stat.S_IFMT(second.st_mode)
271
+ and first.st_size == second.st_size
272
+ and getattr(first, "st_ctime_ns", None) == getattr(second, "st_ctime_ns", None)
273
+ )
274
+
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
+
338
+ class ExclusiveFileLock:
339
+ """Small cross-process exclusive lock using verified regular files."""
340
+
341
+ def __init__(
342
+ self,
343
+ lock_path: PathLike,
344
+ *,
345
+ timeout: float | None = 10.0,
346
+ poll_interval: float = 0.05,
347
+ ) -> None:
348
+ if timeout is not None and timeout < 0:
349
+ raise ValueError("timeout must be non-negative or None")
350
+ if poll_interval <= 0:
351
+ raise ValueError("poll_interval must be positive")
352
+ self.path = Path(lock_path)
353
+ self.timeout = timeout
354
+ self.poll_interval = poll_interval
355
+ self._fd: int | None = None
356
+
357
+ def _try_lock(self, fd: int) -> None:
358
+ _lock_fd(fd)
359
+
360
+ def _unlock(self, fd: int) -> None:
361
+ _unlock_fd(fd)
362
+
363
+ def acquire(self) -> "ExclusiveFileLock":
364
+ """Acquire the lock, waiting until timeout when another process owns it."""
365
+
366
+ if self._fd is not None:
367
+ raise LockError(f"lock is already acquired: {self.path}")
368
+ if not self.path.parent.is_dir():
369
+ raise LockError(f"lock parent directory does not exist: {self.path.parent}")
370
+ if _is_link_or_reparse_path(self.path.parent):
371
+ raise LockError(
372
+ f"lock parent must not be a link or reparse point: {self.path.parent}"
373
+ )
374
+
375
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
376
+ fd: int | None = None
377
+ expected_identity: os.stat_result | None = None
378
+ try:
379
+ try:
380
+ fd = os.open(
381
+ self.path,
382
+ os.O_RDWR | os.O_CREAT | os.O_EXCL | nofollow,
383
+ 0o600,
384
+ )
385
+ except FileExistsError:
386
+ if _is_link_or_reparse_path(self.path):
387
+ raise LockError(
388
+ f"lock file must not be a link or reparse point: {self.path}"
389
+ )
390
+ expected_identity = self.path.lstat()
391
+ if not stat.S_ISREG(expected_identity.st_mode):
392
+ raise LockError(f"lock path is not a regular file: {self.path}")
393
+ fd = os.open(self.path, os.O_RDWR | nofollow)
394
+
395
+ opened = os.fstat(fd)
396
+ if not stat.S_ISREG(opened.st_mode):
397
+ raise LockError(f"opened lock is not a regular file: {self.path}")
398
+ opened_attributes = getattr(opened, "st_file_attributes", 0)
399
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
400
+ if opened_attributes & reparse_flag:
401
+ raise LockError(f"opened lock is a reparse point: {self.path}")
402
+ if expected_identity is not None and not _same_file_identity(
403
+ expected_identity,
404
+ opened,
405
+ ):
406
+ raise LockError(f"lock file changed while being opened: {self.path}")
407
+ if opened.st_size == 0:
408
+ # ``O_EXCL`` 与首次写入之间无法做到单个系统调用原子化。
409
+ # 若创建者在该窗口崩溃,后继进程必须能够安全补齐同一个
410
+ # 固定锁字节,否则零字节文件会永久阻断项目。多个修复者写入
411
+ # 相同字节不会放宽后续 OS 级互斥。
412
+ os.lseek(fd, 0, os.SEEK_SET)
413
+ written = os.write(fd, b"\0")
414
+ if written != 1:
415
+ raise OSError(f"short lock initialization write: {written}/1")
416
+ os.fsync(fd)
417
+ opened = os.fstat(fd)
418
+
419
+ current_identity = self.path.lstat()
420
+ if not _same_file_identity(opened, current_identity):
421
+ raise LockError(f"lock file changed during initialization: {self.path}")
422
+ except LockError:
423
+ if fd is not None:
424
+ os.close(fd)
425
+ raise
426
+ except OSError as exc:
427
+ if fd is not None:
428
+ os.close(fd)
429
+ raise LockError(f"cannot safely open lock file {self.path}: {exc}") from exc
430
+
431
+ if fd is None: # pragma: no cover - all successful branches assign fd
432
+ raise LockError(f"lock file descriptor was not created: {self.path}")
433
+ deadline = None if self.timeout is None else time.monotonic() + self.timeout
434
+ try:
435
+ while True:
436
+ try:
437
+ self._try_lock(fd)
438
+ self._fd = fd
439
+ return self
440
+ except OSError as exc:
441
+ if exc.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
442
+ raise LockError(f"cannot lock {self.path}: {exc}") from exc
443
+ if deadline is not None and time.monotonic() >= deadline:
444
+ raise LockTimeoutError(
445
+ f"timed out acquiring exclusive lock: {self.path}"
446
+ ) from exc
447
+ time.sleep(self.poll_interval)
448
+ except BaseException:
449
+ os.close(fd)
450
+ raise
451
+
452
+ def release(self) -> None:
453
+ """Release this instance's lock and close its file descriptor."""
454
+
455
+ fd = self._fd
456
+ if fd is None:
457
+ return
458
+ self._fd = None
459
+ unlock_error: OSError | None = None
460
+ try:
461
+ self._unlock(fd)
462
+ except OSError as exc:
463
+ unlock_error = exc
464
+ finally:
465
+ os.close(fd)
466
+ if unlock_error is not None:
467
+ raise LockError(
468
+ f"cannot unlock {self.path}: {unlock_error}"
469
+ ) from unlock_error
470
+
471
+ def __enter__(self) -> "ExclusiveFileLock":
472
+ return self.acquire()
473
+
474
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
475
+ self.release()
476
+
477
+
478
+ @contextmanager
479
+ def exclusive_lock(
480
+ lock_path: PathLike,
481
+ *,
482
+ timeout: float | None = 10.0,
483
+ poll_interval: float = 0.05,
484
+ ) -> Iterator[ExclusiveFileLock]:
485
+ """Context manager for a Windows ``msvcrt`` / POSIX ``fcntl`` lock."""
486
+
487
+ lock = ExclusiveFileLock(
488
+ lock_path,
489
+ timeout=timeout,
490
+ poll_interval=poll_interval,
491
+ )
492
+ with lock:
493
+ yield lock
494
+
495
+
496
+ def exclusive_file_lock(
497
+ lock_path: PathLike,
498
+ *,
499
+ timeout: float | None = 10.0,
500
+ poll_interval: float = 0.05,
501
+ ) -> Iterator[ExclusiveFileLock]:
502
+ """Alias with an explicit file-lock name for importing callers."""
503
+
504
+ return exclusive_lock(
505
+ lock_path,
506
+ timeout=timeout,
507
+ poll_interval=poll_interval,
508
+ )
509
+
510
+
511
+ def project_sync_lock_path(project_root: PathLike) -> Path:
512
+ """Return one process-shared lock path without polluting the project tree."""
513
+
514
+ supplied = Path(project_root)
515
+ try:
516
+ root = supplied.resolve(strict=True)
517
+ except (OSError, RuntimeError) as exc:
518
+ raise LockError(
519
+ f"project root cannot be resolved for locking: {supplied}"
520
+ ) from exc
521
+ if not root.is_dir():
522
+ raise LockError(f"project root is not a directory: {root}")
523
+ lock_parent = Path(tempfile.gettempdir()) / "proj-doc-builder-locks"
524
+ try:
525
+ lock_parent.mkdir(mode=0o700, parents=True, exist_ok=True)
526
+ except OSError as exc:
527
+ raise LockError(
528
+ f"cannot create shared lock directory {lock_parent}: {exc}"
529
+ ) from exc
530
+ if _is_link_or_reparse_path(lock_parent):
531
+ raise LockError(f"shared lock directory is untrusted: {lock_parent}")
532
+ digest = sha256_bytes(os.path.normcase(str(root)).encode("utf-8"))
533
+ return lock_parent / f"{digest}.lock"
534
+
535
+
536
+ def coordinator_publish_journal_paths(project_root: PathLike) -> dict[str, Path]:
537
+ """Return every reserved coordinator journal slot in the shared lock domain."""
538
+
539
+ lock_path = project_sync_lock_path(project_root)
540
+ return {
541
+ "prepared": lock_path.with_name(
542
+ f"{lock_path.stem}{COORDINATOR_JOURNAL_SUFFIX}"
543
+ ),
544
+ "committed": lock_path.with_name(
545
+ f"{lock_path.stem}{COORDINATOR_COMMITTED_SUFFIX}"
546
+ ),
547
+ "rolled_back": lock_path.with_name(
548
+ f"{lock_path.stem}{COORDINATOR_ROLLED_BACK_SUFFIX}"
549
+ ),
550
+ }
551
+
552
+
553
+ def coordinator_pending_publish_status(
554
+ project_root: PathLike,
555
+ ) -> dict[str, Any] | None:
556
+ """Detect journals and crash residues without parsing coordinator internals.
557
+
558
+ Every caller holds the same project lock while acting on this result. A temp
559
+ residue is treated as pending rather than deleted because its ownership cannot
560
+ be inferred from its pathname after a process crash.
561
+ """
562
+
563
+ slots = coordinator_publish_journal_paths(project_root)
564
+ parent = next(iter(slots.values())).parent
565
+ if _is_link_or_reparse_path(parent):
566
+ raise LockError(f"coordinator journal directory is untrusted: {parent}")
567
+ try:
568
+ entries = list(parent.iterdir())
569
+ except OSError as exc:
570
+ raise LockError(
571
+ f"cannot inspect coordinator journal directory {parent}: {exc}"
572
+ ) from exc
573
+
574
+ slot_by_name = {path.name: phase for phase, path in slots.items()}
575
+ prepared_name = slots["prepared"].name
576
+ temp_prefix = f"{prepared_name}{COORDINATOR_TEMP_MARKER}"
577
+ artifact_prefix = (
578
+ f"{slots['prepared'].stem}{COORDINATOR_ARTIFACT_ROOT_MARKER}"
579
+ )
580
+ history_prefix = (
581
+ f"{slots['prepared'].stem}{COORDINATOR_HISTORY_MARKER}"
582
+ )
583
+ found: list[dict[str, str]] = []
584
+ for entry in entries:
585
+ phase = slot_by_name.get(entry.name)
586
+ is_temporary = entry.name.startswith(temp_prefix) and entry.name.endswith(
587
+ ".tmp"
588
+ )
589
+ is_artifact_root = entry.name.startswith(artifact_prefix)
590
+ is_history = entry.name.startswith(history_prefix)
591
+ if phase is None and not is_temporary and not is_artifact_root and not is_history:
592
+ continue
593
+ if _is_link_or_reparse_path(entry):
594
+ raise LockError(f"coordinator publish path is indirect: {entry}")
595
+ try:
596
+ info = entry.lstat()
597
+ except OSError as exc:
598
+ raise LockError(f"cannot inspect coordinator publish path {entry}: {exc}") from exc
599
+ expected_directory = phase is None and is_artifact_root
600
+ if expected_directory:
601
+ if not stat.S_ISDIR(info.st_mode):
602
+ raise LockError(
603
+ f"coordinator artifact path is not a directory: {entry}"
604
+ )
605
+ elif not stat.S_ISREG(info.st_mode):
606
+ raise LockError(f"coordinator journal path is not a regular file: {entry}")
607
+ found.append(
608
+ {
609
+ "phase": (
610
+ phase
611
+ if phase is not None
612
+ else "artifact-residue"
613
+ if is_artifact_root
614
+ else "history"
615
+ if is_history
616
+ else "temporary"
617
+ ),
618
+ "name": entry.name,
619
+ }
620
+ )
621
+
622
+ if not found:
623
+ return None
624
+ found.sort(key=lambda item: (item["phase"], item["name"]))
625
+ blocking = [
626
+ entry
627
+ for entry in found
628
+ if entry["phase"] != "history"
629
+ ]
630
+ if not blocking:
631
+ return None
632
+ return {"required": True, "entries": blocking}
633
+
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
+
788
+ @contextmanager
789
+ def project_sync_lock(
790
+ project_root: PathLike,
791
+ *,
792
+ timeout: float | None = 10.0,
793
+ poll_interval: float = 0.05,
794
+ ) -> Iterator[ExclusiveFileLock]:
795
+ """Acquire the canonical root lock used by every project_docs writer."""
796
+
797
+ with exclusive_lock(
798
+ project_sync_lock_path(project_root),
799
+ timeout=timeout,
800
+ poll_interval=poll_interval,
801
+ ) as lock:
802
+ yield lock
803
+
804
+
805
+ def read_utf8(path: PathLike) -> str:
806
+ """Read a text file as strict UTF-8; malformed input is never substituted."""
807
+
808
+ file_path = Path(path)
809
+ try:
810
+ return file_path.read_bytes().decode("utf-8")
811
+ except UnicodeDecodeError as exc:
812
+ raise StrictUtf8Error(f"invalid UTF-8 in {file_path}: {exc}") from exc
813
+
814
+
815
+ def _read_utf8_bytes(path: PathLike) -> tuple[bytes, str]:
816
+ file_path = Path(path)
817
+ raw = file_path.read_bytes()
818
+ try:
819
+ return raw, raw.decode("utf-8")
820
+ except UnicodeDecodeError as exc:
821
+ raise StrictUtf8Error(f"invalid UTF-8 in {file_path}: {exc}") from exc
822
+
823
+
824
+ def sha256_bytes(data: bytes) -> str:
825
+ """Return the lowercase SHA-256 hex digest for bytes."""
826
+
827
+ return hashlib.sha256(data).hexdigest()
828
+
829
+
830
+ def sha256_file(path: PathLike, *, chunk_size: int = 1024 * 1024) -> str:
831
+ """Stream a file and return its lowercase SHA-256 digest."""
832
+
833
+ if chunk_size <= 0:
834
+ raise ValueError("chunk_size must be positive")
835
+ digest = hashlib.sha256()
836
+ with Path(path).open("rb") as file_obj:
837
+ while True:
838
+ chunk = file_obj.read(chunk_size)
839
+ if not chunk:
840
+ break
841
+ digest.update(chunk)
842
+ return digest.hexdigest()
843
+
844
+
845
+ def _reject_json_constant(value: str) -> Any:
846
+ raise JsonContractError(f"non-standard JSON constant is forbidden: {value}")
847
+
848
+
849
+ def _parse_json_float(value: str) -> float:
850
+ parsed = float(value)
851
+ if not math.isfinite(parsed):
852
+ raise JsonContractError(f"non-finite JSON number is forbidden: {value}")
853
+ return parsed
854
+
855
+
856
+ @functools.lru_cache(maxsize=8192)
857
+ def _contains_surrogate(value: str) -> bool:
858
+ return any(0xD800 <= ord(character) <= 0xDFFF for character in value)
859
+
860
+
861
+ def _validate_json_unicode(value: Any, path: str = "$") -> None:
862
+ if isinstance(value, str):
863
+ if _contains_surrogate(value):
864
+ raise JsonContractError(
865
+ f"isolated Unicode surrogate is forbidden at {path}"
866
+ )
867
+ return
868
+ if isinstance(value, list):
869
+ for index, item in enumerate(value):
870
+ _validate_json_unicode(item, f"{path}[{index}]")
871
+ return
872
+ if isinstance(value, Mapping):
873
+ for key, item in value.items():
874
+ if _contains_surrogate(key):
875
+ raise JsonContractError(
876
+ f"isolated Unicode surrogate is forbidden in object key at {path}"
877
+ )
878
+ _validate_json_unicode(item, f"{path}[{key!r}]")
879
+
880
+
881
+ def _unique_object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
882
+ result: dict[str, Any] = {}
883
+ for key, value in pairs:
884
+ if key in result:
885
+ raise JsonContractError(f"duplicate JSON object key: {key!r}")
886
+ result[key] = value
887
+ return result
888
+
889
+
890
+ def parse_json_strict(text: str, *, source: str = "<memory>") -> Any:
891
+ """Parse strict JSON text, rejecting duplicates, NaN, and surrogates."""
892
+
893
+ if not isinstance(text, str):
894
+ raise JsonContractError("strict JSON input must be text")
895
+ try:
896
+ value = json.loads(
897
+ text,
898
+ object_pairs_hook=_unique_object_pairs,
899
+ parse_constant=_reject_json_constant,
900
+ parse_float=_parse_json_float,
901
+ )
902
+ _validate_json_unicode(value)
903
+ return value
904
+ except JsonContractError:
905
+ raise
906
+ except (json.JSONDecodeError, ValueError) as exc:
907
+ raise JsonContractError(f"invalid JSON in {source}: {exc}") from exc
908
+
909
+
910
+ def read_json_strict(path: PathLike) -> Any:
911
+ """Read strict UTF-8 JSON, rejecting duplicate keys and NaN/Infinity."""
912
+
913
+ file_path = Path(path)
914
+ text = read_utf8(file_path)
915
+ return parse_json_strict(text, source=str(file_path))
916
+
917
+
918
+ def stable_json_dumps(value: Any) -> str:
919
+ """Encode deterministic UTF-8 JSON with sorted keys and a final newline."""
920
+
921
+ try:
922
+ rendered = (
923
+ json.dumps(
924
+ value,
925
+ ensure_ascii=False,
926
+ sort_keys=True,
927
+ indent=2,
928
+ allow_nan=False,
929
+ )
930
+ + "\n"
931
+ )
932
+ rendered.encode("utf-8")
933
+ return rendered
934
+ except (TypeError, ValueError, UnicodeEncodeError) as exc:
935
+ raise JsonContractError(
936
+ f"value cannot be encoded as strict JSON: {exc}"
937
+ ) from exc
938
+
939
+
940
+ def configure_stdio_utf8() -> None:
941
+ """Configure both process text streams for strict UTF-8 when supported."""
942
+
943
+ for stream in (sys.stdout, sys.stderr):
944
+ reconfigure = getattr(stream, "reconfigure", None)
945
+ if callable(reconfigure):
946
+ try:
947
+ reconfigure(encoding="utf-8", errors="strict")
948
+ except (AttributeError, OSError, ValueError):
949
+ pass
950
+
951
+
952
+ def _canonical_json_bytes(value: Any) -> bytes:
953
+ try:
954
+ rendered = json.dumps(
955
+ value,
956
+ ensure_ascii=False,
957
+ sort_keys=True,
958
+ separators=(",", ":"),
959
+ allow_nan=False,
960
+ )
961
+ return rendered.encode("utf-8")
962
+ except (TypeError, ValueError, UnicodeEncodeError) as exc:
963
+ raise JsonContractError(f"value cannot be canonically encoded: {exc}") from exc
964
+
965
+
966
+ def _fsync_parent_directory(parent: Path) -> None:
967
+ if os.name != "posix":
968
+ return
969
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
970
+ directory_fd = os.open(parent, flags)
971
+ try:
972
+ os.fsync(directory_fd)
973
+ finally:
974
+ os.close(directory_fd)
975
+
976
+
977
+ def _atomic_write_bytes(path: PathLike, payload: bytes) -> Path:
978
+ destination = Path(path)
979
+ parent = destination.parent
980
+ if not parent.is_dir():
981
+ raise AtomicWriteError(f"destination parent does not exist: {parent}")
982
+
983
+ fd = -1
984
+ temporary: Path | None = None
985
+ replaced = False
986
+ try:
987
+ fd, temp_name = tempfile.mkstemp(
988
+ prefix=f".{destination.name}.",
989
+ suffix=".tmp",
990
+ dir=parent,
991
+ )
992
+ temporary = Path(temp_name)
993
+ with os.fdopen(fd, "wb") as file_obj:
994
+ fd = -1
995
+ file_obj.write(payload)
996
+ file_obj.flush()
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
1016
+ os.replace(temporary, destination)
1017
+ replaced = True
1018
+ _fsync_parent_directory(parent)
1019
+ return destination
1020
+ except OSError as exc:
1021
+ raise AtomicWriteError(f"atomic write failed for {destination}: {exc}") from exc
1022
+ finally:
1023
+ if fd >= 0:
1024
+ os.close(fd)
1025
+ if not replaced and temporary is not None:
1026
+ try:
1027
+ temporary.unlink()
1028
+ except OSError:
1029
+ pass
1030
+
1031
+
1032
+ def atomic_write_utf8(path: PathLike, text: str) -> Path:
1033
+ """Atomically replace a text file using strict UTF-8 bytes."""
1034
+
1035
+ try:
1036
+ payload = text.encode("utf-8")
1037
+ except UnicodeEncodeError as exc:
1038
+ raise StrictUtf8Error(f"text cannot be encoded as UTF-8: {exc}") from exc
1039
+ return _atomic_write_bytes(path, payload)
1040
+
1041
+
1042
+ def atomic_write_json(path: PathLike, value: Any) -> Path:
1043
+ """Atomically write stable JSON through a unique same-directory temp file."""
1044
+
1045
+ return atomic_write_utf8(path, stable_json_dumps(value))
1046
+
1047
+
1048
+ @functools.lru_cache(maxsize=8192)
1049
+ def _validate_portable_path_segment(segment: str, path: str) -> None:
1050
+ if any(
1051
+ ord(character) < 32 or character in _WINDOWS_FORBIDDEN_CHARS
1052
+ for character in segment
1053
+ ):
1054
+ raise PathValidationError(
1055
+ f"document path contains a non-portable filename character: {path!r}"
1056
+ )
1057
+ if segment.endswith((" ", ".")):
1058
+ raise PathValidationError(
1059
+ f"document path segment ends with a space or dot: {path!r}"
1060
+ )
1061
+ device_stem = segment.split(".", 1)[0]
1062
+ if _WINDOWS_RESERVED_NAME_RE.fullmatch(device_stem):
1063
+ raise PathValidationError(
1064
+ f"document path uses a reserved Windows device name: {path!r}"
1065
+ )
1066
+
1067
+
1068
+ @functools.lru_cache(maxsize=16384)
1069
+ def validate_manifest_relative_path(
1070
+ relative_path: str | PurePosixPath,
1071
+ ) -> PurePosixPath:
1072
+ """Validate the lexical form of one portable manifest document path."""
1073
+
1074
+ raw = (
1075
+ relative_path.as_posix()
1076
+ if isinstance(relative_path, PurePosixPath)
1077
+ else relative_path
1078
+ )
1079
+ if not isinstance(raw, str):
1080
+ raise PathValidationError("manifest path must be a string or PurePosixPath")
1081
+ if not raw:
1082
+ raise PathValidationError("manifest path must not be empty")
1083
+ if "\0" in raw:
1084
+ raise PathValidationError("manifest path contains NUL")
1085
+ if "\\" in raw:
1086
+ raise PathValidationError("manifest path must use POSIX '/' separators")
1087
+ if raw.startswith("//") or PureWindowsPath(raw).is_absolute():
1088
+ raise PathValidationError(f"UNC manifest path is forbidden: {raw!r}")
1089
+ if raw.startswith("/"):
1090
+ raise PathValidationError(f"absolute manifest path is forbidden: {raw!r}")
1091
+ if _WINDOWS_DRIVE_RE.match(raw) or PureWindowsPath(raw).drive:
1092
+ raise PathValidationError(
1093
+ f"drive-qualified manifest path is forbidden: {raw!r}"
1094
+ )
1095
+
1096
+ segments = raw.split("/")
1097
+ if any(segment == "" for segment in segments):
1098
+ raise PathValidationError(f"manifest path contains an empty segment: {raw!r}")
1099
+ if any(segment in (".", "..") for segment in segments):
1100
+ raise PathValidationError(f"manifest path contains '.' or '..': {raw!r}")
1101
+ for segment in segments:
1102
+ _validate_portable_path_segment(segment, raw)
1103
+
1104
+ pure_path = PurePosixPath(raw)
1105
+ if pure_path.is_absolute():
1106
+ raise PathValidationError(f"absolute manifest path is forbidden: {raw!r}")
1107
+ if pure_path.suffix != ".md" or pure_path.name == ".md":
1108
+ raise PathValidationError(
1109
+ f"manifest path must end in a named '.md' file: {raw!r}"
1110
+ )
1111
+ if pure_path.as_posix() != raw:
1112
+ raise PathValidationError(f"manifest path is not canonical POSIX form: {raw!r}")
1113
+ return pure_path
1114
+
1115
+
1116
+ def manifest_path_depth(relative_path: str | PurePosixPath) -> int:
1117
+ """Derive manifest depth from POSIX parts (a root-level document is 0)."""
1118
+
1119
+ pure_path = validate_manifest_relative_path(relative_path)
1120
+ return len(pure_path.parts) - 1
1121
+
1122
+
1123
+ def _resolved_docs_root(docs_root: PathLike) -> Path:
1124
+ root = Path(docs_root)
1125
+ try:
1126
+ if _is_directory_link_or_junction(root):
1127
+ raise PathValidationError(
1128
+ f"project_docs root must not be a symlink or reparse point: {root}"
1129
+ )
1130
+ resolved = root.resolve(strict=True)
1131
+ except PathValidationError:
1132
+ raise
1133
+ except (OSError, RuntimeError) as exc:
1134
+ raise PathValidationError(f"project_docs root does not exist: {root}") from exc
1135
+ if not resolved.is_dir():
1136
+ raise PathValidationError(f"project_docs root is not a directory: {root}")
1137
+ return resolved
1138
+
1139
+
1140
+ def resolve_docs_root(docs_root: PathLike) -> Path:
1141
+ """验证并返回真实 ``project_docs`` 根,拒绝根级间接路径。"""
1142
+
1143
+ return _resolved_docs_root(docs_root)
1144
+
1145
+
1146
+ def _ensure_below_root(candidate: Path, root: Path, description: str) -> None:
1147
+ try:
1148
+ candidate.relative_to(root)
1149
+ except ValueError as exc:
1150
+ raise PathValidationError(
1151
+ f"{description} resolves outside project_docs root: {candidate}"
1152
+ ) from exc
1153
+
1154
+
1155
+ def resolve_manifest_document(
1156
+ docs_root: PathLike,
1157
+ relative_path: str | PurePosixPath,
1158
+ *,
1159
+ must_exist: bool = True,
1160
+ ) -> SafeManifestPath:
1161
+ """Resolve a manifest path and reject symlink/junction escapes."""
1162
+
1163
+ root = _resolved_docs_root(docs_root)
1164
+ pure_path = validate_manifest_relative_path(relative_path)
1165
+ lexical = root.joinpath(*pure_path.parts)
1166
+ try:
1167
+ resolved = lexical.resolve(strict=must_exist)
1168
+ except (OSError, RuntimeError) as exc:
1169
+ raise PathValidationError(
1170
+ f"manifest document cannot be safely resolved: {pure_path.as_posix()}"
1171
+ ) from exc
1172
+ _ensure_below_root(resolved, root, f"manifest path {pure_path.as_posix()!r}")
1173
+ if must_exist and not resolved.is_file():
1174
+ raise PathValidationError(
1175
+ f"manifest path is not a regular document file: {pure_path.as_posix()}"
1176
+ )
1177
+ return SafeManifestPath(
1178
+ relative_path=pure_path.as_posix(),
1179
+ pure_path=pure_path,
1180
+ resolved_path=resolved,
1181
+ depth=len(pure_path.parts) - 1,
1182
+ )
1183
+
1184
+
1185
+ def _read_all_fd(fd: int, *, chunk_size: int = 1024 * 1024) -> bytes:
1186
+ chunks: list[bytes] = []
1187
+ while True:
1188
+ chunk = os.read(fd, chunk_size)
1189
+ if not chunk:
1190
+ return b"".join(chunks)
1191
+ chunks.append(chunk)
1192
+
1193
+
1194
+ def _read_posix_document_fd(root: Path, pure_path: PurePosixPath) -> bytes:
1195
+ no_follow = getattr(os, "O_NOFOLLOW", 0)
1196
+ directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | no_follow
1197
+ opened_fds: list[int] = []
1198
+ try:
1199
+ current_fd = os.open(root, directory_flags)
1200
+ opened_fds.append(current_fd)
1201
+ for segment in pure_path.parts[:-1]:
1202
+ next_fd = os.open(
1203
+ segment,
1204
+ directory_flags,
1205
+ dir_fd=current_fd,
1206
+ )
1207
+ if not stat.S_ISDIR(os.fstat(next_fd).st_mode):
1208
+ os.close(next_fd)
1209
+ raise PathValidationError(
1210
+ f"document parent is not a directory: {pure_path.as_posix()}"
1211
+ )
1212
+ opened_fds.append(next_fd)
1213
+ current_fd = next_fd
1214
+
1215
+ file_fd = os.open(
1216
+ pure_path.name,
1217
+ os.O_RDONLY | no_follow,
1218
+ dir_fd=current_fd,
1219
+ )
1220
+ opened_fds.append(file_fd)
1221
+ if not stat.S_ISREG(os.fstat(file_fd).st_mode):
1222
+ raise PathValidationError(
1223
+ f"document is not a regular file: {pure_path.as_posix()}"
1224
+ )
1225
+ return _read_all_fd(file_fd)
1226
+ finally:
1227
+ for fd in reversed(opened_fds):
1228
+ os.close(fd)
1229
+
1230
+
1231
+ def _is_reparse_point(path: Path) -> bool:
1232
+ attributes = getattr(path.lstat(), "st_file_attributes", 0)
1233
+ marker = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
1234
+ return bool(attributes & marker)
1235
+
1236
+
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)
1244
+
1245
+
1246
+ def _read_checked_document_fd(root: Path, pure_path: PurePosixPath) -> bytes:
1247
+ lexical = root.joinpath(*pure_path.parts)
1248
+ current = root
1249
+ for index, segment in enumerate(pure_path.parts):
1250
+ current = current / segment
1251
+ current_stat = current.lstat()
1252
+ if _is_stat_link_or_reparse(current_stat):
1253
+ raise PathValidationError(
1254
+ f"document path contains a symlink or reparse point: {pure_path.as_posix()}"
1255
+ )
1256
+ if index < len(pure_path.parts) - 1 and not stat.S_ISDIR(current_stat.st_mode):
1257
+ raise PathValidationError(
1258
+ f"document parent is not a directory: {pure_path.as_posix()}"
1259
+ )
1260
+
1261
+ before = lexical.lstat()
1262
+ if not stat.S_ISREG(before.st_mode):
1263
+ raise PathValidationError(
1264
+ f"document is not a regular file: {pure_path.as_posix()}"
1265
+ )
1266
+
1267
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
1268
+ fd = os.open(lexical, flags)
1269
+ try:
1270
+ opened = os.fstat(fd)
1271
+ after = lexical.lstat()
1272
+ before_identity = (before.st_dev, before.st_ino)
1273
+ if before_identity != (opened.st_dev, opened.st_ino) or before_identity != (
1274
+ after.st_dev,
1275
+ after.st_ino,
1276
+ ):
1277
+ raise PathValidationError(
1278
+ f"document changed while it was being opened: {pure_path.as_posix()}"
1279
+ )
1280
+ if _is_stat_link_or_reparse(after) or not stat.S_ISREG(opened.st_mode):
1281
+ raise PathValidationError(
1282
+ f"document is not a stable regular file: {pure_path.as_posix()}"
1283
+ )
1284
+ return _read_all_fd(fd)
1285
+ finally:
1286
+ os.close(fd)
1287
+
1288
+
1289
+ def _read_project_document_bytes(
1290
+ docs_root: PathLike,
1291
+ relative_path: str | PurePosixPath,
1292
+ ) -> tuple[SafeManifestPath, bytes, str]:
1293
+ safe_path = resolve_manifest_document(docs_root, relative_path, must_exist=True)
1294
+ root = _resolved_docs_root(docs_root)
1295
+ try:
1296
+ if os.name == "posix":
1297
+ raw = _read_posix_document_fd(root, safe_path.pure_path)
1298
+ else:
1299
+ raw = _read_checked_document_fd(root, safe_path.pure_path)
1300
+ except PathValidationError:
1301
+ raise
1302
+ except (OSError, RuntimeError) as exc:
1303
+ raise PathValidationError(
1304
+ f"document cannot be securely opened: {safe_path.relative_path}"
1305
+ ) from exc
1306
+ try:
1307
+ content = raw.decode("utf-8")
1308
+ except UnicodeDecodeError as exc:
1309
+ raise StrictUtf8Error(
1310
+ f"invalid UTF-8 in {safe_path.resolved_path}: {exc}"
1311
+ ) from exc
1312
+ return safe_path, raw, content
1313
+
1314
+
1315
+ def read_project_document(
1316
+ docs_root: PathLike,
1317
+ relative_path: str | PurePosixPath,
1318
+ ) -> str:
1319
+ """Safely read one in-root regular document as strict UTF-8."""
1320
+
1321
+ _, _, content = _read_project_document_bytes(docs_root, relative_path)
1322
+ return content
1323
+
1324
+
1325
+ def ensure_unique_manifest_paths(
1326
+ relative_paths: Iterable[str | PurePosixPath],
1327
+ ) -> list[PurePosixPath]:
1328
+ """Validate paths and reject exact duplicates and case-only conflicts."""
1329
+
1330
+ seen: dict[str, str] = {}
1331
+ validated: list[PurePosixPath] = []
1332
+ for value in relative_paths:
1333
+ pure_path = validate_manifest_relative_path(value)
1334
+ canonical = pure_path.as_posix()
1335
+ folded = canonical.casefold()
1336
+ previous = seen.get(folded)
1337
+ if previous is not None:
1338
+ kind = "duplicate" if previous == canonical else "case conflict"
1339
+ raise PathConflictError(
1340
+ f"manifest path {kind}: {previous!r} conflicts with {canonical!r}"
1341
+ )
1342
+ seen[folded] = canonical
1343
+ validated.append(pure_path)
1344
+ return validated
1345
+
1346
+
1347
+ def validate_manifest_paths(
1348
+ docs_root: PathLike,
1349
+ relative_paths: Iterable[str | PurePosixPath],
1350
+ *,
1351
+ must_exist: bool = True,
1352
+ ) -> list[SafeManifestPath]:
1353
+ """Validate uniqueness and safely resolve a collection of manifest paths."""
1354
+
1355
+ paths = ensure_unique_manifest_paths(relative_paths)
1356
+ return [
1357
+ resolve_manifest_document(docs_root, path, must_exist=must_exist)
1358
+ for path in paths
1359
+ ]
1360
+
1361
+
1362
+ def _source_document_path(
1363
+ source_doc: PathLike, docs_root: PathLike
1364
+ ) -> tuple[Path, Path]:
1365
+ """返回源码文档的逻辑路径,不跟随最后一刻出现的间接路径。"""
1366
+
1367
+ root = _resolved_docs_root(docs_root)
1368
+ raw = os.fspath(source_doc)
1369
+ if not isinstance(raw, str):
1370
+ raise LinkResolutionError("source document path must be text")
1371
+ if "\0" in raw:
1372
+ raise LinkResolutionError("source document path contains NUL")
1373
+ if isinstance(source_doc, str) and "\\" in raw:
1374
+ raise LinkResolutionError(
1375
+ "text source document paths must use POSIX separators"
1376
+ )
1377
+
1378
+ source = Path(raw)
1379
+ try:
1380
+ if source.is_absolute():
1381
+ lexical = Path(os.path.abspath(raw))
1382
+ relative = lexical.relative_to(root).as_posix()
1383
+ validate_manifest_relative_path(relative)
1384
+ else:
1385
+ pure_path = validate_manifest_relative_path(raw)
1386
+ lexical = root.joinpath(*pure_path.parts)
1387
+ except (OSError, RuntimeError, ValueError, PathValidationError) as exc:
1388
+ raise LinkResolutionError(
1389
+ f"source document is outside or invalid for project_docs root: {source_doc}"
1390
+ ) from exc
1391
+
1392
+ try:
1393
+ if os.path.lexists(lexical) and _is_directory_link_or_junction(lexical):
1394
+ raise LinkResolutionError(
1395
+ f"source document is outside or uses an indirect path: {source_doc}"
1396
+ )
1397
+ except LinkResolutionError:
1398
+ raise
1399
+ except OSError as exc:
1400
+ raise LinkResolutionError(
1401
+ f"source document path cannot be inspected safely: {source_doc}"
1402
+ ) from exc
1403
+ return root, lexical
1404
+
1405
+
1406
+ def _link_result(
1407
+ *,
1408
+ raw_target: str,
1409
+ source_path: Path,
1410
+ disposition: LinkDisposition,
1411
+ reason: str,
1412
+ normalized_target: str | None = None,
1413
+ project_relative_path: str | None = None,
1414
+ resolved_path: Path | None = None,
1415
+ exists: bool | None = None,
1416
+ query: str | None = None,
1417
+ fragment: str | None = None,
1418
+ ) -> MarkdownLinkResult:
1419
+ return MarkdownLinkResult(
1420
+ text="",
1421
+ raw_target=raw_target,
1422
+ disposition=disposition,
1423
+ source_path=source_path,
1424
+ normalized_target=normalized_target,
1425
+ project_relative_path=project_relative_path,
1426
+ resolved_path=resolved_path,
1427
+ exists=exists,
1428
+ reason=reason,
1429
+ query=query,
1430
+ fragment=fragment,
1431
+ )
1432
+
1433
+
1434
+ def resolve_markdown_target(
1435
+ target: str,
1436
+ *,
1437
+ source_doc: PathLike,
1438
+ docs_root: PathLike,
1439
+ ) -> MarkdownLinkResult:
1440
+ """Classify and safely resolve one Markdown link target.
1441
+
1442
+ Invalid local paths are represented as ``INVALID`` results rather than being
1443
+ silently normalized. Broken-but-safe document links remain ``LOCAL_DOCUMENT``
1444
+ with ``exists=False`` so callers can report them consistently.
1445
+ """
1446
+
1447
+ root, source_path = _source_document_path(source_doc, docs_root)
1448
+ if not isinstance(target, str):
1449
+ return _link_result(
1450
+ raw_target=repr(target),
1451
+ source_path=source_path,
1452
+ disposition=LinkDisposition.INVALID,
1453
+ reason="target-is-not-text",
1454
+ )
1455
+
1456
+ raw_target = target
1457
+ cleaned = target.strip()
1458
+ if cleaned.startswith("<") or cleaned.endswith(">"):
1459
+ if not (cleaned.startswith("<") and cleaned.endswith(">")):
1460
+ return _link_result(
1461
+ raw_target=raw_target,
1462
+ source_path=source_path,
1463
+ disposition=LinkDisposition.INVALID,
1464
+ reason="malformed-angle-target",
1465
+ )
1466
+ cleaned = cleaned[1:-1].strip()
1467
+
1468
+ if not cleaned:
1469
+ return _link_result(
1470
+ raw_target=raw_target,
1471
+ source_path=source_path,
1472
+ disposition=LinkDisposition.SKIPPED,
1473
+ reason="empty-target",
1474
+ )
1475
+ if cleaned.startswith("#"):
1476
+ return _link_result(
1477
+ raw_target=raw_target,
1478
+ source_path=source_path,
1479
+ disposition=LinkDisposition.SKIPPED,
1480
+ reason="same-document-anchor",
1481
+ fragment=cleaned[1:] or None,
1482
+ )
1483
+ if "\0" in cleaned or "\\" in cleaned:
1484
+ return _link_result(
1485
+ raw_target=raw_target,
1486
+ source_path=source_path,
1487
+ disposition=LinkDisposition.INVALID,
1488
+ reason="forbidden-path-character",
1489
+ )
1490
+ if _WINDOWS_DRIVE_RE.match(cleaned):
1491
+ return _link_result(
1492
+ raw_target=raw_target,
1493
+ source_path=source_path,
1494
+ disposition=LinkDisposition.INVALID,
1495
+ reason="drive-qualified-target",
1496
+ )
1497
+ if cleaned.startswith("//"):
1498
+ return _link_result(
1499
+ raw_target=raw_target,
1500
+ source_path=source_path,
1501
+ disposition=LinkDisposition.SKIPPED,
1502
+ reason="network-url",
1503
+ )
1504
+ if _URI_SCHEME_RE.match(cleaned):
1505
+ return _link_result(
1506
+ raw_target=raw_target,
1507
+ source_path=source_path,
1508
+ disposition=LinkDisposition.SKIPPED,
1509
+ reason="external-uri-scheme",
1510
+ )
1511
+
1512
+ path_and_query, fragment_separator, fragment = cleaned.partition("#")
1513
+ path_text, query_separator, query = path_and_query.partition("?")
1514
+ fragment_value = fragment if fragment_separator else None
1515
+ query_value = query if query_separator else None
1516
+ if not path_text:
1517
+ return _link_result(
1518
+ raw_target=raw_target,
1519
+ source_path=source_path,
1520
+ disposition=LinkDisposition.SKIPPED,
1521
+ reason="empty-local-path",
1522
+ query=query_value,
1523
+ fragment=fragment_value,
1524
+ )
1525
+ if _INVALID_PERCENT_RE.search(path_text):
1526
+ return _link_result(
1527
+ raw_target=raw_target,
1528
+ source_path=source_path,
1529
+ disposition=LinkDisposition.INVALID,
1530
+ reason="malformed-percent-escape",
1531
+ query=query_value,
1532
+ fragment=fragment_value,
1533
+ )
1534
+
1535
+ try:
1536
+ decoded = unquote(path_text, encoding="utf-8", errors="strict")
1537
+ except UnicodeDecodeError:
1538
+ return _link_result(
1539
+ raw_target=raw_target,
1540
+ source_path=source_path,
1541
+ disposition=LinkDisposition.INVALID,
1542
+ reason="invalid-utf8-percent-escape",
1543
+ query=query_value,
1544
+ fragment=fragment_value,
1545
+ )
1546
+
1547
+ if "\0" in decoded or "\\" in decoded:
1548
+ return _link_result(
1549
+ raw_target=raw_target,
1550
+ source_path=source_path,
1551
+ disposition=LinkDisposition.INVALID,
1552
+ reason="forbidden-decoded-character",
1553
+ query=query_value,
1554
+ fragment=fragment_value,
1555
+ )
1556
+ if _WINDOWS_DRIVE_RE.match(decoded):
1557
+ return _link_result(
1558
+ raw_target=raw_target,
1559
+ source_path=source_path,
1560
+ disposition=LinkDisposition.INVALID,
1561
+ reason="drive-qualified-target",
1562
+ query=query_value,
1563
+ fragment=fragment_value,
1564
+ )
1565
+ if _URI_SCHEME_RE.match(decoded):
1566
+ return _link_result(
1567
+ raw_target=raw_target,
1568
+ source_path=source_path,
1569
+ disposition=LinkDisposition.SKIPPED,
1570
+ reason="external-uri-scheme",
1571
+ query=query_value,
1572
+ fragment=fragment_value,
1573
+ )
1574
+
1575
+ pure_target = PurePosixPath(decoded)
1576
+ if pure_target.is_absolute():
1577
+ return _link_result(
1578
+ raw_target=raw_target,
1579
+ source_path=source_path,
1580
+ disposition=LinkDisposition.INVALID,
1581
+ reason="absolute-local-target",
1582
+ query=query_value,
1583
+ fragment=fragment_value,
1584
+ )
1585
+ decoded_segments = decoded.split("/")
1586
+ if any(segment == "" for segment in decoded_segments):
1587
+ return _link_result(
1588
+ raw_target=raw_target,
1589
+ source_path=source_path,
1590
+ disposition=LinkDisposition.INVALID,
1591
+ reason="empty-local-path-segment",
1592
+ query=query_value,
1593
+ fragment=fragment_value,
1594
+ )
1595
+ try:
1596
+ for segment in decoded_segments:
1597
+ if segment not in (".", ".."):
1598
+ _validate_portable_path_segment(segment, decoded)
1599
+ except PathValidationError:
1600
+ return _link_result(
1601
+ raw_target=raw_target,
1602
+ source_path=source_path,
1603
+ disposition=LinkDisposition.INVALID,
1604
+ reason="non-portable-local-target",
1605
+ query=query_value,
1606
+ fragment=fragment_value,
1607
+ )
1608
+
1609
+ suffix = pure_target.suffix.casefold()
1610
+ if suffix in SOURCE_FILE_EXTENSIONS:
1611
+ return _link_result(
1612
+ raw_target=raw_target,
1613
+ source_path=source_path,
1614
+ disposition=LinkDisposition.SKIPPED,
1615
+ reason="source-file-reference",
1616
+ normalized_target=pure_target.as_posix(),
1617
+ query=query_value,
1618
+ fragment=fragment_value,
1619
+ )
1620
+ if not suffix:
1621
+ pure_target = PurePosixPath(pure_target.as_posix() + ".md")
1622
+ elif suffix != ".md" or pure_target.suffix != ".md":
1623
+ return _link_result(
1624
+ raw_target=raw_target,
1625
+ source_path=source_path,
1626
+ disposition=LinkDisposition.SKIPPED,
1627
+ reason="non-markdown-reference",
1628
+ normalized_target=pure_target.as_posix(),
1629
+ query=query_value,
1630
+ fragment=fragment_value,
1631
+ )
1632
+
1633
+ try:
1634
+ resolved = source_path.parent.joinpath(*pure_target.parts).resolve(strict=False)
1635
+ resolved.relative_to(root)
1636
+ except (OSError, RuntimeError, ValueError):
1637
+ return _link_result(
1638
+ raw_target=raw_target,
1639
+ source_path=source_path,
1640
+ disposition=LinkDisposition.INVALID,
1641
+ reason="target-outside-docs-root",
1642
+ normalized_target=pure_target.as_posix(),
1643
+ query=query_value,
1644
+ fragment=fragment_value,
1645
+ )
1646
+
1647
+ relative = resolved.relative_to(root).as_posix()
1648
+ try:
1649
+ validate_manifest_relative_path(relative)
1650
+ except PathValidationError:
1651
+ return _link_result(
1652
+ raw_target=raw_target,
1653
+ source_path=source_path,
1654
+ disposition=LinkDisposition.INVALID,
1655
+ reason="noncanonical-document-target",
1656
+ normalized_target=pure_target.as_posix(),
1657
+ query=query_value,
1658
+ fragment=fragment_value,
1659
+ )
1660
+
1661
+ return _link_result(
1662
+ raw_target=raw_target,
1663
+ source_path=source_path,
1664
+ disposition=LinkDisposition.LOCAL_DOCUMENT,
1665
+ reason="resolved-document" if resolved.is_file() else "missing-document",
1666
+ normalized_target=pure_target.as_posix(),
1667
+ project_relative_path=relative,
1668
+ resolved_path=resolved,
1669
+ exists=resolved.is_file(),
1670
+ query=query_value,
1671
+ fragment=fragment_value,
1672
+ )
1673
+
1674
+
1675
+ def _reference_label(value: str) -> str:
1676
+ return " ".join(value.split()).casefold()
1677
+
1678
+
1679
+ def _span_overlaps(span: tuple[int, int], occupied: Sequence[tuple[int, int]]) -> bool:
1680
+ return any(span[0] < end and start < span[1] for start, end in occupied)
1681
+
1682
+
1683
+ def parse_markdown_links(
1684
+ content: str,
1685
+ *,
1686
+ source_doc: PathLike,
1687
+ docs_root: PathLike,
1688
+ ) -> list[MarkdownLinkResult]:
1689
+ """Parse inline, reference-style, and HTML-anchor document links.
1690
+
1691
+ Reference labels follow CommonMark's whitespace folding and case-insensitive
1692
+ lookup. The first definition wins, matching CommonMark behavior.
1693
+ """
1694
+
1695
+ results: list[MarkdownLinkResult] = []
1696
+ occupied: list[tuple[int, int]] = []
1697
+ definitions: dict[str, str] = {}
1698
+ definition_spans: list[tuple[int, int]] = []
1699
+ for match in _MARKDOWN_REFERENCE_DEFINITION_RE.finditer(content):
1700
+ label = _reference_label(match.group(1))
1701
+ if label and label not in definitions:
1702
+ definitions[label] = match.group(2)
1703
+ definition_spans.append(match.span())
1704
+
1705
+ for match in _MARKDOWN_LINK_RE.finditer(content):
1706
+ result = resolve_markdown_target(
1707
+ match.group(2),
1708
+ source_doc=source_doc,
1709
+ docs_root=docs_root,
1710
+ )
1711
+ results.append(
1712
+ replace(
1713
+ result,
1714
+ text=match.group(1),
1715
+ span=match.span(),
1716
+ )
1717
+ )
1718
+ occupied.append(match.span())
1719
+
1720
+ for match in _MARKDOWN_REFERENCE_LINK_RE.finditer(content):
1721
+ if _span_overlaps(match.span(), occupied) or _span_overlaps(
1722
+ match.span(), definition_spans
1723
+ ):
1724
+ continue
1725
+ raw_label = match.group(2) or match.group(1)
1726
+ target = definitions.get(_reference_label(raw_label))
1727
+ if target is None:
1728
+ continue
1729
+ result = resolve_markdown_target(
1730
+ target,
1731
+ source_doc=source_doc,
1732
+ docs_root=docs_root,
1733
+ )
1734
+ results.append(replace(result, text=match.group(1), span=match.span()))
1735
+ occupied.append(match.span())
1736
+
1737
+ for match in _MARKDOWN_SHORTCUT_REFERENCE_RE.finditer(content):
1738
+ if _span_overlaps(match.span(), occupied) or _span_overlaps(
1739
+ match.span(), definition_spans
1740
+ ):
1741
+ continue
1742
+ target = definitions.get(_reference_label(match.group(1)))
1743
+ if target is None:
1744
+ continue
1745
+ result = resolve_markdown_target(
1746
+ target,
1747
+ source_doc=source_doc,
1748
+ docs_root=docs_root,
1749
+ )
1750
+ results.append(replace(result, text=match.group(1), span=match.span()))
1751
+ occupied.append(match.span())
1752
+
1753
+ for match in _HTML_HREF_RE.finditer(content):
1754
+ if _span_overlaps(match.span(), occupied):
1755
+ continue
1756
+ target = match.group(1) if match.group(1) is not None else match.group(2)
1757
+ result = resolve_markdown_target(
1758
+ target,
1759
+ source_doc=source_doc,
1760
+ docs_root=docs_root,
1761
+ )
1762
+ results.append(replace(result, text="", span=match.span()))
1763
+
1764
+ results.sort(key=lambda result: result.span or (0, 0))
1765
+ return results
1766
+
1767
+
1768
+ def read_markdown_links(
1769
+ source_doc: PathLike,
1770
+ docs_root: PathLike,
1771
+ ) -> list[MarkdownLinkResult]:
1772
+ """Contain, securely open, and parse one strict UTF-8 document."""
1773
+
1774
+ root, lexical_source = _source_document_path(source_doc, docs_root)
1775
+ relative_source = lexical_source.relative_to(root).as_posix()
1776
+ _, _, content = _read_project_document_bytes(root, relative_source)
1777
+ return parse_markdown_links(
1778
+ content,
1779
+ source_doc=lexical_source,
1780
+ docs_root=root,
1781
+ )
1782
+
1783
+
1784
+ def iter_local_document_links(
1785
+ links: Iterable[MarkdownLinkResult],
1786
+ ) -> Iterator[MarkdownLinkResult]:
1787
+ """Yield only safely resolved local document links."""
1788
+
1789
+ for link in links:
1790
+ if link.is_local_document:
1791
+ yield link
1792
+
1793
+
1794
+ def _logical_relative_document(
1795
+ path: PathLike,
1796
+ root: Path,
1797
+ *,
1798
+ must_exist: bool,
1799
+ ) -> str:
1800
+ raw = os.fspath(path)
1801
+ if not isinstance(raw, str):
1802
+ raise PathValidationError("document path must be text")
1803
+ candidate = Path(raw)
1804
+ if candidate.is_absolute():
1805
+ try:
1806
+ resolved = candidate.resolve(strict=must_exist)
1807
+ relative = resolved.relative_to(root).as_posix()
1808
+ except (OSError, RuntimeError, ValueError) as exc:
1809
+ raise PathValidationError(
1810
+ f"document is outside project_docs: {path}"
1811
+ ) from exc
1812
+ else:
1813
+ pure_path = validate_manifest_relative_path(raw)
1814
+ relative = resolve_manifest_document(
1815
+ root,
1816
+ pure_path,
1817
+ must_exist=must_exist,
1818
+ ).relative_path
1819
+ validate_manifest_relative_path(relative)
1820
+ return relative
1821
+
1822
+
1823
+ def compute_relative_doc_link(
1824
+ from_doc: PathLike,
1825
+ to_doc: PathLike,
1826
+ docs_root: PathLike,
1827
+ *,
1828
+ must_exist: bool = False,
1829
+ ) -> str:
1830
+ """Compute a safe POSIX link, including for documents not written yet."""
1831
+
1832
+ root = _resolved_docs_root(docs_root)
1833
+ source = PurePosixPath(
1834
+ _logical_relative_document(from_doc, root, must_exist=must_exist)
1835
+ )
1836
+ target = _logical_relative_document(to_doc, root, must_exist=must_exist)
1837
+ source_parent = source.parent.as_posix()
1838
+ return posixpath.relpath(target, source_parent if source_parent != "." else ".")
1839
+
1840
+
1841
+ def parse_last_synced_marker(content: str) -> str | None:
1842
+ """Extract the timestamp from the first complete Last synced marker.
1843
+
1844
+ The non-greedy marker match deliberately stops at the first ``-->`` so a
1845
+ historical duplicated suffix after the marker cannot contaminate the value.
1846
+ """
1847
+
1848
+ match = _LAST_SYNCED_RE.search(content)
1849
+ if match is None:
1850
+ return None
1851
+ first_segment = re.split(r"\s+by\s+", match.group(1).strip(), maxsplit=1)[0].strip()
1852
+ return first_segment or None
1853
+
1854
+
1855
+ def parse_document_metadata(
1856
+ content: str,
1857
+ relative_path: str | PurePosixPath,
1858
+ *,
1859
+ fallback_synced_at: str | None = None,
1860
+ ) -> DocumentMetadata:
1861
+ """Parse first H1 title, status section, and first Last synced marker."""
1862
+
1863
+ pure_path = validate_manifest_relative_path(relative_path)
1864
+ title_match = _TITLE_RE.search(content.lstrip(""))
1865
+ title = (
1866
+ title_match.group(1).strip()
1867
+ if title_match is not None
1868
+ else pure_path.with_suffix("").as_posix()
1869
+ )
1870
+
1871
+ status = "❓"
1872
+ status_match = _STATUS_SECTION_RE.search(content)
1873
+ if status_match is not None:
1874
+ body = status_match.group(1)
1875
+ for marker in _STATUS_MARKERS:
1876
+ if marker in body:
1877
+ status = marker
1878
+ break
1879
+
1880
+ synced_at = parse_last_synced_marker(content) or fallback_synced_at
1881
+ return DocumentMetadata(title=title, status=status, synced_at=synced_at)
1882
+
1883
+
1884
+ def _utc_now_iso() -> str:
1885
+ return datetime.now(timezone.utc).isoformat()
1886
+
1887
+
1888
+ def _parse_timestamp(value: Any, field: str) -> str:
1889
+ if not isinstance(value, str) or not value.strip():
1890
+ raise ManifestValidationError(f"{field} must be a non-empty ISO-8601 string")
1891
+ normalized = value.strip()
1892
+ candidate = normalized[:-1] + "+00:00" if normalized.endswith("Z") else normalized
1893
+ try:
1894
+ parsed = datetime.fromisoformat(candidate)
1895
+ except ValueError as exc:
1896
+ raise ManifestValidationError(
1897
+ f"{field} is not valid ISO-8601: {value!r}"
1898
+ ) from exc
1899
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
1900
+ raise ManifestValidationError(f"{field} must include a timezone: {value!r}")
1901
+ return normalized
1902
+
1903
+
1904
+ def _timestamp_or_none(value: Any) -> str | None:
1905
+ try:
1906
+ return _parse_timestamp(value, "timestamp")
1907
+ except ManifestValidationError:
1908
+ return None
1909
+
1910
+
1911
+ def _mtime_iso(path: Path) -> str:
1912
+ return datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()
1913
+
1914
+
1915
+ def _depth_counts(files: Sequence[Mapping[str, Any]]) -> dict[str, int]:
1916
+ counts: dict[str, int] = {}
1917
+ for entry in files:
1918
+ key = str(entry["depth"])
1919
+ counts[key] = counts.get(key, 0) + 1
1920
+ return dict(sorted(counts.items(), key=lambda item: int(item[0])))
1921
+
1922
+
1923
+ def compute_generation_id(files: Sequence[Mapping[str, Any]]) -> str:
1924
+ """Hash canonical, non-volatile document content metadata."""
1925
+
1926
+ fields = ("path", "depth", "title", "status", "bytes", "sha256")
1927
+ canonical_files: list[dict[str, Any]] = []
1928
+ for index, entry in enumerate(files):
1929
+ missing = [field for field in fields if field not in entry]
1930
+ if missing:
1931
+ raise ManifestValidationError(
1932
+ f"files[{index}] lacks generation fields: {', '.join(missing)}"
1933
+ )
1934
+ canonical_files.append({field: entry[field] for field in fields})
1935
+ canonical_files.sort(key=lambda entry: entry["path"])
1936
+ return sha256_bytes(_canonical_json_bytes({"files": canonical_files}))
1937
+
1938
+
1939
+ def discover_active_markdown_paths(docs_root: PathLike) -> list[str]:
1940
+ """Return the complete active Markdown set without following indirections."""
1941
+
1942
+ root = _resolved_docs_root(docs_root)
1943
+ relative_paths: list[str] = []
1944
+
1945
+ def visit(directory: Path) -> None:
1946
+ try:
1947
+ before = directory.lstat()
1948
+ if _is_stat_link_or_reparse(before) or not stat.S_ISDIR(before.st_mode):
1949
+ raise PathValidationError(
1950
+ f"active document directory is indirect or invalid: {directory}"
1951
+ )
1952
+ with os.scandir(directory) as iterator:
1953
+ entries = sorted(
1954
+ iterator,
1955
+ key=lambda item: (item.name.casefold(), item.name),
1956
+ )
1957
+ after = directory.lstat()
1958
+ except PathValidationError:
1959
+ raise
1960
+ except OSError as exc:
1961
+ raise PathValidationError(
1962
+ f"cannot securely enumerate active documents: {directory}"
1963
+ ) from exc
1964
+
1965
+ if _is_stat_link_or_reparse(after) or not _same_file_identity(
1966
+ before,
1967
+ after,
1968
+ ):
1969
+ raise PathValidationError(
1970
+ f"active document directory changed while scanning: {directory}"
1971
+ )
1972
+
1973
+ for item in entries:
1974
+ path = Path(item.path)
1975
+ try:
1976
+ item_stat = item.stat(follow_symlinks=False)
1977
+ indirect = _is_stat_link_or_reparse(item_stat)
1978
+ except OSError as exc:
1979
+ raise PathValidationError(
1980
+ f"active document path changed while scanning: {path}"
1981
+ ) from exc
1982
+ if indirect:
1983
+ raise PathValidationError(
1984
+ f"active document tree contains a symlink or reparse point: {path}"
1985
+ )
1986
+ if stat.S_ISDIR(item_stat.st_mode):
1987
+ is_root_quarantine = (
1988
+ directory == root
1989
+ and item.name.casefold() == QUARANTINE_DIRNAME.casefold()
1990
+ )
1991
+ if is_root_quarantine and item.name != QUARANTINE_DIRNAME:
1992
+ raise PathValidationError(
1993
+ "root quarantine directory must use canonical lowercase name: "
1994
+ f"{path}"
1995
+ )
1996
+ if not is_root_quarantine:
1997
+ visit(path)
1998
+ continue
1999
+ if not stat.S_ISREG(item_stat.st_mode):
2000
+ continue
2001
+ if path.suffix.casefold() == ".md" and path.suffix != ".md":
2002
+ raise PathValidationError(
2003
+ f"Markdown extension must use canonical lowercase '.md': {path}"
2004
+ )
2005
+ if path.suffix == ".md":
2006
+ relative_paths.append(path.relative_to(root).as_posix())
2007
+
2008
+ visit(root)
2009
+ ensure_unique_manifest_paths(relative_paths)
2010
+ return sorted(relative_paths)
2011
+
2012
+
2013
+ def _validate_manifest_document_set(root: Path, paths: Sequence[str]) -> None:
2014
+ """Require a verified manifest to cover the complete active Markdown set."""
2015
+
2016
+ active_paths = discover_active_markdown_paths(root)
2017
+ manifest_paths = set(paths)
2018
+ active_set = set(active_paths)
2019
+ if manifest_paths == active_set:
2020
+ return
2021
+
2022
+ manifest_by_folded = {path.casefold(): path for path in manifest_paths}
2023
+ active_by_folded = {path.casefold(): path for path in active_set}
2024
+ case_mismatches = sorted(
2025
+ f"{manifest_by_folded[key]!r} != {active_by_folded[key]!r}"
2026
+ for key in manifest_by_folded.keys() & active_by_folded.keys()
2027
+ if manifest_by_folded[key] != active_by_folded[key]
2028
+ )
2029
+ unregistered = sorted(active_set - manifest_paths)
2030
+ missing = sorted(manifest_paths - active_set)
2031
+ details: list[str] = []
2032
+ if unregistered:
2033
+ details.append(f"unregistered active documents={unregistered!r}")
2034
+ if missing:
2035
+ details.append(f"missing registered documents={missing!r}")
2036
+ if case_mismatches:
2037
+ details.append(f"case mismatches={case_mismatches!r}")
2038
+ raise ManifestFileMismatchError("document set mismatch: " + "; ".join(details))
2039
+
2040
+
2041
+ def _document_record(
2042
+ root: Path,
2043
+ relative_path: str,
2044
+ *,
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,
2049
+ ) -> dict[str, Any]:
2050
+ safe_path, raw, content = _read_project_document_bytes(root, relative_path)
2051
+ metadata = parse_document_metadata(
2052
+ content,
2053
+ relative_path,
2054
+ fallback_synced_at=fallback_synced_at,
2055
+ )
2056
+ synced_at = _parse_timestamp(
2057
+ metadata.synced_at,
2058
+ f"file {relative_path!r} synced_at",
2059
+ )
2060
+ file_sha256 = sha256_bytes(raw)
2061
+ record: dict[str, Any] = {
2062
+ "path": relative_path,
2063
+ "depth": safe_path.depth,
2064
+ "title": metadata.title,
2065
+ "status": metadata.status,
2066
+ "bytes": len(raw),
2067
+ "sha256": file_sha256,
2068
+ "synced_at": synced_at,
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
2086
+
2087
+
2088
+ def build_manifest(
2089
+ docs_root: PathLike,
2090
+ *,
2091
+ producer: Mapping[str, str] | None = None,
2092
+ last_synced: str | None = None,
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,
2097
+ ) -> dict[str, Any]:
2098
+ """Build a deterministic-order schema-v2 manifest from strict UTF-8 docs."""
2099
+
2100
+ root = _resolved_docs_root(docs_root)
2101
+ producer_value = dict(
2102
+ producer
2103
+ or {
2104
+ "name": DEFAULT_PRODUCER_NAME,
2105
+ "version": DEFAULT_PRODUCER_VERSION,
2106
+ }
2107
+ )
2108
+ for field in ("name", "version"):
2109
+ if not isinstance(producer_value.get(field), str) or not producer_value[field]:
2110
+ raise ManifestValidationError(
2111
+ f"producer.{field} must be a non-empty string"
2112
+ )
2113
+ effective_generator = (
2114
+ generator
2115
+ if generator is not None
2116
+ else f"{producer_value['name']}/{producer_value['version']}"
2117
+ )
2118
+
2119
+ synced_at = _parse_timestamp(last_synced or _utc_now_iso(), "last_synced")
2120
+ label = docs_root_label if docs_root_label is not None else root.name
2121
+ if not isinstance(label, str) or not label or "\0" in label:
2122
+ raise ManifestValidationError(
2123
+ "docs_root label must be a non-empty NUL-free string"
2124
+ )
2125
+
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
+ ]
2163
+ files.sort(key=lambda entry: entry["path"])
2164
+ manifest = {
2165
+ "schema_version": MANIFEST_SCHEMA_VERSION,
2166
+ "producer": producer_value,
2167
+ "generation_id": compute_generation_id(files),
2168
+ "docs_root": label,
2169
+ "files": files,
2170
+ "total": len(files),
2171
+ "depth_counts": _depth_counts(files),
2172
+ "last_synced": synced_at,
2173
+ }
2174
+ return validate_manifest_v2(
2175
+ manifest,
2176
+ root,
2177
+ verify_files=False,
2178
+ verify_complete_set=False,
2179
+ )
2180
+
2181
+
2182
+ def _require_mapping(value: Any, field: str) -> Mapping[str, Any]:
2183
+ if not isinstance(value, Mapping):
2184
+ raise ManifestSchemaError(f"{field} must be an object")
2185
+ return value
2186
+
2187
+
2188
+ def _require_nonempty_string(value: Any, field: str) -> str:
2189
+ if not isinstance(value, str) or not value:
2190
+ raise ManifestValidationError(f"{field} must be a non-empty string")
2191
+ return value
2192
+
2193
+
2194
+ def _require_integer(value: Any, field: str, *, minimum: int = 0) -> int:
2195
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
2196
+ raise ManifestValidationError(f"{field} must be an integer >= {minimum}")
2197
+ return value
2198
+
2199
+
2200
+ def _validate_depth_counts(value: Any, expected: Mapping[str, int]) -> None:
2201
+ mapping = _require_mapping(value, "depth_counts")
2202
+ normalized: dict[str, int] = {}
2203
+ for key, count in mapping.items():
2204
+ if not isinstance(key, str) or not re.fullmatch(r"0|[1-9][0-9]*", key):
2205
+ raise ManifestValidationError(
2206
+ "depth_counts keys must be canonical non-negative decimal strings"
2207
+ )
2208
+ normalized[key] = _require_integer(count, f"depth_counts[{key!r}]", minimum=1)
2209
+ if normalized != dict(expected):
2210
+ raise ManifestValidationError(
2211
+ f"depth_counts mismatch: expected {dict(expected)!r}, got {normalized!r}"
2212
+ )
2213
+
2214
+
2215
+ def _verify_single_file_v2(
2216
+ path: str,
2217
+ byte_count: int,
2218
+ digest: str,
2219
+ synced_at: str,
2220
+ title: str,
2221
+ status: str,
2222
+ root: Path,
2223
+ manifest_synced_at: str,
2224
+ ) -> None:
2225
+ safe_path, raw, content = _read_project_document_bytes(root, path)
2226
+ actual_digest = sha256_bytes(raw)
2227
+ if byte_count != len(raw):
2228
+ raise ManifestFileMismatchError(
2229
+ f"file size mismatch for {path!r}: manifest={byte_count}, actual={len(raw)}"
2230
+ )
2231
+ if digest != actual_digest:
2232
+ raise ManifestFileMismatchError(
2233
+ f"SHA-256 mismatch for {path!r}: manifest={digest}, actual={actual_digest}"
2234
+ )
2235
+ metadata = parse_document_metadata(
2236
+ content,
2237
+ path,
2238
+ fallback_synced_at=manifest_synced_at,
2239
+ )
2240
+ expected_synced_at = _parse_timestamp(
2241
+ metadata.synced_at,
2242
+ f"document {path!r} synced_at",
2243
+ )
2244
+ metadata_pairs = (
2245
+ ("title", title, metadata.title),
2246
+ ("status", status, metadata.status),
2247
+ ("synced_at", synced_at, expected_synced_at),
2248
+ )
2249
+ for field, manifest_value, document_value in metadata_pairs:
2250
+ if manifest_value != document_value:
2251
+ raise ManifestFileMismatchError(
2252
+ f"{field} mismatch for {path!r}: "
2253
+ f"manifest={manifest_value!r}, document={document_value!r}"
2254
+ )
2255
+
2256
+
2257
+ def validate_manifest_v2(
2258
+ manifest: Mapping[str, Any],
2259
+ docs_root: PathLike,
2260
+ *,
2261
+ verify_files: bool = True,
2262
+ verify_complete_set: bool = True,
2263
+ target_paths: Iterable[str] | None = None,
2264
+ ) -> dict[str, Any]:
2265
+ """Strictly validate a schema-v2 manifest and return an isolated copy."""
2266
+
2267
+ data = copy.deepcopy(dict(_require_mapping(manifest, "manifest")))
2268
+ schema_version = data.get("schema_version")
2269
+ if type(schema_version) is not int or schema_version != MANIFEST_SCHEMA_VERSION:
2270
+ raise ManifestSchemaError(
2271
+ f"expected schema_version={MANIFEST_SCHEMA_VERSION}, got {schema_version!r}"
2272
+ )
2273
+
2274
+ producer = _require_mapping(data.get("producer"), "producer")
2275
+ _require_nonempty_string(producer.get("name"), "producer.name")
2276
+ _require_nonempty_string(producer.get("version"), "producer.version")
2277
+ _require_nonempty_string(data.get("docs_root"), "docs_root")
2278
+ manifest_synced_at = _parse_timestamp(data.get("last_synced"), "last_synced")
2279
+
2280
+ generation_id = _require_nonempty_string(data.get("generation_id"), "generation_id")
2281
+ if _SHA256_RE.fullmatch(generation_id) is None:
2282
+ raise ManifestValidationError(
2283
+ "generation_id must be a lowercase SHA-256 digest"
2284
+ )
2285
+
2286
+ files_value = data.get("files")
2287
+ if not isinstance(files_value, list):
2288
+ raise ManifestSchemaError("files must be an array")
2289
+ files: list[dict[str, Any]] = []
2290
+ paths: list[str] = []
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
+ )
2297
+
2298
+ verify_tasks: list[tuple[str, int, str, str, str, str, Path, str]] = []
2299
+ for index, raw_entry in enumerate(files_value):
2300
+ entry = dict(_require_mapping(raw_entry, f"files[{index}]"))
2301
+ path = _require_nonempty_string(entry.get("path"), f"files[{index}].path")
2302
+ pure_path = validate_manifest_relative_path(path)
2303
+ paths.append(path)
2304
+
2305
+ depth = _require_integer(entry.get("depth"), f"files[{index}].depth")
2306
+ expected_depth = len(pure_path.parts) - 1
2307
+ if depth != expected_depth:
2308
+ raise ManifestValidationError(
2309
+ f"files[{index}].depth is {depth}, expected {expected_depth} from {path!r}"
2310
+ )
2311
+ title = _require_nonempty_string(entry.get("title"), f"files[{index}].title")
2312
+ status = _require_nonempty_string(entry.get("status"), f"files[{index}].status")
2313
+ if status not in _STATUS_MARKERS:
2314
+ raise ManifestValidationError(
2315
+ f"files[{index}].status must be one of {_STATUS_MARKERS!r}"
2316
+ )
2317
+ byte_count = _require_integer(entry.get("bytes"), f"files[{index}].bytes")
2318
+ digest = _require_nonempty_string(entry.get("sha256"), f"files[{index}].sha256")
2319
+ if _SHA256_RE.fullmatch(digest) is None:
2320
+ raise ManifestValidationError(
2321
+ f"files[{index}].sha256 must be a lowercase SHA-256 digest"
2322
+ )
2323
+ synced_at = _parse_timestamp(
2324
+ entry.get("synced_at"),
2325
+ f"files[{index}].synced_at",
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
+ )
2337
+
2338
+ if verify_files and (target_set is None or path in target_set):
2339
+ verify_tasks.append(
2340
+ (path, byte_count, digest, synced_at, title, status, root, manifest_synced_at)
2341
+ )
2342
+ elif target_set is None:
2343
+ resolve_manifest_document(root, path, must_exist=False)
2344
+ files.append(entry)
2345
+
2346
+ if verify_files and verify_tasks:
2347
+ if len(verify_tasks) > 1:
2348
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
2349
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
2350
+ list(executor.map(lambda t: _verify_single_file_v2(*t), verify_tasks))
2351
+ else:
2352
+ for task in verify_tasks:
2353
+ _verify_single_file_v2(*task)
2354
+
2355
+ ensure_unique_manifest_paths(paths)
2356
+ if verify_files and verify_complete_set:
2357
+ _validate_manifest_document_set(root, paths)
2358
+ expected_order = sorted(paths)
2359
+ if paths != expected_order:
2360
+ raise ManifestValidationError("files must be sorted by path")
2361
+
2362
+ total = _require_integer(data.get("total"), "total")
2363
+ if total != len(files):
2364
+ raise ManifestValidationError(
2365
+ f"total mismatch: manifest={total}, files={len(files)}"
2366
+ )
2367
+ expected_depth_counts = _depth_counts(files)
2368
+ _validate_depth_counts(data.get("depth_counts"), expected_depth_counts)
2369
+
2370
+ expected_generation = compute_generation_id(files)
2371
+ if generation_id != expected_generation:
2372
+ raise ManifestValidationError(
2373
+ f"generation_id mismatch: manifest={generation_id}, expected={expected_generation}"
2374
+ )
2375
+ return data
2376
+
2377
+
2378
+ def _normalize_manifest_v1(
2379
+ manifest: Mapping[str, Any],
2380
+ docs_root: PathLike,
2381
+ *,
2382
+ verify_complete_set: bool = True,
2383
+ ) -> dict[str, Any]:
2384
+ data = copy.deepcopy(dict(_require_mapping(manifest, "manifest")))
2385
+ files_value = data.get("files")
2386
+ if not isinstance(files_value, list):
2387
+ raise ManifestSchemaError("v1 files must be an array")
2388
+
2389
+ warnings.warn(
2390
+ "manifest v1 depth values are untrusted and were recomputed in memory; "
2391
+ "the source manifest was not rewritten",
2392
+ LegacyManifestWarning,
2393
+ stacklevel=3,
2394
+ )
2395
+
2396
+ root = _resolved_docs_root(docs_root)
2397
+ top_synced_at = _timestamp_or_none(data.get("last_synced"))
2398
+ raw_paths: list[str] = []
2399
+ entries: list[dict[str, Any]] = []
2400
+
2401
+ for index, raw_entry in enumerate(files_value):
2402
+ entry = dict(_require_mapping(raw_entry, f"files[{index}]"))
2403
+ path = _require_nonempty_string(entry.get("path"), f"files[{index}].path")
2404
+ raw_paths.append(path)
2405
+ safe_path, raw, content = _read_project_document_bytes(root, path)
2406
+ fallback = top_synced_at or _mtime_iso(safe_path.resolved_path)
2407
+ metadata = parse_document_metadata(content, path, fallback_synced_at=fallback)
2408
+
2409
+ title = entry.get("title")
2410
+ status = entry.get("status")
2411
+ entry.update(
2412
+ {
2413
+ "path": path,
2414
+ "depth": safe_path.depth,
2415
+ "title": title if isinstance(title, str) and title else metadata.title,
2416
+ "status": (
2417
+ status if isinstance(status, str) and status else metadata.status
2418
+ ),
2419
+ "bytes": len(raw),
2420
+ "sha256": sha256_bytes(raw),
2421
+ "synced_at": _parse_timestamp(
2422
+ metadata.synced_at,
2423
+ f"files[{index}].synced_at",
2424
+ ),
2425
+ }
2426
+ )
2427
+ entries.append(entry)
2428
+
2429
+ ensure_unique_manifest_paths(raw_paths)
2430
+ if verify_complete_set:
2431
+ _validate_manifest_document_set(root, raw_paths)
2432
+ entries.sort(key=lambda entry: entry["path"])
2433
+ data["schema_version"] = 1
2434
+ data["files"] = entries
2435
+ data["total"] = len(entries)
2436
+ data["depth_counts"] = _depth_counts(entries)
2437
+ data.setdefault("docs_root", root.name)
2438
+ if top_synced_at is not None:
2439
+ data["last_synced"] = top_synced_at
2440
+ return data
2441
+
2442
+
2443
+ def validate_manifest(
2444
+ manifest: Mapping[str, Any],
2445
+ docs_root: PathLike,
2446
+ *,
2447
+ verify_files: bool = True,
2448
+ verify_complete_set: bool = True,
2449
+ target_paths: Iterable[str] | None = None,
2450
+ ) -> dict[str, Any]:
2451
+ """Validate v2 or normalize legacy v1 without writing it back."""
2452
+
2453
+ mapping = _require_mapping(manifest, "manifest")
2454
+ if "schema_version" not in mapping:
2455
+ return _normalize_manifest_v1(
2456
+ mapping,
2457
+ docs_root,
2458
+ verify_complete_set=verify_complete_set,
2459
+ )
2460
+
2461
+ schema_version = mapping.get("schema_version")
2462
+ if type(schema_version) is int and schema_version == 1:
2463
+ return _normalize_manifest_v1(
2464
+ mapping,
2465
+ docs_root,
2466
+ verify_complete_set=verify_complete_set,
2467
+ )
2468
+ if type(schema_version) is int and schema_version == MANIFEST_SCHEMA_VERSION:
2469
+ return validate_manifest_v2(
2470
+ mapping,
2471
+ docs_root,
2472
+ verify_files=verify_files,
2473
+ verify_complete_set=verify_complete_set,
2474
+ target_paths=target_paths,
2475
+ )
2476
+ raise ManifestSchemaError(
2477
+ f"unsupported manifest schema_version: {schema_version!r}"
2478
+ )
2479
+
2480
+
2481
+ def _manifest_location(
2482
+ manifest_path_or_root: PathLike,
2483
+ docs_root: PathLike | None,
2484
+ ) -> tuple[Path, Path]:
2485
+ supplied = Path(manifest_path_or_root)
2486
+ if supplied.is_dir():
2487
+ manifest_path = supplied / MANIFEST_FILENAME
2488
+ root = supplied
2489
+ else:
2490
+ manifest_path = supplied
2491
+ root = Path(docs_root) if docs_root is not None else supplied.parent
2492
+ return manifest_path, root
2493
+
2494
+
2495
+ def load_manifest(
2496
+ manifest_path_or_root: PathLike,
2497
+ *,
2498
+ docs_root: PathLike | None = None,
2499
+ verify_files: bool = True,
2500
+ verify_complete_set: bool = True,
2501
+ target_paths: Iterable[str] | None = None,
2502
+ ) -> dict[str, Any]:
2503
+ """Strictly load and validate ``_manifest.json`` or a supplied JSON path."""
2504
+
2505
+ manifest_path, root = _manifest_location(manifest_path_or_root, docs_root)
2506
+ value = read_json_strict(manifest_path)
2507
+ if not isinstance(value, Mapping):
2508
+ raise ManifestSchemaError("manifest JSON root must be an object")
2509
+ return validate_manifest(
2510
+ value,
2511
+ root,
2512
+ verify_files=verify_files,
2513
+ verify_complete_set=verify_complete_set,
2514
+ target_paths=target_paths,
2515
+ )
2516
+
2517
+
2518
+ def write_manifest(
2519
+ manifest_path_or_root: PathLike,
2520
+ manifest: Mapping[str, Any],
2521
+ *,
2522
+ timeout: float | None = 10.0,
2523
+ use_lock: bool = True,
2524
+ ) -> Path:
2525
+ """Atomically write a manifest, serializing concurrent writers by default."""
2526
+
2527
+ supplied = Path(manifest_path_or_root)
2528
+ manifest_path = supplied / MANIFEST_FILENAME if supplied.is_dir() else supplied
2529
+ if not use_lock:
2530
+ return atomic_write_json(manifest_path, dict(manifest))
2531
+ lock_path = manifest_path.with_name(manifest_path.name + ".lock")
2532
+ project_root = manifest_path.parent.resolve(strict=True).parent
2533
+ with project_sync_lock(project_root, timeout=timeout):
2534
+ with exclusive_lock(lock_path, timeout=timeout):
2535
+ return atomic_write_json(manifest_path, dict(manifest))
2536
+
2537
+
2538
+ def build_and_write_manifest(
2539
+ docs_root: PathLike,
2540
+ *,
2541
+ manifest_path: PathLike | None = None,
2542
+ producer: Mapping[str, str] | None = None,
2543
+ last_synced: str | None = None,
2544
+ docs_root_label: str | None = None,
2545
+ timeout: float | None = 10.0,
2546
+ ) -> dict[str, Any]:
2547
+ """Lock the complete schema-v2 snapshot-and-replace transaction."""
2548
+
2549
+ supplied = Path(manifest_path or Path(docs_root) / MANIFEST_FILENAME)
2550
+ destination = supplied / MANIFEST_FILENAME if supplied.is_dir() else supplied
2551
+ lock_path = destination.with_name(destination.name + ".lock")
2552
+ project_root = Path(docs_root).resolve(strict=True).parent
2553
+ with project_sync_lock(project_root, timeout=timeout):
2554
+ with exclusive_lock(lock_path, timeout=timeout):
2555
+ manifest = build_manifest(
2556
+ docs_root,
2557
+ producer=producer,
2558
+ last_synced=last_synced,
2559
+ docs_root_label=docs_root_label,
2560
+ )
2561
+ atomic_write_json(destination, manifest)
2562
+ return manifest
2563
+
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
+
2662
+ __all__ = [
2663
+ "AtomicWriteError",
2664
+ "DEFAULT_PRODUCER_NAME",
2665
+ "DEFAULT_PRODUCER_VERSION",
2666
+ "DOC_CONTRACT_VERSION",
2667
+ "DocumentMetadata",
2668
+ "ExclusiveFileLock",
2669
+ "JsonContractError",
2670
+ "LegacyManifestWarning",
2671
+ "LinkDisposition",
2672
+ "LinkResolutionError",
2673
+ "LockError",
2674
+ "LockTimeoutError",
2675
+ "MANIFEST_FILENAME",
2676
+ "MANIFEST_SCHEMA_VERSION",
2677
+ "ManifestError",
2678
+ "ManifestFileMismatchError",
2679
+ "ManifestSchemaError",
2680
+ "ManifestValidationError",
2681
+ "MarkdownLinkResult",
2682
+ "PathConflictError",
2683
+ "PathValidationError",
2684
+ "ProjectDocsContractError",
2685
+ "QUARANTINE_DIRNAME",
2686
+ "SOURCE_FILE_EXTENSIONS",
2687
+ "SafeManifestPath",
2688
+ "StrictUtf8Error",
2689
+ "atomic_write_json",
2690
+ "atomic_write_utf8",
2691
+ "build_and_write_manifest",
2692
+ "build_manifest",
2693
+ "compute_generation_id",
2694
+ "compute_relative_doc_link",
2695
+ "configure_stdio_utf8",
2696
+ "discover_active_markdown_paths",
2697
+ "ensure_unique_manifest_paths",
2698
+ "exclusive_file_lock",
2699
+ "exclusive_lock",
2700
+ "iter_local_document_links",
2701
+ "load_manifest",
2702
+ "manifest_path_depth",
2703
+ "migrate_manifest",
2704
+ "parse_document_metadata",
2705
+ "parse_json_strict",
2706
+ "parse_last_synced_marker",
2707
+ "parse_markdown_links",
2708
+ "project_sync_lock",
2709
+ "project_sync_lock_path",
2710
+ "read_json_strict",
2711
+ "read_markdown_links",
2712
+ "read_project_document",
2713
+ "read_utf8",
2714
+ "resolve_docs_root",
2715
+ "resolve_manifest_document",
2716
+ "resolve_markdown_target",
2717
+ "sha256_bytes",
2718
+ "sha256_file",
2719
+ "stable_json_dumps",
2720
+ "validate_manifest",
2721
+ "validate_manifest_paths",
2722
+ "validate_manifest_relative_path",
2723
+ "validate_manifest_v2",
2724
+ "write_manifest",
2725
+ ]