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,1285 @@
1
+ """Local lexical compilation, immutable rendered artifacts and authorized inspection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import sqlite3
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ from jsonschema import Draft202012Validator
13
+
14
+ from memoryking.adapters.dense_search import search as dense_search
15
+ from memoryking.adapters.knowledge_store import Knowledge
16
+ from memoryking.adapters.local_files import private_file
17
+ from memoryking.adapters.local_store import (
18
+ ARTIFACT_BYTES_LIMIT,
19
+ ARTIFACT_LIMIT,
20
+ RETRY_MS,
21
+ uid,
22
+ )
23
+ from memoryking.adapters.token_count import counter
24
+ from memoryking.application.store_core import StoreCore
25
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
26
+ from memoryking.domain.anchors import anchors_in
27
+ from memoryking.domain.briefing import (
28
+ COMPILER,
29
+ CONFIGURATION,
30
+ QUERY_TERM_LIMIT,
31
+ counted,
32
+ pack,
33
+ relevance,
34
+ term_window,
35
+ terms,
36
+ )
37
+ from memoryking.domain.briefing_text import textualize
38
+ from memoryking.domain.local import Decision, LocalError, Released
39
+ from memoryking.domain.selectors import bindings
40
+
41
+ # Salience: a bounded, documented nudge from use, never a rewrite of the record.
42
+ RERANK_WINDOW = 16 # fused candidates the cross-encoder reorders
43
+ RERANK_TEXT_BYTES = 16384 # the reranker's per-text limit
44
+ SALIENCE_WEIGHT = 100_000 # at most a tenth of a full lexical score, in millionths
45
+ SALIENCE_WINDOW_MS = 90 * 86_400_000 # deliveries older than this do not count
46
+ SALIENCE_HALF_LIFE_MS = 30 * 86_400_000 # use fades by half every thirty days
47
+ ARCHIVE_AFTER_MS = 180 * 86_400_000 # never-used records older than this rank last
48
+ ARCHIVAL_PENALTY = 4_000_000 # below any reachable score; archival stays searchable
49
+ VALIDATOR = Draft202012Validator(
50
+ json.loads(Path(__file__).with_name("retrieval.schema.json").read_text())
51
+ )
52
+
53
+
54
+ class Retrieval:
55
+ def __init__(self, store: StoreCore):
56
+ self.s, self.db, self.k = store, store.db, Knowledge(store)
57
+ if not hasattr(store, "retrieval_cache"):
58
+ store.retrieval_cache = {}
59
+
60
+ def execute(self, credential: str, command: dict[str, Any]) -> Released:
61
+ if len(canonical_bytes(command)) > 131072 or not VALIDATOR.is_valid(command):
62
+ raise LocalError("invalid_request")
63
+ if command["incarnation"] != self.s.incarnation:
64
+ raise LocalError("history_changed")
65
+ action, args = command["action"], command["args"]
66
+ access_id = uid("rcpt")
67
+ with self.s.transaction() as decision:
68
+ at = decision.evaluated_ms
69
+ who = self.s._auth(credential, "read", args["project"], at)
70
+ self._expire(at)
71
+ predecessor = None
72
+ if action == "rerun":
73
+ previous = self.db.execute(
74
+ "SELECT incarnation FROM rendered_artifacts WHERE tenant=? AND principal=? AND project=? AND id=?",
75
+ (who["tenant"], who["principal"], args["project"], args["predecessor"]),
76
+ ).fetchone()
77
+ if previous is None:
78
+ raise LocalError("replay_missing")
79
+ if previous["incarnation"] != self.s.incarnation:
80
+ raise LocalError("history_changed")
81
+ # Linking an owned tombstone does not read the expired/purged body.
82
+ # All new inputs are explicit and undergo fresh eligibility below.
83
+ predecessor = args["predecessor"]
84
+ if args["brief"]["project"] != args["project"]:
85
+ raise LocalError("invalid_request")
86
+ args = args["brief"]
87
+ action = "brief"
88
+ deps: list[dict[str, str]] = []
89
+ if action in {"brief", "fetch", "atlas"}:
90
+ if action == "atlas":
91
+ from memoryking.adapters.atlas import query
92
+
93
+ raw, diag, deps = query(self, who, args, decision, access_id)
94
+ elif action == "brief":
95
+ raw, diag, deps = self._brief(who, args, decision, access_id)
96
+ raw, diag = self.textual(args, "brief", raw, diag)
97
+ else:
98
+ raw, diag, deps = self._fetch(who, args, decision, access_id)
99
+ diag["predecessor"] = predecessor
100
+ self._retain(who, args, access_id, raw, diag, deps, at)
101
+ elif action in {"replay", "receipt"}:
102
+ row = self._artifact(who, args["project"], args["receipt"], at)
103
+ deps = json.loads(row["dependencies"])
104
+ if action == "replay":
105
+ raw = bytes(row["body"])
106
+ else:
107
+ raw = canonical_bytes(
108
+ {
109
+ "receipt": row["id"],
110
+ "diagnostics": json.loads(row["diagnostics"]),
111
+ "rendered_hash": row["body_hash"],
112
+ "expires_ms": row["expires"],
113
+ "access_receipt": access_id,
114
+ "evaluated_ms": at,
115
+ "deadline_ms": decision.deadline_ms,
116
+ "replay": "available",
117
+ }
118
+ )
119
+ else:
120
+ raw = canonical_bytes(
121
+ {
122
+ "items": self.list_receipts(who, args["project"], at),
123
+ "access_receipt": access_id,
124
+ }
125
+ )
126
+ epochs = self.db.execute(
127
+ "SELECT policy_epoch,purge_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
128
+ ).fetchone()
129
+ self.db.execute(
130
+ "INSERT INTO receipts VALUES (?,?,?,?,?,?,?,?,?,?)",
131
+ (
132
+ who["tenant"],
133
+ access_id,
134
+ who["principal"],
135
+ self.s.incarnation,
136
+ at,
137
+ decision.deadline_ms,
138
+ *epochs,
139
+ hashlib.sha256(raw).hexdigest(),
140
+ json.dumps([d["id"] for d in deps if d["kind"] == "observation"]),
141
+ ),
142
+ )
143
+ self.s.fault("after_validation")
144
+ self.s._expose()
145
+ return Released(raw, decision, self.s.clock, access_id)
146
+
147
+ def _auto_dense(self, who: dict[str, Any], args: dict[str, Any]) -> dict[str, Any]:
148
+ """Embed the query with the daemon's model when the project has a partition for it.
149
+
150
+ Only when the caller sent no `dense` request: an explicit request, including an
151
+ explicit vector, is never overridden. Without a model or a matching experimental
152
+ partition the briefing stays lexical, exactly as before.
153
+ """
154
+ embedder = self.s.embedder
155
+ if embedder is None or "dense" in args:
156
+ return args
157
+ row = self.db.execute(
158
+ "SELECT 1 FROM embedding_partitions WHERE tenant=? AND project=? AND fingerprint=? AND state='experimental' AND incarnation=?",
159
+ (who["tenant"], args["project"], embedder.fingerprint, self.s.incarnation),
160
+ ).fetchone()
161
+ if row is None:
162
+ return args
163
+ try:
164
+ batch = embedder.embed([args["query"]])
165
+ except Exception: # a model failure degrades to lexical retrieval, never a refusal
166
+ return args
167
+ return {
168
+ **args,
169
+ "dense": {
170
+ "fingerprint": embedder.fingerprint,
171
+ "query_hash": canonical_hash(args["query"]),
172
+ "vector": batch.vectors[0],
173
+ },
174
+ }
175
+
176
+ def textual(
177
+ self, args: dict[str, Any], kind: str, raw: bytes, diag: dict[str, Any]
178
+ ) -> tuple[bytes, dict[str, Any]]:
179
+ """Render the packet as cited Markdown when the caller asked for text."""
180
+ if args.get("format") != "text":
181
+ return raw, diag
182
+ count, _ = counter(args["tokenizer"])
183
+ envelope = textualize(json.loads(raw), kind, count)
184
+ raw = canonical_bytes(envelope)
185
+ diag = {
186
+ **diag,
187
+ "format": "text",
188
+ "usage": {
189
+ **diag.get("usage", {}),
190
+ "output_tokens": envelope["usage"]["output_tokens"],
191
+ "serialized_bytes": len(raw),
192
+ },
193
+ }
194
+ return raw, diag
195
+
196
+ def _make_room(self, who: dict[str, Any], incoming: int) -> int:
197
+ """Evict the oldest retained artifacts at capacity, the caller's own first.
198
+
199
+ Replay of an evicted receipt reports replay_expired. A caller looping on brief
200
+ therefore consumes its own retention before anyone else's.
201
+ """
202
+ if incoming > ARTIFACT_BYTES_LIMIT:
203
+ raise LocalError("retention_capacity")
204
+ evicted = 0
205
+ while True:
206
+ count, size = self.db.execute(
207
+ "SELECT count(*),coalesce(sum(length(body)),0) FROM rendered_artifacts WHERE tenant=? AND state='retained'",
208
+ (who["tenant"],),
209
+ ).fetchone()
210
+ if count < ARTIFACT_LIMIT and size + incoming <= ARTIFACT_BYTES_LIMIT:
211
+ return evicted
212
+ oldest = (
213
+ self.db.execute(
214
+ "SELECT id FROM rendered_artifacts WHERE tenant=? AND principal=? AND state='retained' ORDER BY created,id LIMIT 1",
215
+ (who["tenant"], who["principal"]),
216
+ ).fetchone()
217
+ or self.db.execute(
218
+ "SELECT id FROM rendered_artifacts WHERE tenant=? AND state='retained' ORDER BY created,id LIMIT 1",
219
+ (who["tenant"],),
220
+ ).fetchone()
221
+ )
222
+ if oldest is None:
223
+ raise LocalError("retention_capacity")
224
+ self.db.execute(
225
+ "UPDATE rendered_artifacts SET state='evicted',body=NULL,request_json=NULL,diagnostics=NULL,dependencies='[]' WHERE tenant=? AND id=?",
226
+ (who["tenant"], oldest["id"]),
227
+ )
228
+ evicted += 1
229
+
230
+ def _expire(self, at: int) -> None:
231
+ self.db.execute(
232
+ "UPDATE rendered_artifacts SET state='expired',body=NULL,request_json=NULL,diagnostics=NULL,dependencies='[]' WHERE state='retained' AND expires<=?",
233
+ (at,),
234
+ )
235
+
236
+ def _artifact(self, who: dict[str, Any], project: str, receipt: str, at: int) -> sqlite3.Row:
237
+ row = self.db.execute(
238
+ "SELECT * FROM rendered_artifacts WHERE tenant=? AND id=? AND principal=? AND project=?",
239
+ (who["tenant"], receipt, who["principal"], project),
240
+ ).fetchone()
241
+ if row is None:
242
+ raise LocalError("replay_missing")
243
+ if row["incarnation"] != self.s.incarnation:
244
+ raise LocalError("history_changed")
245
+ if row["state"] == "purged":
246
+ raise LocalError("replay_purged")
247
+ if row["state"] in {"expired", "evicted"} or at >= row["expires"]:
248
+ raise LocalError("replay_expired")
249
+ if row["body"] is None or hashlib.sha256(row["body"]).hexdigest() != row["body_hash"]:
250
+ raise LocalError("replay_integrity_failure")
251
+ for dep in json.loads(row["dependencies"]):
252
+ self._dependency(who, dep, at)
253
+ return cast(sqlite3.Row, row)
254
+
255
+ def _dependency(self, who: dict[str, Any], dep: dict[str, str], at: int) -> None:
256
+ if dep["kind"] == "observation":
257
+ row = self.db.execute(
258
+ "SELECT * FROM observations WHERE tenant=? AND id=?", (who["tenant"], dep["id"])
259
+ ).fetchone()
260
+ if row is None or not self.s._visible(who, row, at):
261
+ raise LocalError("replay_denied")
262
+ elif dep["kind"] == "experience_record":
263
+ from memoryking.adapters.experience_records import ExperienceRecords
264
+
265
+ ExperienceRecords(self.s).verify_dependency(who, dep["id"], at)
266
+ elif dep["kind"] == "procedure_activation":
267
+ from memoryking.adapters.experience import Experience
268
+
269
+ Experience(self.s).verify_dependency(who, dep["id"], at)
270
+ elif dep["kind"] == "code_validation":
271
+ from memoryking.adapters.repository_store import Repository
272
+
273
+ Repository(self.s).verify_proof(who, dep["id"], at)
274
+ elif dep["kind"] == "handoff_view":
275
+ from memoryking.adapters.handoff import Handoff
276
+
277
+ Handoff(self.s).verify_dependency(who, dep["id"], at)
278
+ elif dep["kind"] == "checkpoint":
279
+ row = self.db.execute(
280
+ "SELECT * FROM checkpoints WHERE tenant=? AND id=?", (who["tenant"], dep["id"])
281
+ ).fetchone()
282
+ if (
283
+ row is None
284
+ or row["incarnation"] != self.s.incarnation
285
+ or row["state"] != "available"
286
+ or row["body"] is None
287
+ or who["principal"] not in json.loads(row["readers"])
288
+ or hashlib.sha256(row["body"].encode()).hexdigest() != row["body_hash"]
289
+ ):
290
+ raise LocalError("replay_denied")
291
+ token = self.s._token("credential", tenant=who["tenant"], principal=who["principal"])
292
+ self.s._subject_auth(token, "read", row["project"], at)
293
+ for source in json.loads(row["dependencies"]):
294
+ self._dependency(who, source, at)
295
+ else:
296
+ revision = self.k._revision(who["tenant"], dep["id"])
297
+ if (
298
+ not self.k._available(who, revision, at)
299
+ or self.k._state(who["tenant"], dep["id"], 9007199254740991)[1]
300
+ ):
301
+ raise LocalError("replay_denied")
302
+
303
+ def list_receipts(self, who: dict[str, Any], project: str, at: int) -> list[dict[str, Any]]:
304
+ items = []
305
+ for candidate in self.db.execute(
306
+ "SELECT id FROM rendered_artifacts WHERE tenant=? AND principal=? AND project=? AND incarnation=? AND state='retained' AND expires>? ORDER BY created DESC,id DESC LIMIT 32",
307
+ (who["tenant"], who["principal"], project, self.s.incarnation, at),
308
+ ).fetchall():
309
+ try:
310
+ row = self._artifact(who, project, candidate["id"], at)
311
+ except LocalError:
312
+ continue
313
+ diag = json.loads(row["diagnostics"])
314
+ items.append(
315
+ {
316
+ "receipt": row["id"],
317
+ "created_ms": row["created"],
318
+ "expires_ms": row["expires"],
319
+ "rendered_hash": row["body_hash"],
320
+ "status": diag["status"],
321
+ "usage": diag["usage"],
322
+ "cache": diag.get("cache", "not_applicable"),
323
+ }
324
+ )
325
+ return items
326
+
327
+ def citations(self, who: dict[str, Any], project: str, at: int) -> dict[str, int]:
328
+ """How many of the caller's retained briefings, fetches and reruns depend on each record.
329
+
330
+ Atlas pages depend on every node they show, so they are not citations. Only the
331
+ caller's own artifacts count: a receipt is private to the principal that holds it.
332
+ """
333
+ counts: dict[str, int] = {}
334
+ for row in self.db.execute(
335
+ "SELECT diagnostics,dependencies FROM rendered_artifacts WHERE tenant=? AND principal=? AND project=? AND incarnation=? AND state='retained' AND expires>?",
336
+ (who["tenant"], who["principal"], project, self.s.incarnation, at),
337
+ ).fetchall():
338
+ if json.loads(row["diagnostics"]).get("kind") == "atlas":
339
+ continue
340
+ for dep in json.loads(row["dependencies"]):
341
+ counts[dep["id"]] = counts.get(dep["id"], 0) + 1
342
+ return counts
343
+
344
+ def list_citations(
345
+ self, who: dict[str, Any], project: str, node: str, at: int
346
+ ) -> list[dict[str, Any]]:
347
+ """The caller's retained receipts that depend on one record, newest first.
348
+
349
+ Each receipt is re-authorized exactly as `receipts` does, so a record whose
350
+ evidence the caller may no longer read yields no receipt.
351
+ """
352
+ if not re.fullmatch(r"[A-Za-z0-9_.:|-]{1,256}", node):
353
+ raise LocalError("invalid_request")
354
+ items = []
355
+ for candidate in self.db.execute(
356
+ "SELECT id,diagnostics,dependencies FROM rendered_artifacts WHERE tenant=? AND principal=? AND project=? AND incarnation=? AND state='retained' AND expires>? ORDER BY created DESC,id DESC",
357
+ (who["tenant"], who["principal"], project, self.s.incarnation, at),
358
+ ).fetchall():
359
+ if json.loads(candidate["diagnostics"]).get("kind") == "atlas":
360
+ continue
361
+ kinds = [d["kind"] for d in json.loads(candidate["dependencies"]) if d["id"] == node]
362
+ if not kinds:
363
+ continue
364
+ try:
365
+ row = self._artifact(who, project, candidate["id"], at)
366
+ except LocalError:
367
+ continue
368
+ diag = json.loads(row["diagnostics"])
369
+ items.append(
370
+ {
371
+ "receipt": row["id"],
372
+ "created_ms": row["created"],
373
+ "expires_ms": row["expires"],
374
+ "rendered_hash": row["body_hash"],
375
+ "status": diag["status"],
376
+ "usage": diag["usage"],
377
+ "dependency_kind": kinds[0],
378
+ "format": diag.get("format", "json"),
379
+ }
380
+ )
381
+ if len(items) >= 32:
382
+ break
383
+ return items
384
+
385
+ def _retain(
386
+ self,
387
+ who: dict[str, Any],
388
+ args: dict[str, Any],
389
+ receipt: str,
390
+ raw: bytes,
391
+ diag: dict[str, Any],
392
+ deps: list[dict[str, str]],
393
+ at: int,
394
+ ) -> None:
395
+ self._make_room(who, len(raw))
396
+ if len(canonical_bytes(diag)) > 65536:
397
+ raise LocalError("diagnostic_limit")
398
+ self.db.execute(
399
+ "INSERT INTO rendered_artifacts VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
400
+ (
401
+ who["tenant"],
402
+ receipt,
403
+ who["principal"],
404
+ args["project"],
405
+ self.s.incarnation,
406
+ at,
407
+ at + RETRY_MS,
408
+ "retained",
409
+ raw,
410
+ hashlib.sha256(raw).hexdigest(),
411
+ json.dumps(args),
412
+ json.dumps(diag),
413
+ json.dumps(deps),
414
+ ),
415
+ )
416
+
417
+ def _base(
418
+ self, args: dict[str, Any], decision: Decision, receipt: str, usage: dict[str, Any]
419
+ ) -> dict[str, Any]:
420
+ return {
421
+ "version": 1,
422
+ "status": "partial",
423
+ "receipt": receipt,
424
+ "incarnation": self.s.incarnation,
425
+ "evaluated_ms": decision.evaluated_ms,
426
+ "deadline_ms": decision.deadline_ms,
427
+ "usage": {
428
+ **usage,
429
+ "max_output_tokens": args["max_output_tokens"],
430
+ "budget_compliant": True,
431
+ "provider_usage": "unknown",
432
+ },
433
+ "warnings": ["untrusted_evidence", "host_and_protocol_tokens_excluded"]
434
+ + (["token_estimate_no_exact_guarantee"] if usage["counting"] != "exact" else []),
435
+ "constraints": [],
436
+ "conflicts": [],
437
+ "guidance": [],
438
+ }
439
+
440
+ def _brief(
441
+ self,
442
+ who: dict[str, Any],
443
+ args: dict[str, Any],
444
+ decision: Decision,
445
+ receipt: str,
446
+ *,
447
+ ranking_override: dict[str, Any] | None = None,
448
+ ) -> tuple[bytes, dict[str, Any], list[dict[str, str]]]:
449
+ at, tenant = decision.evaluated_ms, who["tenant"]
450
+ start = self.s.clock.monotonic_ms()
451
+ bindings(args["bindings"])
452
+ count, usage = counter(args["tokenizer"])
453
+ from memoryking.adapters.ranking import Ranking
454
+
455
+ tenant_row = self.db.execute("SELECT * FROM tenants WHERE tenant=?", (tenant,)).fetchone()
456
+ source = tenant_row["position"]
457
+ if "as_of_ms" in args:
458
+ # One instant stands for both clocks: the history frontier as it was then
459
+ # (the last event recorded by that wall time) and the claim validity time.
460
+ if "recorded_position" in args or "valid_ms" in args:
461
+ raise LocalError("invalid_request")
462
+ frontier = self.db.execute(
463
+ "SELECT coalesce(max(position),0) FROM events WHERE tenant=? AND at_ms<=?",
464
+ (tenant, args["as_of_ms"]),
465
+ ).fetchone()[0]
466
+ args = {**args, "recorded_position": int(frontier), "valid_ms": args["as_of_ms"]}
467
+ ranking: dict[str, Any] = (
468
+ ranking_override
469
+ if ranking_override is not None
470
+ else {"state": "historical_override_disabled", "adjustments": {}}
471
+ if "recorded_position" in args or "valid_ms" in args
472
+ else Ranking(self.s).active(who, args["project"], at)
473
+ )
474
+ consistency = args.get("consistency", {})
475
+ target_position = source
476
+ if token := consistency.get("at_least_watermark"):
477
+ target = self.s._decode(token, "watermark")
478
+ if target["tenant"] != tenant:
479
+ raise LocalError("denied")
480
+ if target["position"] > source:
481
+ raise LocalError("index_not_ready")
482
+ target_position = target["position"]
483
+ recorded = args.get("recorded_position", source)
484
+ if recorded > source:
485
+ raise LocalError("invalid_recorded_position")
486
+ args = self._auto_dense(who, args)
487
+ dense = dense_search(self.s, who, args, recorded, target_position)
488
+ missing = [
489
+ c
490
+ for c in consistency.get("required_channels", ["lexical"])
491
+ if c == "dense" and dense["availability"] != "ready"
492
+ ]
493
+ if missing and consistency.get("on_timeout", "error") != "partial":
494
+ # A disabled channel cannot advance during a wait; fail without holding
495
+ # the release gate or pretending an absent provider is merely indexed.
496
+ raise LocalError("index_not_ready")
497
+ scope: dict[str, Any] = {
498
+ k: args[k]
499
+ for k in ("project", "bindings", "task", "run", "valid_ms", "recorded_position")
500
+ if k in args
501
+ }
502
+ mandatory = self.k.query(who, scope, at, constraints=True)
503
+ if (
504
+ args.get("freshness", "any") == "attested"
505
+ and mandatory["status"] == "complete"
506
+ and any(not item["attestations"] for item in mandatory["items"])
507
+ ):
508
+ mandatory = {"status": "blocked", "reason": "verification_unavailable", "items": []}
509
+ policy_finished = self.s.clock.monotonic_ms()
510
+ base = self._base(args, decision, receipt, usage)
511
+ base.update(
512
+ objective=args["query"],
513
+ coverage={
514
+ "lexical": "ready",
515
+ "dense": dense["availability"],
516
+ "optional": "uncalibrated",
517
+ "required_missing": missing,
518
+ },
519
+ snapshot={
520
+ "source_position": source,
521
+ "recorded_position": recorded,
522
+ "valid_ms": args.get("valid_ms", at),
523
+ **({"as_of_ms": args["as_of_ms"]} if "as_of_ms" in args else {}),
524
+ },
525
+ )
526
+ diag: dict[str, Any] = {
527
+ "configuration": CONFIGURATION,
528
+ "compiler": COMPILER,
529
+ "selector_version": "1",
530
+ "store": self.s.store_id,
531
+ "incarnation": self.s.incarnation,
532
+ "actor": who["principal"],
533
+ "project": args["project"],
534
+ "source_position": source,
535
+ "source_watermark": self.s._token("watermark", tenant=tenant, position=source),
536
+ "channel_frontiers": {
537
+ "lexical": {"position": source, "configuration": CONFIGURATION},
538
+ "dense": {key: value for key, value in dense.items() if key != "scores"},
539
+ },
540
+ "policy_epoch": tenant_row["policy_epoch"],
541
+ "purge_epoch": tenant_row["purge_epoch"],
542
+ "corpus_generation": source,
543
+ "constraint_generation": mandatory.get("constraint_generation"),
544
+ "evaluated_ms": at,
545
+ "deadline_ms": decision.deadline_ms,
546
+ "valid_ms": args.get("valid_ms", at),
547
+ "recorded_position": recorded,
548
+ **({"as_of_ms": args["as_of_ms"]} if "as_of_ms" in args else {}),
549
+ "repository_validation": "exact_snapshot_for_declared_code_dependencies",
550
+ "model_fingerprints": [dense["fingerprint"]] if "fingerprint" in dense else [],
551
+ "scope_assumptions": ["local_default_workspace"],
552
+ "cache": "not_used",
553
+ "trace": [],
554
+ }
555
+ if term_window(args["query"])[1]:
556
+ # Long queries are searched on their leading terms; the cut is disclosed.
557
+ diag["query_terms_truncated"] = QUERY_TERM_LIMIT
558
+ groups: list[list[dict[str, Any]]] = []
559
+ if mandatory["status"] != "complete":
560
+ base.update(status="blocked", reason=mandatory["reason"])
561
+ # Only explicitly authorized conflicts are ever present in this result.
562
+ if mandatory["reason"] == "unresolved_conflict":
563
+ base["constraints"] = [self._claim(i) for i in mandatory["items"]]
564
+ base["conflicts"] = mandatory.get("conflicts", [])
565
+ else:
566
+ base["constraints"] = [self._claim(i) for i in mandatory["items"]]
567
+ knowledge = self.k.query(who, scope, at, constraints=False)
568
+ from memoryking.adapters.experience import Experience
569
+
570
+ if "recorded_position" not in args and "valid_ms" not in args:
571
+ procedures = Experience(self.s).query(who, scope, at)
572
+ knowledge["items"].extend(procedures["items"])
573
+ if procedures["status"] != "complete":
574
+ base["warnings"].append("procedure_guidance_withheld")
575
+ knowledge["status"] = "blocked"
576
+ knowledge["reason"] = procedures.get("reason", "procedure_guidance_withheld")
577
+ else:
578
+ base["warnings"].append("procedures_require_current_query")
579
+ if args.get("freshness", "any") == "attested":
580
+ original = knowledge["items"]
581
+ knowledge["items"] = [i for i in original if i["attestations"]]
582
+ if len(knowledge["items"]) != len(original):
583
+ knowledge["status"] = "blocked"
584
+ knowledge["reason"] = "verification_unavailable"
585
+ eligibility_finished = self.s.clock.monotonic_ms()
586
+ groups, trace, cache = self._candidates(
587
+ who,
588
+ args,
589
+ knowledge,
590
+ source,
591
+ recorded,
592
+ at,
593
+ dense,
594
+ ranking,
595
+ evaluation=ranking_override is not None,
596
+ )
597
+ for stage in trace:
598
+ if stage.get("stage") == "rerank_v1" and "model" in stage:
599
+ diag["model_fingerprints"].append(stage["model"])
600
+ diag.update(
601
+ trace=[
602
+ {
603
+ "stage": "authorization_and_policy",
604
+ "duration_ms": max(0, policy_finished - start),
605
+ },
606
+ {
607
+ "stage": "claim_eligibility",
608
+ "duration_ms": max(0, eligibility_finished - policy_finished),
609
+ },
610
+ *trace,
611
+ {
612
+ "stage": "optional_search_expand_rank",
613
+ "duration_ms": max(0, self.s.clock.monotonic_ms() - eligibility_finished),
614
+ },
615
+ ],
616
+ cache=cache,
617
+ )
618
+ if knowledge["status"] != "complete":
619
+ base["warnings"].append("optional_eligibility_incomplete")
620
+ if (
621
+ not any(t.get("visible_candidates", 0) for t in trace)
622
+ and not any(t.get("candidate_limit_reached", False) for t in trace)
623
+ and not base["constraints"]
624
+ and knowledge["status"] == "complete"
625
+ and not missing
626
+ and "dense" not in args
627
+ ):
628
+ base["status"] = "no_relevant_memory"
629
+ base["coverage"]["optional"] = "no_literal_overlap"
630
+ else:
631
+ # Literal overlap is useful evidence, not a held-out task-coverage calibration.
632
+ base["status"] = "partial"
633
+ base["warnings"].append("optional_coverage_uncalibrated")
634
+ if knowledge.get("conflicts"):
635
+ base["warnings"].append("optional_conflict_possible")
636
+ if any(t.get("candidate_limit_reached", False) for t in trace):
637
+ base["warnings"].append("optional_candidate_limit")
638
+ raw, used, selected, omitted = pack(base, groups, count, args["max_output_tokens"])
639
+ output = json.loads(raw)
640
+ rendered_items = output["constraints"] + selected
641
+ deps = self._dependencies(rendered_items)
642
+ if ranking["state"] == "experimental":
643
+ deps.append({"kind": "experience_record", "id": ranking["configuration"]})
644
+ diag["ranking_experiment"] = {
645
+ key: value for key, value in ranking.items() if key != "adjustments"
646
+ }
647
+ diag.update(
648
+ status=output["status"],
649
+ minimum_required_tokens=output.get("minimum_required_tokens"),
650
+ budget_count_scope="failure_envelope"
651
+ if output["status"] == "budget_insufficient"
652
+ else "context",
653
+ usage={**output["usage"], "output_tokens": used, "serialized_bytes": len(raw)},
654
+ coverage=output["coverage"],
655
+ selected=[
656
+ {
657
+ "reference": i["reference"],
658
+ "authority": i["authority"],
659
+ "reason": i["selection_reason"],
660
+ "score_ppm": i.get("lexical_score_ppm"),
661
+ }
662
+ for i in rendered_items
663
+ ],
664
+ omissions=sorted(set(omitted)),
665
+ duration_ms=max(0, self.s.clock.monotonic_ms() - start),
666
+ )
667
+ return raw, diag, deps
668
+
669
+ def _claim(self, item: dict[str, Any]) -> dict[str, Any]:
670
+ body = item["body"]
671
+ return {
672
+ "reference": item["revision"],
673
+ "authority": item["authority"],
674
+ "family": item["family"],
675
+ "text": body["text"],
676
+ "selector": body["selector"],
677
+ "valid_start": body["valid_start"],
678
+ "valid_end": body["valid_end"],
679
+ "task": body["task"],
680
+ "run": body["run"],
681
+ "applicability": item["applicability"],
682
+ "code_validation": item.get("code_validation", []),
683
+ "issuer_authority": body["authority"],
684
+ "effect": body["effect"],
685
+ "rule_key": body["rule_key"],
686
+ "rule_value": body["rule_value"],
687
+ "evidence": body["evidence"],
688
+ "assurance": "reviewed_not_code_verified",
689
+ "attestations": item["attestations"],
690
+ "selection_reason": "mandatory_registry"
691
+ if body["kind"] == "constraint"
692
+ else "literal_overlap",
693
+ "conflicts": [],
694
+ **(
695
+ {
696
+ "procedure": body["procedure"],
697
+ "activation": item["activation"],
698
+ "procedure_family_version": item["family_version"],
699
+ "execution_privileges": False,
700
+ }
701
+ if body["kind"] == "procedure"
702
+ else {}
703
+ ),
704
+ }
705
+
706
+ def _candidates(
707
+ self,
708
+ who: dict[str, Any],
709
+ args: dict[str, Any],
710
+ knowledge: dict[str, Any],
711
+ source: int,
712
+ recorded: int,
713
+ at: int,
714
+ dense: dict[str, Any],
715
+ ranking: dict[str, Any],
716
+ *,
717
+ evaluation: bool = False,
718
+ ) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]], str]:
719
+ query = terms(args["query"])
720
+ anchors = anchors_in(args["query"])[:16]
721
+ candidates = knowledge["items"]
722
+ key = canonical_hash(
723
+ {
724
+ "tenant": who["tenant"],
725
+ "principal": who["principal"],
726
+ "store": self.s.store_id,
727
+ "incarnation": self.s.incarnation,
728
+ "generation": source,
729
+ "configuration": CONFIGURATION,
730
+ "compiler": COMPILER,
731
+ "request": args,
732
+ "eligible": [[i["revision"], i.get("body_hash")] for i in candidates],
733
+ }
734
+ )
735
+ cache = self.s.retrieval_cache
736
+ entry = cache.get(key)
737
+ hit = entry is not None and at < entry["expires"]
738
+ if hit and entry is not None:
739
+ ids = entry["ids"]
740
+ else:
741
+ ids = []
742
+ if query and args.get("freshness", "any") != "attested":
743
+ # Tenant/scope/audience filtering precedes the candidate limit. Each term
744
+ # gets its own newest-first window, so a common word cannot crowd out the
745
+ # documents that match the rare ones; the windows are merged by how many
746
+ # terms a document matches, then by recency, and the top 257 are scored.
747
+ coverage: dict[str, int] = {}
748
+ position: dict[str, int] = {}
749
+ limited = False
750
+ for term in query:
751
+ rows = self.db.execute(
752
+ "SELECT o.id,o.position FROM observations o WHERE o.tenant=? AND o.project=? AND o.deleted=0 AND o.position<=? AND (o.readers='null' OR EXISTS(SELECT 1 FROM json_each(o.readers) WHERE value=?)) AND o.id IN(SELECT id FROM lexical WHERE tenant=? AND "
753
+ + self.s.dialect.lexical_match()
754
+ + ") ORDER BY o.position DESC,o.id DESC LIMIT 257",
755
+ (
756
+ who["tenant"],
757
+ args["project"],
758
+ recorded,
759
+ who["principal"],
760
+ who["tenant"],
761
+ '"' + term.replace('"', '""') + '"',
762
+ ),
763
+ ).fetchall()
764
+ limited = limited or len(rows) > 256
765
+ for row in rows:
766
+ coverage[row["id"]] = coverage.get(row["id"], 0) + 1
767
+ position[row["id"]] = row["position"]
768
+ # An anchor in the query (a path, symbol, ticket, URL, host or error code)
769
+ # gets its own newest-first window too, and counts double in coverage:
770
+ # naming the thing exactly outranks sharing a word with it.
771
+ for anchor in anchors:
772
+ rows = self.db.execute(
773
+ "SELECT o.id,o.position FROM observations o WHERE o.tenant=? AND o.project=? AND o.deleted=0 AND o.position<=? AND (o.readers='null' OR EXISTS(SELECT 1 FROM json_each(o.readers) WHERE value=?)) AND o.id IN(SELECT id FROM anchors WHERE tenant=? AND anchor=?) ORDER BY o.position DESC,o.id DESC LIMIT 257",
774
+ (
775
+ who["tenant"],
776
+ args["project"],
777
+ recorded,
778
+ who["principal"],
779
+ who["tenant"],
780
+ anchor,
781
+ ),
782
+ ).fetchall()
783
+ limited = limited or len(rows) > 256
784
+ for row in rows:
785
+ coverage[row["id"]] = coverage.get(row["id"], 0) + 2
786
+ position[row["id"]] = row["position"]
787
+ ordered = sorted(coverage, key=lambda i: (-coverage[i], -position[i], i))
788
+ ids = ordered[:256] + (ordered[256:257] if limited or len(ordered) > 256 else [])
789
+ if len(cache) >= 64:
790
+ cache.pop(next(iter(cache)))
791
+ cache[key] = {"expires": at + 60000, "ids": ids}
792
+ anchor_sets: dict[str, set[str]] = {}
793
+ if anchors and ids:
794
+ for row in self.db.execute(
795
+ "SELECT id,anchor FROM anchors WHERE tenant=? AND id IN ("
796
+ + ",".join("?" for _ in ids)
797
+ + ")",
798
+ (who["tenant"], *ids),
799
+ ).fetchall():
800
+ anchor_sets.setdefault(row["id"], set()).add(row["anchor"])
801
+ by_id = {i["revision"]: i for i in candidates}
802
+ adjacency: dict[str, set[str]] = {i: set() for i in by_id}
803
+ for left, right in knowledge.get("conflicts", []):
804
+ if left in by_id and right in by_id:
805
+ adjacency[left].add(right)
806
+ adjacency[right].add(left)
807
+ unresolved: set[str] = set()
808
+ conflict_work = 0
809
+ # Resolve registered endpoints directly, including those with no query
810
+ # similarity. Invisible disagreement cannot be silently presented as a
811
+ # single uncontested claim. A generic incomplete marker reveals no peer.
812
+ for revision in by_id:
813
+ if by_id[revision]["body"]["kind"] == "procedure":
814
+ continue # The procedure registry already resolved all active peers.
815
+ edges = self.db.execute(
816
+ "SELECT left_revision,right_revision FROM conflicts WHERE tenant=? AND position<=? AND (left_revision=? OR right_revision=?) LIMIT 257",
817
+ (who["tenant"], recorded, revision, revision),
818
+ ).fetchall()
819
+ if len(edges) > 256:
820
+ unresolved.add(revision)
821
+ continue
822
+ for edge in edges:
823
+ peer = edge[1] if edge[0] == revision else edge[0]
824
+ if peer in by_id:
825
+ continue # Applicability-qualified visible edges already resolved above.
826
+ other = self.k._revision(who["tenant"], peer)
827
+ lifecycle, quarantine = self.k._state(who["tenant"], peer, recorded)
828
+ if lifecycle != "accepted":
829
+ continue
830
+ if other["body"] is None:
831
+ unresolved.add(revision)
832
+ continue
833
+ body = json.loads(other["body"])
834
+ if any(body[k] is not None and body[k] != args.get(k) for k in ("task", "run")):
835
+ continue
836
+ conflict_work += len(args["bindings"]) * (
837
+ sum(len(c["all_of"]) for c in body["selector"]["any_of"])
838
+ + 128
839
+ * self.db.execute(
840
+ "SELECT count(*) FROM replacements WHERE tenant=? AND predecessor=? AND position<=?",
841
+ (who["tenant"], peer, recorded),
842
+ ).fetchone()[0]
843
+ )
844
+ if conflict_work > 65536:
845
+ unresolved.add(revision)
846
+ continue
847
+ if any(
848
+ self.k._eligible(other, body, b, args.get("valid_ms", at), recorded, who, at)
849
+ != "false"
850
+ for b in args["bindings"]
851
+ ):
852
+ unresolved.add(revision)
853
+ # Registered same-family disagreement must be expanded independent of rank.
854
+ # The live evaluator supplies applicability-qualified edges; suppressed or
855
+ # unavailable endpoints never become text or counts in this trace.
856
+ ranked: list[tuple[int, str, list[dict[str, Any]]]] = []
857
+ visited: set[str] = set()
858
+ for key_id, item in by_id.items():
859
+ score = relevance(query, item["body"]["text"])
860
+ if not score or key_id in visited:
861
+ continue
862
+ group_ids, pending = set(), [key_id]
863
+ while pending:
864
+ current = pending.pop()
865
+ if current not in group_ids:
866
+ group_ids.add(current)
867
+ pending.extend(adjacency[current] - group_ids)
868
+ visited |= group_ids
869
+ group = []
870
+ for revision in sorted(group_ids):
871
+ claim = self._claim(by_id[revision])
872
+ claim["lexical_score_ppm"] = relevance(query, by_id[revision]["body"]["text"])
873
+ claim["conflicts"] = sorted(adjacency[revision])
874
+ claim["conflict_resolution"] = (
875
+ "incomplete" if group_ids & unresolved else "complete"
876
+ )
877
+ if revision != key_id:
878
+ claim["selection_reason"] = "conflict_expansion"
879
+ group.append(claim)
880
+ score = max(relevance(query, by_id[i]["body"]["text"]) for i in group_ids)
881
+ ranked.append((score, min(group_ids), group))
882
+ dense_scores = dense["scores"]
883
+ positions: dict[str, int] = {}
884
+ for observation in dict.fromkeys([*ids[:256], *dense_scores]):
885
+ row = self.db.execute(
886
+ "SELECT * FROM observations WHERE tenant=? AND id=?", (who["tenant"], observation)
887
+ ).fetchone()
888
+ if row is None or not self.s._visible(who, row, at):
889
+ continue
890
+ positions[observation] = row["position"]
891
+ raw = self._blob(row)
892
+ # A whole atomic excerpt has attribution and bounds; never a paraphrase.
893
+ full = raw.decode()
894
+ score = relevance(query, full)
895
+ anchor_hits = 0
896
+ if anchors:
897
+ # Exact overlap of the query's anchors with the record's, in millionths,
898
+ # on the same scale as term overlap; the larger of the two is the score.
899
+ anchor_hits = sum(1 for a in anchors if a in anchor_sets.get(observation, ()))
900
+ score = max(score, anchor_hits * 1000000 // len(anchors))
901
+ offset = 0
902
+ if score and not relevance(query, raw[:4096].decode("utf-8", errors="ignore")):
903
+ # Locate an actual term in the original text; avoid byte/character
904
+ # offsets derived from casefold, which can change Unicode length.
905
+ import re
906
+
907
+ match = next(
908
+ (m for m in re.finditer(r"[^\W_]+", full) if m.group().casefold() in query),
909
+ None,
910
+ )
911
+ if match:
912
+ offset = len(full[: max(0, match.start() - 256)].encode())
913
+ excerpt = raw[offset : offset + 4096].decode("utf-8", errors="ignore")
914
+ if score or observation in dense_scores:
915
+ ranked.append(
916
+ (
917
+ score,
918
+ observation,
919
+ [
920
+ {
921
+ "reference": observation,
922
+ "authority": "observed_episode",
923
+ "text": excerpt,
924
+ "actor": row["principal"],
925
+ "source": row["source"],
926
+ "observed_at_ms": row["observed_at_ms"],
927
+ "assurance": "actor_reported",
928
+ "selection_reason": "anchor_match"
929
+ if anchor_hits
930
+ else "literal_overlap"
931
+ if score
932
+ else "semantic_similarity",
933
+ "lexical_score_ppm": score,
934
+ **(
935
+ {"dense_score_ppm": dense_scores[observation]}
936
+ if observation in dense_scores
937
+ else {}
938
+ ),
939
+ "excerpt_start_byte": offset,
940
+ "excerpt_end_byte": offset + len(excerpt.encode()),
941
+ "source_bytes": len(raw),
942
+ "content_hash": row["blob"],
943
+ }
944
+ ],
945
+ )
946
+ )
947
+ ranked.sort(key=lambda i: (-i[0], i[1]))
948
+ if "dense" in args:
949
+ # Equal-channel reciprocal-rank fusion; similarity never changes
950
+ # authority, policy completeness or registered conflict expansion.
951
+ lexical_order = {
952
+ reference: rank
953
+ for rank, (_, reference, _) in enumerate(
954
+ (item for item in ranked if item[0] > 0), 1
955
+ )
956
+ }
957
+ dense_order = {reference: rank for rank, reference in enumerate(dense_scores, 1)}
958
+ ranked = [
959
+ (
960
+ (
961
+ 1000000 // (60 + lexical_order[reference])
962
+ if reference in lexical_order
963
+ else 0
964
+ )
965
+ + (1000000 // (60 + dense_order[reference]) if reference in dense_order else 0),
966
+ reference,
967
+ group,
968
+ )
969
+ for _, reference, group in ranked
970
+ ]
971
+ ranked.sort(key=lambda item: (-item[0], item[1]))
972
+ historical = "recorded_position" in args or "valid_ms" in args
973
+ salience_trace: dict[str, Any] = {"stage": "salience_v1"}
974
+ if historical:
975
+ salience_trace["state"] = "disabled_for_historical_view"
976
+ elif evaluation:
977
+ # A ranking experiment compares two arms that must differ only by the
978
+ # adjustment under test; use-based strength would make the first arm's
979
+ # own delivery tilt the second.
980
+ salience_trace["state"] = "disabled_for_ranking_evaluation"
981
+ elif ranking["state"] != "disabled":
982
+ # An explicit, frozen ranking policy supersedes the implicit nudge: the
983
+ # operator's recorded decision is the only adjustment in force.
984
+ salience_trace["state"] = "disabled_for_active_ranking_policy"
985
+ elif args.get("salience") != "on":
986
+ # Off unless the caller asks: a briefing's order must not depend on what
987
+ # earlier briefings delivered unless that is what the caller wants.
988
+ salience_trace["state"] = "off_unless_requested"
989
+ else:
990
+ salience = self._salience(who, args["project"], positions, at)
991
+ archival = 0
992
+ rescored = []
993
+ for score, reference, group in ranked:
994
+ item = salience.get(reference)
995
+ if item is None:
996
+ rescored.append((score, reference, group))
997
+ continue
998
+ for entry in group:
999
+ entry["salience"] = {
1000
+ "strength_ppm": item["strength_ppm"],
1001
+ "tier": item["tier"],
1002
+ "deliveries_90d": item["deliveries"],
1003
+ "helpful_votes": item["helpful"],
1004
+ }
1005
+ score += SALIENCE_WEIGHT * item["strength_ppm"] // 1_000_000
1006
+ if item["tier"] == "archival":
1007
+ # Still searchable and cited when nothing else matches; ranked last.
1008
+ score -= ARCHIVAL_PENALTY
1009
+ archival += 1
1010
+ rescored.append((score, reference, group))
1011
+ ranked = sorted(rescored, key=lambda item: (-item[0], item[1]))
1012
+ salience_trace.update(
1013
+ weight_ppm=SALIENCE_WEIGHT,
1014
+ delivery_window_days=SALIENCE_WINDOW_MS // 86_400_000,
1015
+ half_life_days=SALIENCE_HALF_LIFE_MS // 86_400_000,
1016
+ archive_after_days=ARCHIVE_AFTER_MS // 86_400_000,
1017
+ archival_candidates=archival,
1018
+ )
1019
+ rerank_trace: dict[str, Any] = {"stage": "rerank_v1"}
1020
+ reranker = self.s.reranker
1021
+ if args.get("rerank") != "on":
1022
+ # Off unless asked: a model's opinion of relevance enters a briefing only
1023
+ # when the caller wants it, and the trace says so either way.
1024
+ rerank_trace["state"] = "off_unless_requested"
1025
+ elif evaluation:
1026
+ rerank_trace["state"] = "disabled_for_ranking_evaluation"
1027
+ elif ranking["state"] not in {"disabled", "historical_override_disabled"}:
1028
+ rerank_trace["state"] = "disabled_for_active_ranking_policy"
1029
+ elif reranker is None:
1030
+ rerank_trace["state"] = "unavailable_no_model"
1031
+ else:
1032
+ # The cross-encoder reads the query against each of the top fused candidates
1033
+ # and reorders that window only; everything below keeps the fused order, and
1034
+ # a model failure keeps it too. Authority, policy and conflict expansion are
1035
+ # untouched: the model moves records, it never admits or removes one.
1036
+ started = self.s.clock.monotonic_ms()
1037
+ head = ranked[:RERANK_WINDOW]
1038
+ texts = [
1039
+ (group[0].get("text") or reference)
1040
+ .encode()[:RERANK_TEXT_BYTES]
1041
+ .decode("utf-8", errors="ignore")
1042
+ or reference
1043
+ for _, reference, group in head
1044
+ ]
1045
+ try:
1046
+ scores = reranker.score(args["query"], texts) if head else []
1047
+ except LocalError as exc:
1048
+ rerank_trace.update(state="failed_fused_order_kept", error=exc.code)
1049
+ else:
1050
+ order = sorted(range(len(head)), key=lambda i: (-scores[i], i))
1051
+ for index, (_, _, group) in enumerate(head):
1052
+ for entry in group:
1053
+ entry["rerank_score_ppm"] = scores[index]
1054
+ ranked = [head[i] for i in order] + ranked[len(head) :]
1055
+ rerank_trace.update(
1056
+ state="applied",
1057
+ model=reranker.fingerprint,
1058
+ window=RERANK_WINDOW,
1059
+ candidates=len(head),
1060
+ moved=sum(1 for new, old in enumerate(order) if new != old),
1061
+ duration_ms=max(0, self.s.clock.monotonic_ms() - started),
1062
+ )
1063
+ if ranking["state"] == "experimental":
1064
+ from memoryking.domain.learning import adjust
1065
+
1066
+ ranked = adjust(ranked, ranking["adjustments"])
1067
+ limit = args.get("top_k", 8)
1068
+ trace = [
1069
+ {"stage": "authorized_eligibility", "visible_claims": len(candidates)},
1070
+ {
1071
+ "stage": "lexical",
1072
+ "visible_candidates": len(ranked),
1073
+ "candidate_limit_reached": len(ids) > 256,
1074
+ "max_candidates": 256,
1075
+ },
1076
+ {
1077
+ "stage": "rank",
1078
+ "metric": "literal_term_overlap_v1",
1079
+ "selected_groups": min(limit, len(ranked)),
1080
+ },
1081
+ ]
1082
+ if "dense" in args:
1083
+ trace[1]["visible_candidates"] = len(lexical_order)
1084
+ trace.insert(
1085
+ 2,
1086
+ {
1087
+ "stage": "dense",
1088
+ "visible_candidates": len(dense_scores),
1089
+ "candidate_limit_reached": dense["candidate_limit_reached"],
1090
+ "availability": dense["availability"],
1091
+ "max_candidates": 256,
1092
+ },
1093
+ )
1094
+ trace[-1]["metric"] = "equal_channel_rrf60_v1"
1095
+ # The rank stage stays last among the fixed stages; salience and the reranker
1096
+ # sit before it, in the order they ran.
1097
+ trace.insert(len(trace) - 1, salience_trace)
1098
+ trace.insert(len(trace) - 1, rerank_trace)
1099
+ if ranking["state"] != "disabled":
1100
+ trace.append(
1101
+ {
1102
+ "stage": "bounded_ranking_experiment",
1103
+ **{key: value for key, value in ranking.items() if key != "adjustments"},
1104
+ }
1105
+ )
1106
+ return [group for _, _, group in ranked[:limit]], trace, "hit" if hit else "miss"
1107
+
1108
+ def _salience(
1109
+ self, who: dict[str, Any], project: str, positions: dict[str, int], at: int
1110
+ ) -> dict[str, dict[str, Any]]:
1111
+ """Strength from the caller's own use: how often this principal was delivered a
1112
+ record lately, whether they said it helped, and how long ago; a record nobody at
1113
+ all has used past the archive age sinks.
1114
+
1115
+ Receipts and feedback are private to the principal that holds them, and another
1116
+ principal's feedback must never reorder a reader's briefing, so strength counts
1117
+ only the caller's own deliveries and votes. The archival tier looks at whether
1118
+ any principal used the record, which is a fact of the store's operation, not an
1119
+ opinion. Nothing is written or deleted; an as-of view never sees any of it."""
1120
+ import math
1121
+
1122
+ if not positions:
1123
+ return {}
1124
+ wanted = set(positions)
1125
+ deliveries: dict[str, int] = {}
1126
+ last_used: dict[str, int] = {}
1127
+ used_by_anyone: set[str] = set()
1128
+ for row in self.db.execute(
1129
+ "SELECT principal,created,diagnostics,dependencies FROM rendered_artifacts WHERE tenant=? AND project=? AND state='retained' AND created>=?",
1130
+ (who["tenant"], project, at - SALIENCE_WINDOW_MS),
1131
+ ).fetchall():
1132
+ diagnostics = json.loads(row["diagnostics"] or "{}")
1133
+ if diagnostics.get("kind") == "atlas":
1134
+ continue # looking at the graph never counts as use
1135
+ mine = row["principal"] == who["principal"]
1136
+ for dep in json.loads(row["dependencies"]):
1137
+ reference = dep.get("id")
1138
+ if reference not in wanted:
1139
+ continue
1140
+ used_by_anyone.add(reference)
1141
+ if mine:
1142
+ deliveries[reference] = deliveries.get(reference, 0) + 1
1143
+ last_used[reference] = max(last_used.get(reference, 0), row["created"])
1144
+ helpful: dict[str, int] = {}
1145
+ for row in self.db.execute(
1146
+ "SELECT body FROM experience_records WHERE tenant=? AND project=? AND principal=? AND kind='feedback' AND body IS NOT NULL",
1147
+ (who["tenant"], project, who["principal"]),
1148
+ ).fetchall():
1149
+ body = json.loads(row["body"])
1150
+ reference = body.get("reference")
1151
+ if reference in wanted and body.get("usefulness") == "helpful":
1152
+ helpful[reference] = helpful.get(reference, 0) + 1
1153
+ recorded: dict[int, int] = {}
1154
+ chunk = list(positions.values())
1155
+ for start in range(0, len(chunk), 500):
1156
+ part = chunk[start : start + 500]
1157
+ for row in self.db.execute(
1158
+ "SELECT position,at_ms FROM events WHERE tenant=? AND position IN ("
1159
+ + ",".join("?" for _ in part)
1160
+ + ")",
1161
+ (who["tenant"], *part),
1162
+ ).fetchall():
1163
+ recorded[row["position"]] = row["at_ms"]
1164
+ result: dict[str, dict[str, Any]] = {}
1165
+ for reference, position in positions.items():
1166
+ count = deliveries.get(reference, 0)
1167
+ votes = helpful.get(reference, 0)
1168
+ if count:
1169
+ age = max(0, at - last_used[reference])
1170
+ recency = 0.5 ** (age / SALIENCE_HALF_LIFE_MS)
1171
+ use = min(1.0, math.log2(1 + count) / 4) * recency
1172
+ else:
1173
+ use = 0.0
1174
+ strength = min(1_000_000, int(500_000 * use) + 250_000 * min(2, votes))
1175
+ captured_ms = recorded.get(position, at)
1176
+ tier = (
1177
+ "archival"
1178
+ if reference not in used_by_anyone
1179
+ and not votes
1180
+ and at - captured_ms > ARCHIVE_AFTER_MS
1181
+ else "active"
1182
+ )
1183
+ if strength or tier == "archival":
1184
+ result[reference] = {
1185
+ "strength_ppm": strength,
1186
+ "tier": tier,
1187
+ "deliveries": count,
1188
+ "helpful": votes,
1189
+ }
1190
+ return result
1191
+
1192
+ def _blob(self, row: sqlite3.Row) -> bytes:
1193
+ path = self.s.root / "blobs" / row["tenant"] / row["blob"]
1194
+ private_file(path)
1195
+ raw: bytes = path.read_bytes()
1196
+ if hashlib.sha256(raw).hexdigest() != row["blob"]:
1197
+ raise LocalError("blob_corrupt")
1198
+ return raw
1199
+
1200
+ def _dependencies(self, items: list[dict[str, Any]]) -> list[dict[str, str]]:
1201
+ deps: set[tuple[str, str]] = set()
1202
+ for item in items:
1203
+ kind = "observation" if item["authority"] == "observed_episode" else "revision"
1204
+ deps.add((kind, item["reference"]))
1205
+ if item["authority"] == "active_procedure":
1206
+ deps.add(
1207
+ (
1208
+ "procedure_activation",
1209
+ f"{item['reference']}|{item['activation']['position']}|{item['procedure_family_version']}",
1210
+ )
1211
+ )
1212
+ for proof in item.get("code_validation", []):
1213
+ deps.add(("code_validation", proof["dependency"]))
1214
+ deps.update(("observation", source) for source in proof["evidence"])
1215
+ for span in item.get("evidence", []):
1216
+ deps.add(("observation", span["observation"]))
1217
+ return [{"kind": k, "id": v} for k, v in sorted(deps)]
1218
+
1219
+ def _fetch(
1220
+ self, who: dict[str, Any], args: dict[str, Any], decision: Decision, receipt: str
1221
+ ) -> tuple[bytes, dict[str, Any], list[dict[str, str]]]:
1222
+ start, end = args["start_byte"], args["end_byte"]
1223
+ if end <= start or end - start > 16384:
1224
+ raise LocalError("invalid_range")
1225
+ at = decision.evaluated_ms
1226
+ if args["kind"] == "observation":
1227
+ row = self.db.execute(
1228
+ "SELECT * FROM observations WHERE tenant=? AND project=? AND id=?",
1229
+ (who["tenant"], args["project"], args["reference"]),
1230
+ ).fetchone()
1231
+ if row is None or not self.s._visible(who, row, at):
1232
+ raise LocalError("unavailable")
1233
+ raw = self._blob(row)
1234
+ authority = "observed_episode"
1235
+ deps = [{"kind": "observation", "id": row["id"]}]
1236
+ else:
1237
+ row = self.k._revision(who["tenant"], args["reference"], args["project"])
1238
+ state, quarantine = self.k._state(who["tenant"], row["id"], 9007199254740991)
1239
+ if not self.k._available(who, row, at) or quarantine:
1240
+ raise LocalError("unavailable")
1241
+ if state != "accepted":
1242
+ self.s._subject_auth(
1243
+ self.s._token("credential", tenant=who["tenant"], principal=who["principal"]),
1244
+ "review",
1245
+ args["project"],
1246
+ at,
1247
+ )
1248
+ raw = json.loads(row["body"])["text"].encode()
1249
+ authority = "revision_evidence_only"
1250
+ deps = [{"kind": "revision", "id": row["id"]}]
1251
+ if end > len(raw):
1252
+ raise LocalError("invalid_range")
1253
+ try:
1254
+ raw[:start].decode()
1255
+ excerpt = raw[start:end].decode()
1256
+ except UnicodeDecodeError as exc:
1257
+ raise LocalError("invalid_range") from exc
1258
+ count, usage = counter(args["tokenizer"])
1259
+ result = self._base(args, decision, receipt, usage)
1260
+ result.update(
1261
+ status="partial",
1262
+ reason="evidence_excerpt_not_a_briefing",
1263
+ reference=args["reference"],
1264
+ authority=authority,
1265
+ excerpt=excerpt,
1266
+ start_byte=start,
1267
+ end_byte=end,
1268
+ source_bytes=len(raw),
1269
+ source_hash=hashlib.sha256(raw).hexdigest(),
1270
+ )
1271
+ body, used = counted(result, count)
1272
+ if used > args["max_output_tokens"]:
1273
+ result.update(status="budget_insufficient", excerpt="", minimum_required_tokens=used)
1274
+ result["usage"]["budget_compliant"] = False
1275
+ body, used = counted(result, count)
1276
+ deps = []
1277
+ return (
1278
+ body,
1279
+ {
1280
+ "status": result["status"],
1281
+ "usage": {**result["usage"], "output_tokens": used, "serialized_bytes": len(body)},
1282
+ "operation": "fetch",
1283
+ },
1284
+ deps,
1285
+ )