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,441 @@
1
+ """Bounded, current-authorized evidence graph; layout never creates authority."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from typing import Any
8
+
9
+ from memoryking.contracts.canonical import canonical_bytes, canonical_hash
10
+ from memoryking.domain.briefing import relevance, terms
11
+ from memoryking.domain.local import Decision, LocalError
12
+
13
+
14
+ def query(
15
+ retrieval: Any, who: dict[str, Any], args: dict[str, Any], decision: Decision, receipt: str
16
+ ) -> tuple[bytes, dict[str, Any], list[dict[str, str]]]:
17
+ s, db, k = retrieval.s, retrieval.db, retrieval.k
18
+ at, tenant = decision.evaluated_ms, who["tenant"]
19
+ scope: dict[str, Any] = {
20
+ key: args[key]
21
+ for key in ("project", "bindings", "task", "run", "valid_ms", "recorded_position")
22
+ if key in args
23
+ }
24
+ state = db.execute("SELECT * FROM tenants WHERE tenant=?", (tenant,)).fetchone()
25
+ recorded = args.get("recorded_position", state["position"])
26
+ if recorded > state["position"]:
27
+ raise LocalError("invalid_recorded_position")
28
+ # No search, degree or aggregate is computed from an unauthorized graph.
29
+ # The scan is finite; these counts only describe the loaded authorized window.
30
+ rows = db.execute(
31
+ "SELECT o.* 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=?)) ORDER BY o.position,o.id LIMIT 1001",
32
+ (tenant, args["project"], recorded, who["principal"]),
33
+ ).fetchall()
34
+ nodes: dict[str, dict[str, Any]] = {}
35
+ dependencies: dict[str, list[dict[str, str]]] = {}
36
+ edges: list[dict[str, Any]] = []
37
+ limits: set[str] = {"observation_scan"} if len(rows) > 1000 else set()
38
+ for row in rows[:1000]:
39
+ if not s._visible(who, row, at):
40
+ continue
41
+ raw = retrieval._blob(row)
42
+ nodes[row["id"]] = {
43
+ "id": row["id"],
44
+ "type": "observation",
45
+ "label": raw.decode()[:256],
46
+ "authority": "observed_episode",
47
+ "content_hash": row["blob"],
48
+ "source": row["source"],
49
+ "position": row["position"],
50
+ "anchors": [],
51
+ }
52
+ dependencies[row["id"]] = [{"kind": "observation", "id": row["id"]}]
53
+ # Exact names the loaded observations share (paths, symbols, tickets, hosts, errors)
54
+ # link them, A-MEM style, without any model: an anchor held by two to eight of the
55
+ # loaded records is rare enough to mean something; a commoner one is just a word.
56
+ by_anchor: dict[str, list[str]] = {}
57
+ if nodes:
58
+ loaded = list(nodes)
59
+ for start in range(0, len(loaded), 500):
60
+ chunk = loaded[start : start + 500]
61
+ for item in db.execute(
62
+ "SELECT id,anchor,kind FROM anchors WHERE tenant=? AND id IN ("
63
+ + ",".join("?" for _ in chunk)
64
+ + ") ORDER BY id,anchor",
65
+ (tenant, *chunk),
66
+ ).fetchall():
67
+ if len(nodes[item["id"]]["anchors"]) < 16:
68
+ nodes[item["id"]]["anchors"].append(
69
+ {"kind": item["kind"], "anchor": item["anchor"]}
70
+ )
71
+ by_anchor.setdefault(item["anchor"], []).append(item["id"])
72
+
73
+ anchor_links = 0
74
+
75
+ def edge(source: str, target: str, kind: str, provenance: dict[str, Any]) -> None:
76
+ if source in nodes and target in nodes:
77
+ if len(edges) >= 6000:
78
+ limits.add("edge_scan")
79
+ return
80
+ item = {"source": source, "target": target, "type": kind, "provenance": provenance}
81
+ edges.append({"id": canonical_hash(item), **item})
82
+
83
+ for anchor, holders in sorted(by_anchor.items()):
84
+ holders = sorted(set(holders))
85
+ if not 2 <= len(holders) <= 8:
86
+ continue
87
+ for left, right in zip(holders, holders[1:], strict=False):
88
+ if anchor_links >= 512:
89
+ limits.add("anchor_links")
90
+ break
91
+ edge(left, right, "shares_anchor", {"kind": "shared_anchor", "anchor": anchor})
92
+ anchor_links += 1
93
+
94
+ attestation_count = 0
95
+ # A reviewer also sees proposed, rejected, deprecated and quarantined claims, in the
96
+ # same diagnostic mode the review queue uses; a plain reader sees accepted ones only.
97
+ try:
98
+ s._subject_auth(
99
+ s._token("credential", tenant=tenant, principal=who["principal"]),
100
+ "review",
101
+ args["project"],
102
+ at,
103
+ )
104
+ reviewer = True
105
+ except LocalError:
106
+ reviewer = False
107
+ for constraints in (False, True):
108
+ result = k.query(
109
+ who,
110
+ {**scope, "diagnostic": True} if reviewer and not constraints else scope,
111
+ at,
112
+ constraints=constraints,
113
+ attestation_limit=33,
114
+ )
115
+ if result["status"] != "complete":
116
+ limits.add("claim_resolution_incomplete")
117
+ for item in result["items"]:
118
+ ident, body = item["revision"], item["body"]
119
+ if "created_position" not in item:
120
+ # A claim whose selector the store cannot evaluate has no recorded
121
+ # position in this result; it is listed in the review queue instead.
122
+ limits.add("unsupported_selector_claims_omitted")
123
+ continue
124
+ nodes[ident] = {
125
+ "id": ident,
126
+ "type": "claim",
127
+ "label": body["text"][:256],
128
+ "authority": item["authority"],
129
+ "content_hash": item["body_hash"],
130
+ "family": item["family"],
131
+ "state": item["state"],
132
+ "quarantined": bool(item.get("quarantined", False)),
133
+ "applicability": item["applicability"],
134
+ "position": item["created_position"],
135
+ }
136
+ dependencies[ident] = retrieval._dependencies([retrieval._claim(item)])
137
+ for span in body["evidence"]:
138
+ edge(
139
+ span["observation"],
140
+ ident,
141
+ "supports",
142
+ {"kind": "recorded_evidence_span", **span},
143
+ )
144
+ for att in item["attestations"][:32]:
145
+ if attestation_count >= 256:
146
+ limits.add("attestation_scan")
147
+ break
148
+ attestation_count += 1
149
+ aid = "attestation:" + ident + ":" + str(att["position"])
150
+ nodes[aid] = {
151
+ "id": aid,
152
+ "type": "attestation",
153
+ "label": att["statement"][:256],
154
+ "authority": "actor_attestation",
155
+ "actor": att["actor"],
156
+ "expires_ms": att["expires"],
157
+ "position": att["position"],
158
+ }
159
+ dependencies[aid] = dependencies[ident]
160
+ edge(
161
+ ident, aid, "verified_by", {"kind": "attestation", "position": att["position"]}
162
+ )
163
+ if len(item["attestations"]) > 32:
164
+ limits.add("attestation_limit")
165
+ for left, right in result.get("conflicts", []):
166
+ edge(left, right, "contradicts", {"kind": "eligible_claim_conflict"})
167
+
168
+ # P10 adds actual procedure/checkpoint relationships. Historical requests do
169
+ # not mix present procedure activation into an older recorded frontier.
170
+ if not {"recorded_position", "valid_ms"}.intersection(args):
171
+ from memoryking.adapters.experience import Experience
172
+
173
+ if len(args["bindings"]) <= 32:
174
+ procedures = Experience(s).query(who, scope, at)
175
+ if procedures["status"] != "complete":
176
+ limits.add("procedure_resolution_incomplete")
177
+ for item in procedures["items"]:
178
+ ident, body = item["revision"], item["body"]
179
+ nodes[ident] = {
180
+ "id": ident,
181
+ "type": "procedure",
182
+ "label": body["text"][:256],
183
+ "authority": item["authority"],
184
+ "state": item["effective_state"],
185
+ "position": item["created_position"],
186
+ "content_hash": item["body_hash"],
187
+ "execution_privileges": False,
188
+ }
189
+ dependencies[ident] = retrieval._dependencies([retrieval._claim(item)])
190
+ activation = item["activation"]
191
+ if activation is not None:
192
+ dependencies[ident].append(
193
+ {
194
+ "kind": "procedure_activation",
195
+ "id": f"{ident}|{activation['position']}|{item['family_version']}",
196
+ }
197
+ )
198
+ for span in body["evidence"]:
199
+ edge(
200
+ span["observation"],
201
+ ident,
202
+ "supports",
203
+ {"kind": "recorded_evidence_span", **span},
204
+ )
205
+ else:
206
+ limits.add("procedure_binding_limit")
207
+ else:
208
+ limits.add("historical_procedures_omitted")
209
+
210
+ from memoryking.adapters.execution import Execution
211
+
212
+ execution = Execution(s).snapshot(who, args["project"], at, args.get("recorded_position"))
213
+ if execution["status"] != "available":
214
+ limits.add("checkpoint_projection_unavailable")
215
+ for task in execution["tasks"]:
216
+ if (
217
+ args.get("task", task["task"]) != task["task"]
218
+ or args.get("run", task["run"]) != task["run"]
219
+ ):
220
+ continue
221
+ ident = task["checkpoint"]
222
+ row = db.execute(
223
+ "SELECT body,dependencies FROM checkpoints WHERE tenant=? AND id=?", (tenant, ident)
224
+ ).fetchone()
225
+ body = json.loads(row["body"]) if row is not None and row["body"] else {}
226
+ plan = body.get("plan")
227
+ nodes[ident] = {
228
+ "id": ident,
229
+ "type": "plan" if plan else "checkpoint",
230
+ "label": (plan["title"] if plan else task["objective"])[:256],
231
+ "authority": "recorded_plan" if plan else "producer_checkpoint",
232
+ "position": task["source_position"],
233
+ "revision": task["revision"],
234
+ "content_hash": task["body_hash"],
235
+ **({"status": plan["status"]} if plan else {}),
236
+ }
237
+ dependencies[ident] = [{"kind": "checkpoint", "id": ident}]
238
+ if plan:
239
+ # Steps are the plan's own structure: declared by the plan, ordered by their
240
+ # prerequisites, and tied to the observations they cite as proof. A step
241
+ # shares the plan's receipt dependency; it never becomes evidence itself.
242
+ for step in plan["steps"]:
243
+ sid = "step:" + ident + ":" + step["id"]
244
+ nodes[sid] = {
245
+ "id": sid,
246
+ "type": "step",
247
+ "label": step["description"][:256],
248
+ "authority": "recorded_plan_step",
249
+ "position": task["source_position"],
250
+ "status": step["status"],
251
+ "phase": step["phase"],
252
+ }
253
+ dependencies[sid] = dependencies[ident]
254
+ for step in plan["steps"]:
255
+ sid = "step:" + ident + ":" + step["id"]
256
+ edge(ident, sid, "declares", {"kind": "plan_step", "checkpoint": ident})
257
+ for prerequisite in step["depends_on"]:
258
+ edge(
259
+ sid,
260
+ "step:" + ident + ":" + prerequisite,
261
+ "depends_on",
262
+ {"kind": "plan_step_prerequisite", "checkpoint": ident},
263
+ )
264
+ for proof in step["evidence"]:
265
+ edge(
266
+ sid,
267
+ proof["id"],
268
+ "cites",
269
+ {
270
+ "kind": "plan_step_evidence",
271
+ "checkpoint": ident,
272
+ "status": step["status"],
273
+ },
274
+ )
275
+ for lesson in plan["lessons"]:
276
+ edge(ident, lesson["id"], "cites", {"kind": "plan_lesson", "checkpoint": ident})
277
+ tid = "task:" + args["project"] + ":" + task["task"]
278
+ nodes[tid] = {
279
+ "id": tid,
280
+ "type": "task",
281
+ "label": task["task"],
282
+ "authority": "recorded_task_identity",
283
+ "position": task["source_position"],
284
+ }
285
+ dependencies.setdefault(tid, []).extend(dependencies[ident])
286
+ edge(ident, tid, "documented_in", {"kind": "checkpoint_scope", "checkpoint": ident})
287
+ if task["run"] is not None:
288
+ rid = "run:" + canonical_hash([args["project"], task["task"], task["run"]])
289
+ nodes[rid] = {
290
+ "id": rid,
291
+ "type": "run",
292
+ "label": task["run"],
293
+ "authority": "recorded_run_identity",
294
+ "position": task["source_position"],
295
+ }
296
+ dependencies[rid] = dependencies[ident]
297
+ edge(rid, tid, "documented_in", {"kind": "checkpoint_scope", "checkpoint": ident})
298
+ edge(ident, rid, "documented_in", {"kind": "checkpoint_scope", "checkpoint": ident})
299
+ for dep in json.loads(row["dependencies"]) if row is not None else []:
300
+ edge(
301
+ ident,
302
+ dep["id"],
303
+ "depends_on",
304
+ {
305
+ "kind": "checkpoint_dependency",
306
+ "checkpoint": ident,
307
+ "dependency_kind": dep["kind"],
308
+ },
309
+ )
310
+ limits.add("checkpoint_window")
311
+ # Size by citation: how many of the caller's own retained briefings, fetches and
312
+ # reruns depended on the record. Atlas pages are excluded, so looking never cites.
313
+ cited = retrieval.citations(who, args["project"], at)
314
+ for ident, node in nodes.items():
315
+ node["citations"] = cited.get(ident, 0)
316
+ wanted_types = set(
317
+ args.get(
318
+ "types",
319
+ [
320
+ "observation",
321
+ "claim",
322
+ "attestation",
323
+ "procedure",
324
+ "checkpoint",
325
+ "plan",
326
+ "step",
327
+ "task",
328
+ "run",
329
+ ],
330
+ )
331
+ )
332
+ visible = {i for i, node in nodes.items() if node["type"] in wanted_types}
333
+ search = terms(args.get("query", ""))
334
+ if search:
335
+ visible = {i for i in visible if relevance(search, nodes[i]["label"])}
336
+ if args.get("focus"):
337
+ seeds = set(args["focus"]) & visible
338
+ visible = seeds | {
339
+ i
340
+ for e in edges
341
+ if e["source"] in seeds or e["target"] in seeds
342
+ for i in (e["source"], e["target"])
343
+ if i in visible
344
+ }
345
+ ordered = sorted(visible, key=lambda i: (nodes[i]["position"], i))
346
+ visible_edges = sorted(
347
+ (e for e in edges if e["source"] in visible and e["target"] in visible),
348
+ key=lambda e: e["id"],
349
+ )
350
+ binding = {
351
+ "store": s.store_id,
352
+ "tenant": tenant,
353
+ "principal": who["principal"],
354
+ "project": args["project"],
355
+ "incarnation": s.incarnation,
356
+ "authorization_epoch": state["policy_epoch"],
357
+ "purge_epoch": state["purge_epoch"],
358
+ "delegation_chain": who.get("delegation_chain", []),
359
+ }
360
+ # Re-evaluate membership on every page, including temporal expiry. A changed
361
+ # authorized view invalidates offsets; old cursors cannot stand in for grants.
362
+ fingerprint = hashlib.sha256(
363
+ canonical_bytes(
364
+ {
365
+ "binding": binding,
366
+ "source": state["position"],
367
+ "request": {key: value for key, value in args.items() if key != "cursor"},
368
+ }
369
+ )
370
+ )
371
+ for item in [*(nodes[i] for i in ordered), *visible_edges]:
372
+ fingerprint.update(canonical_bytes(item))
373
+ fingerprint.update(b"\n")
374
+ view_hash = fingerprint.hexdigest()
375
+ offset = 0
376
+ if args.get("cursor"):
377
+ cursor = s._decode(args["cursor"], "atlas")
378
+ if cursor.get("view") != view_hash or at >= cursor.get("expires", 0):
379
+ raise LocalError("atlas_resync_required")
380
+ offset = cursor["offset"]
381
+ selected = ordered[offset : offset + args.get("max_nodes", 200)]
382
+ edge_limit = args.get("max_edges", 400)
383
+
384
+ def materialize() -> dict[str, Any]:
385
+ page = set(selected)
386
+ permitted_edges = [e for e in visible_edges if e["source"] in page and e["target"] in page]
387
+ truncated = set(limits)
388
+ if len(permitted_edges) > edge_limit:
389
+ truncated.add("edge_limit")
390
+ if offset or offset + len(selected) < len(ordered):
391
+ truncated.add("node_page")
392
+ if any((e["source"] in page) != (e["target"] in page) for e in visible_edges):
393
+ truncated.add("edges_outside_page")
394
+ next_offset = offset + len(selected)
395
+ return {
396
+ "schema": "atlas-v1",
397
+ "status": "partial",
398
+ "label_scope": "first_256_characters_inspection_only",
399
+ "receipt": receipt,
400
+ "evaluated_ms": at,
401
+ "deadline_ms": decision.deadline_ms,
402
+ "binding": binding,
403
+ "nodes": [nodes[i] for i in selected],
404
+ "edges": permitted_edges[:edge_limit],
405
+ "list": [
406
+ {"id": i, "label": nodes[i]["label"], "type": nodes[i]["type"]} for i in selected
407
+ ],
408
+ "counts": {
409
+ kind: sum(nodes[i]["type"] == kind for i in selected)
410
+ for kind in sorted(wanted_types)
411
+ },
412
+ "count_scope": "returned_page_only",
413
+ "coverage": "bounded_current_authorized_window",
414
+ "truncation": sorted(truncated),
415
+ "source_position": state["position"],
416
+ "next_cursor": s._token("atlas", view=view_hash, offset=next_offset, expires=at + 60000)
417
+ if next_offset < len(ordered)
418
+ else None,
419
+ "similarity": "unavailable",
420
+ "layout_distance": "not_confidence",
421
+ }
422
+
423
+ response = materialize()
424
+ while len(json.dumps(response, ensure_ascii=False).encode()) > 196608 and selected:
425
+ limits.add("response_bytes")
426
+ selected.pop()
427
+ response = materialize()
428
+ deps = {(d["kind"], d["id"]) for i in selected for d in dependencies[i]}
429
+ raw = canonical_bytes(response)
430
+ return (
431
+ raw,
432
+ {
433
+ "kind": "atlas",
434
+ "status": "partial",
435
+ "usage": {"serialized_bytes": len(raw), "provider_usage": "not_used"},
436
+ "coverage": response["coverage"],
437
+ "truncation": response["truncation"],
438
+ "serialized_bytes": len(raw),
439
+ },
440
+ [{"kind": kind, "id": ident} for kind, ident in sorted(deps)],
441
+ )
@@ -0,0 +1,125 @@
1
+ """Cookie UI boundary: session validation inside each domain authorization decision."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ from collections.abc import Callable
7
+ from typing import Any, Protocol, cast
8
+
9
+ from memoryking.application.store_core import StoreCore
10
+ from memoryking.contracts.canonical import canonical_bytes
11
+ from memoryking.domain.local import LocalError, Released
12
+
13
+
14
+ class CommandService(Protocol):
15
+ def execute(self, credential: str, command: dict[str, Any]) -> Released: ...
16
+
17
+
18
+ class BrowserStore:
19
+ """Request-local facade; never mutate the shared store's authentication method.
20
+
21
+ The domain opens its own transaction and passes its persisted evaluation instant
22
+ to _auth. Session expiry/epoch and operation capability are checked at that same
23
+ instant. Subject/intersection checks keep the real store's identity semantics.
24
+ """
25
+
26
+ def __init__(self, store: StoreCore, session: dict[str, Any], check_session: Callable[[], Any]):
27
+ self.store, self.session = store, dict(session)
28
+ self.check_session = check_session
29
+
30
+ def __getattr__(self, name: str) -> Any:
31
+ return getattr(self.store, name)
32
+
33
+ def _auth(self, credential: str, capability: str, project: str, at: int) -> dict[str, Any]:
34
+ value, store = self.session, self.store
35
+ self.check_session()
36
+ if credential != value["credential"]:
37
+ raise LocalError("mixed_authentication")
38
+ who = store._auth(credential, "admin", "*", at)
39
+ epoch = store.db.execute(
40
+ "SELECT policy_epoch FROM tenants WHERE tenant=?", (who["tenant"],)
41
+ ).fetchone()[0]
42
+ if (
43
+ at >= value["expires"]
44
+ or value["epoch"] != epoch
45
+ or value["incarnation"] != store.incarnation
46
+ or who["tenant"] != value["tenant"]
47
+ ):
48
+ raise LocalError("session_changed")
49
+ return store._auth(credential, capability, project, at)
50
+
51
+
52
+ def execute(
53
+ store: StoreCore,
54
+ session: dict[str, Any],
55
+ body: dict[str, Any],
56
+ check_session: Callable[[], Any],
57
+ ) -> Released:
58
+ from memoryking.adapters.experience import Experience
59
+ from memoryking.adapters.handoff import Handoff
60
+ from memoryking.adapters.inference import Inference
61
+ from memoryking.adapters.inspection import Inspection
62
+ from memoryking.adapters.knowledge_store import Knowledge
63
+ from memoryking.adapters.repository_store import Repository
64
+ from memoryking.adapters.retrieval import Retrieval
65
+ from memoryking.adapters.working import Working
66
+
67
+ if (
68
+ set(body) != {"csrf", "operation", "command"}
69
+ or not isinstance(body["csrf"], str)
70
+ or not secrets.compare_digest(body["csrf"], session["csrf"])
71
+ ):
72
+ raise LocalError("csrf_rejected")
73
+ if len(canonical_bytes(body)) > 131072 or not isinstance(body["command"], dict):
74
+ raise LocalError("invalid_request")
75
+ operation, command = body["operation"], body["command"]
76
+ allowed = {
77
+ "retrieval": {"atlas", "fetch", "replay", "brief", "rerun"},
78
+ "knowledge": {"query", "constraints", "propose", "draft", "review", "attest"},
79
+ "experience": {
80
+ "query",
81
+ "records",
82
+ "record",
83
+ "review",
84
+ "activate",
85
+ "suspend",
86
+ "ranking_inspect",
87
+ },
88
+ "repository": {"impact", "history", "coverage"},
89
+ "working": {"resume", "operations"},
90
+ "handoff": {"prepare", "preview", "materialize", "cancel"},
91
+ "inspection": {
92
+ "history",
93
+ "operations",
94
+ "cost",
95
+ "handoffs",
96
+ "retention_preview",
97
+ "purge",
98
+ "influence",
99
+ "trust",
100
+ "trust_list",
101
+ "held",
102
+ "release",
103
+ "health",
104
+ },
105
+ "inference": {"audit"},
106
+ }
107
+ if (
108
+ not isinstance(operation, str)
109
+ or operation not in allowed
110
+ or not isinstance(command.get("action"), str)
111
+ or command["action"] not in allowed[operation]
112
+ ):
113
+ raise LocalError("dashboard_action_unsupported")
114
+ services: dict[str, Callable[[StoreCore], CommandService]] = {
115
+ "retrieval": Retrieval,
116
+ "knowledge": Knowledge,
117
+ "experience": Experience,
118
+ "repository": Repository,
119
+ "working": Working,
120
+ "handoff": Handoff,
121
+ "inspection": Inspection,
122
+ "inference": Inference,
123
+ }
124
+ guarded = cast(StoreCore, BrowserStore(store, session, check_session))
125
+ return services[operation](guarded).execute(session["credential"], command)