memoryking 0.1.0__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 (179) hide show
  1. memoryking/__init__.py +3 -0
  2. memoryking/__main__.py +1328 -0
  3. memoryking/adapters/__init__.py +1 -0
  4. memoryking/adapters/adapter_state.py +242 -0
  5. memoryking/adapters/anchor_schema.sql +7 -0
  6. memoryking/adapters/atlas.py +441 -0
  7. memoryking/adapters/browser_commands.py +125 -0
  8. memoryking/adapters/dashboard.py +510 -0
  9. memoryking/adapters/dense_search.py +86 -0
  10. memoryking/adapters/egress_policy.py +244 -0
  11. memoryking/adapters/egress_schema.sql +13 -0
  12. memoryking/adapters/embedding.schema.json +302 -0
  13. memoryking/adapters/embedding_store.py +469 -0
  14. memoryking/adapters/execution.py +369 -0
  15. memoryking/adapters/experience.py +423 -0
  16. memoryking/adapters/experience.schema.json +1508 -0
  17. memoryking/adapters/experience_records.py +239 -0
  18. memoryking/adapters/experience_schema.sql +23 -0
  19. memoryking/adapters/handoff.py +494 -0
  20. memoryking/adapters/handoff.schema.json +299 -0
  21. memoryking/adapters/handoff_schema.sql +17 -0
  22. memoryking/adapters/index_schema.sql +11 -0
  23. memoryking/adapters/inference.py +454 -0
  24. memoryking/adapters/inference.schema.json +541 -0
  25. memoryking/adapters/inspection.py +1128 -0
  26. memoryking/adapters/inspection.schema.json +568 -0
  27. memoryking/adapters/knowledge.schema.json +633 -0
  28. memoryking/adapters/knowledge_schema.sql +37 -0
  29. memoryking/adapters/knowledge_store.py +800 -0
  30. memoryking/adapters/legacy_snapshot.py +358 -0
  31. memoryking/adapters/legacy_tables.py +49 -0
  32. memoryking/adapters/local_contract.py +45 -0
  33. memoryking/adapters/local_embeddings.py +189 -0
  34. memoryking/adapters/local_files.py +242 -0
  35. memoryking/adapters/local_ipc.py +258 -0
  36. memoryking/adapters/local_schema.sql +44 -0
  37. memoryking/adapters/local_store.py +632 -0
  38. memoryking/adapters/local_wire.schema.json +7672 -0
  39. memoryking/adapters/models/minilm-l6-v2-onnx.json +57 -0
  40. memoryking/adapters/models/ms-marco-minilm-l6-v2-onnx.json +57 -0
  41. memoryking/adapters/optional_schema.sql +43 -0
  42. memoryking/adapters/plan_dashboard.py +51 -0
  43. memoryking/adapters/plans.py +253 -0
  44. memoryking/adapters/postgres_admin.py +300 -0
  45. memoryking/adapters/postgres_anchor_schema.sql +9 -0
  46. memoryking/adapters/postgres_counter.sql +14 -0
  47. memoryking/adapters/postgres_egress_schema.sql +15 -0
  48. memoryking/adapters/postgres_experience_schema.sql +39 -0
  49. memoryking/adapters/postgres_index_schema.sql +7 -0
  50. memoryking/adapters/postgres_optional_schema.sql +71 -0
  51. memoryking/adapters/postgres_pool.py +77 -0
  52. memoryking/adapters/postgres_recovery.py +525 -0
  53. memoryking/adapters/postgres_schema.sql +365 -0
  54. memoryking/adapters/postgres_sql.py +102 -0
  55. memoryking/adapters/postgres_store.py +428 -0
  56. memoryking/adapters/postgres_summary_schema.sql +12 -0
  57. memoryking/adapters/postgres_trust_schema.sql +20 -0
  58. memoryking/adapters/processing.schema.json +471 -0
  59. memoryking/adapters/processing_store.py +346 -0
  60. memoryking/adapters/projects.py +83 -0
  61. memoryking/adapters/proposals.py +238 -0
  62. memoryking/adapters/ranking.py +315 -0
  63. memoryking/adapters/repository.schema.json +664 -0
  64. memoryking/adapters/repository_git.py +264 -0
  65. memoryking/adapters/repository_schema.sql +25 -0
  66. memoryking/adapters/repository_store.py +960 -0
  67. memoryking/adapters/retrieval.py +1285 -0
  68. memoryking/adapters/retrieval.schema.json +553 -0
  69. memoryking/adapters/retrieval_schema.sql +10 -0
  70. memoryking/adapters/shared_control.py +40 -0
  71. memoryking/adapters/shared_dashboard.py +636 -0
  72. memoryking/adapters/shared_gateway.py +63 -0
  73. memoryking/adapters/shared_http.py +216 -0
  74. memoryking/adapters/shared_mcp.py +159 -0
  75. memoryking/adapters/shared_service.py +124 -0
  76. memoryking/adapters/stdio.py +193 -0
  77. memoryking/adapters/stdio.tools.json +6776 -0
  78. memoryking/adapters/summary_schema.sql +10 -0
  79. memoryking/adapters/team.py +253 -0
  80. memoryking/adapters/timeline.py +80 -0
  81. memoryking/adapters/token_count.py +55 -0
  82. memoryking/adapters/tokenizers/LICENSE +21 -0
  83. memoryking/adapters/tokenizers/cl100k_base.tiktoken +100256 -0
  84. memoryking/adapters/trust.py +123 -0
  85. memoryking/adapters/trust_schema.sql +13 -0
  86. memoryking/adapters/web/app.css +1251 -0
  87. memoryking/adapters/web/app.js +907 -0
  88. memoryking/adapters/web/brand.js +44 -0
  89. memoryking/adapters/web/crown-mono.svg +1 -0
  90. memoryking/adapters/web/crown.svg +8 -0
  91. memoryking/adapters/web/elephant.png +0 -0
  92. memoryking/adapters/web/favicon.svg +8 -0
  93. memoryking/adapters/web/graph-layout.js +52 -0
  94. memoryking/adapters/web/graph-worker.js +10 -0
  95. memoryking/adapters/web/graph.js +570 -0
  96. memoryking/adapters/web/index.html +208 -0
  97. memoryking/adapters/web/observatory.js +1208 -0
  98. memoryking/adapters/web/team.js +151 -0
  99. memoryking/adapters/web/wordmark.svg +1 -0
  100. memoryking/adapters/working.py +971 -0
  101. memoryking/adapters/working.schema.json +1717 -0
  102. memoryking/adapters/working_schema.sql +24 -0
  103. memoryking/application/__init__.py +1 -0
  104. memoryking/application/conformance.py +50 -0
  105. memoryking/application/legacy_import.py +337 -0
  106. memoryking/application/local_port.py +9 -0
  107. memoryking/application/storage.py +117 -0
  108. memoryking/application/store_core.py +1292 -0
  109. memoryking/backups.py +131 -0
  110. memoryking/contracts/__init__.py +6 -0
  111. memoryking/contracts/__main__.py +20 -0
  112. memoryking/contracts/canonical.py +88 -0
  113. memoryking/contracts/embedding.schema.json +302 -0
  114. memoryking/contracts/embedding_generated.py +65 -0
  115. memoryking/contracts/experience.schema.json +1508 -0
  116. memoryking/contracts/experience_generated.py +239 -0
  117. memoryking/contracts/generated.py +122 -0
  118. memoryking/contracts/handoff.schema.json +299 -0
  119. memoryking/contracts/handoff_generated.py +69 -0
  120. memoryking/contracts/inference.schema.json +541 -0
  121. memoryking/contracts/inference_generated.py +106 -0
  122. memoryking/contracts/processing.schema.json +471 -0
  123. memoryking/contracts/processing_generated.py +82 -0
  124. memoryking/contracts/py.typed +0 -0
  125. memoryking/contracts/repository.schema.json +664 -0
  126. memoryking/contracts/repository_generated.py +144 -0
  127. memoryking/contracts/retrieval.schema.json +553 -0
  128. memoryking/contracts/retrieval_generated.py +110 -0
  129. memoryking/contracts/schema.json +696 -0
  130. memoryking/contracts/validation.py +92 -0
  131. memoryking/contracts/working.schema.json +1717 -0
  132. memoryking/contracts/working_generated.py +291 -0
  133. memoryking/domain/__init__.py +1 -0
  134. memoryking/domain/anchors.py +97 -0
  135. memoryking/domain/briefing.py +108 -0
  136. memoryking/domain/briefing_text.py +222 -0
  137. memoryking/domain/checkpoint.py +118 -0
  138. memoryking/domain/compression.py +64 -0
  139. memoryking/domain/delta.py +129 -0
  140. memoryking/domain/embeddings.py +90 -0
  141. memoryking/domain/hints.py +465 -0
  142. memoryking/domain/http_status.py +45 -0
  143. memoryking/domain/learning.py +62 -0
  144. memoryking/domain/local.py +65 -0
  145. memoryking/domain/plans.py +140 -0
  146. memoryking/domain/repository.py +118 -0
  147. memoryking/domain/selectors.py +356 -0
  148. memoryking/domain/summary.py +88 -0
  149. memoryking/domain/usage.py +163 -0
  150. memoryking/embedding_loop.py +98 -0
  151. memoryking/embedding_worker.py +131 -0
  152. memoryking/harness.py +882 -0
  153. memoryking/harness_context.py +376 -0
  154. memoryking/hooks.py +171 -0
  155. memoryking/host_hooks.py +454 -0
  156. memoryking/lean.py +352 -0
  157. memoryking/memory_tool.py +776 -0
  158. memoryking/migration.py +194 -0
  159. memoryking/model_install.py +78 -0
  160. memoryking/observability.py +101 -0
  161. memoryking/observability_metrics.py +100 -0
  162. memoryking/profiles.py +150 -0
  163. memoryking/providers.py +330 -0
  164. memoryking/py.typed +0 -0
  165. memoryking/pytest_plugin.py +69 -0
  166. memoryking/reference_agent.py +152 -0
  167. memoryking/repository_worker.py +57 -0
  168. memoryking/resume_adapter.py +154 -0
  169. memoryking/sdk.py +302 -0
  170. memoryking/shared.py +301 -0
  171. memoryking/shared_sdk.py +101 -0
  172. memoryking/vault.py +176 -0
  173. memoryking-0.1.0.dist-info/METADATA +157 -0
  174. memoryking-0.1.0.dist-info/RECORD +179 -0
  175. memoryking-0.1.0.dist-info/WHEEL +5 -0
  176. memoryking-0.1.0.dist-info/entry_points.txt +7 -0
  177. memoryking-0.1.0.dist-info/licenses/LICENSE +202 -0
  178. memoryking-0.1.0.dist-info/licenses/NOTICE +12 -0
  179. memoryking-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1292 @@
1
+ """Backend-agnostic store operations behind the storage port.
2
+
3
+ Authorization, capture, reads, grants, purge policy, idempotent retries, jobs, context
4
+ and status live here once, written in portable SQL against a dialect. A backend (SQLite
5
+ in `adapters.local_store`, PostgreSQL in `adapters.postgres_store`) supplies the
6
+ connection, the transaction discipline, the control tree and token signing. Neither
7
+ backend subclasses the other.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import secrets
16
+ import threading
17
+ from collections.abc import Iterator
18
+ from contextlib import contextmanager
19
+ from pathlib import Path
20
+ from typing import Any, Self, cast
21
+
22
+ from memoryking.adapters.local_contract import validate_capture
23
+ from memoryking.adapters.local_files import atomic, private_dir, private_file, sync_dir
24
+ from memoryking.application.storage import Dialect, insert_ignore, upsert
25
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
26
+ from memoryking.domain.local import Clock, Decision, LocalError, Released, temporal_valid
27
+
28
+ Row = Any
29
+
30
+
31
+ CAPABILITIES = {
32
+ "capture",
33
+ "read",
34
+ "export",
35
+ "jobs",
36
+ "admin",
37
+ "review",
38
+ "policy",
39
+ "attest",
40
+ "task_constraint",
41
+ "checkpoint",
42
+ "handoff",
43
+ "inference",
44
+ "repository",
45
+ }
46
+
47
+
48
+ RETRY_MS = 30 * 24 * 60 * 60 * 1000
49
+
50
+
51
+ QUEUE_LIMIT = 1000
52
+
53
+
54
+ CONCURRENCY_LIMIT = 4
55
+
56
+
57
+ MAX_ATTEMPTS = 5
58
+
59
+
60
+ MAX_COUNTER = 9_007_199_254_740_991
61
+
62
+
63
+ ARTIFACT_LIMIT = 1024
64
+
65
+
66
+ ARTIFACT_BYTES_LIMIT = 134217728
67
+
68
+
69
+ INTENT_LIMIT = 4096
70
+
71
+
72
+ INTENT_SCOPE_LIMIT = 32
73
+
74
+
75
+ USAGE_LIMIT = 100000
76
+
77
+
78
+ OPEN_INTENT_STATES = ("intent_recorded", "dispatching", "unknown")
79
+
80
+
81
+ CAPACITY_LIMITS = {
82
+ "jobs": QUEUE_LIMIT,
83
+ "rendered_artifacts": ARTIFACT_LIMIT,
84
+ "rendered_bytes": ARTIFACT_BYTES_LIMIT,
85
+ "operation_intents": INTENT_LIMIT,
86
+ "processing_usage": USAGE_LIMIT,
87
+ }
88
+
89
+
90
+ def identifier(value: str) -> str:
91
+ if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,96}", value):
92
+ raise LocalError("invalid_identifier")
93
+ return value
94
+
95
+
96
+ def uid(prefix: str) -> str:
97
+ return prefix + "_" + secrets.token_hex(16)
98
+
99
+
100
+ class StoreCore:
101
+ """What every backend shares; the attributes below are supplied by the backend."""
102
+
103
+ db: Any
104
+ dialect: Dialect
105
+ control: Any
106
+ control_path: Path
107
+ root: Path
108
+ clock: Clock
109
+ lock: threading.RLock
110
+ store_id: str
111
+ incarnation: str
112
+ healthy: bool
113
+ fault: Any
114
+ counters: Any
115
+ timings: Any
116
+ retrieval_cache: dict[str, Any]
117
+ anchor: dict[str, Any]
118
+ last_utc: int
119
+ # Daemon-side policies default off; the serving backend sets them from its flags.
120
+ backup_policy: Any | None = None
121
+ embedder: Any | None = None
122
+ reranker: Any | None = None
123
+ summary_idle_ms = 0
124
+ _last_housekeeping = 0
125
+ _last_summary_scan = 0
126
+
127
+ # The operator's egress policy; None means the local recorder is the only provider.
128
+ # A class default so every store, including PostgreSQL, reports a revision.
129
+ egress_policy: Any | None = None
130
+
131
+ dashboard: Any = None
132
+
133
+ def __enter__(self) -> Self:
134
+ return self
135
+
136
+ def __exit__(self, *args: Any) -> None:
137
+ self.close()
138
+
139
+ def close(self) -> None:
140
+ raise NotImplementedError
141
+
142
+ @contextmanager
143
+ def transaction(self) -> Iterator[Decision]:
144
+ """A backend opens its transaction and yields the authorization instant."""
145
+ raise NotImplementedError
146
+ yield # pragma: no cover
147
+
148
+ def _expose(self) -> None:
149
+ """A backend durably exposes committed evidence before releasing bytes."""
150
+ raise NotImplementedError
151
+
152
+ def gc(self) -> int:
153
+ """A backend removes unreferenced blobs and expired results in its own way."""
154
+ raise NotImplementedError
155
+
156
+ def _now(self) -> Decision:
157
+ now = self.clock.utc_ms()
158
+ if now < self.last_utc:
159
+ raise LocalError("clock_untrusted")
160
+ self.last_utc = now
161
+ return Decision(now, self.clock.monotonic_ms(), now + 5000)
162
+
163
+ def _token(self, kind: str, **fields: Any) -> str:
164
+ return str(
165
+ self.control.sign(
166
+ {"kind": kind, "store": self.store_id, "incarnation": self.incarnation, **fields}
167
+ )
168
+ )
169
+
170
+ def _decode(self, token: str, kind: str) -> dict[str, Any]:
171
+ body = self.control.verify(token)
172
+ if body.get("store") != self.store_id or body.get("kind") != kind:
173
+ raise LocalError("invalid_token")
174
+ if body.get("incarnation") != self.incarnation:
175
+ raise LocalError("history_changed")
176
+ return cast(dict[str, Any], body)
177
+
178
+ def _auth(self, token: str, capability: str, project: str, at: int) -> dict[str, Any]:
179
+ identity = self._decode(token, "credential")
180
+ rows = self.db.execute(
181
+ "SELECT * FROM grants WHERE tenant=? AND principal=? AND project IN (?, '*')",
182
+ (identity["tenant"], identity["principal"], project),
183
+ ).fetchall()
184
+ if not any(
185
+ (
186
+ capability in json.loads(row["capabilities"])
187
+ or "admin" in json.loads(row["capabilities"])
188
+ )
189
+ and temporal_valid(at, row["starts"], row["expires"])
190
+ for row in rows
191
+ ):
192
+ raise LocalError("denied")
193
+ return identity
194
+
195
+ def _subject_auth(self, token: str, capability: str, project: str, at: int) -> dict[str, Any]:
196
+ """Internal intersection check; never an alternate transport credential entry point."""
197
+ return self._auth(token, capability, project, at)
198
+
199
+ def namespace(self, credential: str, project: str, name: str | None = None) -> str:
200
+ """A capture namespace token.
201
+
202
+ A named namespace is deterministic for the principal, so a retry with the same
203
+ key from any process replays or conflicts exactly as documented. An unnamed
204
+ namespace is fresh and random.
205
+ """
206
+ with self.transaction() as decision:
207
+ identity = self._auth(credential, "capture", project, decision.evaluated_ms)
208
+ token = self._token(
209
+ "namespace",
210
+ tenant=identity["tenant"],
211
+ principal=identity["principal"],
212
+ id="nsn_" + identifier(name) if name is not None else uid("ns"),
213
+ )
214
+ self._expose()
215
+ return token
216
+
217
+ def _event(self, tenant: str, kind: str, subject: str, at: int, actor: str = "system") -> int:
218
+ if (
219
+ self.db.execute("SELECT position FROM tenants WHERE tenant=?", (tenant,)).fetchone()[0]
220
+ >= MAX_COUNTER
221
+ ):
222
+ raise LocalError("counter_exhausted")
223
+ self.db.execute("UPDATE tenants SET position=position+1 WHERE tenant=?", (tenant,))
224
+ position: int = self.db.execute(
225
+ "SELECT position FROM tenants WHERE tenant=?", (tenant,)
226
+ ).fetchone()[0]
227
+ self.db.execute(
228
+ "INSERT INTO events VALUES (?,?,?,?,?,?,?,?)",
229
+ (tenant, position, uid("evt"), kind, subject, self.incarnation, at, actor),
230
+ )
231
+ return position
232
+
233
+ def _blob(self, tenant: str, content: bytes) -> str:
234
+ digest = hashlib.sha256(content).hexdigest()
235
+ directory = self.root / "blobs" / identifier(tenant)
236
+ private_dir(directory, create=True)
237
+ sync_dir(directory.parent)
238
+ path = directory / digest
239
+ if not path.exists():
240
+ atomic(path, content)
241
+ else:
242
+ private_file(path)
243
+ if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
244
+ raise LocalError("blob_corrupt")
245
+ self.fault("after_blob")
246
+ return digest
247
+
248
+ def capture(
249
+ self, credential: str, namespace: str, key: str, request: dict[str, Any]
250
+ ) -> dict[str, Any]:
251
+ identifier(key)
252
+ validate_capture(request)
253
+ readers = request["readers"]
254
+ digest = canonical_hash(request)
255
+ with self.transaction() as decision:
256
+ who = self._auth(credential, "capture", request["project"], decision.evaluated_ms)
257
+ ns = self._decode(namespace, "namespace")
258
+ if any(ns[x] != who[x] for x in ("tenant", "principal")):
259
+ raise LocalError("denied")
260
+ tenant = who["tenant"]
261
+ lookup = (tenant, self.incarnation, ns["id"], who["principal"], "capture", key)
262
+ retry = self.db.execute(
263
+ "SELECT * FROM retries WHERE tenant=? AND incarnation=? AND namespace=? AND principal=? AND operation=? AND key=?",
264
+ lookup,
265
+ ).fetchone()
266
+ if retry is not None:
267
+ if retry["hash"] != digest:
268
+ raise LocalError("idempotency_conflict")
269
+ if retry["result"] is None or decision.evaluated_ms >= retry["expires"]:
270
+ raise LocalError("idempotency_result_expired")
271
+ result = cast(dict[str, Any], json.loads(retry["result"]))
272
+ else:
273
+ if self.db.execute(
274
+ "SELECT 1 FROM retired_sources WHERE tenant=? AND principal=? AND source=? AND source_event=?",
275
+ (tenant, who["principal"], request["source"], request["source_event"]),
276
+ ).fetchone():
277
+ raise LocalError("source_retired")
278
+ occurrence = self.db.execute(
279
+ "SELECT * FROM observations WHERE tenant=? AND principal=? AND source=? AND source_event=?",
280
+ (tenant, who["principal"], request["source"], request["source_event"]),
281
+ ).fetchone()
282
+ if occurrence is not None:
283
+ if occurrence["deleted"]:
284
+ raise LocalError("source_retired")
285
+ if occurrence["payload_hash"] != digest:
286
+ raise LocalError("source_conflict")
287
+ from memoryking.adapters.trust import Trust
288
+
289
+ result = {
290
+ **self._capture_result(tenant, occurrence["id"], occurrence["position"]),
291
+ "held": Trust(self).held(tenant, occurrence["id"]),
292
+ }
293
+ else:
294
+ count = self.db.execute(
295
+ "SELECT count(*) FROM jobs WHERE tenant=? AND state IN ('pending','leased')",
296
+ (tenant,),
297
+ ).fetchone()[0]
298
+ if count >= QUEUE_LIMIT:
299
+ raise LocalError("queue_full")
300
+ blob = self._blob(tenant, request["text"].encode())
301
+ obs = uid("obs")
302
+ position = self._event(
303
+ tenant, "observation_captured", obs, decision.evaluated_ms, who["principal"]
304
+ )
305
+ self.db.execute(
306
+ "INSERT INTO observations(tenant,id,project,principal,source,source_event,payload_hash,blob,readers,position,origin,classification,observed_at_ms) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
307
+ (
308
+ tenant,
309
+ obs,
310
+ request["project"],
311
+ who["principal"],
312
+ request["source"],
313
+ request["source_event"],
314
+ digest,
315
+ blob,
316
+ json.dumps(readers),
317
+ position,
318
+ self.incarnation,
319
+ request["classification"],
320
+ request["observed_at_ms"],
321
+ ),
322
+ )
323
+ self.db.execute(
324
+ "INSERT INTO lexical VALUES (?,?,?)", (tenant, obs, request["text"])
325
+ )
326
+ self._index_anchors(tenant, obs, request["text"])
327
+ from memoryking.adapters.trust import Trust
328
+
329
+ trust = Trust(self)
330
+ held = trust.level(tenant, request["project"], request["source"]) == "untrusted"
331
+ if held:
332
+ # Recorded exactly like any capture, but invisible to every read
333
+ # until an admin releases it; nothing is derived from it meanwhile.
334
+ trust.hold(
335
+ tenant,
336
+ request["project"],
337
+ obs,
338
+ request["source"],
339
+ decision.evaluated_ms,
340
+ )
341
+ self._enqueue(tenant, position, obs, who["principal"])
342
+ result = {**self._capture_result(tenant, obs, position), "held": held}
343
+ self.db.execute(
344
+ "INSERT INTO retries VALUES (?,?,?,?,?,?,?,?,?,?)",
345
+ (
346
+ *lookup,
347
+ digest,
348
+ json.dumps(result),
349
+ result["observation"],
350
+ decision.evaluated_ms + RETRY_MS,
351
+ ),
352
+ )
353
+ with self.lock:
354
+ self._expose()
355
+ return result
356
+
357
+ def _index_anchors(self, tenant: str, observation: str, text: str) -> int:
358
+ """Record the exact names the text carries; deterministic, bounded, no model."""
359
+ from memoryking.domain.anchors import extract
360
+
361
+ found = extract(text)
362
+ for kind, anchor in found:
363
+ self.db.execute(
364
+ insert_ignore("anchors", 4),
365
+ (tenant, observation, anchor, kind),
366
+ )
367
+ return len(found)
368
+
369
+ def _capture_result(self, tenant: str, observation: str, position: int) -> dict[str, Any]:
370
+ return {
371
+ "observation": observation,
372
+ "position": position,
373
+ "incarnation": self.incarnation,
374
+ "watermark": self._token("watermark", tenant=tenant, position=position),
375
+ "handle": self._token("observation", tenant=tenant, id=observation),
376
+ }
377
+
378
+ def _enqueue(self, tenant: str, position: int, obs: str | None, principal: str) -> None:
379
+ epoch = self.db.execute(
380
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (tenant,)
381
+ ).fetchone()[0]
382
+ generation = self.db.execute(
383
+ "SELECT generation FROM projections WHERE tenant=?", (tenant,)
384
+ ).fetchone()[0]
385
+ self.db.execute(
386
+ "INSERT INTO jobs(tenant,id,position,observation,incarnation,generation,state,purge_epoch,revision,principal) VALUES (?,?,?,?,?,?,?,?,?,?)",
387
+ (
388
+ tenant,
389
+ uid("job"),
390
+ position,
391
+ obs,
392
+ self.incarnation,
393
+ generation,
394
+ "pending" if obs else "noop",
395
+ epoch,
396
+ 1,
397
+ principal,
398
+ ),
399
+ )
400
+
401
+ def _visible(self, who: dict[str, Any], row: Row, at: int) -> bool:
402
+ if row["deleted"]:
403
+ return False
404
+ # A held capture is on nobody's reading list until an admin releases it.
405
+ if (
406
+ self.db.execute(
407
+ "SELECT 1 FROM observation_holds WHERE tenant=? AND id=? AND state='held'",
408
+ (row["tenant"], row["id"]),
409
+ ).fetchone()
410
+ is not None
411
+ ):
412
+ return False
413
+ try:
414
+ self._subject_auth(
415
+ self._token("credential", tenant=who["tenant"], principal=who["principal"]),
416
+ "read",
417
+ row["project"],
418
+ at,
419
+ )
420
+ except LocalError:
421
+ return False
422
+ readers = json.loads(row["readers"])
423
+ return readers is None or who["principal"] in readers
424
+
425
+ def read(
426
+ self,
427
+ credential: str,
428
+ project: str,
429
+ *,
430
+ observation: str | None = None,
431
+ query: str | None = None,
432
+ cursor: str | None = None,
433
+ export: bool = False,
434
+ temporal_requirements: list[tuple[int | None, int | None]] | None = None,
435
+ ) -> Released:
436
+ """Bounded capture inspection/export; ranked retrieval belongs to P04.
437
+
438
+ temporal_requirements is an internal seam for future constraint/verification
439
+ checks, not a caller-supplied policy API. All use the one persisted instant.
440
+ """
441
+ identifier(project)
442
+ with self.transaction() as decision:
443
+ who = self._auth(
444
+ credential, "export" if export else "read", project, decision.evaluated_ms
445
+ )
446
+ if temporal_requirements and not all(
447
+ temporal_valid(decision.evaluated_ms, a, b) for a, b in temporal_requirements
448
+ ):
449
+ raise LocalError("temporal_requirement_failed")
450
+ after = 0
451
+ if cursor:
452
+ resume = self._decode(cursor, "cursor")
453
+ if (
454
+ any(resume[x] != who[x] for x in ("tenant", "principal"))
455
+ or resume["project"] != project
456
+ or resume["query"] != query
457
+ or resume["export"] != export
458
+ ):
459
+ raise LocalError("denied")
460
+ after = resume["position"]
461
+ args: list[Any] = [who["tenant"], project, after]
462
+ sql = "SELECT o.* FROM observations o WHERE tenant=? AND project=? AND position>? AND deleted=0"
463
+ if observation:
464
+ sql += " AND id=?"
465
+ handle = self._decode(observation, "observation")
466
+ if handle["tenant"] != who["tenant"]:
467
+ raise LocalError("denied")
468
+ args.append(handle["id"])
469
+ if query:
470
+ if len(query) > 256:
471
+ raise LocalError("invalid_query")
472
+ sql += (
473
+ " AND id IN (SELECT id FROM lexical WHERE tenant=? AND "
474
+ + self.dialect.lexical_match()
475
+ + ")"
476
+ )
477
+ args.extend([who["tenant"], '"' + query.replace('"', '""') + '"'])
478
+ rows = self.db.execute(sql + " ORDER BY position LIMIT 32", args).fetchall()
479
+ items: list[dict[str, Any]] = []
480
+ last = after
481
+ for row in rows:
482
+ last = row["position"]
483
+ if self._visible(who, row, decision.evaluated_ms):
484
+ path = self.root / "blobs" / who["tenant"] / row["blob"]
485
+ private_file(path)
486
+ raw = path.read_bytes()
487
+ if hashlib.sha256(raw).hexdigest() != row["blob"]:
488
+ raise LocalError("blob_corrupt")
489
+ items.append(
490
+ {
491
+ "id": row["id"],
492
+ "authority": "observed_episode",
493
+ "assurance": "actor_reported",
494
+ "handle": self._token(
495
+ "observation", tenant=who["tenant"], id=row["id"]
496
+ ),
497
+ "source": row["source"],
498
+ "source_event": row["source_event"],
499
+ "principal": row["principal"],
500
+ "project": row["project"],
501
+ "text": raw.decode(),
502
+ "position": row["position"],
503
+ "origin": row["origin"],
504
+ "classification": row["classification"],
505
+ "observed_at_ms": row["observed_at_ms"],
506
+ }
507
+ )
508
+ if sum(len(i["text"].encode()) for i in items) >= 131072:
509
+ break
510
+ if observation and not items:
511
+ raise LocalError("unavailable")
512
+ receipt = uid("rcpt")
513
+ resume_token = (
514
+ self._token(
515
+ "cursor",
516
+ tenant=who["tenant"],
517
+ principal=who["principal"],
518
+ project=project,
519
+ position=last,
520
+ query=query,
521
+ export=export,
522
+ )
523
+ if rows
524
+ else None
525
+ )
526
+ result = {
527
+ "items": items,
528
+ "cursor": resume_token,
529
+ "receipt": receipt,
530
+ "incarnation": self.incarnation,
531
+ "evaluated_ms": decision.evaluated_ms,
532
+ "deadline_ms": decision.deadline_ms,
533
+ }
534
+ epochs = self.db.execute(
535
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
536
+ ).fetchone()
537
+ self.db.execute(
538
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
539
+ (
540
+ who["tenant"],
541
+ receipt,
542
+ who["principal"],
543
+ self.incarnation,
544
+ decision.evaluated_ms,
545
+ decision.deadline_ms,
546
+ *epochs,
547
+ canonical_hash(result),
548
+ json.dumps([i["id"] for i in items]),
549
+ ),
550
+ )
551
+ self.fault("after_validation")
552
+ with self.lock:
553
+ self._expose()
554
+ return Released(canonical_bytes(result), decision, self.clock)
555
+
556
+ def grant(
557
+ self,
558
+ credential: str,
559
+ principal: str,
560
+ project: str,
561
+ capabilities: list[str],
562
+ *,
563
+ starts: int | None = None,
564
+ expires: int | None = None,
565
+ ) -> str:
566
+ identifier(principal)
567
+ identifier(project)
568
+ if not capabilities or not set(capabilities) <= CAPABILITIES - {"admin"}:
569
+ raise LocalError("invalid_capabilities")
570
+ if starts is not None and expires is not None and starts >= expires:
571
+ raise LocalError("invalid_interval")
572
+ with self.transaction() as decision:
573
+ who = self._auth(credential, "admin", "*", decision.evaluated_ms)
574
+ # Replacement can reduce authority, so every change goes to the current journal.
575
+ action = {
576
+ "kind": "grant",
577
+ "actor": who["principal"],
578
+ "tenant": who["tenant"],
579
+ "principal": principal,
580
+ "project": project,
581
+ "capabilities": capabilities,
582
+ "starts": starts,
583
+ "expires": expires,
584
+ }
585
+ record = self._journal(action)
586
+ self._apply(record, decision.evaluated_ms)
587
+ self._expose()
588
+ return self._token("credential", tenant=who["tenant"], principal=principal)
589
+
590
+ def grants(self, credential: str) -> list[dict[str, Any]]:
591
+ """Every grant in the caller's tenant, for operators; needs admin rights."""
592
+ with self.transaction() as decision:
593
+ who = self._auth(credential, "admin", "*", decision.evaluated_ms)
594
+ at = decision.evaluated_ms
595
+ items = []
596
+ for row in self.db.execute(
597
+ "SELECT principal,project,capabilities,starts,expires FROM grants WHERE tenant=? ORDER BY principal,project",
598
+ (who["tenant"],),
599
+ ).fetchall():
600
+ capabilities = row["capabilities"]
601
+ if isinstance(capabilities, str):
602
+ capabilities = json.loads(capabilities)
603
+ items.append(
604
+ {
605
+ "principal": row["principal"],
606
+ "project": row["project"],
607
+ "capabilities": sorted(capabilities),
608
+ "starts": row["starts"],
609
+ "expires": row["expires"],
610
+ "valid_now": temporal_valid(at, row["starts"], row["expires"]),
611
+ }
612
+ )
613
+ self._expose()
614
+ return items
615
+
616
+ def revoke(self, credential: str, principal: str, project: str) -> None:
617
+ identifier(principal)
618
+ identifier(project)
619
+ self._policy(credential, {"kind": "revoke", "principal": principal, "project": project})
620
+
621
+ def purge(self, credential: str, observation: str) -> None:
622
+ self._policy(credential, {"kind": "purge", "observation": identifier(observation)})
623
+ self.gc()
624
+
625
+ def _policy(self, credential: str, action: dict[str, Any]) -> None:
626
+ with self.transaction() as decision:
627
+ who = self._auth(credential, "admin", "*", decision.evaluated_ms)
628
+ action["tenant"] = who["tenant"]
629
+ action["actor"] = who["principal"]
630
+ record = self._journal(action)
631
+ self._apply(record, decision.evaluated_ms)
632
+ self._expose()
633
+
634
+ def _journal(self, action: dict[str, Any]) -> dict[str, Any]:
635
+ if action["kind"] == "purge":
636
+ row = self.db.execute(
637
+ "SELECT principal,source,source_event FROM observations WHERE tenant=? AND id=?",
638
+ (action["tenant"], action["observation"]),
639
+ ).fetchone()
640
+ if row is None:
641
+ raise LocalError("unavailable")
642
+ action["source_identity"] = list(row)
643
+ try:
644
+ record = self.control.append(self.anchor, action)
645
+ self.fault("after_journal")
646
+ return cast(dict[str, Any], record)
647
+ except LocalError as exc:
648
+ if exc.code != "journal_record_limit":
649
+ # Nothing was written for a refused oversized record; the store stays usable.
650
+ self.healthy = False
651
+ raise
652
+ except BaseException:
653
+ self.healthy = False
654
+ raise
655
+
656
+ def _purge_dependents(self, tenant: str, observation: str) -> None:
657
+ """Erase derived copies along recorded dependencies.
658
+
659
+ Rendered artifacts, checkpoints, handoffs and experience records record the
660
+ observations and claims they were built from, so only those built from the purged
661
+ source or its dependent claims are retired. Replay results carry no dependency
662
+ index and are retired tenant-wide; ranking is disabled when any experience record
663
+ was retired, because its evaluation may have scored the purged material.
664
+ """
665
+ from memoryking.adapters.knowledge_store import Knowledge
666
+
667
+ purged = {observation}
668
+ purged.update(
669
+ row[0]
670
+ for row in self.db.execute(
671
+ "SELECT revision FROM evidence_spans WHERE tenant=? AND observation=?",
672
+ (tenant, observation),
673
+ ).fetchall()
674
+ )
675
+ Knowledge(self).purge_dependencies(tenant, observation)
676
+
677
+ def depends(raw: Any) -> bool:
678
+ try:
679
+ deps = json.loads(raw) if isinstance(raw, str) else raw
680
+ except ValueError:
681
+ return True
682
+ if not isinstance(deps, list):
683
+ return True
684
+ return any(isinstance(d, dict) and d.get("id") in purged for d in deps)
685
+
686
+ # A fixed point: whatever is retired here joins the purged set, so anything
687
+ # derived from it (a summary of a purged checkpoint, an atlas page over a
688
+ # handoff view, an artifact over a retired experience record) goes too.
689
+ retired = 0
690
+ purged_checkpoints: set[str] = set()
691
+ purged_artifacts: set[str] = set()
692
+ changed = True
693
+ while changed:
694
+ changed = False
695
+ for row in self.db.execute(
696
+ "SELECT id,dependencies FROM checkpoints WHERE tenant=? AND state!='purged'",
697
+ (tenant,),
698
+ ).fetchall():
699
+ if depends(row["dependencies"]):
700
+ self.db.execute(
701
+ "UPDATE checkpoints SET state='purged',body=NULL,dependencies='[]' WHERE tenant=? AND id=?",
702
+ (tenant, row["id"]),
703
+ )
704
+ purged.update(
705
+ handoff[0]
706
+ for handoff in self.db.execute(
707
+ "SELECT id FROM handoffs WHERE tenant=? AND checkpoint=?",
708
+ (tenant, row["id"]),
709
+ ).fetchall()
710
+ )
711
+ self.db.execute(
712
+ "UPDATE handoffs SET state='purged' WHERE tenant=? AND checkpoint=?",
713
+ (tenant, row["id"]),
714
+ )
715
+ purged.add(row["id"])
716
+ purged_checkpoints.add(row["id"])
717
+ changed = True
718
+ for row in self.db.execute(
719
+ "SELECT id,dependencies FROM experience_records WHERE tenant=? AND body IS NOT NULL",
720
+ (tenant,),
721
+ ).fetchall():
722
+ if depends(row["dependencies"]):
723
+ self.db.execute(
724
+ "UPDATE experience_records SET body=NULL,dependencies='[]',readers=NULL WHERE tenant=? AND id=?",
725
+ (tenant, row["id"]),
726
+ )
727
+ purged.add(row["id"])
728
+ retired += 1
729
+ changed = True
730
+ for row in self.db.execute(
731
+ "SELECT id,dependencies FROM rendered_artifacts WHERE tenant=? AND state='retained'",
732
+ (tenant,),
733
+ ).fetchall():
734
+ if depends(row["dependencies"]):
735
+ self.db.execute(
736
+ "UPDATE rendered_artifacts SET state='purged',body=NULL,request_json=NULL,diagnostics=NULL,dependencies='[]' WHERE tenant=? AND id=?",
737
+ (tenant, row["id"]),
738
+ )
739
+ purged.add(row["id"])
740
+ purged_artifacts.add(row["id"])
741
+ changed = True
742
+ # Session summaries hold verbatim checkpoint text: erase every summary of a
743
+ # purged checkpoint or whose artifact was purged.
744
+ for identifier in purged_checkpoints:
745
+ self.db.execute(
746
+ "DELETE FROM session_summaries WHERE tenant=? AND checkpoint=?",
747
+ (tenant, identifier),
748
+ )
749
+ for identifier in purged_artifacts:
750
+ self.db.execute(
751
+ "DELETE FROM session_summaries WHERE tenant=? AND id=?", (tenant, identifier)
752
+ )
753
+ self.db.execute(
754
+ "UPDATE retries SET result=NULL WHERE tenant=? AND namespace IN ('working-v1','handoff-v1','experience-v1')",
755
+ (tenant,),
756
+ )
757
+ if retired:
758
+ self.db.execute(
759
+ "UPDATE ranking_state SET configuration=NULL,version=version+1,reconciliation=0 WHERE tenant=?",
760
+ (tenant,),
761
+ )
762
+
763
+ def _apply(self, record: dict[str, Any], at: int) -> None:
764
+ sequence = int(self.db.execute("SELECT value FROM meta WHERE key='journal'").fetchone()[0])
765
+ if record["sequence"] <= sequence:
766
+ return
767
+ action = record["action"]
768
+ tenant = action["tenant"]
769
+ if self.db.execute("SELECT 1 FROM tenants WHERE tenant=?", (tenant,)).fetchone() is None:
770
+ raise LocalError("journal_tenant_missing")
771
+ kind = action["kind"]
772
+ if kind == "grant":
773
+ self.db.execute(
774
+ upsert("grants"),
775
+ (
776
+ tenant,
777
+ action["principal"],
778
+ action["project"],
779
+ json.dumps(action["capabilities"]),
780
+ action["starts"],
781
+ action["expires"],
782
+ ),
783
+ )
784
+ elif kind == "revoke":
785
+ self.db.execute(
786
+ "DELETE FROM grants WHERE tenant=? AND principal=? AND project=?",
787
+ (tenant, action["principal"], action["project"]),
788
+ )
789
+ elif kind == "purge":
790
+ obs = action["observation"]
791
+ self.db.execute(
792
+ insert_ignore("retired_sources", 4),
793
+ (tenant, *action["source_identity"]),
794
+ )
795
+ self.db.execute(
796
+ "UPDATE observations SET deleted=1,blob=NULL,readers=NULL,revision=revision+1 WHERE tenant=? AND id=?",
797
+ (tenant, obs),
798
+ )
799
+ self.db.execute("DELETE FROM lexical WHERE tenant=? AND id=?", (tenant, obs))
800
+ self.db.execute("DELETE FROM anchors WHERE tenant=? AND id=?", (tenant, obs))
801
+ self.db.execute(
802
+ "DELETE FROM projection_items WHERE tenant=? AND observation=?", (tenant, obs)
803
+ )
804
+ self.db.execute(
805
+ "DELETE FROM embedding_items WHERE tenant=? AND observation=?", (tenant, obs)
806
+ )
807
+ self.db.execute(
808
+ "UPDATE embedding_jobs SET state='noop',fence=fence+1 WHERE tenant=? AND observation=?",
809
+ (tenant, obs),
810
+ )
811
+ self.db.execute("DELETE FROM adapter_bases WHERE tenant=?", (tenant,))
812
+ self.db.execute(
813
+ "UPDATE retries SET result=NULL WHERE tenant=? AND observation=?", (tenant, obs)
814
+ )
815
+ self.db.execute(
816
+ "UPDATE jobs SET state='noop',fence=fence+1 WHERE tenant=? AND observation=?",
817
+ (tenant, obs),
818
+ )
819
+ # Receipts that list the source are deleted; the epoch bump retires the rest.
820
+ self.db.execute(
821
+ "DELETE FROM receipts WHERE tenant=? AND observation_ids LIKE ?",
822
+ (tenant, '%"' + obs + '"%'),
823
+ )
824
+ self.db.execute(
825
+ "UPDATE tenants SET purge_epoch=purge_epoch+1 WHERE tenant=?", (tenant,)
826
+ )
827
+ elif kind == "ranking":
828
+ from memoryking.adapters.ranking import Ranking
829
+
830
+ Ranking(self).apply_policy(action, at)
831
+ elif kind == "procedure":
832
+ from memoryking.adapters.experience import Experience
833
+
834
+ Experience(self).apply_policy(action, at)
835
+ elif kind == "knowledge":
836
+ from memoryking.adapters.knowledge_store import Knowledge
837
+
838
+ Knowledge(self).apply_policy(action, at)
839
+ elif kind == "operation":
840
+ from memoryking.adapters.working import Working
841
+
842
+ Working(self).apply_operation(action)
843
+ elif kind in {"trust", "hold"}:
844
+ from memoryking.adapters.trust import Trust
845
+
846
+ Trust(self).apply_policy(action, at)
847
+ else:
848
+ raise LocalError("journal_invalid")
849
+ if kind == "purge":
850
+ self._purge_dependents(tenant, action["observation"])
851
+ if kind != "operation":
852
+ self.db.execute(
853
+ "UPDATE tenants SET policy_epoch=policy_epoch+1 WHERE tenant=?", (tenant,)
854
+ )
855
+ position = self._event(
856
+ tenant,
857
+ kind,
858
+ action.get("observation", action.get("operation", action.get("principal", "policy"))),
859
+ at,
860
+ action.get("actor", "system"),
861
+ )
862
+ self._enqueue(tenant, position, None, "system")
863
+ self.db.execute("UPDATE meta SET value=? WHERE key='journal'", (str(record["sequence"]),))
864
+
865
+ def expire_results(self) -> int:
866
+ with self.transaction() as decision:
867
+ count = self.db.execute(
868
+ "UPDATE retries SET result=NULL WHERE result IS NOT NULL AND expires<=?",
869
+ (decision.evaluated_ms,),
870
+ ).rowcount
871
+ self.db.execute(
872
+ "UPDATE rendered_artifacts SET state='expired',body=NULL,request_json=NULL,diagnostics=NULL,dependencies='[]' WHERE state='retained' AND expires<=?",
873
+ (decision.evaluated_ms,),
874
+ )
875
+ # Usage rows keep their 30-day retention; expired rows release capacity.
876
+ self.db.execute(
877
+ "DELETE FROM processing_usage WHERE expires<=?", (decision.evaluated_ms,)
878
+ )
879
+ # Access receipts are evidence for 30 days; the dashboard writes one per poll.
880
+ self.db.execute(
881
+ "DELETE FROM receipts WHERE evaluated<=?", (decision.evaluated_ms - RETRY_MS,)
882
+ )
883
+ # Egress audit records outlive purge (the delivery happened) but not retention.
884
+ self.db.execute("DELETE FROM egress_audit WHERE expires<=?", (decision.evaluated_ms,))
885
+ self.db.execute(
886
+ "DELETE FROM session_summaries WHERE expires<=?", (decision.evaluated_ms,)
887
+ )
888
+ return int(count)
889
+
890
+ def housekeeping(self, interval_ms: int = 3_600_000) -> bool:
891
+ """Expire results, artifacts, usage rows and receipts at most once per interval.
892
+
893
+ The serving daemon calls this between requests so retention never depends on an
894
+ operator remembering to run `gc`.
895
+ """
896
+ now = self.clock.utc_ms()
897
+ if self.backup_policy is not None:
898
+ self.backup_policy.maybe_run(self, now)
899
+ if self.summary_idle_ms and now - self._last_summary_scan >= 60_000:
900
+ self._last_summary_scan = now
901
+ self.idle_summaries(now)
902
+ if now - self._last_housekeeping < interval_ms:
903
+ return False
904
+ self._last_housekeeping = now
905
+ self.expire_results()
906
+ return True
907
+
908
+ def idle_summaries(self, now: int | None = None) -> int:
909
+ """Summaries for streams idle past the threshold, as the owner, when it may read them."""
910
+ from memoryking.adapters.working import Working
911
+
912
+ credential_file = self.control_path / "owner.credential"
913
+ if not self.summary_idle_ms or not credential_file.is_file():
914
+ return 0
915
+ try:
916
+ credential = credential_file.read_text().strip()
917
+ return Working(self).idle_summaries(
918
+ credential, self.summary_idle_ms, self.clock.utc_ms() if now is None else now
919
+ )
920
+ except (OSError, LocalError):
921
+ return 0
922
+
923
+ def claim(self, credential: str, project: str) -> dict[str, Any] | None:
924
+ with self.transaction() as decision:
925
+ who = self._auth(credential, "jobs", project, decision.evaluated_ms)
926
+ tenant, at = who["tenant"], decision.evaluated_ms
927
+ self.db.execute(
928
+ "UPDATE jobs SET state='dead',fence=fence+1 WHERE tenant=? AND state='leased' AND lease_until<=? AND attempts>=?",
929
+ (tenant, at, MAX_ATTEMPTS),
930
+ )
931
+ active = self.db.execute(
932
+ "SELECT count(*) FROM jobs WHERE tenant=? AND state='leased' AND lease_until>?",
933
+ (tenant, at),
934
+ ).fetchone()[0]
935
+ if active >= CONCURRENCY_LIMIT:
936
+ raise LocalError("concurrency_limit")
937
+ row = self.db.execute(
938
+ "SELECT j.* FROM jobs j JOIN observations o ON j.tenant=o.tenant AND j.observation=o.id WHERE j.tenant=? AND o.project=? AND o.deleted=0 AND j.attempts<? AND ((j.state='pending' AND j.available<=?) OR (j.state='leased' AND j.lease_until<=?)) ORDER BY j.position LIMIT 1",
939
+ (tenant, project, MAX_ATTEMPTS, at, at),
940
+ ).fetchone()
941
+ if row is None:
942
+ return None
943
+ fence = row["fence"] + 1
944
+ self.db.execute(
945
+ "UPDATE jobs SET state='leased',attempts=attempts+1,fence=?,lease_until=?,purge_epoch=(SELECT purge_epoch FROM tenants WHERE tenant=?) WHERE tenant=? AND id=?",
946
+ (fence, at + 30000, tenant, tenant, row["id"]),
947
+ )
948
+ result = {
949
+ "job": row["id"],
950
+ "lease": self._token(
951
+ "lease",
952
+ tenant=tenant,
953
+ principal=who["principal"],
954
+ job=row["id"],
955
+ fence=fence,
956
+ generation=row["generation"],
957
+ ),
958
+ "lease_until_ms": at + 30000,
959
+ }
960
+ self._expose()
961
+ return result
962
+
963
+ def finish(self, credential: str, project: str, lease: str, outcome: str) -> None:
964
+ if outcome not in {"complete", "retry", "cancel"}:
965
+ raise LocalError("invalid_request")
966
+ with self.transaction() as decision:
967
+ who = self._auth(credential, "jobs", project, decision.evaluated_ms)
968
+ token = self._decode(lease, "lease")
969
+ if any(token[k] != who[k] for k in ("tenant", "principal")):
970
+ raise LocalError("denied")
971
+ row = self.db.execute(
972
+ "SELECT * FROM jobs WHERE tenant=? AND id=?", (who["tenant"], token["job"])
973
+ ).fetchone()
974
+ if (
975
+ row is None
976
+ or row["state"] != "leased"
977
+ or row["fence"] != token["fence"]
978
+ or row["generation"] != token["generation"]
979
+ or row["lease_until"] <= decision.evaluated_ms
980
+ ):
981
+ raise LocalError("stale_lease")
982
+ obs = self.db.execute(
983
+ "SELECT * FROM observations WHERE tenant=? AND id=?",
984
+ (who["tenant"], row["observation"]),
985
+ ).fetchone()
986
+ epoch = self.db.execute(
987
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
988
+ ).fetchone()[0]
989
+ if (
990
+ obs is None
991
+ or obs["deleted"]
992
+ or obs["revision"] != row["revision"]
993
+ or obs["project"] != project
994
+ ):
995
+ raise LocalError("stale_source")
996
+ self._subject_auth(
997
+ self._token("credential", tenant=who["tenant"], principal=row["principal"]),
998
+ "capture",
999
+ project,
1000
+ decision.evaluated_ms,
1001
+ )
1002
+ if row["purge_epoch"] != epoch:
1003
+ # A different observation's purge forces a fresh lease with current metadata.
1004
+ raise LocalError("stale_source")
1005
+ if outcome == "complete":
1006
+ path = self.root / "blobs" / who["tenant"] / obs["blob"]
1007
+ private_file(path)
1008
+ raw = path.read_bytes()
1009
+ if hashlib.sha256(raw).hexdigest() != obs["blob"]:
1010
+ raise LocalError("blob_corrupt")
1011
+ self.db.execute(
1012
+ upsert("projection_items"),
1013
+ (
1014
+ who["tenant"],
1015
+ obs["id"],
1016
+ self.incarnation,
1017
+ row["generation"],
1018
+ obs["revision"],
1019
+ obs["blob"],
1020
+ len(raw),
1021
+ ),
1022
+ )
1023
+ state = (
1024
+ "complete"
1025
+ if outcome == "complete"
1026
+ else "cancelled"
1027
+ if outcome == "cancel"
1028
+ else "dead"
1029
+ if row["attempts"] >= MAX_ATTEMPTS
1030
+ else "pending"
1031
+ )
1032
+ delay = min(60000, (2 ** row["attempts"]) * 1000) + secrets.randbelow(1000)
1033
+ self.db.execute(
1034
+ "UPDATE jobs SET state=?,fence=fence+1,available=? WHERE tenant=? AND id=?",
1035
+ (state, decision.evaluated_ms + delay, who["tenant"], row["id"]),
1036
+ )
1037
+ self._advance(who["tenant"])
1038
+ self._expose()
1039
+
1040
+ def _advance(self, tenant: str) -> None:
1041
+ projection = self.db.execute(
1042
+ "SELECT * FROM projections WHERE tenant=?", (tenant,)
1043
+ ).fetchone()
1044
+ frontier = projection["frontier"]
1045
+ maximum = self.db.execute(
1046
+ "SELECT position FROM tenants WHERE tenant=?", (tenant,)
1047
+ ).fetchone()[0]
1048
+ while frontier < maximum:
1049
+ rows = self.db.execute(
1050
+ "SELECT state FROM jobs WHERE tenant=? AND position=? AND incarnation=? AND generation=?",
1051
+ (tenant, frontier + 1, self.incarnation, projection["generation"]),
1052
+ ).fetchall()
1053
+ if not rows or any(row[0] not in {"complete", "noop"} for row in rows):
1054
+ break
1055
+ frontier += 1
1056
+ self.db.execute("UPDATE projections SET frontier=? WHERE tenant=?", (frontier, tenant))
1057
+
1058
+ def _context_details(
1059
+ self, who: dict[str, Any], capabilities: set[str], project: str, at: int
1060
+ ) -> dict[str, Any]:
1061
+ return {"capabilities": sorted(capabilities), "delegation_chain": []}
1062
+
1063
+ def egress_revision(self) -> str:
1064
+ """The policy revision every conversation binds to; a change retires them all."""
1065
+ policy = self.egress_policy
1066
+ return "local-recording-v1" if policy is None else str(policy.binding)
1067
+
1068
+ def context(self, credential: str, project: str) -> Released:
1069
+ """Read-scoped identity discovery; aggregate/admin status remains separate."""
1070
+ identifier(project)
1071
+ receipt = uid("rcpt")
1072
+ with self.transaction() as decision:
1073
+ at = decision.evaluated_ms
1074
+ who = self._auth(credential, "read", project, at)
1075
+ epochs = self.db.execute(
1076
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
1077
+ ).fetchone()
1078
+ capabilities: set[str] = set()
1079
+ for row in self.db.execute(
1080
+ "SELECT * FROM grants WHERE tenant=? AND principal=? AND project IN (?,?)",
1081
+ (who["tenant"], who["principal"], project, "*"),
1082
+ ):
1083
+ if temporal_valid(at, row["starts"], row["expires"]):
1084
+ capabilities.update(json.loads(row["capabilities"]))
1085
+ if "admin" in capabilities:
1086
+ capabilities.update(CAPABILITIES)
1087
+ raw = canonical_bytes(
1088
+ {
1089
+ "store": self.store_id,
1090
+ "tenant": who["tenant"],
1091
+ "principal": who["principal"],
1092
+ "project": project,
1093
+ "incarnation": self.incarnation,
1094
+ "authorization_epoch": epochs[0],
1095
+ "purge_epoch": epochs[1],
1096
+ "egress_policy_revision": self.egress_revision(),
1097
+ **self._context_details(who, capabilities, project, at),
1098
+ "evaluated_ms": at,
1099
+ "deadline_ms": decision.deadline_ms,
1100
+ "receipt": receipt,
1101
+ }
1102
+ )
1103
+ self.db.execute(
1104
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
1105
+ (
1106
+ who["tenant"],
1107
+ receipt,
1108
+ who["principal"],
1109
+ self.incarnation,
1110
+ at,
1111
+ decision.deadline_ms,
1112
+ *epochs,
1113
+ hashlib.sha256(raw).hexdigest(),
1114
+ "[]",
1115
+ ),
1116
+ )
1117
+ self.fault("after_validation")
1118
+ self._expose()
1119
+ return Released(raw, decision, self.clock, receipt)
1120
+
1121
+ def status(self, credential: str, project: str, watermark: str | None = None) -> dict[str, Any]:
1122
+ with self.transaction() as decision:
1123
+ who = self._auth(credential, "admin", "*", decision.evaluated_ms)
1124
+ tenant = who["tenant"]
1125
+ self._advance(tenant)
1126
+ projection = dict(
1127
+ self.db.execute("SELECT * FROM projections WHERE tenant=?", (tenant,)).fetchone()
1128
+ )
1129
+ position = self.db.execute(
1130
+ "SELECT position FROM tenants WHERE tenant=?", (tenant,)
1131
+ ).fetchone()[0]
1132
+ satisfied = None
1133
+ if watermark:
1134
+ target = self._decode(watermark, "watermark")
1135
+ if target["tenant"] != tenant:
1136
+ raise LocalError("denied")
1137
+ satisfied = projection["frontier"] >= target["position"]
1138
+ result = {
1139
+ "store": self.store_id,
1140
+ "incarnation": self.incarnation,
1141
+ "position": position,
1142
+ "projection": projection,
1143
+ "satisfied": satisfied,
1144
+ "jobs": dict(
1145
+ self.db.execute(
1146
+ "SELECT state,count(*) FROM jobs WHERE tenant=? GROUP BY state", (tenant,)
1147
+ )
1148
+ ),
1149
+ "capacity": self._capacity(tenant),
1150
+ }
1151
+ self._expose()
1152
+ return result
1153
+
1154
+ def _capacity(self, tenant: str) -> dict[str, dict[str, Any]]:
1155
+ """Utilisation of every bounded per-tenant resource; warning at 80 percent."""
1156
+
1157
+ def count(statement: str) -> int:
1158
+ return int(self.db.execute(statement, (tenant,)).fetchone()[0])
1159
+
1160
+ artifacts, artifact_bytes = self.db.execute(
1161
+ "SELECT count(*),coalesce(sum(length(body)),0) FROM rendered_artifacts WHERE tenant=? AND state='retained'",
1162
+ (tenant,),
1163
+ ).fetchone()
1164
+ used = {
1165
+ "jobs": count(
1166
+ "SELECT count(*) FROM jobs WHERE tenant=? AND state IN ('pending','leased')"
1167
+ ),
1168
+ "rendered_artifacts": int(artifacts),
1169
+ "rendered_bytes": int(artifact_bytes),
1170
+ "operation_intents": count(
1171
+ "SELECT count(*) FROM operation_intents WHERE tenant=? AND state IN ('intent_recorded','dispatching','unknown')"
1172
+ ),
1173
+ "processing_usage": count("SELECT count(*) FROM processing_usage WHERE tenant=?"),
1174
+ }
1175
+ return {
1176
+ name: {"used": used[name], "limit": limit, "warning": used[name] * 5 >= limit * 4}
1177
+ for name, limit in CAPACITY_LIMITS.items()
1178
+ }
1179
+
1180
+ def drain(self, limit: int = 256) -> int:
1181
+ """Complete pending audit_probe jobs in-process.
1182
+
1183
+ The serving daemon calls this between requests, so a default installation never
1184
+ needs a separate worker to keep accepting captures. Explicit claim/finish workers
1185
+ remain valid for the same jobs.
1186
+ """
1187
+ completed = 0
1188
+ with self.lock:
1189
+ # A plain read keeps idle polling free of write transactions and fsyncs.
1190
+ try:
1191
+ idle = (
1192
+ self.healthy
1193
+ and self.db.execute(
1194
+ "SELECT 1 FROM jobs WHERE state='pending' AND available<=? LIMIT 1",
1195
+ (self.clock.utc_ms(),),
1196
+ ).fetchone()
1197
+ is None
1198
+ )
1199
+ except LocalError as exc:
1200
+ if exc.code != "database_transaction_required":
1201
+ raise
1202
+ idle = False # Backends that gate reads check inside the transaction.
1203
+ if idle:
1204
+ return 0
1205
+ with self.transaction() as decision:
1206
+ at = decision.evaluated_ms
1207
+ for tenant_row in self.db.execute(
1208
+ "SELECT tenant FROM tenants ORDER BY tenant"
1209
+ ).fetchall():
1210
+ tenant = tenant_row[0]
1211
+ rows = self.db.execute(
1212
+ "SELECT j.id,j.generation,o.id AS observation,o.blob,o.revision FROM jobs j JOIN observations o ON j.tenant=o.tenant AND j.observation=o.id WHERE j.tenant=? AND j.state='pending' AND j.available<=? AND j.attempts<? AND o.deleted=0 ORDER BY j.position LIMIT ?",
1213
+ (tenant, at, MAX_ATTEMPTS, limit - completed),
1214
+ ).fetchall()
1215
+ for row in rows:
1216
+ path = self.root / "blobs" / tenant / row["blob"]
1217
+ try:
1218
+ private_file(path)
1219
+ raw = path.read_bytes()
1220
+ if hashlib.sha256(raw).hexdigest() != row["blob"]:
1221
+ raise LocalError("blob_corrupt")
1222
+ except (LocalError, OSError):
1223
+ # One unreadable blob costs only its own job an attempt (with the
1224
+ # worker backoff, dead at MAX_ATTEMPTS); the pass continues.
1225
+ attempts = self.db.execute(
1226
+ "SELECT attempts FROM jobs WHERE tenant=? AND id=?", (tenant, row["id"])
1227
+ ).fetchone()[0]
1228
+ self.db.execute(
1229
+ "UPDATE jobs SET state=?,fence=fence+1,attempts=attempts+1,available=? WHERE tenant=? AND id=?",
1230
+ (
1231
+ "dead" if attempts + 1 >= MAX_ATTEMPTS else "pending",
1232
+ at + min(60000, (2 ** (attempts + 1)) * 1000),
1233
+ tenant,
1234
+ row["id"],
1235
+ ),
1236
+ )
1237
+ continue
1238
+ self.db.execute(
1239
+ upsert("projection_items"),
1240
+ (
1241
+ tenant,
1242
+ row["observation"],
1243
+ self.incarnation,
1244
+ row["generation"],
1245
+ row["revision"],
1246
+ row["blob"],
1247
+ len(raw),
1248
+ ),
1249
+ )
1250
+ self.db.execute(
1251
+ "UPDATE jobs SET state='complete',fence=fence+1,attempts=attempts+1 WHERE tenant=? AND id=?",
1252
+ (tenant, row["id"]),
1253
+ )
1254
+ completed += 1
1255
+ if rows:
1256
+ self._advance(tenant)
1257
+ if completed >= limit:
1258
+ break
1259
+ if completed:
1260
+ self._expose()
1261
+ return completed
1262
+
1263
+ def reindex(self, credential: str) -> None:
1264
+ with self.transaction() as decision:
1265
+ who = self._auth(credential, "admin", "*", decision.evaluated_ms)
1266
+ self._reindex(who["tenant"])
1267
+ self._expose()
1268
+
1269
+ def _reindex(self, tenant: str) -> None:
1270
+ self.db.execute("DELETE FROM projection_items WHERE tenant=?", (tenant,))
1271
+ # Anchors are derived from the retained text, so a reindex rebuilds them too:
1272
+ # stores created before anchors existed gain them without a re-capture.
1273
+ self.db.execute("DELETE FROM anchors WHERE tenant=?", (tenant,))
1274
+ for row in self.db.execute(
1275
+ "SELECT l.id,l.text FROM lexical l JOIN observations o ON o.tenant=l.tenant AND o.id=l.id WHERE l.tenant=? AND o.deleted=0",
1276
+ (tenant,),
1277
+ ).fetchall():
1278
+ self._index_anchors(tenant, row["id"], row["text"])
1279
+ self.db.execute(
1280
+ "UPDATE projections SET incarnation=?,generation=generation+1,frontier=0 WHERE tenant=?",
1281
+ (self.incarnation, tenant),
1282
+ )
1283
+ generation = self.db.execute(
1284
+ "SELECT generation FROM projections WHERE tenant=?", (tenant,)
1285
+ ).fetchone()[0]
1286
+ epoch = self.db.execute(
1287
+ "SELECT purge_epoch FROM tenants WHERE tenant=?", (tenant,)
1288
+ ).fetchone()[0]
1289
+ self.db.execute(
1290
+ "UPDATE jobs SET incarnation=?,generation=?,fence=fence+1,attempts=0,lease_until=0,available=0,purge_epoch=?,state=CASE WHEN observation IS NULL OR observation IN (SELECT id FROM observations WHERE tenant=? AND deleted=1) THEN 'noop' ELSE 'pending' END WHERE tenant=?",
1291
+ (self.incarnation, generation, epoch, tenant, tenant),
1292
+ )