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,745 @@
1
+ """Owner-held, rebuildable dense index derived from canonical SQLite memory.
2
+
3
+ The Qdrant collection in this module is deliberately *not* the legacy
4
+ ``.dandelion/qdrant`` store. SQLite remains authoritative: Qdrant only holds
5
+ a deterministic point id and non-content bookkeeping. Consequently a dense
6
+ hit is always reloaded and hydrated from SQLite before it is returned.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import sqlite3
14
+ import time
15
+ import uuid
16
+ from pathlib import Path
17
+ from typing import Any, Protocol, Sequence
18
+
19
+ from dandelion.canonical_memory import CanonicalMemory
20
+ from dandelion.retrieval import collect_ranked_candidates, hydrate_candidate
21
+ from dandelion.security import is_sensitive_value, public_egress
22
+
23
+
24
+ DERIVED_COLLECTION = "canonical_memory_dense_v1"
25
+ DERIVED_DIRECTORY = "derived_qdrant"
26
+ # A public owner request is intentionally small: embedded Qdrant calls may be
27
+ # slow on first use, and the single owner must return to its socket loop between
28
+ # batches. This is a ceiling, not a background worker configuration.
29
+ # One durable event bounds work count, not wall time: embedding and local
30
+ # Qdrant calls are synchronous and can exceed a client's deadline.
31
+ # The owner's cooperative maintenance hook uses the same single-event ceiling.
32
+ DEFAULT_CONSUME_BATCH_SIZE = 1
33
+ MAX_CONSUME_BATCH_SIZE = 1
34
+ AUTOMATIC_RETRY_BASE_SECONDS = 5.0
35
+ AUTOMATIC_RETRY_MAX_SECONDS = 60.0
36
+
37
+ # Search asks both indexes for a small, fixed superset before fusion. This is
38
+ # deliberately a request bound rather than a tuning knob: the owner remains
39
+ # responsive and callers cannot turn a single search into an unbounded scan.
40
+ MAX_SEARCH_CANDIDATES = 20
41
+
42
+
43
+ def __getattr__(name: str) -> Any:
44
+ if name in {"QdrantClient", "models"}:
45
+ import qdrant_client
46
+ value = getattr(qdrant_client, name)
47
+ globals()[name] = value
48
+ return value
49
+ raise AttributeError(name)
50
+
51
+
52
+ class DenseEmbedder(Protocol):
53
+ """Small injectable embedding boundary; no model is owned by this module."""
54
+
55
+ def embed(self, text: str) -> Sequence[float]: ...
56
+
57
+
58
+ class DerivedIndex:
59
+ """A single-owner Qdrant projection maintained through SQLite outbox rows."""
60
+
61
+ def __init__(
62
+ self,
63
+ canonical: CanonicalMemory,
64
+ embedder: DenseEmbedder,
65
+ *,
66
+ path: Path | None = None,
67
+ collection_name: str = DERIVED_COLLECTION,
68
+ ) -> None:
69
+ self.canonical = canonical
70
+ self.embedder = embedder
71
+ self.path = (path or canonical.directory / DERIVED_DIRECTORY).resolve()
72
+ legacy_path = (canonical.directory / "qdrant").resolve()
73
+ if self.path == legacy_path:
74
+ raise ValueError("Derived Qdrant path must not reuse the legacy Qdrant directory")
75
+ self.path.mkdir(parents=True, exist_ok=True)
76
+ self.collection_name = collection_name
77
+ with self.canonical._connect() as db:
78
+ db.execute(
79
+ "CREATE INDEX IF NOT EXISTS legacy_index_outbox_status_queue "
80
+ "ON legacy_index_outbox(status, attempts, created_at, memory_id)"
81
+ )
82
+ db.execute("INSERT OR IGNORE INTO metadata VALUES('dense_source_id', ?)", (str(uuid.uuid4()),))
83
+ db.execute("INSERT OR IGNORE INTO metadata VALUES('dense_source_generation', '0')")
84
+ for action in ("INSERT", "UPDATE", "DELETE"):
85
+ db.execute(
86
+ f"CREATE TRIGGER IF NOT EXISTS dense_source_{action.lower()} AFTER {action} ON memories "
87
+ "BEGIN UPDATE metadata SET value=CAST(value AS INTEGER)+1 "
88
+ "WHERE key='dense_source_generation'; END"
89
+ )
90
+ client_type = globals().get("QdrantClient") or __getattr__("QdrantClient")
91
+ if "models" not in globals():
92
+ __getattr__("models")
93
+ self._client = client_type(path=str(self.path))
94
+ self._dimension: int | None = None
95
+ self._next_failed_retry = time.monotonic() + AUTOMATIC_RETRY_BASE_SECONDS
96
+ if self._fingerprint() is not None:
97
+ with self.canonical._connect() as db:
98
+ empty = not db.execute("SELECT 1 FROM memories LIMIT 1").fetchone()
99
+ if empty and self._projection() is None:
100
+ self._prepare_projection()
101
+
102
+ def close(self) -> None:
103
+ """Release the embedded Qdrant local lock held by this owner."""
104
+ self._client.close()
105
+
106
+ def _embed(self, text: str, *, query: bool = False) -> list[float]:
107
+ if query and hasattr(self.embedder, "embed_query"):
108
+ vector = self.embedder.embed_query(text) # type: ignore[attr-defined]
109
+ elif not query and hasattr(self.embedder, "embed_passage"):
110
+ vector = self.embedder.embed_passage(text) # type: ignore[attr-defined]
111
+ else:
112
+ vector = self.embedder.embed(text)
113
+ result = [float(value) for value in vector]
114
+ if not result:
115
+ raise ValueError("Dense embedder returned an empty vector")
116
+ descriptor = getattr(self.embedder, "fingerprint", {})
117
+ if len(result) != descriptor.get("dimension"):
118
+ raise ValueError("Dense embedder dimension does not match its verified descriptor")
119
+ if self._dimension is not None and len(result) != self._dimension:
120
+ raise ValueError("Dense embedder dimension changed during index lifetime")
121
+ self._dimension = len(result)
122
+ return result
123
+
124
+ def _ensure_collection(self) -> None:
125
+ if self._dimension is None:
126
+ self._embed("")
127
+ if not self._client.collection_exists(self.collection_name):
128
+ self._client.create_collection(
129
+ collection_name=self.collection_name,
130
+ vectors_config=models.VectorParams(
131
+ size=self._dimension,
132
+ distance=models.Distance.COSINE,
133
+ ),
134
+ )
135
+
136
+ def _fingerprint(self) -> str | None:
137
+ try:
138
+ descriptor = getattr(self.embedder, "fingerprint", None)
139
+ except Exception:
140
+ return None
141
+ if (not isinstance(descriptor, dict) or descriptor.get("verified") is not True
142
+ or type(descriptor.get("dimension")) is not int or descriptor["dimension"] < 1
143
+ or not descriptor.get("implementation") or descriptor["implementation"] == "unknown"):
144
+ return None
145
+ material = {key: value for key, value in descriptor.items() if key != "digest"}
146
+ try:
147
+ return hashlib.sha256(json.dumps(material, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
148
+ except (TypeError, ValueError):
149
+ return None
150
+
151
+ def _source_identity(self, db: sqlite3.Connection) -> tuple[str, int]:
152
+ values = dict(db.execute("SELECT key,value FROM metadata WHERE key IN "
153
+ "('dense_source_id','dense_source_generation')").fetchall())
154
+ return str(values["dense_source_id"]), int(values["dense_source_generation"])
155
+
156
+ def _projection(self) -> dict[str, Any] | None:
157
+ with self.canonical._connect() as db:
158
+ row = db.execute("SELECT value FROM metadata WHERE key='dense_projection'").fetchone()
159
+ try:
160
+ result = json.loads(row[0]) if row else None
161
+ return result if isinstance(result, dict) else None
162
+ except (ValueError, TypeError):
163
+ return None
164
+
165
+ @staticmethod
166
+ def _save_projection(db: sqlite3.Connection, projection: dict[str, Any]) -> None:
167
+ db.execute("INSERT OR REPLACE INTO metadata VALUES('dense_projection', ?)",
168
+ (json.dumps(projection, sort_keys=True),))
169
+
170
+ def _projection_valid(self, projection: dict[str, Any] | None) -> bool:
171
+ fingerprint = self._fingerprint()
172
+ if not projection or fingerprint is None:
173
+ return False
174
+ with self.canonical._connect() as db:
175
+ source_id, _ = self._source_identity(db)
176
+ if (projection.get("source_id") != source_id
177
+ or projection.get("schema_version") != self.canonical.SCHEMA_VERSION
178
+ or projection.get("fingerprint") != fingerprint
179
+ or projection.get("collection") != self.collection_name):
180
+ return False
181
+ try:
182
+ if not self._client.collection_exists(self.collection_name):
183
+ return False
184
+ marker = self._client.retrieve(self.collection_name, ids=[projection["id"]],
185
+ with_payload=True, with_vectors=False)
186
+ return bool(marker and (marker[0].payload or {}).get("projection_marker") == projection["id"])
187
+ except Exception:
188
+ return False
189
+
190
+ def _prepare_projection(self) -> None:
191
+ fingerprint = self._fingerprint()
192
+ if fingerprint is None:
193
+ return
194
+ with self.canonical._connect() as db:
195
+ source_id, generation = self._source_identity(db)
196
+ projection = {"id": str(uuid.uuid4()), "source_id": source_id,
197
+ "generation": generation, "schema_version": self.canonical.SCHEMA_VERSION,
198
+ "fingerprint": fingerprint, "collection": self.collection_name,
199
+ "complete": False}
200
+ self._save_projection(db, projection)
201
+ db.execute("UPDATE legacy_index_outbox SET action=CASE WHEN memory_id IN "
202
+ "(SELECT id FROM memories WHERE active=1) THEN 'UPSERT' ELSE 'DELETE' END, "
203
+ "status='PENDING', attempts=0, error_digest=NULL")
204
+ db.execute("INSERT OR IGNORE INTO legacy_index_outbox "
205
+ "(memory_id,action,content_hash,status,created_at) "
206
+ "SELECT id,'UPSERT','','PENDING',? FROM memories WHERE active=1", (time.time(),))
207
+ if self._client.collection_exists(self.collection_name):
208
+ self._client.delete_collection(self.collection_name)
209
+ self._dimension = None
210
+ self._ensure_collection()
211
+ self._client.upsert(self.collection_name, points=[models.PointStruct(
212
+ id=projection["id"], vector=[1.0] + [0.0] * (self._dimension - 1),
213
+ payload={"projection_marker": projection["id"]},
214
+ )], wait=True)
215
+ self._finish_projection()
216
+
217
+ def _finish_projection(self) -> None:
218
+ projection = self._projection()
219
+ if not self._projection_valid(projection):
220
+ return
221
+ with self.canonical._connect() as db:
222
+ if db.execute("SELECT 1 FROM legacy_index_outbox WHERE status!='READY' LIMIT 1").fetchone():
223
+ return
224
+ _, generation = self._source_identity(db)
225
+ if projection.get("complete") and projection.get("generation") == generation:
226
+ return
227
+ expected = int(db.execute("SELECT count(*) FROM memories WHERE active=1").fetchone()[0])
228
+ actual = self._client.count(self.collection_name, count_filter=models.Filter(must=[
229
+ models.FieldCondition(key="projection_id", match=models.MatchValue(value=projection["id"]))
230
+ ]), exact=True).count
231
+ if actual != expected:
232
+ projection["complete"] = False
233
+ self._save_projection(db, projection)
234
+ return
235
+ _, projection["generation"] = self._source_identity(db)
236
+ projection["complete"] = True
237
+ self._save_projection(db, projection)
238
+
239
+ @staticmethod
240
+ def _point_id(memory_id: str) -> str:
241
+ try:
242
+ return str(uuid.UUID(memory_id))
243
+ except ValueError:
244
+ return str(uuid.uuid5(uuid.NAMESPACE_URL, f"dandelion-derived:{memory_id}"))
245
+
246
+ @staticmethod
247
+ def _error_digest(error: Exception) -> str:
248
+ # Do not persist error text: canonical templates and exception messages
249
+ # may contain restricted material. The type-only digest remains useful
250
+ # for grouping operational failures.
251
+ return hashlib.sha256(type(error).__name__.encode("utf-8")).hexdigest()
252
+
253
+ @staticmethod
254
+ def _content_hash(row: sqlite3.Row) -> str:
255
+ material = "\x1f".join(
256
+ str(row[name]) for name in ("id", "domain", "template", "active", "supersedes")
257
+ )
258
+ return hashlib.sha256(material.encode("utf-8")).hexdigest()
259
+
260
+ def _load_memory(self, db: sqlite3.Connection, memory_id: str) -> sqlite3.Row | None:
261
+ return db.execute("SELECT * FROM memories WHERE id=?", (memory_id,)).fetchone()
262
+
263
+ def _upsert_row(self, row: sqlite3.Row) -> None:
264
+ vector = self._embed(f"{row['domain']} {row['template']}")
265
+ # No template, fact value, source, or security classification enters
266
+ # Qdrant payload. Every return value is reconstructed from SQLite.
267
+ self._client.upsert(
268
+ collection_name=self.collection_name,
269
+ points=[models.PointStruct(
270
+ id=self._point_id(str(row["id"])),
271
+ vector=vector,
272
+ payload={"memory_id": str(row["id"]), "content_hash": self._content_hash(row),
273
+ "projection_id": self._projection()["id"]},
274
+ )],
275
+ wait=True,
276
+ )
277
+
278
+ def _delete_memory(self, memory_id: str) -> None:
279
+ self._client.delete(
280
+ collection_name=self.collection_name,
281
+ points_selector=models.PointIdsList(points=[self._point_id(memory_id)]),
282
+ wait=True,
283
+ )
284
+
285
+ def _mark_outbox(
286
+ self,
287
+ memory_id: str,
288
+ *,
289
+ status: str,
290
+ error_digest: str | None,
291
+ ) -> None:
292
+ with self.canonical._connect() as db:
293
+ db.execute(
294
+ "UPDATE legacy_index_outbox SET status=?, attempts=attempts+1, error_digest=? "
295
+ "WHERE memory_id=? AND status IN ('PENDING', 'FAILED')",
296
+ (status, error_digest, memory_id),
297
+ )
298
+
299
+ def maintain_pending(self) -> dict[str, Any]:
300
+ """Run one owner checkpoint, spacing failed retries across checkpoints."""
301
+ return self.process_pending(retry_failed=time.monotonic() >= self._next_failed_retry)
302
+
303
+ def process_pending(
304
+ self, *, limit: int = DEFAULT_CONSUME_BATCH_SIZE, retry_failed: bool = True,
305
+ ) -> dict[str, Any]:
306
+ """Apply one small, bounded batch of durable outbox events.
307
+
308
+ A crash after the Qdrant operation but before ``READY`` leaves the row
309
+ PENDING. A failed operation remains visible as ``FAILED`` and is
310
+ retried by a later explicit call or a backed-off owner checkpoint.
311
+ Each call ACKs only its own completed Qdrant work and then returns
312
+ control to the sole owner. A single embedding call remains synchronous.
313
+ """
314
+ if limit < 1:
315
+ raise ValueError("limit must be positive")
316
+ if self._fingerprint() is None:
317
+ readiness = self.readiness()
318
+ return {"processed": 0, "ready": 0, "batch_size": 1,
319
+ "remaining": readiness["pending"] + readiness["failed"], "complete": False, **readiness}
320
+ projection = self._projection()
321
+ with self.canonical._connect() as db:
322
+ _, generation = self._source_identity(db)
323
+ queued = db.execute("SELECT 1 FROM legacy_index_outbox WHERE status!='READY' LIMIT 1").fetchone()
324
+ if (not self._projection_valid(projection)
325
+ or (not queued and (not projection.get("complete")
326
+ or projection.get("generation") != generation))):
327
+ self._prepare_projection()
328
+ batch_size = min(int(limit), MAX_CONSUME_BATCH_SIZE)
329
+ with self.canonical._connect() as db:
330
+ rows = db.execute(
331
+ "SELECT memory_id, action, attempts FROM legacy_index_outbox "
332
+ "WHERE status='PENDING' ORDER BY attempts, created_at, memory_id LIMIT ?",
333
+ (batch_size,),
334
+ ).fetchall()
335
+ if not rows and retry_failed:
336
+ rows = db.execute(
337
+ "SELECT memory_id, action, attempts FROM legacy_index_outbox "
338
+ "WHERE status='FAILED' ORDER BY attempts, created_at, memory_id LIMIT ?",
339
+ (batch_size,),
340
+ ).fetchall()
341
+
342
+ ready = failed = 0
343
+ for event in rows:
344
+ memory_id, action = str(event["memory_id"]), str(event["action"])
345
+ try:
346
+ if action == "DELETE":
347
+ self._delete_memory(memory_id)
348
+ elif action == "UPSERT":
349
+ with self.canonical._connect() as db:
350
+ memory = self._load_memory(db, memory_id)
351
+ # Inactive or deleted canonical rows must never remain
352
+ # candidates. Treat a stale UPSERT as idempotent DELETE.
353
+ if memory is None or not bool(memory["active"]):
354
+ self._delete_memory(memory_id)
355
+ else:
356
+ self._upsert_row(memory)
357
+ else:
358
+ raise ValueError(f"Unsupported derived-index outbox action: {action}")
359
+ except Exception as error:
360
+ self._mark_outbox(memory_id, status="FAILED", error_digest=self._error_digest(error))
361
+ delay = min(AUTOMATIC_RETRY_MAX_SECONDS,
362
+ AUTOMATIC_RETRY_BASE_SECONDS * 2 ** min(int(event["attempts"]), 4))
363
+ self._next_failed_retry = time.monotonic() + delay
364
+ failed += 1
365
+ else:
366
+ self._mark_outbox(memory_id, status="READY", error_digest=None)
367
+ ready += 1
368
+ self._finish_projection()
369
+ readiness = self.readiness()
370
+ remaining = readiness["pending"] + readiness["failed"]
371
+ return {
372
+ "processed": len(rows),
373
+ "ready": ready,
374
+ "failed": failed,
375
+ "batch_size": batch_size,
376
+ "remaining": remaining,
377
+ "complete": remaining == 0 and readiness["readiness"] == "READY",
378
+ **readiness,
379
+ }
380
+
381
+ def readiness(self) -> dict[str, Any]:
382
+ with self.canonical._connect() as db:
383
+ counts = {
384
+ status: int(db.execute(
385
+ "SELECT count(*) FROM legacy_index_outbox WHERE status=?", (status,)
386
+ ).fetchone()[0])
387
+ for status in ("PENDING", "FAILED")
388
+ }
389
+ state = "DEGRADED" if counts["FAILED"] else ("PENDING" if counts["PENDING"] else "READY")
390
+ projection = self._projection()
391
+ with self.canonical._connect() as db:
392
+ _, generation = self._source_identity(db)
393
+ if (not self._projection_valid(projection)
394
+ or (state == "READY" and (not projection.get("complete")
395
+ or projection.get("generation") != generation))):
396
+ state = "NOT_READY"
397
+ return {"readiness": state, "pending": counts["PENDING"], "failed": counts["FAILED"]}
398
+
399
+ def rebuild(self) -> dict[str, Any]:
400
+ """Start a fresh projection and consume one bounded owner batch."""
401
+ self._prepare_projection()
402
+ progress = self.process_pending()
403
+ with self.canonical._connect() as db:
404
+ rebuilt = int(db.execute("SELECT count(*) FROM memories m JOIN legacy_index_outbox o "
405
+ "ON o.memory_id=m.id WHERE m.active=1 AND o.status='READY'").fetchone()[0])
406
+ return {"rebuilt": rebuilt, "acknowledged": progress["ready"], **progress}
407
+
408
+ def recall(
409
+ self,
410
+ query: str,
411
+ *,
412
+ domain: str = "",
413
+ limit: int = 5,
414
+ allow_restricted: bool = False,
415
+ ) -> dict[str, Any]:
416
+ """Dense retrieval that hydrates only authoritative canonical records."""
417
+ if limit < 1:
418
+ raise ValueError("limit must be positive")
419
+ ready = self.readiness()
420
+ if ready["readiness"] == "NOT_READY":
421
+ return {"status": "NOT_READY", "results": [], **ready}
422
+ projection = self._projection()
423
+ hits = self._client.query_points(
424
+ collection_name=self.collection_name,
425
+ query=self._embed(query, query=True),
426
+ limit=max(limit * 4, limit),
427
+ with_payload=True,
428
+ with_vectors=False,
429
+ query_filter=models.Filter(must=[models.FieldCondition(
430
+ key="projection_id", match=models.MatchValue(value=projection["id"]),
431
+ )]),
432
+ ).points
433
+ results: list[dict[str, Any]] = []
434
+ with self.canonical._connect() as db:
435
+ for hit in hits:
436
+ payload = hit.payload or {}
437
+ memory_id = payload.get("memory_id")
438
+ if not isinstance(memory_id, str):
439
+ continue
440
+ row = self._load_memory(db, memory_id)
441
+ if row is None or not bool(row["active"]) or (domain and row["domain"] != domain):
442
+ continue
443
+ event = db.execute(
444
+ "SELECT action,status FROM legacy_index_outbox WHERE memory_id=?", (memory_id,),
445
+ ).fetchone()
446
+ if (event is None or event["status"] != "READY" or event["action"] != "UPSERT"
447
+ or payload.get("content_hash") != self._content_hash(row)):
448
+ continue
449
+ restricted = row["security_class"] != "PUBLIC" or is_sensitive_value(row["template"])
450
+ # Match canonical lexical recall's non-enumerating public
451
+ # policy. A placeholder would still leak identity and
452
+ # provenance metadata from the authoritative row.
453
+ if restricted and not allow_restricted:
454
+ continue
455
+ text, references = self.canonical._resolve_memory_content(
456
+ db, row["id"], row["template"], created_at=row["created_at"], allow_restricted=allow_restricted,
457
+ )
458
+ results.append({
459
+ "memory_id": row["id"],
460
+ "domain": row["domain"],
461
+ "template": row["template"],
462
+ "text": text,
463
+ "references": references,
464
+ "status": "SUPPORTED",
465
+ "source": row["source"],
466
+ "authority": row["authority"],
467
+ "reason": row["reason"],
468
+ **({"claim_kind": "ASSERTED"}
469
+ if self.canonical._is_asserted_memory(db, row) else {}),
470
+ "score": float(hit.score),
471
+ })
472
+ if len(results) >= limit:
473
+ break
474
+ status = "SUPPORTED" if results else ("UNKNOWN" if ready["readiness"] == "READY" else "NOT_READY")
475
+ return {"status": status, "results": results, **ready}
476
+
477
+
478
+ class CanonicalDerivedService:
479
+ """Explicit owner-service composition hook for ``MemoryOwner`` callers.
480
+
481
+ It intentionally leaves existing canonical operations untouched and adds
482
+ only five owner operations: ``consume_dense``, ``rebuild_dense``,
483
+ ``dense_recall``, ``search``, and ``index_status``.
484
+ """
485
+
486
+ def __init__(self, canonical: CanonicalMemory, derived: DerivedIndex | None = None) -> None:
487
+ self.canonical = canonical
488
+ self.derived = derived
489
+
490
+ def owner_stop_status(self) -> dict[str, Any]:
491
+ return self.canonical.owner_stop_status()
492
+
493
+ def recover_owner_operations(self) -> None:
494
+ self.canonical.recover_owner_operations()
495
+
496
+ def maintain_owner(self) -> None:
497
+ if self.derived is not None and self.owner_stop_status()["status"] != "BUSY":
498
+ self.derived.maintain_pending()
499
+
500
+ def close(self) -> None:
501
+ if self.derived is not None:
502
+ self.derived.close()
503
+
504
+ def backup(self, **payload: Any) -> dict[str, Any]:
505
+ return self.canonical.backup(**payload)
506
+
507
+ def readiness(self) -> dict[str, Any]:
508
+ if self.derived is None:
509
+ with self.canonical._connect() as db:
510
+ pending = int(db.execute("SELECT count(*) FROM legacy_index_outbox WHERE status='PENDING'").fetchone()[0])
511
+ failed = int(db.execute("SELECT count(*) FROM legacy_index_outbox WHERE status='FAILED'").fetchone()[0])
512
+ return {"readiness": "DISABLED", "profile": "lexical", "lexical_readiness": "READY",
513
+ "dense_enabled": False, "pending": pending, "failed": failed}
514
+ return self.derived.readiness()
515
+
516
+ @staticmethod
517
+ def _search_limit(limit: int) -> int:
518
+ if limit < 1:
519
+ raise ValueError("limit must be positive")
520
+ return min(MAX_SEARCH_CANDIDATES, max(limit, limit * 3))
521
+
522
+ @staticmethod
523
+ def _public_memory_result(item: dict[str, Any]) -> dict[str, Any]:
524
+ """Keep hydrated canonical fields while not echoing raw templates."""
525
+ return {
526
+ "memory_id": item["memory_id"],
527
+ "result_type": "memory",
528
+ "domain": item.get("domain", ""),
529
+ "text": item.get("text", ""),
530
+ "references": item.get("references", []),
531
+ "access_status": item.get("status", "UNKNOWN"),
532
+ "source": item.get("source", ""),
533
+ "authority": item.get("authority", ""),
534
+ "reason": item.get("reason", ""),
535
+ **({"claim_kind": item["claim_kind"]} if "claim_kind" in item else {}),
536
+ **({"semantics": item["semantics"]} if "semantics" in item else {}),
537
+ }
538
+
539
+ def op_search(
540
+ self,
541
+ query: str,
542
+ domain: str = "",
543
+ limit: int = 5,
544
+ exact_key: str = "",
545
+ ) -> dict[str, Any]:
546
+ """Bounded, owner-authoritative lexical + dense discovery.
547
+
548
+ ``MATCHES`` denotes exact or lexical retrieval evidence; ``CANDIDATES``
549
+ means the result came only from dense similarity. Index readiness is
550
+ intentionally orthogonal so an unavailable dense projection never
551
+ changes a lexical/exact match into a failure claim.
552
+ """
553
+ if not isinstance(query, str) or not query.strip():
554
+ raise ValueError("search query must be a non-empty string")
555
+ if not isinstance(exact_key, str):
556
+ raise ValueError("exact_key must be a string")
557
+ if exact_key and len(exact_key) > 256:
558
+ raise ValueError("exact_key is too long")
559
+ candidate_limit = self._search_limit(limit)
560
+ allow_restricted = self.canonical.allows_restricted
561
+ readiness = self.readiness()
562
+ dense: dict[str, Any] = {"results": []}
563
+ dense_error: str | None = None
564
+ if self.derived is not None:
565
+ # Unlike the diagnostic dense operation, search never permits a
566
+ # request payload to choose a security policy.
567
+ try:
568
+ dense = self.derived.recall(
569
+ query, domain=domain, limit=candidate_limit,
570
+ allow_restricted=allow_restricted,
571
+ )
572
+ readiness = {**readiness, "readiness": dense.get("readiness", readiness["readiness"])}
573
+ except Exception as error:
574
+ # Discovery remains useful when the rebuildable projection
575
+ # fails mid-query. Do not expose error text, which can carry
576
+ # local paths or restricted query material.
577
+ dense_error = type(error).__name__
578
+ readiness = {**readiness, "readiness": "DEGRADED"}
579
+
580
+ core = collect_ranked_candidates(
581
+ self.canonical, [query], scope={"domain": domain} if domain else {},
582
+ dense_candidates=list(dense.get("results", [])),
583
+ explicit_keys=[exact_key] if exact_key.strip() else [],
584
+ limit=candidate_limit, allow_restricted_memories=allow_restricted,
585
+ allow_restricted_exact=allow_restricted, strict_fact_index=True,
586
+ )
587
+ dense_scores = {str(item.get("memory_id")): float(item["score"])
588
+ for item in dense.get("results", [])
589
+ if isinstance(item.get("memory_id"), str) and "score" in item}
590
+ results: list[dict[str, Any]] = []
591
+ for found in core["candidates"][:max(candidate_limit * 4, limit)]:
592
+ record = hydrate_candidate(self.canonical, found, domain=domain,
593
+ allow_restricted=allow_restricted)
594
+ if record is None:
595
+ continue
596
+ record_kind, key, revision = found["record_kind"], found["id"], found["revision"]
597
+ raw_channels = set(found["channels"])
598
+ channels = set()
599
+ if "exact_key" in raw_channels or "path_scope" in raw_channels:
600
+ channels.add("exact")
601
+ if "dense" in raw_channels:
602
+ channels.add("dense")
603
+ lexical_channel = "fact_lexical" if record_kind == "fact" else "lexical"
604
+ if raw_channels & {"fact_lexical", "memory_lexical", "memory_aux", "exact_value"}:
605
+ channels.add(lexical_channel)
606
+ lexical_rank = found.get("lexical_rank")
607
+ dense_rank = found.get("dense_rank")
608
+ ranks = {}
609
+ if lexical_rank is not None:
610
+ ranks[lexical_channel] = lexical_rank
611
+ if dense_rank is not None:
612
+ ranks["dense"] = dense_rank
613
+ if "exact" in channels:
614
+ ranks["exact"] = 1
615
+ contributions = []
616
+ if "exact" in channels:
617
+ contributions.append({"channel": "exact", "rank": 1, "weight": 1.0,
618
+ "rrf": 1.0 / 61})
619
+ if lexical_rank is not None:
620
+ contributions.append({"channel": lexical_channel, "rank": lexical_rank,
621
+ "weight": 1.0, "rrf": 1.0 / (60 + lexical_rank)})
622
+ if dense_rank is not None:
623
+ contributions.append({"channel": "dense", "rank": dense_rank,
624
+ "weight": 1.0, "rrf": 1.0 / (60 + dense_rank)})
625
+ if record_kind == "fact":
626
+ candidate_id = f"fact:{key}@rev:{revision}"
627
+ result = {
628
+ "memory_id": candidate_id, "result_type": "fact", "key": key,
629
+ "revision": revision, "text": record.get("value", "[UNKNOWN]"),
630
+ "canonical_reference": {"kind": "fact", "key": key, "revision": revision},
631
+ "resolution_method": "get_fact", "channel": "exact" if "exact" in channels else "fact_lexical",
632
+ "access_status": "CANDIDATE", "source": record.get("source", ""),
633
+ "authority": record.get("authority", ""), "reason": record.get("reason", ""),
634
+ "score_provenance": {"method": "canonical_rank", "rank": found["rank"]},
635
+ }
636
+ if "captured_input" in record:
637
+ result.update({name: record[name] for name in (
638
+ "captured_input", "captured_input_page", "continuation", "truncated",
639
+ "linked_memory", "match", "source_identity", "claim_kind",
640
+ ) if name in record})
641
+ else:
642
+ result = self._public_memory_result(record)
643
+ result.update({
644
+ "channels": sorted(channels), "ranks": ranks,
645
+ "dense_score": dense_scores.get(key),
646
+ "sources": [{"channel": channel, "source": record.get("source", ""),
647
+ "authority": record.get("authority", ""),
648
+ "reason": record.get("reason", "")}
649
+ for channel in sorted(channels)],
650
+ "fusion": {"method": "anchor_first_reciprocal_rank", "k": 60,
651
+ "score": sum(part["rrf"] for part in contributions),
652
+ "contributions": contributions},
653
+ })
654
+ results.append(result)
655
+ if len(results) >= limit:
656
+ break
657
+ retrieval_diagnostics = [
658
+ {
659
+ "result_rank": result_rank,
660
+ "channels": row["channels"],
661
+ "channel_ranks": row["ranks"],
662
+ }
663
+ for result_rank, row in enumerate(results, start=1)
664
+ ]
665
+ has_match = any(
666
+ any(channel in row["channels"] for channel in ("exact", "lexical", "fact_lexical"))
667
+ for row in results
668
+ )
669
+ return {
670
+ "status": "MATCHES" if has_match else ("CANDIDATES" if results else "UNKNOWN"),
671
+ "results": results,
672
+ "readiness": readiness["readiness"],
673
+ "dense_readiness": readiness,
674
+ "dense_error": dense_error,
675
+ "candidate_limit": candidate_limit,
676
+ "retrieval_diagnostics": retrieval_diagnostics,
677
+ }
678
+
679
+ def op_recall_v2(self, question: str, terms: list[str], kind: str = "any",
680
+ scope: dict[str, str] | None = None, limit: int = 8,
681
+ offset: int = 0) -> dict[str, Any]:
682
+ """Opt-in v2 facade: fuse lexical/dense candidates after exact anchors."""
683
+ from dandelion.recall_v2 import recall_v2
684
+
685
+ scope = scope or {}
686
+ if not isinstance(scope, dict):
687
+ raise ValueError("scope must be a path/domain mapping")
688
+ readiness = self.readiness()
689
+ dense: list[dict[str, Any]] = []
690
+ dense_error: str | None = None
691
+ if (self.derived is not None and not scope.get("path")
692
+ and kind != "history"):
693
+ try:
694
+ found = self.derived.recall(
695
+ question.strip() or " ".join(terms),
696
+ domain=scope.get("domain", ""), limit=40, allow_restricted=False,
697
+ )
698
+ dense = list(found.get("results", []))
699
+ readiness = {**readiness, "readiness": found.get("readiness", readiness["readiness"])}
700
+ except Exception as error:
701
+ dense_error = type(error).__name__
702
+ readiness = {**readiness, "readiness": "DEGRADED"}
703
+ result = recall_v2(self.canonical, question, terms, kind=kind, scope=scope,
704
+ limit=limit, offset=offset, dense_candidates=dense)
705
+ result["dense_readiness"] = readiness["readiness"]
706
+ result["dense_error"] = dense_error
707
+ return result
708
+
709
+ def dispatch(self, operation: str, payload: dict[str, Any], *, request_id: str = "") -> dict[str, Any]:
710
+ if self.derived is None and operation in {"consume_dense", "rebuild_dense", "dense_recall"}:
711
+ return {"status": "NOT_READY", "results": [], **self.readiness()}
712
+ if operation == "consume_dense":
713
+ if self.owner_stop_status()["status"] == "BUSY":
714
+ return {"status": "BUSY"}
715
+ result = self.derived.process_pending(**payload)
716
+ elif operation == "rebuild_dense":
717
+ if self.owner_stop_status()["status"] == "BUSY":
718
+ return {"status": "BUSY"}
719
+ if payload:
720
+ raise ValueError("rebuild_dense accepts no arguments")
721
+ result = self.derived.rebuild()
722
+ elif operation == "dense_recall":
723
+ # Public RPC arguments cannot weaken the host's access policy.
724
+ payload = dict(payload)
725
+ payload["allow_restricted"] = self.canonical.allows_restricted
726
+ result = self.derived.recall(**payload)
727
+ elif operation == "search":
728
+ result = self.op_search(**payload)
729
+ elif operation == "recall_v2":
730
+ result = self.op_recall_v2(**payload)
731
+ elif operation == "index_status":
732
+ if payload:
733
+ raise ValueError("index_status accepts no arguments")
734
+ result = self.readiness()
735
+ else:
736
+ result = self.canonical.dispatch(operation, payload, request_id=request_id)
737
+ # Canonical memory follows the authenticated owner's selected mode.
738
+ # Preview/source-evidence operations retain their strict public boundary.
739
+ if operation in {"search", "dense_recall"}:
740
+ return self.canonical.egress(result)
741
+ if operation == "recall_v2":
742
+ return public_egress(result)
743
+ # CanonicalMemory.dispatch applies the authenticated mode only to its
744
+ # canonical-memory allowlist and keeps source/evidence operations strict.
745
+ return result