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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +290 -272
  2. package/README.zh-CN.md +258 -240
  3. package/package.json +6 -2
  4. package/skills/proj-doc-builder/SKILL.md +97 -35
  5. package/skills/proj-doc-builder/references/audit_script.md +103 -96
  6. package/skills/proj-doc-builder/references/batch-generation.md +55 -0
  7. package/skills/proj-doc-builder/references/checklist.md +20 -10
  8. package/skills/proj-doc-builder/references/exclusions.md +1 -1
  9. package/skills/proj-doc-builder/references/linking.md +83 -83
  10. package/skills/proj-doc-builder/references/templates.md +57 -17
  11. package/skills/proj-doc-builder/tests/claims.json +76 -0
  12. package/skills/proj-doc-builder/tests/conftest.py +17 -5
  13. package/skills/proj-doc-builder/tests/test_claims_registry.py +81 -0
  14. package/skills/proj-doc-builder/tests/test_e2e_fresh_project.py +156 -0
  15. package/skills/proj-doc-builder/tests/test_load_docs.py +353 -248
  16. package/skills/proj-doc-builder/tests/test_project_docs_contract.py +32 -1
  17. package/skills/proj-doc-builder/tests/test_scan_dirs.py +1 -1
  18. package/skills/proj-doc-builder/tests/test_stage1_stage2_upgrades.py +395 -0
  19. package/skills/proj-doc-builder/tests/test_sync_project_docs.py +2169 -2169
  20. package/skills/proj-doc-builder/tests/test_v41_upgrades.py +614 -0
  21. package/skills/proj-doc-builder/tests/test_v42_upgrades.py +422 -0
  22. package/skills/proj-doc-builder/tests/test_v43_upgrades.py +198 -0
  23. package/skills/proj-doc-builder/tests/test_v44_upgrades.py +361 -0
  24. package/skills/proj-doc-builder/tests/test_v45_upgrades.py +212 -0
  25. package/skills/proj-doc-builder/tests/test_validate_doc.py +172 -15
  26. package/skills/proj-doc-builder/tools/_paths.py +39 -0
  27. package/skills/proj-doc-builder/tools/{claude_doc_index.py → core/claude_doc_index.py} +504 -298
  28. package/skills/proj-doc-builder/tools/{compute_link.py → core/compute_link.py} +239 -233
  29. package/skills/proj-doc-builder/tools/core/proj_doc_config.py +460 -0
  30. package/skills/proj-doc-builder/tools/{project_docs_contract.py → core/project_docs_contract.py} +460 -53
  31. package/skills/proj-doc-builder/tools/phase4/__init__.py +31 -6
  32. package/skills/proj-doc-builder/tools/phase4/cas_storage.py +11 -4
  33. package/skills/proj-doc-builder/tools/phase4/engine.py +17 -2
  34. package/skills/proj-doc-builder/tools/phase4/journal.py +15 -8
  35. package/skills/proj-doc-builder/tools/phase4/platform_handles.py +12 -5
  36. package/skills/proj-doc-builder/tools/phase4_exit.py +153 -47
  37. package/skills/proj-doc-builder/tools/pipeline/gen_docs_from_scaffold.py +789 -0
  38. package/skills/proj-doc-builder/tools/{sync_project_docs.py → pipeline/sync_project_docs.py} +5531 -3639
  39. package/skills/proj-doc-builder/tools/{load_docs.py → reader/load_docs.py} +654 -380
  40. package/skills/proj-doc-builder/tools/{link_check.py → scan/link_check.py} +203 -152
  41. package/skills/proj-doc-builder/tools/{normalize_markers.py → scan/normalize_markers.py} +211 -205
  42. package/skills/proj-doc-builder/tools/{scan_dirs.py → scan/scan_dirs.py} +2735 -2405
  43. package/skills/proj-doc-builder/tools/{validate_doc.py → validate/validate_doc.py} +1911 -1299
  44. package/skills/proj-doc-builder/tests/__pycache__/conftest.cpython-314-pytest-9.0.3.pyc +0 -0
  45. package/skills/proj-doc-builder/tests/__pycache__/test_claude_doc_index.cpython-314-pytest-9.0.3.pyc +0 -0
  46. package/skills/proj-doc-builder/tests/__pycache__/test_link_tools.cpython-314-pytest-9.0.3.pyc +0 -0
  47. package/skills/proj-doc-builder/tests/__pycache__/test_load_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  48. package/skills/proj-doc-builder/tests/__pycache__/test_normalize_markers.cpython-314-pytest-9.0.3.pyc +0 -0
  49. package/skills/proj-doc-builder/tests/__pycache__/test_phase4_exit.cpython-314-pytest-9.0.3.pyc +0 -0
  50. package/skills/proj-doc-builder/tests/__pycache__/test_project_docs_contract.cpython-314-pytest-9.0.3.pyc +0 -0
  51. package/skills/proj-doc-builder/tests/__pycache__/test_scan_dirs.cpython-314-pytest-9.0.3.pyc +0 -0
  52. package/skills/proj-doc-builder/tests/__pycache__/test_sync_project_docs.cpython-314-pytest-9.0.3.pyc +0 -0
  53. package/skills/proj-doc-builder/tools/__pycache__/claude_doc_index.cpython-314.pyc +0 -0
  54. package/skills/proj-doc-builder/tools/__pycache__/compute_link.cpython-314.pyc +0 -0
  55. package/skills/proj-doc-builder/tools/__pycache__/link_check.cpython-314.pyc +0 -0
  56. package/skills/proj-doc-builder/tools/__pycache__/load_docs.cpython-314.pyc +0 -0
  57. package/skills/proj-doc-builder/tools/__pycache__/normalize_markers.cpython-314.pyc +0 -0
  58. package/skills/proj-doc-builder/tools/__pycache__/phase4_exit.cpython-314.pyc +0 -0
  59. package/skills/proj-doc-builder/tools/__pycache__/project_docs_contract.cpython-314.pyc +0 -0
  60. package/skills/proj-doc-builder/tools/__pycache__/scan_dirs.cpython-314.pyc +0 -0
  61. package/skills/proj-doc-builder/tools/__pycache__/sync_project_docs.cpython-314.pyc +0 -0
@@ -12,7 +12,6 @@ from __future__ import annotations
12
12
 
13
13
  import phase4_exit as _core
14
14
 
15
- # Re-export core constants, classes, and entrypoints
16
15
  EXIT_OK = _core.EXIT_OK
17
16
  EXIT_REFUSED = _core.EXIT_REFUSED
18
17
  EXIT_OPERATIONAL_FAILURE = _core.EXIT_OPERATIONAL_FAILURE
@@ -23,18 +22,38 @@ RECEIPT_FILENAME = _core.RECEIPT_FILENAME
23
22
  PAYLOAD_DIRNAME = _core.PAYLOAD_DIRNAME
24
23
  QUARANTINE_REASON = _core.QUARANTINE_REASON
25
24
 
26
- Phase4Error = _core.Phase4Error
27
25
  Phase4Refusal = _core.Phase4Refusal
28
26
  Phase4OperationalError = _core.Phase4OperationalError
27
+ Phase4Error = _core.Phase4Refusal
29
28
  ReceiptRecord = _core.ReceiptRecord
30
- ProjectAnalysis = _core.ProjectAnalysis
29
+ Analysis = _core.Analysis
30
+ ProjectAnalysis = _core.Analysis
31
+ SourceInventory = _core.SourceInventory
31
32
 
32
33
  analyze_project = _core.analyze_project
33
- quarantine_candidates = _core.quarantine_candidates
34
+ analyze_snapshot = _core.analyze_snapshot
35
+ report_project = _core.report_project
36
+ apply_quarantine = _core.apply_quarantine
37
+ quarantine_candidates = _core.apply_quarantine
34
38
  restore_receipt = _core.restore_receipt
35
- recover_pending_transactions = _core.recover_pending_transactions
39
+ pending_recovery_status = _core.pending_recovery_status
40
+ # ``_recover_pending_transaction`` is a private implementation name; expose it
41
+ # as an explicit alias so a rename in ``phase4_exit`` fails loudly at import
42
+ # instead of silently binding the alias to ``None`` (which would make
43
+ # ``--recover`` a no-op that reports nothing).
44
+ recover_pending_transactions = _core._recover_pending_transaction
36
45
  main = _core.main
37
46
 
47
+ # Drift guard: every private name the facade re-exports must still exist on
48
+ # ``phase4_exit``. ``getattr(..., None)`` aliases in the submodules silently
49
+ # become ``None`` on rename, so we assert here once at package import.
50
+ assert hasattr(_core, "_recover_pending_transaction"), (
51
+ "phase4 facade drifted from phase4_exit; missing: "
52
+ + ", ".join(
53
+ n for n in ("_recover_pending_transaction",) if not hasattr(_core, n)
54
+ )
55
+ )
56
+
38
57
  __all__ = [
39
58
  "EXIT_OK",
40
59
  "EXIT_REFUSED",
@@ -44,14 +63,20 @@ __all__ = [
44
63
  "RECEIPT_FILENAME",
45
64
  "PAYLOAD_DIRNAME",
46
65
  "QUARANTINE_REASON",
47
- "Phase4Error",
48
66
  "Phase4Refusal",
49
67
  "Phase4OperationalError",
68
+ "Phase4Error",
50
69
  "ReceiptRecord",
70
+ "Analysis",
51
71
  "ProjectAnalysis",
72
+ "SourceInventory",
52
73
  "analyze_project",
74
+ "analyze_snapshot",
75
+ "report_project",
76
+ "apply_quarantine",
53
77
  "quarantine_candidates",
54
78
  "restore_receipt",
79
+ "pending_recovery_status",
55
80
  "recover_pending_transactions",
56
81
  "main",
57
82
  ]
@@ -5,10 +5,10 @@ from __future__ import annotations
5
5
 
6
6
  import phase4_exit as _core
7
7
 
8
- text_snapshot = getattr(_core, "_text_snapshot", None)
9
- write_exclusive_snapshot = getattr(_core, "_write_exclusive_snapshot", None)
10
- validate_manifest_snapshot = getattr(_core, "_validate_manifest_snapshot", None)
11
- require_receipt_closed_state = getattr(_core, "_require_receipt_closed_state", None)
8
+ text_snapshot = _core._text_snapshot
9
+ write_exclusive_snapshot = _core._write_exclusive_snapshot
10
+ validate_manifest_snapshot = _core._validate_manifest_snapshot
11
+ require_receipt_closed_state = _core._require_receipt_closed_state
12
12
 
13
13
  __all__ = [
14
14
  "text_snapshot",
@@ -16,3 +16,10 @@ __all__ = [
16
16
  "validate_manifest_snapshot",
17
17
  "require_receipt_closed_state",
18
18
  ]
19
+
20
+ # Fail at import time if a private name the facade exposes was renamed
21
+ # or removed from ``phase4_exit`` — a silent ``None`` alias would turn
22
+ # recovery, journaling and fsync into no-ops that report nothing.
23
+ assert hasattr(_core, '_text_snapshot') and hasattr(_core, '_write_exclusive_snapshot') and hasattr(_core, '_validate_manifest_snapshot') and hasattr(_core, '_require_receipt_closed_state'), (
24
+ "phase4 facade drifted from phase4_exit; missing: " + ", ".join(n for n in ['_text_snapshot', '_write_exclusive_snapshot', '_validate_manifest_snapshot', '_require_receipt_closed_state'] if not hasattr(_core, n))
25
+ )
@@ -6,15 +6,30 @@ from __future__ import annotations
6
6
  import phase4_exit as _core
7
7
 
8
8
  analyze_project = _core.analyze_project
9
- quarantine_candidates = _core.quarantine_candidates
9
+ analyze_snapshot = _core.analyze_snapshot
10
+ report_project = _core.report_project
11
+ apply_quarantine = _core.apply_quarantine
12
+ quarantine_candidates = _core.apply_quarantine
10
13
  restore_receipt = _core.restore_receipt
11
- recover_pending_transactions = _core.recover_pending_transactions
14
+ pending_recovery_status = _core.pending_recovery_status
15
+ recover_pending_transactions = _core._recover_pending_transaction
12
16
  main = _core.main
13
17
 
14
18
  __all__ = [
15
19
  "analyze_project",
20
+ "analyze_snapshot",
21
+ "report_project",
22
+ "apply_quarantine",
16
23
  "quarantine_candidates",
17
24
  "restore_receipt",
25
+ "pending_recovery_status",
18
26
  "recover_pending_transactions",
19
27
  "main",
20
28
  ]
29
+
30
+ # Fail at import time if a private name the facade exposes was renamed
31
+ # or removed from ``phase4_exit`` — a silent ``None`` alias would turn
32
+ # recovery, journaling and fsync into no-ops that report nothing.
33
+ assert hasattr(_core, '_recover_pending_transaction'), (
34
+ "phase4 facade drifted from phase4_exit; missing: " + ", ".join(n for n in ['_recover_pending_transaction'] if not hasattr(_core, n))
35
+ )
@@ -5,18 +5,25 @@ from __future__ import annotations
5
5
 
6
6
  import phase4_exit as _core
7
7
 
8
- transaction_fault = getattr(_core, "_transaction_fault", None)
9
- new_transaction_id = getattr(_core, "_new_transaction_id", None)
10
- journal_base = getattr(_core, "_journal_base", None)
11
- write_transaction_journal = getattr(_core, "_write_transaction_journal", None)
12
- clear_transaction_journal = getattr(_core, "_clear_transaction_journal", None)
13
- recover_single_transaction = getattr(_core, "_recover_single_transaction", None)
8
+ transaction_fault = _core._transaction_fault
9
+ new_transaction_id = _core._new_transaction_id
10
+ pending_transaction = _core._pending_transaction
11
+ clear_transaction_journal = _core._clear_transaction_journal
12
+ recover_pending_transaction = _core._recover_pending_transaction
13
+ recover_single_transaction = recover_pending_transaction
14
14
 
15
15
  __all__ = [
16
16
  "transaction_fault",
17
17
  "new_transaction_id",
18
- "journal_base",
19
- "write_transaction_journal",
18
+ "pending_transaction",
20
19
  "clear_transaction_journal",
20
+ "recover_pending_transaction",
21
21
  "recover_single_transaction",
22
22
  ]
23
+
24
+ # Fail at import time if a private name the facade exposes was renamed
25
+ # or removed from ``phase4_exit`` — a silent ``None`` alias would turn
26
+ # recovery, journaling and fsync into no-ops that report nothing.
27
+ assert hasattr(_core, '_transaction_fault') and hasattr(_core, '_new_transaction_id') and hasattr(_core, '_pending_transaction') and hasattr(_core, '_clear_transaction_journal') and hasattr(_core, '_recover_pending_transaction'), (
28
+ "phase4 facade drifted from phase4_exit; missing: " + ", ".join(n for n in ['_transaction_fault', '_new_transaction_id', '_pending_transaction', '_clear_transaction_journal', '_recover_pending_transaction'] if not hasattr(_core, n))
29
+ )
@@ -5,11 +5,11 @@ from __future__ import annotations
5
5
 
6
6
  import phase4_exit as _core
7
7
 
8
- fsync_directory = getattr(_core, "_fsync_directory", None)
9
- fsync_directory_windows = getattr(_core, "_fsync_directory_windows", None)
10
- identity_from_stat = getattr(_core, "_identity_from_stat", None)
11
- read_stable_regular_fd = getattr(_core, "_read_stable_regular_fd", None)
12
- rename_no_replace = getattr(_core, "_rename_no_replace", None)
8
+ fsync_directory = _core._fsync_directory
9
+ fsync_directory_windows = _core._fsync_directory_windows
10
+ identity_from_stat = _core._identity_from_stat
11
+ read_stable_regular_fd = _core._read_stable_regular_fd
12
+ rename_no_replace = _core._rename_no_replace
13
13
 
14
14
  __all__ = [
15
15
  "fsync_directory",
@@ -18,3 +18,10 @@ __all__ = [
18
18
  "read_stable_regular_fd",
19
19
  "rename_no_replace",
20
20
  ]
21
+
22
+ # Fail at import time if a private name the facade exposes was renamed
23
+ # or removed from ``phase4_exit`` — a silent ``None`` alias would turn
24
+ # recovery, journaling and fsync into no-ops that report nothing.
25
+ assert hasattr(_core, '_fsync_directory') and hasattr(_core, '_fsync_directory_windows') and hasattr(_core, '_identity_from_stat') and hasattr(_core, '_read_stable_regular_fd') and hasattr(_core, '_rename_no_replace'), (
26
+ "phase4 facade drifted from phase4_exit; missing: " + ", ".join(n for n in ['_fsync_directory', '_fsync_directory_windows', '_identity_from_stat', '_read_stable_regular_fd', '_rename_no_replace'] if not hasattr(_core, n))
27
+ )
@@ -7,14 +7,20 @@ Filesystem changes require either ``--apply`` (quarantine only) or
7
7
  """
8
8
 
9
9
  from __future__ import annotations
10
+ import sys as _bootstrap_sys
11
+ from pathlib import Path as _bootstrap_path
12
+ _bootstrap_sys.dont_write_bytecode = True
13
+ _bootstrap_sys.path.insert(0, str(_bootstrap_path(__file__).resolve().parent))
14
+ import _paths # noqa: E402
15
+ _paths.install()
10
16
 
11
17
  import argparse
18
+ import concurrent.futures
12
19
  import copy
13
20
  import ctypes
14
21
  import errno
15
22
  import os
16
23
  import re
17
- import shutil
18
24
  import stat
19
25
  import sys
20
26
  import time
@@ -27,6 +33,7 @@ from pathlib import Path, PurePosixPath
27
33
  from typing import Any, Callable, Mapping, Sequence
28
34
 
29
35
  import claude_doc_index
36
+ import proj_doc_config
30
37
  import project_docs_contract as contract
31
38
 
32
39
  AUTO_MARKER = "<!-- AUTO-GENERATED v3.0: folder-doc START -->"
@@ -67,28 +74,7 @@ def directory_fsync_degraded() -> tuple[str, ...]:
67
74
 
68
75
  return tuple(_DEGRADED_DIRECTORY_FSYNC)
69
76
 
70
- _SOURCE_EXCLUSIONS = frozenset(
71
- {
72
- ".git",
73
- ".svn",
74
- ".venv",
75
- "__pycache__",
76
- ".pytest_cache",
77
- ".mypy_cache",
78
- "node_modules",
79
- ".lingma",
80
- ".deepseek",
81
- ".vscode",
82
- ".idea",
83
- ".settings",
84
- ".dsh",
85
- "Debug",
86
- "test_reports",
87
- "project_docs",
88
- "sub_plan",
89
- ".hypothesis",
90
- }
91
- )
77
+ _SOURCE_EXCLUSIONS = proj_doc_config.DEFAULT_EXCLUDE_NAMES
92
78
  _SOURCE_EXCLUSIONS_FOLDED = frozenset(name.casefold() for name in _SOURCE_EXCLUSIONS)
93
79
  _RECEIPT_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,127}\Z")
94
80
  _SHA256_RE = re.compile(r"[0-9a-f]{64}\Z")
@@ -142,6 +128,41 @@ class SourceInventory:
142
128
  boundaries: set[str]
143
129
  unknown_scopes: tuple[dict[str, str], ...] = ()
144
130
  frozen: bool = False
131
+ folded_directories: dict[str, str] = field(init=False, repr=False)
132
+ sorted_boundary_parts: tuple[tuple[str, tuple[str, ...]], ...] = field(
133
+ init=False, repr=False
134
+ )
135
+ sorted_unknown_scopes: tuple[tuple[str, str, str, tuple[str, ...]], ...] = field(
136
+ init=False, repr=False
137
+ )
138
+
139
+ def __post_init__(self) -> None:
140
+ self.folded_directories = {path.casefold(): path for path in self.directories}
141
+ self.sorted_boundary_parts = tuple(
142
+ (
143
+ boundary,
144
+ tuple(part.casefold() for part in PurePosixPath(boundary).parts),
145
+ )
146
+ for boundary in sorted(self.boundaries)
147
+ )
148
+ scopes: list[tuple[str, str, str, tuple[str, ...]]] = []
149
+ for scope in sorted(
150
+ self.unknown_scopes,
151
+ key=lambda item: (
152
+ str(item.get("path", "")).casefold(),
153
+ str(item.get("scope", "")),
154
+ ),
155
+ ):
156
+ path = scope.get("path")
157
+ scope_kind = scope.get("scope")
158
+ reason = scope.get("reason")
159
+ if not isinstance(path, str) or not isinstance(scope_kind, str):
160
+ continue
161
+ scope_parts = tuple(part.casefold() for part in PurePosixPath(path).parts)
162
+ scopes.append(
163
+ (path, scope_kind, str(reason or "unknown"), scope_parts)
164
+ )
165
+ self.sorted_unknown_scopes = tuple(scopes)
145
166
 
146
167
 
147
168
  @dataclass
@@ -251,18 +272,19 @@ def _is_link_or_junction(path: Path) -> bool:
251
272
  """Recognize symbolic links and Windows junction/reparse directory links."""
252
273
 
253
274
  try:
254
- if path.is_symlink():
255
- return True
256
- path_is_junction = getattr(path, "is_junction", None)
257
- if path_is_junction is not None and path_is_junction():
258
- return True
259
- os_is_junction = getattr(os.path, "isjunction", None)
260
- return bool(os_is_junction is not None and os_is_junction(os.fspath(path)))
275
+ info = path.lstat()
276
+ except FileNotFoundError:
277
+ return False
261
278
  except OSError as exc:
262
279
  raise Phase4Refusal(
263
280
  "untrusted-path",
264
281
  f"cannot inspect link or junction state for {path}: {exc}",
265
282
  ) from exc
283
+ if stat.S_ISLNK(info.st_mode):
284
+ return True
285
+ attributes = getattr(info, "st_file_attributes", 0)
286
+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
287
+ return bool(attributes & reparse_flag)
266
288
 
267
289
 
268
290
  def _lexists(path: Path) -> bool:
@@ -5395,6 +5417,11 @@ def _should_prune_source(name: str) -> bool:
5395
5417
  def _discover_source_directories(root: Path, docs_root: Path) -> SourceInventory:
5396
5418
  """Walk source directories, pruning descendants of non-root boundaries."""
5397
5419
 
5420
+ try:
5421
+ project_config = proj_doc_config.load_project_config(root)
5422
+ except proj_doc_config.ConfigError as exc:
5423
+ raise Phase4Refusal("config-invalid", str(exc)) from exc
5424
+
5398
5425
  directories: set[str] = set()
5399
5426
  boundaries: set[str] = set()
5400
5427
  casefold_paths: dict[str, str] = {}
@@ -5453,7 +5480,10 @@ def _discover_source_directories(root: Path, docs_root: Path) -> SourceInventory
5453
5480
  safe_children: list[str] = []
5454
5481
  for dirname in sorted(dirnames):
5455
5482
  child = current / dirname
5456
- if _should_prune_source(dirname):
5483
+ child_rel = dirname if relative == "." else f"{relative}/{dirname}"
5484
+ if proj_doc_config.should_exclude_directory(
5485
+ dirname, child_rel, config=project_config
5486
+ ):
5457
5487
  continue
5458
5488
  try:
5459
5489
  resolved_child = child.resolve(strict=True)
@@ -5488,14 +5518,29 @@ def _discover_source_directories(root: Path, docs_root: Path) -> SourceInventory
5488
5518
  return SourceInventory(directories=directories, boundaries=boundaries)
5489
5519
 
5490
5520
 
5491
- def _boundary_ancestor(source_relative: str, boundaries: set[str]) -> str | None:
5521
+ def _boundary_ancestor(
5522
+ source_relative: str,
5523
+ boundaries: set[str],
5524
+ *,
5525
+ sorted_boundary_parts: tuple[tuple[str, tuple[str, ...]], ...] | None = None,
5526
+ ) -> str | None:
5527
+ if not boundaries:
5528
+ return None
5492
5529
  source_parts = tuple(
5493
5530
  part.casefold() for part in PurePosixPath(source_relative).parts
5494
5531
  )
5495
- for boundary in sorted(boundaries):
5496
- boundary_parts = tuple(
5497
- part.casefold() for part in PurePosixPath(boundary).parts
5532
+ items = (
5533
+ sorted_boundary_parts
5534
+ if sorted_boundary_parts is not None
5535
+ else tuple(
5536
+ (
5537
+ boundary,
5538
+ tuple(part.casefold() for part in PurePosixPath(boundary).parts),
5539
+ )
5540
+ for boundary in sorted(boundaries)
5498
5541
  )
5542
+ )
5543
+ for boundary, boundary_parts in items:
5499
5544
  if (
5500
5545
  len(source_parts) > len(boundary_parts)
5501
5546
  and source_parts[: len(boundary_parts)] == boundary_parts
@@ -5507,10 +5552,28 @@ def _boundary_ancestor(source_relative: str, boundaries: set[str]) -> str | None
5507
5552
  def _unknown_scope_detail(
5508
5553
  source_relative: str,
5509
5554
  scopes: tuple[dict[str, str], ...],
5555
+ *,
5556
+ sorted_scopes: tuple[tuple[str, str, str, tuple[str, ...]], ...] | None = None,
5510
5557
  ) -> str | None:
5558
+ if not scopes and not sorted_scopes:
5559
+ return None
5511
5560
  source_parts = tuple(
5512
5561
  part.casefold() for part in PurePosixPath(source_relative).parts
5513
5562
  )
5563
+ if sorted_scopes is not None:
5564
+ for path, scope_kind, reason, scope_parts in sorted_scopes:
5565
+ same_or_below = source_parts[: len(scope_parts)] == scope_parts
5566
+ applies = same_or_below and (
5567
+ scope_kind == "subtree"
5568
+ or (
5569
+ scope_kind == "descendants"
5570
+ and len(source_parts) > len(scope_parts)
5571
+ )
5572
+ )
5573
+ if applies:
5574
+ return f"{path} ({reason}; {scope_kind})"
5575
+ return None
5576
+
5514
5577
  for scope in sorted(
5515
5578
  scopes,
5516
5579
  key=lambda item: (
@@ -5541,17 +5604,26 @@ def _source_path_state(
5541
5604
  ) -> tuple[str, str | None]:
5542
5605
  """Return ``present``, ``missing``, ``boundary``, or ``untrusted``."""
5543
5606
 
5544
- boundary = _boundary_ancestor(source_relative, inventory.boundaries)
5607
+ boundary = _boundary_ancestor(
5608
+ source_relative,
5609
+ inventory.boundaries,
5610
+ sorted_boundary_parts=inventory.sorted_boundary_parts,
5611
+ )
5545
5612
  if boundary is not None:
5546
5613
  return "boundary", boundary
5547
5614
 
5548
- unknown = _unknown_scope_detail(source_relative, inventory.unknown_scopes)
5615
+ unknown = _unknown_scope_detail(
5616
+ source_relative,
5617
+ inventory.unknown_scopes,
5618
+ sorted_scopes=inventory.sorted_unknown_scopes,
5619
+ )
5549
5620
  if unknown is not None:
5550
5621
  return "untrusted", f"source path is inside an unknown scan scope: {unknown}"
5551
5622
 
5552
- folded_inventory = {path.casefold(): path for path in inventory.directories}
5553
- if source_relative.casefold() in folded_inventory:
5554
- return "present", folded_inventory[source_relative.casefold()]
5623
+ folded_target = source_relative.casefold()
5624
+ matched_present = inventory.folded_directories.get(folded_target)
5625
+ if matched_present is not None:
5626
+ return "present", matched_present
5555
5627
  if inventory.frozen:
5556
5628
  return "missing", None
5557
5629
 
@@ -5587,7 +5659,11 @@ def _build_inbound_sources(
5587
5659
  ) -> tuple[dict[str, set[str]], list[dict[str, str]]]:
5588
5660
  inbound: dict[str, set[str]] = {path: set() for path in active_paths}
5589
5661
  invalid_links: list[dict[str, str]] = []
5590
- for source_relative in sorted(active_paths):
5662
+ sorted_paths = sorted(active_paths)
5663
+
5664
+ def _scan_one(
5665
+ source_relative: str,
5666
+ ) -> tuple[str, list[str], list[dict[str, str]]]:
5591
5667
  try:
5592
5668
  safe_source = contract.resolve_manifest_document(
5593
5669
  docs_root,
@@ -5605,9 +5681,11 @@ def _build_inbound_sources(
5605
5681
  "active-document-unreadable",
5606
5682
  f"active document cannot be read: {source_relative}: {exc}",
5607
5683
  ) from exc
5684
+ targets: list[str] = []
5685
+ invalids: list[dict[str, str]] = []
5608
5686
  for link in links:
5609
5687
  if link.disposition is contract.LinkDisposition.INVALID:
5610
- invalid_links.append(
5688
+ invalids.append(
5611
5689
  {
5612
5690
  "source": source_relative,
5613
5691
  "target": link.raw_target,
@@ -5620,6 +5698,19 @@ def _build_inbound_sources(
5620
5698
  target = link.project_relative_path
5621
5699
  if _is_quarantine_relative(target) or target == source_relative:
5622
5700
  continue
5701
+ targets.append(target)
5702
+ return source_relative, targets, invalids
5703
+
5704
+ if len(sorted_paths) > 1:
5705
+ max_workers = min(32, (os.cpu_count() or 4) * 4)
5706
+ with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
5707
+ results = list(executor.map(_scan_one, sorted_paths))
5708
+ else:
5709
+ results = [_scan_one(path) for path in sorted_paths]
5710
+
5711
+ for source_relative, targets, invalids in results:
5712
+ invalid_links.extend(invalids)
5713
+ for target in targets:
5623
5714
  inbound.setdefault(target, set()).add(source_relative)
5624
5715
  return inbound, invalid_links
5625
5716
 
@@ -5677,6 +5768,7 @@ def _analyze_loaded_snapshot(
5677
5768
  manifest_sha256: str,
5678
5769
  *,
5679
5770
  source_inventory: SourceInventory | None = None,
5771
+ precomputed_links: tuple[dict[str, set[str]], list[dict[str, str]]] | None = None,
5680
5772
  ) -> Analysis:
5681
5773
  """Analyze one already validated document/manifest snapshot."""
5682
5774
 
@@ -5716,7 +5808,17 @@ def _analyze_loaded_snapshot(
5716
5808
  "source-inventory-invalid",
5717
5809
  "source inventory override must be a SourceInventory",
5718
5810
  )
5719
- inbound_sources, invalid_links = _build_inbound_sources(active_paths, docs_root)
5811
+ if precomputed_links is not None:
5812
+ raw_inbound, raw_invalid = precomputed_links
5813
+ inbound_sources = {
5814
+ path: set(raw_inbound.get(path, ())) for path in active_paths
5815
+ }
5816
+ for target_path, sources in raw_inbound.items():
5817
+ if target_path not in inbound_sources:
5818
+ inbound_sources[target_path] = set(sources)
5819
+ invalid_links = list(raw_invalid)
5820
+ else:
5821
+ inbound_sources, invalid_links = _build_inbound_sources(active_paths, docs_root)
5720
5822
 
5721
5823
  generation_value = manifest.get("generation_id")
5722
5824
  generation = (
@@ -5866,6 +5968,8 @@ def analyze_snapshot(
5866
5968
  manifest_value: dict[str, Any],
5867
5969
  *,
5868
5970
  source_inventory: SourceInventory | None = None,
5971
+ precomputed_links: tuple[dict[str, set[str]], list[dict[str, str]]] | None = None,
5972
+ preverified_manifest: bool = False,
5869
5973
  ) -> Analysis:
5870
5974
  """Analyze a staged v2 snapshot against one trusted source inventory.
5871
5975
 
@@ -5899,10 +6003,11 @@ def analyze_snapshot(
5899
6003
  _validate_existing_quarantine(docs_root)
5900
6004
 
5901
6005
  manifest = dict(manifest_value)
5902
- try:
5903
- contract.validate_manifest_v2(manifest, docs_root, verify_files=True)
5904
- except contract.ProjectDocsContractError as exc:
5905
- raise Phase4Refusal("manifest-invalid", str(exc)) from exc
6006
+ if not preverified_manifest:
6007
+ try:
6008
+ contract.validate_manifest_v2(manifest, docs_root, verify_files=True)
6009
+ except contract.ProjectDocsContractError as exc:
6010
+ raise Phase4Refusal("manifest-invalid", str(exc)) from exc
5906
6011
  manifest_sha256 = contract.sha256_bytes(
5907
6012
  contract.stable_json_dumps(manifest).encode("utf-8")
5908
6013
  )
@@ -5913,6 +6018,7 @@ def analyze_snapshot(
5913
6018
  [],
5914
6019
  manifest_sha256,
5915
6020
  source_inventory=source_inventory,
6021
+ precomputed_links=precomputed_links,
5916
6022
  )
5917
6023
 
5918
6024