dandelion-memory 1.0.0rc15__py3-none-any.whl

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 (232) hide show
  1. benchmarks/__init__.py +3 -0
  2. benchmarks/adapters/__init__.py +29 -0
  3. benchmarks/adapters/ablations.py +406 -0
  4. benchmarks/adapters/base.py +72 -0
  5. benchmarks/adapters/controlled/__init__.py +13 -0
  6. benchmarks/adapters/controlled/core_archival.py +115 -0
  7. benchmarks/adapters/controlled/extract_resolve.py +130 -0
  8. benchmarks/adapters/controlled/hybrid_rag.py +120 -0
  9. benchmarks/adapters/controlled/no_late_binding.py +113 -0
  10. benchmarks/adapters/dandelion.py +94 -0
  11. benchmarks/adapters/native/__init__.py +31 -0
  12. benchmarks/adapters/native/base.py +45 -0
  13. benchmarks/adapters/native/dandelion_native.py +164 -0
  14. benchmarks/adapters/native/dandelion_native_b0.py +165 -0
  15. benchmarks/adapters/native/dandelion_native_b1.py +170 -0
  16. benchmarks/adapters/native/dandelion_native_b2.py +169 -0
  17. benchmarks/adapters/native/dandelion_native_b3.py +171 -0
  18. benchmarks/adapters/native/dandelion_native_c4.py +261 -0
  19. benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
  20. benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
  21. benchmarks/adapters/native/event_evidence_b2.py +616 -0
  22. benchmarks/adapters/native/evidence_b2.py +609 -0
  23. benchmarks/adapters/native/letta_native.py +253 -0
  24. benchmarks/adapters/native/mem0_native.py +219 -0
  25. benchmarks/adapters/native/store_vector_b0.py +792 -0
  26. benchmarks/adapters/native/store_vector_b2.py +808 -0
  27. benchmarks/agent_adapter_stdio_acceptance.py +86 -0
  28. benchmarks/bootstrap_cross_stack.py +218 -0
  29. benchmarks/canonical_profile_instrumentation.py +167 -0
  30. benchmarks/canonical_public_baseline.py +288 -0
  31. benchmarks/cli.py +525 -0
  32. benchmarks/collector_public30_offline.py +1653 -0
  33. benchmarks/datasets/__init__.py +45 -0
  34. benchmarks/datasets/conversational_generator.py +238 -0
  35. benchmarks/datasets/generator.py +283 -0
  36. benchmarks/datasets/holdout_topology_generator.py +290 -0
  37. benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
  38. benchmarks/datasets/multi_world.py +1643 -0
  39. benchmarks/datasets/scale_generator.py +289 -0
  40. benchmarks/datasets/schema.py +57 -0
  41. benchmarks/deep_collision_stress.py +199 -0
  42. benchmarks/evaluators/__init__.py +12 -0
  43. benchmarks/evaluators/manifest.py +142 -0
  44. benchmarks/evaluators/metrics.py +277 -0
  45. benchmarks/evaluators/runner.py +258 -0
  46. benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
  47. benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
  48. benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
  49. benchmarks/f1_step0/build_ledger.py +143 -0
  50. benchmarks/f1_step0/build_ledger_v2.py +296 -0
  51. benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
  52. benchmarks/f1_step0/locator_public_smoke.py +172 -0
  53. benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
  54. benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
  55. benchmarks/f1_step0/public_identity_probe.py +191 -0
  56. benchmarks/f1_step0/public_response_mapper.py +101 -0
  57. benchmarks/f1_step0/real_source_public_preflight.py +244 -0
  58. benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
  59. benchmarks/f1_step0/scorer.py +110 -0
  60. benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
  61. benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
  62. benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
  63. benchmarks/f1_step0/test_public_response_mapper.py +110 -0
  64. benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
  65. benchmarks/f1_step0/test_scorer.py +158 -0
  66. benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
  67. benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
  68. benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
  69. benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
  70. benchmarks/forensic_c4_1_dev.py +258 -0
  71. benchmarks/forensic_c4_dev.py +255 -0
  72. benchmarks/forensic_deep25_c4_1.py +478 -0
  73. benchmarks/legacy_migration_acceptance.py +29 -0
  74. benchmarks/longmemeval_actor.py +497 -0
  75. benchmarks/longmemeval_agent_judge.py +593 -0
  76. benchmarks/longmemeval_budget.py +139 -0
  77. benchmarks/longmemeval_full.py +410 -0
  78. benchmarks/longmemeval_judge.py +327 -0
  79. benchmarks/longmemeval_pilot.py +316 -0
  80. benchmarks/longmemeval_s.py +318 -0
  81. benchmarks/memory_bench.py +248 -0
  82. benchmarks/memory_formation/__init__.py +1 -0
  83. benchmarks/memory_formation/audit.py +801 -0
  84. benchmarks/memory_formation/real_audit.py +688 -0
  85. benchmarks/memory_session_acceptance.py +279 -0
  86. benchmarks/native_codex_host.py +513 -0
  87. benchmarks/owner_dense_acceptance.py +126 -0
  88. benchmarks/pilot_seeker_vault.py +266 -0
  89. benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
  90. benchmarks/profile_canonical.py +373 -0
  91. benchmarks/profile_canonical_lanes.py +405 -0
  92. benchmarks/profile_search_chunks.py +351 -0
  93. benchmarks/public_ranges_faq_proof.py +121 -0
  94. benchmarks/public_repos/build_history_scope_v3.py +330 -0
  95. benchmarks/public_repos/build_oracle.py +108 -0
  96. benchmarks/public_repos/build_oracle_v2.py +169 -0
  97. benchmarks/public_repos/build_oracle_v3.py +176 -0
  98. benchmarks/public_repos/map_public_v2.py +296 -0
  99. benchmarks/public_repos/project_prompts_v2.py +31 -0
  100. benchmarks/public_repos/project_prompts_v3.py +29 -0
  101. benchmarks/public_repos/ready_admin_v2.py +214 -0
  102. benchmarks/public_repos/score_public_v2.py +258 -0
  103. benchmarks/public_repos/test_map_public_v2.py +171 -0
  104. benchmarks/public_repos/test_public_repo_v2.py +44 -0
  105. benchmarks/public_repos/test_public_repo_v3.py +46 -0
  106. benchmarks/public_repos/test_ready_admin_v2.py +117 -0
  107. benchmarks/public_repos/test_score_public_v2.py +163 -0
  108. benchmarks/public_repos/test_wire_v2.py +292 -0
  109. benchmarks/public_repos/wire_v2.py +603 -0
  110. benchmarks/real_blocker_fix_acceptance.py +155 -0
  111. benchmarks/real_scan_rescan_acceptance.py +41 -0
  112. benchmarks/recall_v2_20k_smoke.py +112 -0
  113. benchmarks/recall_v2_e1_retrieve.py +70 -0
  114. benchmarks/recall_v2_e1_score.py +271 -0
  115. benchmarks/recall_v2_e2_prepare.py +69 -0
  116. benchmarks/recall_v2_e2_public_score.py +91 -0
  117. benchmarks/recall_v2_e2_score.py +108 -0
  118. benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
  119. benchmarks/recall_v2_reader_capture.py +118 -0
  120. benchmarks/recall_v2_reader_replay.py +136 -0
  121. benchmarks/run_blind_h10_holdout.py +284 -0
  122. benchmarks/run_blind_h9_holdout.py +275 -0
  123. benchmarks/run_c4_2_nightly_scale.py +446 -0
  124. benchmarks/run_context_scale_simulation.py +189 -0
  125. benchmarks/run_conversational_bench.py +170 -0
  126. benchmarks/run_h11_evaluation.py +316 -0
  127. benchmarks/run_h11_v2_evaluation.py +431 -0
  128. benchmarks/run_native_fixed12.py +469 -0
  129. benchmarks/run_native_preflight.py +280 -0
  130. benchmarks/run_scale_stress.py +225 -0
  131. benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
  132. benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
  133. benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
  134. benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
  135. benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
  136. benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
  137. benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
  138. benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
  139. benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
  140. benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
  141. benchmarks/statistics/__init__.py +15 -0
  142. benchmarks/statistics/significance.py +326 -0
  143. benchmarks/test_native_mcp_preflight.py +229 -0
  144. benchmarks/test_prepare_public30_range_owner.py +35 -0
  145. benchmarks/test_public30_source_reference.py +698 -0
  146. benchmarks/test_recall_v2_e1_reader_input.py +89 -0
  147. benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
  148. benchmarks/test_recall_v2_reader_replay.py +41 -0
  149. dandelion/__init__.py +3 -0
  150. dandelion/__main__.py +11 -0
  151. dandelion/agent_adapter.py +2369 -0
  152. dandelion/bootstrap/__init__.py +872 -0
  153. dandelion/bootstrap/alias_policy.py +50 -0
  154. dandelion/bootstrap/authority.py +225 -0
  155. dandelion/bootstrap/canonical_history.py +412 -0
  156. dandelion/bootstrap/classifier.py +403 -0
  157. dandelion/bootstrap/component_graph.py +280 -0
  158. dandelion/bootstrap/discovery.py +279 -0
  159. dandelion/bootstrap/domain_induction.py +180 -0
  160. dandelion/bootstrap/domain_topology.py +673 -0
  161. dandelion/bootstrap/evidence_envelope.py +132 -0
  162. dandelion/bootstrap/extractors/base.py +171 -0
  163. dandelion/bootstrap/extractors/exact.py +1234 -0
  164. dandelion/bootstrap/extractors/generic.py +100 -0
  165. dandelion/bootstrap/extractors/git_temporal.py +111 -0
  166. dandelion/bootstrap/extractors/registry.py +345 -0
  167. dandelion/bootstrap/extractors/relations.py +89 -0
  168. dandelion/bootstrap/extractors/semantic.py +424 -0
  169. dandelion/bootstrap/extractors/status.py +218 -0
  170. dandelion/bootstrap/git_sweeper.py +135 -0
  171. dandelion/bootstrap/manifest.py +246 -0
  172. dandelion/bootstrap/quarantine.py +264 -0
  173. dandelion/bootstrap/report.py +259 -0
  174. dandelion/bootstrap/root_resolver.py +221 -0
  175. dandelion/bootstrap/tech_profiler.py +125 -0
  176. dandelion/bootstrap/topology.py +75 -0
  177. dandelion/bootstrap/topology_index.py +110 -0
  178. dandelion/bootstrap/transaction.py +315 -0
  179. dandelion/canonical_bootstrap.py +257 -0
  180. dandelion/canonical_memory.py +4130 -0
  181. dandelion/captured_input.py +295 -0
  182. dandelion/cli.py +767 -0
  183. dandelion/config.py +40 -0
  184. dandelion/derived_index.py +745 -0
  185. dandelion/domains.py +706 -0
  186. dandelion/embedder.py +229 -0
  187. dandelion/event_evidence.py +571 -0
  188. dandelion/evidence.py +812 -0
  189. dandelion/evidence_response.py +453 -0
  190. dandelion/evidence_workspace.py +2360 -0
  191. dandelion/exact_context.py +129 -0
  192. dandelion/hydrator.py +124 -0
  193. dandelion/inspector.py +442 -0
  194. dandelion/inspector_assets/dandelion-mark.svg +33 -0
  195. dandelion/inspector_assets/dandelion_graph.js +361 -0
  196. dandelion/inspector_assets/inspector.css +223 -0
  197. dandelion/inspector_assets/inspector.html +135 -0
  198. dandelion/inspector_assets/inspector.js +1059 -0
  199. dandelion/legacy_import.py +431 -0
  200. dandelion/live_source_grants.py +133 -0
  201. dandelion/local_owner.py +114 -0
  202. dandelion/memory_client.py +252 -0
  203. dandelion/memory_contract.py +107 -0
  204. dandelion/memory_owner.py +560 -0
  205. dandelion/reader_providers.py +118 -0
  206. dandelion/recall_v2.py +767 -0
  207. dandelion/reconciler.py +219 -0
  208. dandelion/request_budget.py +125 -0
  209. dandelion/retained_basis.py +223 -0
  210. dandelion/retrieval.py +485 -0
  211. dandelion/router.py +405 -0
  212. dandelion/search_terms.py +53 -0
  213. dandelion/security.py +124 -0
  214. dandelion/server.py +810 -0
  215. dandelion/source_content_fts.py +219 -0
  216. dandelion/source_delivery.py +89 -0
  217. dandelion/source_history.py +241 -0
  218. dandelion/source_identity.py +88 -0
  219. dandelion/source_navigator.py +5 -0
  220. dandelion/source_reader.py +444 -0
  221. dandelion/source_references.py +379 -0
  222. dandelion/source_sections.py +265 -0
  223. dandelion/store_kv.py +684 -0
  224. dandelion/store_vector.py +1289 -0
  225. dandelion/studio.py +325 -0
  226. dandelion/wal.py +227 -0
  227. dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
  228. dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
  229. dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
  230. dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
  231. dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
  232. dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
@@ -0,0 +1,110 @@
1
+ """Source-path to partition bindings derived from the component graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Optional, TYPE_CHECKING
7
+
8
+ from dandelion.bootstrap.component_graph import ComponentGraph, ComponentNode
9
+ from dandelion.bootstrap.root_resolver import RootResolutionResult
10
+ from dandelion.domains import PartitionKey
11
+
12
+ if TYPE_CHECKING:
13
+ from dandelion.bootstrap.domain_topology import DomainTopologySnapshot
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class SourcePartition:
18
+ """Explicit storage destination for evidence observed in one source path."""
19
+ project_id: str
20
+ component_id: str
21
+ component: str
22
+ domain: str
23
+ partition_id: str
24
+ domain_id: str
25
+ topology_version: int
26
+
27
+
28
+ class TopologyIndex:
29
+ """Resolve source artifacts against the observed component graph only."""
30
+
31
+ def __init__(self, project_id: str, bindings: dict[str, SourcePartition], root: SourcePartition) -> None:
32
+ self.project_id = project_id
33
+ self._bindings = bindings
34
+ self._root = root
35
+
36
+ @classmethod
37
+ def from_graph(
38
+ cls,
39
+ graph: ComponentGraph,
40
+ root_res: RootResolutionResult,
41
+ topology: Optional[DomainTopologySnapshot] = None,
42
+ ) -> TopologyIndex:
43
+ project_id = root_res.canonical_id
44
+ root_key = PartitionKey(project=project_id, domain="architecture", component="overview")
45
+ root = SourcePartition(
46
+ project_id=project_id,
47
+ component_id=graph.root_id,
48
+ component="overview",
49
+ domain=f"{project_id}.architecture",
50
+ partition_id=root_key.canonical_id,
51
+ domain_id=topology.root_domain_id if topology else root_key.canonical_id,
52
+ topology_version=topology.revision if topology else 0,
53
+ )
54
+ topology_nodes = {
55
+ node.component_id: node
56
+ for node in topology.nodes.values()
57
+ if topology and node.lifecycle.value not in {"REMOVED", "MERGED", "SPLIT"}
58
+ } if topology else {}
59
+ bindings: dict[str, SourcePartition] = {}
60
+ for node in graph.nodes.values():
61
+ if node.is_root or node.kind == "workspace_boundary" or not node.rel_path:
62
+ continue
63
+ bindings[node.rel_path] = cls._binding_for_node(
64
+ project_id,
65
+ node,
66
+ topology_node=topology_nodes.get(node.id),
67
+ topology_version=topology.revision if topology else 0,
68
+ )
69
+ return cls(project_id=project_id, bindings=bindings, root=root)
70
+
71
+ @staticmethod
72
+ def _binding_for_node(
73
+ project_id: str,
74
+ node: ComponentNode,
75
+ topology_node=None,
76
+ topology_version: int = 0,
77
+ ) -> SourcePartition:
78
+ parts = tuple(part for part in node.rel_path.replace("\\", "/").split("/") if part)
79
+ segments = parts if len(parts) > 1 else ("core", parts[0])
80
+ key = PartitionKey(project=project_id, segments=segments)
81
+ return SourcePartition(
82
+ project_id=project_id,
83
+ component_id=node.id,
84
+ component=node.id,
85
+ domain=f"{project_id}." + ".".join(segments),
86
+ partition_id=key.canonical_id,
87
+ domain_id=topology_node.domain_id if topology_node else key.canonical_id,
88
+ topology_version=topology_version,
89
+ )
90
+
91
+ def binding_for(self, source_path: str, evidence_plane: str = "semantic") -> SourcePartition:
92
+ """Return the longest explicit component-path match for an artifact."""
93
+ normalized = source_path.replace("\\", "/").strip("/")
94
+ matches = [
95
+ (path, binding)
96
+ for path, binding in self._bindings.items()
97
+ if normalized == path or normalized.startswith(path + "/")
98
+ ]
99
+ base = max(matches, key=lambda item: len(item[0]))[1] if matches else self._root
100
+ if evidence_plane == "status":
101
+ return SourcePartition(
102
+ project_id=base.project_id,
103
+ component_id=base.component_id,
104
+ component=base.component,
105
+ domain=f"{base.project_id}.status",
106
+ partition_id=base.partition_id,
107
+ domain_id=base.domain_id,
108
+ topology_version=base.topology_version,
109
+ )
110
+ return base
@@ -0,0 +1,315 @@
1
+ """Recoverable cross-store bootstrap transaction journal.
2
+
3
+ The journal deliberately contains only hashes and operation metadata. Raw
4
+ fact values, memory templates, and quarantine evidence remain in their owning
5
+ stores and never gain a second persistence channel here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import re
14
+ import tempfile
15
+ import time
16
+ import uuid
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass, field
19
+ from enum import Enum
20
+ from pathlib import Path
21
+ from typing import Any, Optional
22
+
23
+ import portalocker
24
+
25
+
26
+ class BootstrapTransactionConflict(RuntimeError):
27
+ """Raised when recovery is attempted against a different source snapshot."""
28
+
29
+
30
+ class BootstrapTransactionState(str, Enum):
31
+ PREPARED = "PREPARED"
32
+ APPLYING = "APPLYING"
33
+ COMMITTED = "COMMITTED"
34
+ ABORTED = "ABORTED"
35
+
36
+
37
+ def canonical_digest(value: Any) -> str:
38
+ payload = json.dumps(
39
+ value,
40
+ ensure_ascii=False,
41
+ sort_keys=True,
42
+ separators=(",", ":"),
43
+ ).encode("utf-8")
44
+ return hashlib.sha256(payload).hexdigest()
45
+
46
+
47
+ def _require_digest(name: str, value: str) -> None:
48
+ if not re.fullmatch(r"[0-9a-f]{64}", value):
49
+ raise ValueError(f"{name} must be a SHA-256 digest, not raw bootstrap data")
50
+
51
+
52
+ @dataclass
53
+ class BootstrapTransaction:
54
+ tx_id: str
55
+ state: BootstrapTransactionState
56
+ input_fingerprint: str
57
+ plan_digest: str
58
+ previous_topology_snapshot_id: Optional[str]
59
+ target_topology_snapshot_id: str
60
+ target_topology_revision: int
61
+ participants: dict[str, str] = field(default_factory=dict)
62
+ created_at: float = field(default_factory=time.time)
63
+ updated_at: float = field(default_factory=time.time)
64
+ committed_at: Optional[float] = None
65
+
66
+ def to_dict(self) -> dict[str, Any]:
67
+ return {
68
+ "version": 1,
69
+ "tx_id": self.tx_id,
70
+ "state": self.state.value,
71
+ "input_fingerprint": self.input_fingerprint,
72
+ "plan_digest": self.plan_digest,
73
+ "previous_topology_snapshot_id": self.previous_topology_snapshot_id,
74
+ "target_topology_snapshot_id": self.target_topology_snapshot_id,
75
+ "target_topology_revision": self.target_topology_revision,
76
+ "participants": dict(sorted(self.participants.items())),
77
+ "created_at": self.created_at,
78
+ "updated_at": self.updated_at,
79
+ "committed_at": self.committed_at,
80
+ }
81
+
82
+ @classmethod
83
+ def from_dict(cls, value: dict[str, Any]) -> "BootstrapTransaction":
84
+ if int(value.get("version", 0)) != 1:
85
+ raise ValueError("Unsupported bootstrap transaction journal version")
86
+ return cls(
87
+ tx_id=str(value["tx_id"]),
88
+ state=BootstrapTransactionState(value["state"]),
89
+ input_fingerprint=str(value["input_fingerprint"]),
90
+ plan_digest=str(value["plan_digest"]),
91
+ previous_topology_snapshot_id=value.get("previous_topology_snapshot_id"),
92
+ target_topology_snapshot_id=str(value["target_topology_snapshot_id"]),
93
+ target_topology_revision=int(value["target_topology_revision"]),
94
+ participants={str(k): str(v) for k, v in value.get("participants", {}).items()},
95
+ created_at=float(value.get("created_at", time.time())),
96
+ updated_at=float(value.get("updated_at", time.time())),
97
+ committed_at=(
98
+ float(value["committed_at"])
99
+ if value.get("committed_at") is not None
100
+ else None
101
+ ),
102
+ )
103
+
104
+
105
+ class BootstrapTransactionStore:
106
+ """Atomic bootstrap journal with one writer and consistent-reader leases.
107
+
108
+ Writers take an exclusive process lock for the full non-dry-run bootstrap.
109
+ Public readers take a shared lease before opening either participating store;
110
+ this makes the cross-store apply window invisible. If a writer crashed
111
+ after recording ``APPLYING``, the OS lock is gone but the stores may be
112
+ mixed, so readers fail closed until bootstrap recovery finishes.
113
+ """
114
+
115
+ PARTICIPANTS = ("kv", "vector", "manifest", "quarantine", "artifacts", "topology")
116
+
117
+ def __init__(self, directory: Path) -> None:
118
+ self.directory = directory
119
+ self.path = directory / "bootstrap_transaction.json"
120
+ lock_root = Path(tempfile.gettempdir()) / "dandelion-bootstrap-locks"
121
+ self.lock_path = lock_root / f"{canonical_digest(str(directory.resolve()))}.lock"
122
+ self.history_dir = directory / "bootstrap_transactions.history"
123
+
124
+ @contextmanager
125
+ def lock(self):
126
+ """Hold the project-wide single-writer lease for one bootstrap run."""
127
+ self.lock_path.parent.mkdir(parents=True, exist_ok=True)
128
+ lock = portalocker.Lock(
129
+ str(self.lock_path),
130
+ mode="a+",
131
+ timeout=0,
132
+ flags=portalocker.LOCK_EX | portalocker.LOCK_NB,
133
+ )
134
+ try:
135
+ with lock:
136
+ yield
137
+ except portalocker.exceptions.LockException as exc:
138
+ raise BootstrapTransactionConflict(
139
+ "Another bootstrap transaction is already running for this project"
140
+ ) from exc
141
+
142
+ @contextmanager
143
+ def read_lock(self):
144
+ """Block behind a live bootstrap writer and reject unrecovered applies.
145
+
146
+ The lock is deliberately acquired before callers open KV or Qdrant.
147
+ That fixed ordering (bootstrap lease, then store-local locks) avoids a
148
+ reader holding a store lock while waiting for the bootstrap writer.
149
+ """
150
+ self.lock_path.parent.mkdir(parents=True, exist_ok=True)
151
+ lock = portalocker.Lock(
152
+ str(self.lock_path),
153
+ mode="a+",
154
+ flags=portalocker.LOCK_SH,
155
+ )
156
+ try:
157
+ with lock:
158
+ transaction = self.load()
159
+ if (
160
+ transaction is not None
161
+ and transaction.state is BootstrapTransactionState.APPLYING
162
+ ):
163
+ raise BootstrapTransactionConflict(
164
+ "Bootstrap recovery is required before reads: transaction "
165
+ f"{transaction.tx_id} is APPLYING"
166
+ )
167
+ yield
168
+ except portalocker.exceptions.LockException as exc:
169
+ raise BootstrapTransactionConflict(
170
+ "Cannot acquire the bootstrap consistency lease for this project"
171
+ ) from exc
172
+
173
+ @staticmethod
174
+ def _atomic_write(path: Path, data: bytes) -> None:
175
+ path.parent.mkdir(parents=True, exist_ok=True)
176
+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
177
+ try:
178
+ with open(tmp, "wb") as handle:
179
+ handle.write(data)
180
+ handle.flush()
181
+ os.fsync(handle.fileno())
182
+ os.replace(tmp, path)
183
+ finally:
184
+ tmp.unlink(missing_ok=True)
185
+
186
+ def _write(self, transaction: BootstrapTransaction) -> None:
187
+ transaction.updated_at = time.time()
188
+ payload = json.dumps(
189
+ transaction.to_dict(),
190
+ ensure_ascii=False,
191
+ indent=2,
192
+ sort_keys=True,
193
+ ).encode("utf-8")
194
+ self._atomic_write(self.path, payload)
195
+
196
+ def load(self) -> Optional[BootstrapTransaction]:
197
+ if not self.path.exists():
198
+ return None
199
+ try:
200
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
201
+ if not isinstance(raw, dict):
202
+ raise ValueError("journal root must be an object")
203
+ return BootstrapTransaction.from_dict(raw)
204
+ except Exception as exc:
205
+ raise BootstrapTransactionConflict(
206
+ f"Cannot trust bootstrap transaction journal '{self.path}': {exc}"
207
+ ) from exc
208
+
209
+ def finalize_committed(self) -> Optional[Path]:
210
+ transaction = self.load()
211
+ if transaction is None:
212
+ return None
213
+ if transaction.state is not BootstrapTransactionState.COMMITTED:
214
+ raise BootstrapTransactionConflict(
215
+ f"Cannot finalize bootstrap transaction in state {transaction.state.value}"
216
+ )
217
+ self.history_dir.mkdir(parents=True, exist_ok=True)
218
+ target = self.history_dir / f"{transaction.tx_id}.json"
219
+ payload = self.path.read_bytes()
220
+ if target.exists():
221
+ if target.read_bytes() != payload:
222
+ raise BootstrapTransactionConflict(
223
+ f"Committed transaction history differs for {transaction.tx_id}"
224
+ )
225
+ else:
226
+ self._atomic_write(target, payload)
227
+ self.path.unlink(missing_ok=True)
228
+ return target
229
+
230
+ def prepare_or_resume(
231
+ self,
232
+ *,
233
+ input_fingerprint: str,
234
+ plan_digest: str,
235
+ previous_topology_snapshot_id: Optional[str],
236
+ target_topology_snapshot_id: str,
237
+ target_topology_revision: int,
238
+ ) -> BootstrapTransaction:
239
+ _require_digest("input_fingerprint", input_fingerprint)
240
+ _require_digest("plan_digest", plan_digest)
241
+ transaction = self.load()
242
+ if transaction is not None and transaction.state is BootstrapTransactionState.COMMITTED:
243
+ self.finalize_committed()
244
+ transaction = None
245
+ if transaction is not None:
246
+ expected = (
247
+ transaction.input_fingerprint,
248
+ transaction.plan_digest,
249
+ transaction.target_topology_snapshot_id,
250
+ transaction.target_topology_revision,
251
+ )
252
+ actual = (
253
+ input_fingerprint,
254
+ plan_digest,
255
+ target_topology_snapshot_id,
256
+ target_topology_revision,
257
+ )
258
+ if expected != actual:
259
+ raise BootstrapTransactionConflict(
260
+ "An unfinished bootstrap transaction belongs to a different "
261
+ "source or topology snapshot; restore that input and retry recovery"
262
+ )
263
+ return transaction
264
+
265
+ transaction = BootstrapTransaction(
266
+ tx_id=f"BTX-{int(time.time() * 1000)}-{uuid.uuid4().hex}",
267
+ state=BootstrapTransactionState.PREPARED,
268
+ input_fingerprint=input_fingerprint,
269
+ plan_digest=plan_digest,
270
+ previous_topology_snapshot_id=previous_topology_snapshot_id,
271
+ target_topology_snapshot_id=target_topology_snapshot_id,
272
+ target_topology_revision=target_topology_revision,
273
+ participants={name: "PENDING" for name in self.PARTICIPANTS},
274
+ )
275
+ self._write(transaction)
276
+ return transaction
277
+
278
+ def mark_applying(self, transaction: BootstrapTransaction) -> None:
279
+ if transaction.state not in (
280
+ BootstrapTransactionState.PREPARED,
281
+ BootstrapTransactionState.APPLYING,
282
+ ):
283
+ raise BootstrapTransactionConflict(
284
+ f"Cannot apply bootstrap transaction in state {transaction.state.value}"
285
+ )
286
+ transaction.state = BootstrapTransactionState.APPLYING
287
+ self._write(transaction)
288
+
289
+ def mark_participant(
290
+ self,
291
+ transaction: BootstrapTransaction,
292
+ participant: str,
293
+ state: str = "APPLIED",
294
+ ) -> None:
295
+ if participant not in self.PARTICIPANTS:
296
+ raise ValueError(f"Unknown bootstrap transaction participant: {participant}")
297
+ transaction.participants[participant] = state
298
+ self._write(transaction)
299
+
300
+ def commit(self, transaction: BootstrapTransaction) -> Path:
301
+ incomplete = [
302
+ participant
303
+ for participant in self.PARTICIPANTS
304
+ if transaction.participants.get(participant) not in ("APPLIED", "UNCHANGED")
305
+ ]
306
+ if incomplete:
307
+ raise BootstrapTransactionConflict(
308
+ f"Cannot commit bootstrap transaction; incomplete participants: {', '.join(incomplete)}"
309
+ )
310
+ transaction.state = BootstrapTransactionState.COMMITTED
311
+ transaction.committed_at = time.time()
312
+ self._write(transaction)
313
+ target = self.finalize_committed()
314
+ assert target is not None
315
+ return target
@@ -0,0 +1,257 @@
1
+ """Read-only repository scan producing a canonical-owner ingestion package.
2
+
3
+ The scanner and existing extractors remain the authority for discovery. This
4
+ module deliberately has no store handles: the returned package is committed by
5
+ ``CanonicalMemory`` in one SQLite transaction.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+ from pathlib import PurePosixPath
15
+ from typing import Any
16
+
17
+ from dandelion.bootstrap.component_graph import build_component_graph
18
+ from dandelion.bootstrap.classifier import FileRole, is_sensitive_path
19
+ from dandelion.bootstrap.canonical_history import (
20
+ scan_canonical_history, scan_verified_historical_values,
21
+ )
22
+ from dandelion.bootstrap.discovery import discover_project
23
+ from dandelion.bootstrap.domain_induction import induce_domains_from_graph
24
+ from dandelion.bootstrap.domain_topology import reconcile_component_graph
25
+ from dandelion.bootstrap.extractors.registry import ExtractorRegistry
26
+ from dandelion.bootstrap.root_resolver import resolve_project_root
27
+ from dandelion.bootstrap.tech_profiler import profile_project_technologies
28
+ from dandelion.bootstrap.topology_index import TopologyIndex
29
+ from dandelion.security import is_sensitive_value
30
+ from dandelion.source_reader import PUBLIC_RANGES_V1, SourceReadError, read_current, validate_source_policy
31
+
32
+
33
+ def _digest(value: Any) -> str:
34
+ return hashlib.sha256(
35
+ json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
36
+ ).hexdigest()
37
+
38
+
39
+ def _stable_record(value: dict[str, Any]) -> dict[str, Any]:
40
+ """Drop scan-clock fields; source validity comes from hashes/revisions."""
41
+ stable = dict(value)
42
+ stable.pop("timestamp", None)
43
+ provenance = stable.get("provenance")
44
+ if isinstance(provenance, dict):
45
+ provenance = dict(provenance)
46
+ provenance.pop("observed_at", None)
47
+ stable["provenance"] = provenance
48
+ return stable
49
+
50
+
51
+ def _canonical_fact_identity(record: dict[str, Any], occurrence: int) -> dict[str, Any]:
52
+ """Name one parser slot by source path and semantic key, never by value."""
53
+ result = dict(record)
54
+ key = str(result.get("key", ""))
55
+ source = str(result.get("source_file", "")).replace("\\", "/").strip("/")
56
+ if not source or source.startswith("git:") or source.startswith("git log"):
57
+ return result
58
+ parts = list(PurePosixPath(source).with_suffix("").parts)
59
+ readable_path = [re.sub(r"[^a-z0-9_]+", "_", part.casefold()).strip("_") or "source"
60
+ for part in parts]
61
+ semantic = key.split(".", 1)[1] if "." in key else key
62
+ if semantic.casefold().startswith(readable_path[-1] + "."):
63
+ semantic = semantic[len(readable_path[-1]) + 1:]
64
+ suffix = hashlib.sha256(source.encode("utf-8")).hexdigest()[:12]
65
+ project = key.split(".", 1)[0]
66
+ result["legacy_unscoped_key"] = key
67
+ result["aliases"] = [key]
68
+ result["key"] = ".".join(
69
+ [project, *readable_path, semantic, f"__src_{suffix}", f"__occ_{occurrence:03d}"]
70
+ )
71
+ provenance = dict(result.get("provenance") or {})
72
+ provenance["canonical_identity"] = {
73
+ "version": "path-key-v2", "source_path": source,
74
+ "source_path_digest": suffix, "legacy_unscoped_key": key,
75
+ "occurrence": occurrence,
76
+ }
77
+ result["provenance"] = provenance
78
+ return result
79
+
80
+
81
+ def _navigation_source_catalog(report: Any, source_policy: str | None = None) -> dict[str, dict[str, Any]]:
82
+ """Persist bounded metadata for the public files this scan actually saw."""
83
+ catalog: dict[str, dict[str, Any]] = {}
84
+ validate_source_policy(source_policy)
85
+ for item in report.all_discovered:
86
+ relative = item.rel_path.replace("\\", "/")
87
+ if (item.role == FileRole.SECRET_SENSITIVE or item.abs_path.is_symlink()
88
+ or PurePosixPath(relative).name.casefold().startswith(".env")
89
+ or is_sensitive_path(relative.casefold(), PurePosixPath(relative).name.casefold())
90
+ or item.size_bytes > 2_000_000):
91
+ continue
92
+ try:
93
+ data = item.abs_path.read_bytes()
94
+ text = data.decode("utf-8")
95
+ except (OSError, UnicodeDecodeError):
96
+ continue
97
+ if len(data) != item.size_bytes or b"\x00" in data:
98
+ continue
99
+ digest = hashlib.sha256(data).hexdigest()
100
+ if digest != item.content_hash:
101
+ continue
102
+ if source_policy == PUBLIC_RANGES_V1:
103
+ try:
104
+ value = read_current(report.root_path, relative, expected_sha256=digest,
105
+ max_bytes=2_000_000, source_policy=source_policy)
106
+ headings = value.public_headings()
107
+ except SourceReadError:
108
+ continue
109
+ else:
110
+ if is_sensitive_value(text):
111
+ continue
112
+ headings = [line.strip()[:120] for line in text.splitlines()
113
+ if line.lstrip().startswith(("#", "//", "class ", "def ", "func "))][:8]
114
+ catalog[relative] = {
115
+ "sha256": digest,
116
+ "byte_length": len(data),
117
+ "line_count": len(text.splitlines()),
118
+ "headings": headings,
119
+ }
120
+ if source_policy is not None:
121
+ catalog[relative]["source_policy"] = source_policy
122
+ return catalog
123
+
124
+
125
+ def _canonical_fact_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
126
+ """Collapse only identical source/key/value/line observations."""
127
+ seen: dict[tuple[str, str, str, int | None], str] = {}
128
+ occurrence: dict[tuple[str, str], int] = {}
129
+ result: list[dict[str, Any]] = []
130
+ for record in records:
131
+ source = str(record.get("source_file", "")).replace("\\", "/")
132
+ key = str(record.get("key", ""))
133
+ line = record.get("line_number")
134
+ identity = (source, key, _digest(record.get("value")), line)
135
+ security = str(record.get("security_class", "PUBLIC"))
136
+ if identity in seen:
137
+ if seen[identity] != security:
138
+ raise ValueError("Conflicting security classifications for one source fact")
139
+ continue
140
+ seen[identity] = security
141
+ slot = (source, key)
142
+ occurrence[slot] = occurrence.get(slot, 0) + 1
143
+ result.append(_canonical_fact_identity(record, occurrence[slot]))
144
+ by_alias: dict[str, list[dict[str, Any]]] = {}
145
+ for record in result:
146
+ for alias in record.get("aliases", []):
147
+ by_alias.setdefault(alias, []).append(record)
148
+ for alias, alternatives in by_alias.items():
149
+ if len(alternatives) < 2:
150
+ continue
151
+ group = hashlib.sha256(alias.encode("utf-8")).hexdigest()
152
+ for record in alternatives:
153
+ record["conflict_status"] = "CONFLICT"
154
+ record["conflict_group"] = group
155
+ provenance = dict(record.get("provenance") or {})
156
+ provenance["conflict_status"] = "CONFLICT"
157
+ provenance["conflict_group"] = group
158
+ record["provenance"] = provenance
159
+ return result
160
+
161
+
162
+ def prepare_canonical_bootstrap(source_workspace: Path | str, *,
163
+ source_policy: str | None = None,
164
+ source_content_fts5: bool = False) -> dict[str, Any]:
165
+ """Scan *source_workspace* without creating or changing its memory stores."""
166
+ validate_source_policy(source_policy)
167
+ root = Path(source_workspace).resolve()
168
+ report = discover_project(root)
169
+ root_resolution = resolve_project_root(report)
170
+ technology = profile_project_technologies(report)
171
+ graph = build_component_graph(report, root_resolution, technology)
172
+ topology = reconcile_component_graph(
173
+ graph, None, project_id=root_resolution.canonical_id
174
+ ).snapshot
175
+ topology_index = TopologyIndex.from_graph(graph, root_resolution, topology)
176
+ registry = ExtractorRegistry()
177
+
178
+ exact = registry.run_exact_extraction(report, project_name=root_resolution.project_name)
179
+ status_records, status_memories = registry.run_status_extraction(
180
+ report,
181
+ project_name=root_resolution.project_name,
182
+ topology_index=topology_index,
183
+ component_graph=graph,
184
+ )
185
+ semantic = registry.run_semantic_extraction(
186
+ report,
187
+ project_name=root_resolution.project_name,
188
+ topology_index=topology_index,
189
+ )
190
+
191
+ facts = _canonical_fact_records([_stable_record(record.to_dict()) for record in exact])
192
+ memories = [_stable_record(record.to_dict()) for record in semantic + status_memories]
193
+ history_memories = scan_canonical_history(root, root_resolution.project_name)
194
+ memories.extend(history_memories)
195
+ memories.extend(scan_verified_historical_values(root, root_resolution.project_name, exact))
196
+ domains = [domain.to_dict() for domain in induce_domains_from_graph(graph, root_resolution)]
197
+ source_hashes = {item.rel_path: item.content_hash for item in report.all_discovered}
198
+ source_catalog = _navigation_source_catalog(report, source_policy)
199
+ for record in facts + memories:
200
+ provenance = record.get("provenance")
201
+ if not isinstance(provenance, dict) or provenance.get("commit"):
202
+ continue
203
+ entry = source_catalog.get(provenance.get("source_path"))
204
+ if (record.get("security_class", "PUBLIC") == "PUBLIC" and entry
205
+ and provenance.get("artifact_hash") == entry["sha256"]
206
+ and entry.get("source_policy") is None):
207
+ provenance["source_witness"] = {
208
+ "version": 1, "scope": "ORIGINAL_FULL_FILE",
209
+ "sha256": entry["sha256"], "byte_length": entry["byte_length"],
210
+ }
211
+ topology_data = topology.to_dict()
212
+ topology_data.pop("snapshot_id", None)
213
+ topology_data.pop("created_at", None)
214
+ body = {
215
+ "format": "dandelion-canonical-bootstrap-v1",
216
+ "source_workspace": str(root),
217
+ "source_git_head": report.git_head,
218
+ "source_hashes": source_hashes,
219
+ "source_catalog": source_catalog,
220
+ "project_id": root_resolution.canonical_id,
221
+ "facts": facts,
222
+ "memories": memories,
223
+ "domains": domains,
224
+ "topology": topology_data,
225
+ "status_evidence": [_stable_record(record.to_dict()) for record in status_records],
226
+ "unsupported": {
227
+ "git_history": (
228
+ "Recent commit subjects and paths remain unverified hints. Bounded changed "
229
+ "exact values are indexed from Git blobs and require git show line verification; "
230
+ "this is not complete repository history"
231
+ ),
232
+ "status_claim_rows": (
233
+ "DEFERRED: evidence is preserved in status memories/status_evidence, "
234
+ "but structured claim materialization is not yet lossless"
235
+ ),
236
+ "quarantine_arbitration": (
237
+ "CHANGED: equal-authority conflicting facts reject the whole canonical commit"
238
+ ),
239
+ },
240
+ }
241
+ if source_policy is not None:
242
+ body["source_policy"] = source_policy
243
+ if source_content_fts5:
244
+ # Bind the projection mode to the same source hashes and plan digest.
245
+ # Literal source text is staged separately and never enters this plan.
246
+ body["source_content_projection"] = "FTS5_CURRENT_V1"
247
+ body["plan_digest"] = _digest(body)
248
+ return body
249
+
250
+
251
+ def verify_prepared_source(plan: dict[str, Any]) -> None:
252
+ """Reject an apply if any discovered source changed after preparation."""
253
+ root = Path(str(plan["source_workspace"])).resolve()
254
+ current = discover_project(root)
255
+ hashes = {item.rel_path: item.content_hash for item in current.all_discovered}
256
+ if hashes != plan.get("source_hashes") or current.git_head != plan.get("source_git_head"):
257
+ raise ValueError("Bootstrap source changed after plan preparation")