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,673 @@
1
+ """Versioned, durable domain topology derived from a component graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import tempfile
9
+ import time
10
+ import uuid
11
+ from dataclasses import dataclass, field, replace
12
+ from enum import Enum
13
+ from pathlib import Path
14
+ from typing import Mapping, Optional
15
+
16
+ from dandelion.bootstrap.component_graph import ComponentGraph, ComponentNode
17
+
18
+
19
+ SNAPSHOT_SCHEMA_VERSION = "1.0"
20
+
21
+
22
+ class DomainLifecycle(str, Enum):
23
+ OBSERVED = "OBSERVED"
24
+ PROVISIONAL = "PROVISIONAL"
25
+ CONFIRMED = "CONFIRMED"
26
+ ESTABLISHED = "ESTABLISHED"
27
+ DEPRECATED = "DEPRECATED"
28
+ MERGED = "MERGED"
29
+ SPLIT = "SPLIT"
30
+ REMOVED = "REMOVED"
31
+
32
+
33
+ class TopologyChangeKind(str, Enum):
34
+ CREATE = "CREATE"
35
+ PROMOTE = "PROMOTE"
36
+ REPARENT = "REPARENT"
37
+ RENAME = "RENAME"
38
+ DEPRECATE = "DEPRECATE"
39
+ REMOVE = "REMOVE"
40
+ SPLIT = "SPLIT"
41
+ MERGE = "MERGE"
42
+ REACTIVATE = "REACTIVATE"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class DomainNode:
47
+ """Stable identity for a domain independently of its current graph path."""
48
+
49
+ domain_id: str
50
+ component_id: str
51
+ name: str
52
+ path: str
53
+ parent_domain_id: Optional[str]
54
+ structural_signature: str
55
+ lifecycle: DomainLifecycle
56
+ first_seen_revision: int
57
+ last_seen_revision: int
58
+ lineage: tuple[str, ...] = ()
59
+
60
+ def to_dict(self) -> dict:
61
+ return {
62
+ "domain_id": self.domain_id,
63
+ "component_id": self.component_id,
64
+ "name": self.name,
65
+ "path": self.path,
66
+ "parent_domain_id": self.parent_domain_id,
67
+ "structural_signature": self.structural_signature,
68
+ "lifecycle": self.lifecycle.value,
69
+ "first_seen_revision": self.first_seen_revision,
70
+ "last_seen_revision": self.last_seen_revision,
71
+ "lineage": list(self.lineage),
72
+ }
73
+
74
+ @classmethod
75
+ def from_dict(cls, data: dict) -> DomainNode:
76
+ return cls(
77
+ domain_id=str(data["domain_id"]),
78
+ component_id=str(data["component_id"]),
79
+ name=str(data["name"]),
80
+ path=str(data.get("path", "")),
81
+ parent_domain_id=data.get("parent_domain_id"),
82
+ structural_signature=str(data["structural_signature"]),
83
+ lifecycle=DomainLifecycle(data["lifecycle"]),
84
+ first_seen_revision=int(data["first_seen_revision"]),
85
+ last_seen_revision=int(data["last_seen_revision"]),
86
+ lineage=tuple(str(item) for item in data.get("lineage", [])),
87
+ )
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class DomainTopologySnapshot:
92
+ project_id: str
93
+ revision: int
94
+ root_domain_id: str
95
+ nodes: dict[str, DomainNode]
96
+ graph_fingerprint: str = ""
97
+ snapshot_id: str = field(default_factory=lambda: uuid.uuid4().hex)
98
+ created_at: float = field(default_factory=time.time)
99
+ schema_version: str = SNAPSHOT_SCHEMA_VERSION
100
+
101
+ def to_dict(self) -> dict:
102
+ return {
103
+ "schema_version": self.schema_version,
104
+ "snapshot_id": self.snapshot_id,
105
+ "created_at": self.created_at,
106
+ "project_id": self.project_id,
107
+ "revision": self.revision,
108
+ "root_domain_id": self.root_domain_id,
109
+ "graph_fingerprint": self.graph_fingerprint,
110
+ "nodes": {domain_id: node.to_dict() for domain_id, node in self.nodes.items()},
111
+ }
112
+
113
+ @classmethod
114
+ def from_dict(cls, data: dict) -> DomainTopologySnapshot:
115
+ if data.get("schema_version") != SNAPSHOT_SCHEMA_VERSION:
116
+ raise ValueError(f"Unsupported topology schema: {data.get('schema_version')!r}")
117
+ nodes = {
118
+ domain_id: DomainNode.from_dict(node)
119
+ for domain_id, node in data.get("nodes", {}).items()
120
+ }
121
+ return cls(
122
+ project_id=str(data["project_id"]),
123
+ revision=int(data["revision"]),
124
+ root_domain_id=str(data["root_domain_id"]),
125
+ nodes=nodes,
126
+ graph_fingerprint=str(data.get("graph_fingerprint", "")),
127
+ snapshot_id=str(data["snapshot_id"]),
128
+ created_at=float(data["created_at"]),
129
+ schema_version=str(data["schema_version"]),
130
+ )
131
+
132
+
133
+ @dataclass(frozen=True)
134
+ class TopologyChange:
135
+ kind: TopologyChangeKind
136
+ domain_id: str
137
+ old_path: Optional[str] = None
138
+ new_path: Optional[str] = None
139
+ detail: Optional[str] = None
140
+
141
+ def to_dict(self) -> dict:
142
+ return {
143
+ "kind": self.kind.value,
144
+ "domain_id": self.domain_id,
145
+ "old_path": self.old_path,
146
+ "new_path": self.new_path,
147
+ "detail": self.detail,
148
+ }
149
+
150
+ @classmethod
151
+ def from_dict(cls, data: dict) -> TopologyChange:
152
+ return cls(
153
+ kind=TopologyChangeKind(data["kind"]),
154
+ domain_id=str(data["domain_id"]),
155
+ old_path=data.get("old_path"),
156
+ new_path=data.get("new_path"),
157
+ detail=data.get("detail"),
158
+ )
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class TopologyChangeSet:
163
+ previous_snapshot_id: Optional[str]
164
+ snapshot_id: str
165
+ changes: tuple[TopologyChange, ...]
166
+
167
+ def of_kind(self, kind: TopologyChangeKind) -> list[TopologyChange]:
168
+ return [change for change in self.changes if change.kind == kind]
169
+
170
+ def to_dict(self) -> dict:
171
+ return {
172
+ "previous_snapshot_id": self.previous_snapshot_id,
173
+ "snapshot_id": self.snapshot_id,
174
+ "changes": [change.to_dict() for change in self.changes],
175
+ }
176
+
177
+ @classmethod
178
+ def from_dict(cls, data: dict) -> TopologyChangeSet:
179
+ return cls(
180
+ previous_snapshot_id=data.get("previous_snapshot_id"),
181
+ snapshot_id=str(data["snapshot_id"]),
182
+ changes=tuple(
183
+ TopologyChange.from_dict(change)
184
+ for change in data.get("changes", [])
185
+ ),
186
+ )
187
+
188
+
189
+ @dataclass(frozen=True)
190
+ class TopologyReconciliation:
191
+ snapshot: DomainTopologySnapshot
192
+ changes: TopologyChangeSet
193
+
194
+
195
+ def _normal_path(path: str) -> str:
196
+ return path.replace("\\", "/").strip("/")
197
+
198
+
199
+ def _stable_domain_id(project_id: str, path: str, signature: str) -> str:
200
+ seed = f"{project_id}\x1f{path}\x1f{signature}".encode("utf-8")
201
+ return "dom_" + hashlib.sha256(seed).hexdigest()[:24]
202
+
203
+
204
+ def _structural_signature(node: ComponentNode) -> str:
205
+ """Path-independent signature; preservation is allowed only for a unique match."""
206
+ if node.is_root:
207
+ return hashlib.sha256(b"dandelion-project-root").hexdigest()
208
+ payload = {
209
+ "kind": node.kind,
210
+ "resolution": node.resolution,
211
+ "workspace_boundary": node.is_workspace_boundary,
212
+ "descriptor_names": sorted(Path(item).name for item in node.descriptors),
213
+ "technologies": sorted(node.technologies),
214
+ "files_count": node.files_count,
215
+ "source_files_count": node.source_files_count,
216
+ "in_degree": node.in_degree,
217
+ "out_degree": node.out_degree,
218
+ }
219
+ encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
220
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
221
+
222
+
223
+ def _identity_strength(node: ComponentNode) -> int:
224
+ return sum((
225
+ int(bool(node.descriptors)),
226
+ int(node.source_files_count > 0),
227
+ int(bool(node.technologies)),
228
+ int((node.in_degree + node.out_degree) > 0),
229
+ ))
230
+
231
+
232
+ def _graph_fingerprint(graph: ComponentGraph) -> str:
233
+ payload = {
234
+ "nodes": sorted(
235
+ (
236
+ node.id,
237
+ _normal_path(node.rel_path),
238
+ _structural_signature(node),
239
+ )
240
+ for node in graph.nodes.values()
241
+ ),
242
+ "edges": sorted(
243
+ (edge.source_id, edge.target_id, edge.relation, round(edge.confidence, 6))
244
+ for edge in graph.edges
245
+ ),
246
+ }
247
+ encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":"))
248
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
249
+
250
+
251
+ def _parent_path(path: str, known_paths: set[str]) -> str:
252
+ parent = path.rpartition("/")[0]
253
+ while parent:
254
+ if parent in known_paths:
255
+ return parent
256
+ parent = parent.rpartition("/")[0]
257
+ return ""
258
+
259
+
260
+ def _maturity_for(node: ComponentNode) -> DomainLifecycle:
261
+ """Derive maturity from structural evidence, never from scan count."""
262
+ strength = int(bool(node.descriptors))
263
+ strength += int(node.source_files_count > 0)
264
+ strength += int((node.in_degree + node.out_degree) > 0)
265
+ return (
266
+ DomainLifecycle.ESTABLISHED if strength >= 3 else
267
+ DomainLifecycle.CONFIRMED if strength == 2 else
268
+ DomainLifecycle.PROVISIONAL if strength == 1 else
269
+ DomainLifecycle.OBSERVED
270
+ )
271
+
272
+
273
+ def _is_manual_lifecycle(lifecycle: DomainLifecycle) -> bool:
274
+ return lifecycle in {
275
+ DomainLifecycle.DEPRECATED,
276
+ DomainLifecycle.MERGED,
277
+ DomainLifecycle.SPLIT,
278
+ }
279
+
280
+
281
+ def _normal_lifecycle_matches(node: ComponentNode, previous: DomainNode) -> bool:
282
+ return previous.lifecycle == _maturity_for(node) if not _is_manual_lifecycle(previous.lifecycle) else True
283
+
284
+
285
+ def _is_noop_graph(
286
+ graph: ComponentGraph,
287
+ previous: DomainTopologySnapshot,
288
+ project_id: str,
289
+ ) -> bool:
290
+ if previous.project_id != project_id:
291
+ return False
292
+ if previous.graph_fingerprint != _graph_fingerprint(graph):
293
+ return False
294
+ root = graph.nodes.get(graph.root_id)
295
+ old_root = previous.nodes.get(previous.root_domain_id)
296
+ if not root or not old_root or old_root.component_id != root.id or old_root.name != root.name:
297
+ return False
298
+ if (
299
+ old_root.structural_signature != _structural_signature(root)
300
+ or old_root.lifecycle != _maturity_for(root)
301
+ ):
302
+ return False
303
+ observed = {
304
+ _normal_path(node.rel_path): node
305
+ for node in graph.nodes.values()
306
+ if not node.is_root and node.kind != "workspace_boundary" and _normal_path(node.rel_path)
307
+ }
308
+ active = {
309
+ node.path: node
310
+ for node in previous.nodes.values()
311
+ if node.path and node.lifecycle != DomainLifecycle.REMOVED
312
+ }
313
+ if set(observed) != set(active):
314
+ return False
315
+ return all(
316
+ old.component_id == current.id
317
+ and old.name == current.name
318
+ and old.structural_signature == _structural_signature(current)
319
+ and _normal_lifecycle_matches(current, old)
320
+ for path, current in observed.items()
321
+ for old in [active[path]]
322
+ )
323
+
324
+
325
+ def _change_for_lifecycle(lifecycle: DomainLifecycle) -> Optional[TopologyChangeKind]:
326
+ return {
327
+ DomainLifecycle.DEPRECATED: TopologyChangeKind.DEPRECATE,
328
+ DomainLifecycle.MERGED: TopologyChangeKind.MERGE,
329
+ DomainLifecycle.SPLIT: TopologyChangeKind.SPLIT,
330
+ DomainLifecycle.REMOVED: TopologyChangeKind.REMOVE,
331
+ }.get(lifecycle)
332
+
333
+
334
+ def reconcile_component_graph(
335
+ graph: ComponentGraph,
336
+ previous: Optional[DomainTopologySnapshot] = None,
337
+ *,
338
+ project_id: Optional[str] = None,
339
+ lifecycle_overrides: Optional[Mapping[str, DomainLifecycle]] = None,
340
+ lineage_overrides: Optional[Mapping[str, tuple[str, ...]]] = None,
341
+ now: Optional[float] = None,
342
+ ) -> TopologyReconciliation:
343
+ """Reconcile observed graph nodes into a stable, versioned domain topology.
344
+
345
+ A renamed or reparented component keeps its domain ID only when its
346
+ path-independent signature has exactly one unmatched predecessor and one
347
+ unmatched successor. Ambiguous siblings intentionally receive new IDs.
348
+ """
349
+ resolved_project = project_id or graph.root_id
350
+ if previous and not lifecycle_overrides and not lineage_overrides and _is_noop_graph(graph, previous, resolved_project):
351
+ return TopologyReconciliation(
352
+ snapshot=previous,
353
+ changes=TopologyChangeSet(previous.snapshot_id, previous.snapshot_id, ()),
354
+ )
355
+ revision = (previous.revision + 1) if previous else 1
356
+ observed = {
357
+ _normal_path(node.rel_path): node
358
+ for node in graph.nodes.values()
359
+ if not node.is_root and node.kind != "workspace_boundary" and _normal_path(node.rel_path)
360
+ }
361
+ root_component = graph.nodes.get(graph.root_id)
362
+ root_signature = _structural_signature(root_component) if root_component else "root"
363
+ root_domain_id = previous.root_domain_id if previous else _stable_domain_id(resolved_project, "", root_signature)
364
+ old_nodes = previous.nodes if previous else {}
365
+ old_by_path = {node.path: node for node in old_nodes.values() if node.path and node.lifecycle != DomainLifecycle.REMOVED}
366
+ removed_by_path = {
367
+ node.path: node
368
+ for node in old_nodes.values()
369
+ if node.path and node.lifecycle == DomainLifecycle.REMOVED
370
+ }
371
+ assignments: dict[str, DomainNode] = {}
372
+ changes: list[TopologyChange] = []
373
+ matched_old: set[str] = set()
374
+
375
+ for path, node in observed.items():
376
+ old = old_by_path.get(path)
377
+ if old is None:
378
+ removed = removed_by_path.get(path)
379
+ if removed and removed.structural_signature == _structural_signature(node):
380
+ old = removed
381
+ if old:
382
+ assignments[path] = old
383
+ matched_old.add(old.domain_id)
384
+
385
+ unmatched_old = [
386
+ node for node in old_nodes.values()
387
+ if node.path and node.lifecycle != DomainLifecycle.REMOVED and node.domain_id not in matched_old
388
+ ]
389
+ unmatched_new = [(path, node) for path, node in observed.items() if path not in assignments]
390
+ old_by_signature: dict[str, list[DomainNode]] = {}
391
+ new_by_signature: dict[str, list[tuple[str, ComponentNode]]] = {}
392
+ for node in unmatched_old:
393
+ old_by_signature.setdefault(node.structural_signature, []).append(node)
394
+ for path, node in unmatched_new:
395
+ new_by_signature.setdefault(_structural_signature(node), []).append((path, node))
396
+ for signature, new_candidates in new_by_signature.items():
397
+ old_candidates = old_by_signature.get(signature, [])
398
+ if len(old_candidates) == len(new_candidates) == 1:
399
+ path, candidate = new_candidates[0]
400
+ if _identity_strength(candidate) < 2:
401
+ continue
402
+ old = old_candidates[0]
403
+ assignments[path] = old
404
+ matched_old.add(old.domain_id)
405
+
406
+ known_paths = set(observed)
407
+ node_by_path: dict[str, DomainNode] = {}
408
+ for path in sorted(observed, key=lambda item: (item.count("/"), item)):
409
+ component = observed[path]
410
+ old = assignments.get(path)
411
+ parent_path = _parent_path(path, known_paths)
412
+ parent_id = node_by_path[parent_path].domain_id if parent_path else root_domain_id
413
+ if old is None:
414
+ domain_id = _stable_domain_id(resolved_project, path, _structural_signature(component))
415
+ lifecycle = _maturity_for(component)
416
+ first_seen = revision
417
+ changes.append(TopologyChange(TopologyChangeKind.CREATE, domain_id, new_path=path))
418
+ else:
419
+ domain_id = old.domain_id
420
+ lifecycle = old.lifecycle if _is_manual_lifecycle(old.lifecycle) else _maturity_for(component)
421
+ first_seen = old.first_seen_revision
422
+ if old.lifecycle == DomainLifecycle.REMOVED:
423
+ lifecycle = _maturity_for(component)
424
+ changes.append(TopologyChange(
425
+ TopologyChangeKind.REACTIVATE,
426
+ domain_id,
427
+ old_path=old.path,
428
+ new_path=path,
429
+ ))
430
+ maturity_order = {
431
+ DomainLifecycle.OBSERVED: 0,
432
+ DomainLifecycle.PROVISIONAL: 1,
433
+ DomainLifecycle.CONFIRMED: 2,
434
+ DomainLifecycle.ESTABLISHED: 3,
435
+ }
436
+ if maturity_order.get(lifecycle, -1) > maturity_order.get(old.lifecycle, -1):
437
+ changes.append(TopologyChange(TopologyChangeKind.PROMOTE, domain_id, old_path=old.path, new_path=path))
438
+ if old.path != path:
439
+ old_parent_path = _parent_path(old.path, set(old_by_path))
440
+ old_parent_id = (
441
+ old_by_path[old_parent_path].domain_id
442
+ if old_parent_path else root_domain_id
443
+ )
444
+ if Path(old.path).name != Path(path).name:
445
+ changes.append(TopologyChange(TopologyChangeKind.RENAME, domain_id, old.path, path))
446
+ if old_parent_id != parent_id:
447
+ changes.append(TopologyChange(TopologyChangeKind.REPARENT, domain_id, old.path, path))
448
+
449
+ override = (lifecycle_overrides or {}).get(domain_id)
450
+ lineage = tuple((lineage_overrides or {}).get(domain_id, old.lineage if old else ()))
451
+ if override and override != lifecycle:
452
+ if override in {DomainLifecycle.MERGED, DomainLifecycle.SPLIT} and not lineage:
453
+ raise ValueError(f"{override.value} requires explicit lineage for '{domain_id}'")
454
+ lifecycle = override
455
+ kind = _change_for_lifecycle(override)
456
+ if kind:
457
+ changes.append(TopologyChange(
458
+ kind,
459
+ domain_id,
460
+ old_path=old.path if old else None,
461
+ new_path=path,
462
+ detail=",".join(lineage) or None,
463
+ ))
464
+
465
+ node_by_path[path] = DomainNode(
466
+ domain_id=domain_id,
467
+ component_id=component.id,
468
+ name=component.name,
469
+ path=path,
470
+ parent_domain_id=parent_id,
471
+ structural_signature=_structural_signature(component),
472
+ lifecycle=lifecycle,
473
+ first_seen_revision=first_seen,
474
+ last_seen_revision=revision,
475
+ lineage=lineage,
476
+ )
477
+
478
+ root_old = old_nodes.get(root_domain_id)
479
+ root_lifecycle = _maturity_for(root_component) if root_component else DomainLifecycle.OBSERVED
480
+ root_node = DomainNode(
481
+ domain_id=root_domain_id,
482
+ component_id=graph.root_id,
483
+ name=root_component.name if root_component else resolved_project,
484
+ path="",
485
+ parent_domain_id=None,
486
+ structural_signature=root_signature,
487
+ lifecycle=root_lifecycle,
488
+ first_seen_revision=root_old.first_seen_revision if root_old else revision,
489
+ last_seen_revision=revision,
490
+ lineage=root_old.lineage if root_old else (),
491
+ )
492
+ nodes = {root_domain_id: root_node, **{node.domain_id: node for node in node_by_path.values()}}
493
+
494
+ for old in old_nodes.values():
495
+ if old.domain_id == root_domain_id or old.domain_id in matched_old:
496
+ continue
497
+ if old.lifecycle == DomainLifecycle.REMOVED:
498
+ nodes[old.domain_id] = old
499
+ continue
500
+ removed = replace(old, lifecycle=DomainLifecycle.REMOVED, last_seen_revision=revision)
501
+ nodes[old.domain_id] = removed
502
+ changes.append(TopologyChange(TopologyChangeKind.REMOVE, old.domain_id, old_path=old.path))
503
+
504
+ snapshot = DomainTopologySnapshot(
505
+ project_id=resolved_project,
506
+ revision=revision,
507
+ root_domain_id=root_domain_id,
508
+ nodes=nodes,
509
+ graph_fingerprint=_graph_fingerprint(graph),
510
+ created_at=time.time() if now is None else now,
511
+ )
512
+ return TopologyReconciliation(
513
+ snapshot=snapshot,
514
+ changes=TopologyChangeSet(
515
+ previous_snapshot_id=previous.snapshot_id if previous else None,
516
+ snapshot_id=snapshot.snapshot_id,
517
+ changes=tuple(changes),
518
+ ),
519
+ )
520
+
521
+
522
+ class DomainTopologyStore:
523
+ """Durable current snapshot plus immutable, append-only snapshot history."""
524
+
525
+ def __init__(self, directory: Path) -> None:
526
+ self.directory = directory
527
+ self.current_path = directory / "domain_topology.current.json"
528
+ self.pending_path = directory / "domain_topology.pending.json"
529
+ self.history_dir = directory / "domain_topology.history"
530
+ self.changes_dir = directory / "domain_topology.changes"
531
+ self.aborted_dir = directory / "domain_topology.aborted"
532
+
533
+ @staticmethod
534
+ def _atomic_write(path: Path, payload: bytes) -> None:
535
+ path.parent.mkdir(parents=True, exist_ok=True)
536
+ descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
537
+ try:
538
+ with os.fdopen(descriptor, "wb") as handle:
539
+ handle.write(payload)
540
+ handle.flush()
541
+ os.fsync(handle.fileno())
542
+ os.replace(temporary, path)
543
+ except BaseException:
544
+ try:
545
+ os.unlink(temporary)
546
+ except FileNotFoundError:
547
+ pass
548
+ raise
549
+
550
+ def prepare(
551
+ self,
552
+ snapshot: DomainTopologySnapshot,
553
+ changes: Optional[TopologyChangeSet] = None,
554
+ ) -> None:
555
+ if changes is not None and changes.snapshot_id != snapshot.snapshot_id:
556
+ raise ValueError("Change set does not belong to the prepared snapshot")
557
+ payload = json.dumps(
558
+ {
559
+ "snapshot": snapshot.to_dict(),
560
+ "changes": changes.to_dict() if changes is not None else None,
561
+ },
562
+ ensure_ascii=False,
563
+ indent=2,
564
+ sort_keys=True,
565
+ ).encode("utf-8")
566
+ if self.pending_path.exists():
567
+ if self.pending_path.read_bytes() != payload:
568
+ raise ValueError("A different topology transaction is already pending")
569
+ return
570
+ self._atomic_write(self.pending_path, payload)
571
+
572
+ def load_pending(self) -> Optional[TopologyReconciliation]:
573
+ if not self.pending_path.exists():
574
+ return None
575
+ data = json.loads(self.pending_path.read_text(encoding="utf-8"))
576
+ snapshot = DomainTopologySnapshot.from_dict(data["snapshot"])
577
+ changes = (
578
+ TopologyChangeSet.from_dict(data["changes"])
579
+ if data.get("changes") is not None
580
+ else TopologyChangeSet(None, snapshot.snapshot_id, ())
581
+ )
582
+ return TopologyReconciliation(snapshot=snapshot, changes=changes)
583
+
584
+ def abort_pending(self) -> Optional[Path]:
585
+ """Archive an obsolete prepared snapshot without treating it as history."""
586
+ if not self.pending_path.exists():
587
+ return None
588
+ self.aborted_dir.mkdir(parents=True, exist_ok=True)
589
+ target = self.aborted_dir / f"{int(time.time() * 1000)}-{uuid.uuid4().hex}.json"
590
+ os.replace(self.pending_path, target)
591
+ return target
592
+
593
+ def commit_prepared(self, expected_snapshot_id: Optional[str] = None) -> DomainTopologySnapshot:
594
+ pending = self.load_pending()
595
+ if pending is None:
596
+ raise ValueError("No prepared topology transaction")
597
+ snapshot = pending.snapshot
598
+ changes = pending.changes
599
+ if expected_snapshot_id and snapshot.snapshot_id != expected_snapshot_id:
600
+ raise ValueError("Prepared topology snapshot does not match expected snapshot")
601
+ payload = json.dumps(snapshot.to_dict(), ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
602
+ history_path = self.history_dir / f"{snapshot.revision:08d}-{snapshot.snapshot_id}.json"
603
+ if history_path.exists():
604
+ if history_path.read_bytes() != payload:
605
+ raise ValueError(f"Refusing to overwrite immutable topology history: {history_path.name}")
606
+ else:
607
+ self._atomic_write(history_path, payload)
608
+ if changes is not None:
609
+ change_payload = json.dumps(
610
+ changes.to_dict(),
611
+ ensure_ascii=False,
612
+ indent=2,
613
+ sort_keys=True,
614
+ ).encode("utf-8")
615
+ change_path = self.changes_dir / f"{snapshot.revision:08d}-{snapshot.snapshot_id}.json"
616
+ if change_path.exists():
617
+ if change_path.read_bytes() != change_payload:
618
+ raise ValueError(f"Refusing to overwrite immutable topology changes: {change_path.name}")
619
+ else:
620
+ self._atomic_write(change_path, change_payload)
621
+ self._atomic_write(self.current_path, payload)
622
+ self.pending_path.unlink(missing_ok=True)
623
+ return snapshot
624
+
625
+ def persist(
626
+ self,
627
+ snapshot: DomainTopologySnapshot,
628
+ changes: Optional[TopologyChangeSet] = None,
629
+ ) -> None:
630
+ self.prepare(snapshot, changes)
631
+ self.commit_prepared(snapshot.snapshot_id)
632
+
633
+ def load_current(self) -> Optional[DomainTopologySnapshot]:
634
+ if not self.current_path.exists():
635
+ return None
636
+ return DomainTopologySnapshot.from_dict(json.loads(self.current_path.read_text(encoding="utf-8")))
637
+
638
+ def load_history(self) -> list[DomainTopologySnapshot]:
639
+ if not self.history_dir.exists():
640
+ return []
641
+ return [
642
+ DomainTopologySnapshot.from_dict(json.loads(path.read_text(encoding="utf-8")))
643
+ for path in sorted(self.history_dir.glob("*.json"))
644
+ ]
645
+
646
+ def load_change_history(self) -> list[TopologyChangeSet]:
647
+ if not self.changes_dir.exists():
648
+ return []
649
+ return [
650
+ TopologyChangeSet.from_dict(json.loads(path.read_text(encoding="utf-8")))
651
+ for path in sorted(self.changes_dir.glob("*.json"))
652
+ ]
653
+
654
+
655
+ def persist_domain_topology(directory: Path, snapshot: DomainTopologySnapshot) -> None:
656
+ DomainTopologyStore(directory).persist(snapshot)
657
+
658
+
659
+ def load_domain_topology(directory: Path) -> Optional[DomainTopologySnapshot]:
660
+ return DomainTopologyStore(directory).load_current()
661
+
662
+
663
+ def initialize_root_topology(project_id: str, project_name: Optional[str] = None) -> DomainTopologySnapshot:
664
+ """Create the root-only topology used when a new project is initialized."""
665
+ graph = ComponentGraph(root_id=project_id)
666
+ graph.nodes[project_id] = ComponentNode(
667
+ id=project_id,
668
+ name=project_name or project_id,
669
+ kind="project",
670
+ rel_path="",
671
+ is_root=True,
672
+ )
673
+ return reconcile_component_graph(graph, project_id=project_id).snapshot