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
memoryking/__main__.py ADDED
@@ -0,0 +1,1328 @@
1
+ """MemoryKing local service CLI. Administrative recovery requires an offline owner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import signal
9
+ import sys
10
+ import time
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from memoryking import __version__, profiles
16
+ from memoryking.adapters.dashboard import Dashboard
17
+ from memoryking.adapters.local_files import atomic, private_dir, private_file
18
+ from memoryking.adapters.local_ipc import Server, request
19
+ from memoryking.adapters.local_store import SCHEMA_VERSION, LocalStore
20
+ from memoryking.contracts.canonical import ContractError, canonical_bytes, load_strict
21
+ from memoryking.domain.hints import hint
22
+ from memoryking.domain.local import LocalError
23
+ from memoryking.observability import LEVELS, configure, event
24
+
25
+
26
+ def bar(used: int, limit: int, width: int = 12) -> str:
27
+ filled = min(width, round(width * used / limit)) if limit else 0
28
+ return "[" + "#" * filled + "." * (width - filled) + "]"
29
+
30
+
31
+ def render_status(result: dict[str, Any], version: str) -> str:
32
+ """A human summary of the status operation; `--json` prints the raw result instead."""
33
+ projection = result.get("projection", {})
34
+ jobs = result.get("jobs", {})
35
+ lines = [
36
+ f"MemoryKing {version}",
37
+ f"Store {result['store']}",
38
+ f"History {result['incarnation']}",
39
+ f"Position {result['position']}",
40
+ "Frontier "
41
+ f"{projection.get('frontier', '?')} / {result['position']}"
42
+ f" (projection {projection.get('channel', '?')} generation {projection.get('generation', '?')})",
43
+ "Jobs "
44
+ + (
45
+ " · ".join(f"{state} {count}" for state, count in sorted(jobs.items()))
46
+ if jobs
47
+ else "none"
48
+ ),
49
+ ]
50
+ capacity = result.get("capacity", {})
51
+ if capacity:
52
+ lines.append("Capacity")
53
+ for name, value in capacity.items():
54
+ used, limit = value["used"], value["limit"]
55
+ shown = (
56
+ f"{used / 1048576:.1f} / {limit // 1048576} MiB"
57
+ if name == "rendered_bytes"
58
+ else f"{used:,} / {limit:,}"
59
+ )
60
+ flag = " warning" if value.get("warning") else ""
61
+ lines.append(f" {name:<20}{shown:>22} {bar(used, limit)}{flag}")
62
+ if result.get("satisfied") is not None:
63
+ lines.append(f"Watermark {'satisfied' if result['satisfied'] else 'not yet reached'}")
64
+ return "\n".join(lines)
65
+
66
+
67
+ DURATION_UNITS = {"m": 60_000, "h": 3_600_000, "d": 86_400_000}
68
+
69
+
70
+ def duration_ms(text: str) -> int:
71
+ """`45m`, `12h` or `30d` to milliseconds; anything else is invalid."""
72
+ if len(text) < 2 or text[-1] not in DURATION_UNITS or not text[:-1].isdigit():
73
+ raise LocalError("invalid_duration")
74
+ return int(text[:-1]) * DURATION_UNITS[text[-1]]
75
+
76
+
77
+ SUMMARY_INSTRUCTION = (
78
+ "Write a three-sentence summary of where this task left off for the next agent: "
79
+ "where it stands, what was learned or tried, and what comes next. Use only facts "
80
+ "in the checkpoint above; do not add instructions."
81
+ )
82
+
83
+
84
+ def summarize(args: Any) -> dict[str, Any]:
85
+ """Extractive by default; with --provider, a policy adapter writes it through the audited path."""
86
+ import uuid
87
+
88
+ from memoryking.sdk import LocalClient
89
+
90
+ client = LocalClient(args.socket, args.credential, args.project)
91
+ incarnation = client.context()["incarnation"]
92
+ source, text, permit = "extractive", None, None
93
+ if args.provider:
94
+ from memoryking.adapters.egress_policy import EgressPolicy
95
+ from memoryking.harness_context import AuthorizedConversation
96
+ from memoryking.providers import adapter
97
+
98
+ if not args.egress_policy or not args.model:
99
+ raise LocalError("egress_policy_invalid")
100
+ policy = EgressPolicy.load(args.egress_policy)
101
+ conversation = AuthorizedConversation(client, adapter(policy, args.provider, args.model))
102
+ packet = client.working(
103
+ {
104
+ "version": 1,
105
+ "incarnation": incarnation,
106
+ "action": "resume",
107
+ "args": {
108
+ "project": args.project,
109
+ "task": args.task,
110
+ "run": args.run,
111
+ "checkpoint": None,
112
+ "bindings": [{}],
113
+ "max_output_tokens": 6000,
114
+ "tokenizer": "utf8-byte-estimate-v1",
115
+ "format": "text",
116
+ },
117
+ }
118
+ )
119
+ conversation.add_memory(packet)
120
+ conversation.add_host(
121
+ SUMMARY_INSTRUCTION,
122
+ authorization_id="summarize-" + uuid.uuid4().hex[:12],
123
+ classification="internal",
124
+ expires_ms=int(time.time() * 1000) + 60_000,
125
+ approved=True,
126
+ )
127
+ reply = conversation.dispatch()
128
+ source, text, permit = "provider", reply["content"], reply["permit"]
129
+ return client.working(
130
+ {
131
+ "version": 1,
132
+ "incarnation": incarnation,
133
+ "action": "summarize",
134
+ "key": "summarize-" + uuid.uuid4().hex,
135
+ "args": {
136
+ "project": args.project,
137
+ "task": args.task,
138
+ "run": args.run,
139
+ "checkpoint": None,
140
+ "source": source,
141
+ "text": text,
142
+ "permit": permit,
143
+ "readers": None,
144
+ },
145
+ }
146
+ )
147
+
148
+
149
+ def render_audit(result: dict[str, Any]) -> str:
150
+ """A human table of egress records; hashes are shortened, nothing else is."""
151
+ lines = [f"egress policy {result['policy_revision']}"]
152
+ items = result["items"]
153
+ if not items:
154
+ lines.append("no egress records in the retention window")
155
+ return "\n".join(lines)
156
+ header = (
157
+ "when (utc)",
158
+ "status",
159
+ "provider",
160
+ "model",
161
+ "host",
162
+ "class",
163
+ "bytes",
164
+ "receipts",
165
+ "permit",
166
+ )
167
+ rows = [
168
+ (
169
+ time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(item["evaluated_ms"] / 1000)),
170
+ item["status"],
171
+ item["provider"],
172
+ item["model"],
173
+ item["host"],
174
+ item["classification"],
175
+ str(item["request_bytes"]),
176
+ str(len(item["receipts"])),
177
+ item["permit"],
178
+ )
179
+ for item in items
180
+ ]
181
+ widths = [max(len(r[i]) for r in [header, *rows]) for i in range(len(header))]
182
+ for row in [header, *rows]:
183
+ lines.append(" ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)).rstrip())
184
+ if result.get("next_before") is not None:
185
+ lines.append(f"more: --before {result['next_before']}")
186
+ return "\n".join(lines)
187
+
188
+
189
+ def render_grants(items: list[dict[str, Any]]) -> str:
190
+ if not items:
191
+ return "No grants."
192
+ rows = [("PRINCIPAL", "PROJECT", "CAPABILITIES", "VALID", "EXPIRES")]
193
+ for item in items:
194
+ expires = item["expires"]
195
+ rows.append(
196
+ (
197
+ item["principal"],
198
+ item["project"],
199
+ ",".join(item["capabilities"]),
200
+ "yes" if item["valid_now"] else "no",
201
+ "never"
202
+ if expires is None
203
+ else datetime.fromtimestamp(expires / 1000, timezone.utc).strftime(
204
+ "%Y-%m-%d %H:%MZ"
205
+ ),
206
+ )
207
+ )
208
+ widths = [max(len(r[i]) for r in rows) for i in range(5)]
209
+ return "\n".join(" ".join(c.ljust(widths[i]) for i, c in enumerate(r)).rstrip() for r in rows)
210
+
211
+
212
+ def read_credential(path: Path) -> str:
213
+ private_file(path)
214
+ return path.read_text().strip()
215
+
216
+
217
+ def doctor(
218
+ store: Path,
219
+ control: Path,
220
+ socket: Path | None,
221
+ credential: Path | None,
222
+ embedding_model: Path | None = None,
223
+ backup_dir: Path | None = None,
224
+ backup_every: str | None = None,
225
+ *,
226
+ reranker_model: Path | None = None,
227
+ ) -> list[tuple[str, str, str]]:
228
+ """Health checks an operator can run while the daemon is up. Each is (level, name, detail)."""
229
+ import sqlite3
230
+
231
+ from memoryking.adapters.local_files import Control, private_dir
232
+ from memoryking.adapters.token_count import encoding
233
+
234
+ findings: list[tuple[str, str, str]] = []
235
+
236
+ def record(level: str, name: str, detail: str) -> None:
237
+ findings.append((level, name, detail))
238
+
239
+ if sys.version_info[:2] == (3, 12):
240
+ record("ok", "python", sys.version.split()[0])
241
+ else:
242
+ record("fail", "python", f"{sys.version.split()[0]} found; MemoryKing needs 3.12")
243
+ for label, path in (("store", store), ("control", control)):
244
+ try:
245
+ private_dir(path)
246
+ record("ok", label + " directory", f"{path} is owner-private")
247
+ except (LocalError, OSError) as exc:
248
+ code = exc.code if isinstance(exc, LocalError) else type(exc).__name__
249
+ record("fail", label + " directory", f"{path}: {code}; chmod 700 and check ownership")
250
+ try:
251
+ from memoryking.adapters.local_store import paths
252
+
253
+ paths(store, control)
254
+ record("ok", "directory layout", "store and control are independent")
255
+ except LocalError as exc:
256
+ record("fail", "directory layout", f"{exc.code}; neither directory may contain the other")
257
+ sock = socket or store / "service.sock"
258
+ if len(os.fsencode(sock)) > 100:
259
+ record("fail", "socket path", f"{len(os.fsencode(sock))} bytes; must fit in 100")
260
+ elif sock.exists():
261
+ record("ok", "socket", f"{sock} present")
262
+ else:
263
+ record("warn", "socket", f"{sock} absent; is `memoryking serve` running?")
264
+ database = store / "store.sqlite"
265
+ if database.exists():
266
+ try:
267
+ with sqlite3.connect(f"file:{database}?mode=ro", uri=True) as db:
268
+ version = db.execute("PRAGMA user_version").fetchone()[0]
269
+ record(
270
+ "ok" if version == SCHEMA_VERSION else "warn",
271
+ "schema",
272
+ f"SQLite schema {version}"
273
+ + (
274
+ ""
275
+ if version == SCHEMA_VERSION
276
+ else f"; the daemon migrates to {SCHEMA_VERSION} on next start"
277
+ ),
278
+ )
279
+ except sqlite3.Error as exc:
280
+ record("fail", "schema", f"cannot read {database}: {type(exc).__name__}")
281
+ else:
282
+ record("fail", "schema", f"{database} missing; run `memoryking init`")
283
+ try:
284
+ controller = Control(control)
285
+ anchor = controller.read_anchor()
286
+ records = controller.journal(anchor)
287
+ detail = f"{len(records)} records, state {anchor['state']}"
288
+ record("ok" if anchor["state"] == "active" else "warn", "journal", detail)
289
+ except LocalError as exc:
290
+ record("fail", "journal", f"{exc.code}; stay offline and use the recovery guide")
291
+ except OSError as exc:
292
+ record("fail", "journal", f"{type(exc).__name__} reading {control}")
293
+ try:
294
+ encoding()
295
+ record("ok", "tokenizer", "exact cl100k_base available")
296
+ except LocalError:
297
+ record("warn", "tokenizer", "exact tokenizer missing; byte estimate is used and disclosed")
298
+ from importlib.util import find_spec
299
+
300
+ if find_spec("onnxruntime") is not None:
301
+ record("ok", "embeddings runtime", "onnxruntime installed")
302
+ else:
303
+ record(
304
+ "warn",
305
+ "embeddings runtime",
306
+ "not installed; `pip install --require-hashes -r requirements-embeddings.lock` enables local semantic search",
307
+ )
308
+ if embedding_model is not None:
309
+ try:
310
+ from memoryking.adapters.local_embeddings import model_files
311
+
312
+ model_files(embedding_model)
313
+ record("ok", "embedding model", f"{embedding_model} verified")
314
+ except (LocalError, OSError) as exc:
315
+ code = exc.code if isinstance(exc, LocalError) else type(exc).__name__
316
+ record(
317
+ "fail",
318
+ "embedding model",
319
+ f"{embedding_model}: {code}; run `python -m memoryking.model_install --destination DIR`",
320
+ )
321
+ else:
322
+ record(
323
+ "warn",
324
+ "embedding model",
325
+ "no model configured; `serve --embedding-model DIR` after installing one enables semantic search",
326
+ )
327
+ if reranker_model is not None:
328
+ try:
329
+ from memoryking.adapters.local_embeddings import RERANKER, model_files, model_manifest
330
+
331
+ model_files(reranker_model, model_manifest(RERANKER))
332
+ record("ok", "reranker model", f"{reranker_model} verified")
333
+ except (LocalError, OSError) as exc:
334
+ code = exc.code if isinstance(exc, LocalError) else type(exc).__name__
335
+ record(
336
+ "fail",
337
+ "reranker model",
338
+ f"{reranker_model}: {code}; run `python -m memoryking.model_install --model reranker --destination DIR`",
339
+ )
340
+ from memoryking.backups import check as backup_check
341
+
342
+ level, detail = backup_check(backup_dir, backup_every, int(time.time() * 1000))
343
+ record(level, "backups", detail)
344
+ if socket is not None and credential is not None and sock.exists():
345
+ try:
346
+ result = request(sock, read_credential(credential), "status", {"project": "main"})
347
+ warnings = [k for k, v in result.get("capacity", {}).items() if v.get("warning")]
348
+ frontier = result["projection"]["frontier"]
349
+ detail = f"position {result['position']}, frontier {frontier}"
350
+ if warnings:
351
+ record("warn", "capacity", ", ".join(warnings) + " at 80 percent or more")
352
+ else:
353
+ record("ok", "capacity", "all resources under 80 percent")
354
+ record("ok" if frontier == result["position"] else "warn", "daemon", detail)
355
+ except LocalError as exc:
356
+ record("fail", "daemon", f"status request failed: {exc.code}")
357
+ except OSError as exc:
358
+ record("fail", "daemon", f"socket unreachable: {type(exc).__name__}")
359
+ return findings
360
+
361
+
362
+ def render_influence(report: dict[str, Any]) -> str:
363
+ """A reverse-dependency report as readable text: what was built from the record."""
364
+ counts = report["counts"]
365
+
366
+ def stamp(ms: int) -> str:
367
+ return datetime.fromtimestamp(ms / 1000, timezone.utc).strftime("%Y-%m-%d %H:%M")
368
+
369
+ lines = [
370
+ f"Observation {report['observation']} from {report['source']} by {report['captured_by']}",
371
+ f"Reached {counts['principals']} principal(s): {', '.join(report['principals']) or 'none'}",
372
+ "",
373
+ ]
374
+ for title, key, render in (
375
+ (
376
+ "Claims citing it",
377
+ "claims",
378
+ lambda c: f"{c['revision']} ({c['kind']} by {c['issuer']}, family {c['family']})",
379
+ ),
380
+ (
381
+ "Checkpoints built on it",
382
+ "checkpoints",
383
+ lambda c: (
384
+ f"{c['checkpoint']} task {c['task']} rev {c['revision']} by {c['writer']} for {', '.join(c['readers'])} at {stamp(c['created_ms'])}"
385
+ ),
386
+ ),
387
+ (
388
+ "Handoffs that carried it",
389
+ "handoffs",
390
+ lambda h: (
391
+ f"{h['handoff']} {h['sender']} -> {h['recipient']} ({h['state']}) at {stamp(h['created_ms'])}"
392
+ ),
393
+ ),
394
+ (
395
+ "Summaries derived from it",
396
+ "summaries",
397
+ lambda s: f"{s['summary']} of {s['checkpoint']} by {s['principal']} ({s['method']})",
398
+ ),
399
+ (
400
+ "Deliveries that included it",
401
+ "deliveries",
402
+ lambda d: f"{d['receipt']} {d['kind']} to {d['principal']} at {stamp(d['created_ms'])}",
403
+ ),
404
+ ("Experience records", "experience", lambda x: x["record"]),
405
+ ):
406
+ items = report[key]
407
+ lines.append(
408
+ f"{title}: {len(items)}" + (" (truncated)" if key in report["truncation"] else "")
409
+ )
410
+ lines.extend(f" - {render(item)}" for item in items)
411
+ lines += ["", f"Coverage: {report['coverage'].replace('_', ' ').replace(';', ';')}"]
412
+ return "\n".join(lines) + "\n"
413
+
414
+
415
+ def render_health(report: dict[str, Any]) -> str:
416
+ """The memory-health report as readable text: signals first, then the counts."""
417
+ window = report["window"]
418
+ observations, briefings = report["observations"], report["briefings"]
419
+ feedback, claims, backlog = report["feedback"], report["claims"], report["backlog"]
420
+
421
+ def ratio(ppm: int | None) -> str:
422
+ return "n/a" if ppm is None else f"{ppm / 10000:.0f}%"
423
+
424
+ lines = [f"Memory health for {report['project']} over the last {window['days']} day(s)", ""]
425
+ for item in report["signals"]:
426
+ lines.append(f"[{item['level']}] {item['name']}: {item['text']}")
427
+ lines += [
428
+ "",
429
+ f"Observations: {observations['total']} live, {observations['recent']} captured in the window, {observations['held']} held, {observations['purged']} purged",
430
+ f" reached a retained delivery: {observations['delivered']}; never delivered: {observations['never_delivered']} ({ratio(observations['never_delivered_ppm'])})",
431
+ f"Briefings: {briefings['total']} retained; no relevant memory: {briefings['no_relevant_memory']} ({ratio(briefings['no_relevant_memory_ppm'])}); deliveries of every kind: {briefings['deliveries']}",
432
+ f"Feedback: {feedback['votes']} vote(s), {feedback['rated']} rated, {feedback['helpful']} helpful ({ratio(feedback['helpful_ppm'])})",
433
+ f"Claims: {claims['families']} families; "
434
+ + ", ".join(f"{count} {state}" for state, count in claims["by_state"].items())
435
+ + f"; {claims['quarantined']} quarantined, {claims['evidence_purged']} lost their evidence, {claims['superseded']} replaced",
436
+ f"Review backlog: {backlog['proposed']} waiting"
437
+ + (
438
+ f", oldest {backlog['oldest_age_ms'] // 86_400_000} day(s)"
439
+ if backlog["oldest_age_ms"] is not None
440
+ else ""
441
+ ),
442
+ ]
443
+ for item in backlog["items"]:
444
+ lines.append(
445
+ f" - {item['revision']} {item['logical_key']} ({item['kind']} by {item['issuer']}, {item['age_ms'] // 86_400_000} day(s))"
446
+ )
447
+ if backlog["truncated"]:
448
+ lines.append(" - ...")
449
+ lines += ["", f"Coverage: {report['coverage'].replace('_', ' ')}"]
450
+ return "\n".join(lines) + "\n"
451
+
452
+
453
+ def main() -> int:
454
+ parser = argparse.ArgumentParser(description=__doc__)
455
+ parser.add_argument("--version", action="version", version=f"memoryking {__version__}")
456
+ parser.add_argument(
457
+ "--profile",
458
+ default=os.environ.get("MEMORYKING_PROFILE"),
459
+ help="Named store from the profiles config; fills omitted --store, --control, "
460
+ "--socket and --credential (MEMORYKING_PROFILE)",
461
+ )
462
+ parser.add_argument(
463
+ "--config", type=Path, help="Profiles file; default ~/.memoryking/config.toml"
464
+ )
465
+ commands = parser.add_subparsers(dest="command", required=True)
466
+ prof = commands.add_parser("profile", help="Name a store so commands need no paths")
467
+ prof_commands = prof.add_subparsers(dest="profile_command", required=True)
468
+ adder = prof_commands.add_parser("add")
469
+ adder.add_argument("name")
470
+ adder.add_argument("--store", type=Path, required=True)
471
+ adder.add_argument("--control", type=Path, required=True)
472
+ adder.add_argument("--credential", type=Path, help="Default admin credential file")
473
+ adder.add_argument("--socket", type=Path, help="Default: STORE/service.sock")
474
+ adder.add_argument("--dashboard-port", type=int)
475
+ adder.add_argument("--embedding-model", type=Path, help="Installed local model directory")
476
+ adder.add_argument("--reranker-model", type=Path, help="Installed local reranker directory")
477
+ adder.add_argument("--backup-dir", type=Path)
478
+ adder.add_argument("--backup-every", help="Such as 12h or 1d")
479
+ adder.add_argument("--backup-keep", type=int)
480
+ prof_commands.add_parser("list")
481
+ prof_commands.add_parser("remove").add_argument("name")
482
+ for name in ("init", "serve", "backup", "restore", "gc", "control-checkpoint"):
483
+ cmd = commands.add_parser(name)
484
+ cmd.add_argument("--store", type=Path)
485
+ cmd.add_argument("--control", type=Path)
486
+ if name == "serve":
487
+ cmd.add_argument(
488
+ "--dashboard-port",
489
+ type=int,
490
+ help="Opt-in loopback port; 0 chooses a free port; a profile may set it",
491
+ )
492
+ cmd.add_argument("--backup-dir", type=Path, help="Directory for scheduled backups")
493
+ cmd.add_argument("--backup-every", help="Backup interval such as 12h or 1d")
494
+ cmd.add_argument(
495
+ "--backup-keep", type=int, help="Complete backups to retain; default 14"
496
+ )
497
+ cmd.add_argument(
498
+ "--embedding-model",
499
+ type=Path,
500
+ help="Installed local model directory; the daemon then embeds queries and "
501
+ "indexes every enabled project itself (a profile may set it)",
502
+ )
503
+ cmd.add_argument(
504
+ "--reranker-model",
505
+ type=Path,
506
+ help="Installed local cross-encoder; briefings that ask for `rerank` have "
507
+ "their top candidates reordered by it (a profile may set it)",
508
+ )
509
+ cmd.add_argument(
510
+ "--log-level",
511
+ default="warning",
512
+ choices=LEVELS,
513
+ help="Redacted operator log level on stderr; request ids link replies to lines",
514
+ )
515
+ cmd.add_argument(
516
+ "--trace",
517
+ action="store_true",
518
+ help="Log one timing line per request (operation, action, outcome, elapsed, "
519
+ "lock wait, transaction time, response size); implies --log-level info",
520
+ )
521
+ cmd.add_argument(
522
+ "--egress-policy",
523
+ type=Path,
524
+ help="Private TOML policy naming the providers, models and hosts retained "
525
+ "context may reach; without it only the local recorder is accepted",
526
+ )
527
+ cmd.add_argument(
528
+ "--summary-idle",
529
+ default="30m",
530
+ help="Derive a 'where this left off' summary for a task idle this long "
531
+ "(e.g. 30m, 2h); 0 disables",
532
+ )
533
+ if name == "init":
534
+ cmd.add_argument("--tenant", default="main")
535
+ cmd.add_argument("--principal", default="owner")
536
+ if name in {"backup", "restore"}:
537
+ cmd.add_argument("--backup", type=Path, required=True)
538
+ if name == "restore":
539
+ cmd.add_argument(
540
+ "--lost-anchor-journal-head",
541
+ help="Current independently retained journal head; only for a missing anchor",
542
+ )
543
+ status = commands.add_parser(
544
+ "status", help="Show store health, frontier, jobs and capacity through the daemon"
545
+ )
546
+ status.add_argument("--socket", type=Path)
547
+ status.add_argument("--credential", type=Path)
548
+ status.add_argument("--project", default="main")
549
+ status.add_argument("--json", action="store_true", help="Print the raw status result")
550
+ doc = commands.add_parser("doctor", help="Check the installation and report fixes")
551
+ doc.add_argument("--store", type=Path)
552
+ doc.add_argument("--control", type=Path)
553
+ doc.add_argument("--socket", type=Path, help="Also query the running daemon")
554
+ doc.add_argument("--credential", type=Path, help="Admin credential for the daemon query")
555
+ doc.add_argument("--embedding-model", type=Path, help="Model directory to verify")
556
+ doc.add_argument("--reranker-model", type=Path, help="Reranker directory to verify")
557
+ doc.add_argument("--backup-dir", type=Path, help="Scheduled backup directory to check")
558
+ doc.add_argument("--backup-every", help="Backup policy interval the directory should meet")
559
+ cred = commands.add_parser("credential", help="Issue, list and revoke agent credentials")
560
+ cred_commands = cred.add_subparsers(dest="credential_command", required=True)
561
+ for name in ("issue", "list", "revoke"):
562
+ item = cred_commands.add_parser(name)
563
+ item.add_argument("--socket", type=Path)
564
+ item.add_argument("--credential", type=Path, help="Admin credential")
565
+ if name in {"issue", "revoke"}:
566
+ item.add_argument("principal")
567
+ item.add_argument("--project", required=True)
568
+ if name == "issue":
569
+ item.add_argument(
570
+ "--capabilities", required=True, help="Comma-separated, for example capture,read"
571
+ )
572
+ item.add_argument("--expires", help="Validity such as 45m, 12h or 30d")
573
+ item.add_argument("--output", type=Path, required=True, help="New private file")
574
+ if name == "list":
575
+ item.add_argument("--json", action="store_true")
576
+ summ = commands.add_parser(
577
+ "summarize", help="Derive a 'where this left off' summary of a task, with its own receipt"
578
+ )
579
+ summ.add_argument("--socket", type=Path)
580
+ summ.add_argument("--credential", type=Path)
581
+ summ.add_argument("--project", required=True)
582
+ summ.add_argument("--task", required=True)
583
+ summ.add_argument("--run")
584
+ summ.add_argument("--egress-policy", type=Path, help="With --provider: the daemon's policy")
585
+ summ.add_argument("--provider", help="Write the summary with this policy adapter")
586
+ summ.add_argument("--model", help="A model the policy allows for that provider")
587
+ summ.add_argument("--json", action="store_true")
588
+ audit = commands.add_parser(
589
+ "egress-audit",
590
+ help="List what left this store for a model provider, and whether it arrived",
591
+ )
592
+ audit.add_argument("--socket", type=Path)
593
+ audit.add_argument("--credential", type=Path, help="Credential with inference capability")
594
+ audit.add_argument("--project", required=True)
595
+ audit.add_argument("--before", type=int, help="Page further back from this evaluated_ms")
596
+ audit.add_argument("--json", action="store_true")
597
+ dash = commands.add_parser("dashboard", help="Open the dashboard in a browser")
598
+ dash_commands = dash.add_subparsers(dest="dashboard_command", required=True)
599
+ opener = dash_commands.add_parser("open")
600
+ opener.add_argument("--socket", type=Path)
601
+ opener.add_argument("--credential", type=Path)
602
+ opener.add_argument(
603
+ "--print-only", action="store_true", help="Print the sign-in link instead of opening it"
604
+ )
605
+ emb = commands.add_parser("embeddings", help="Enable or inspect local semantic search")
606
+ emb_commands = emb.add_subparsers(dest="embeddings_command", required=True)
607
+ for name in ("enable", "status"):
608
+ item = emb_commands.add_parser(name)
609
+ item.add_argument("--socket", type=Path)
610
+ item.add_argument("--credential", type=Path, help="Admin credential")
611
+ item.add_argument("--project", required=True)
612
+ cap = commands.add_parser("capture", help="Save one observation from text or stdin")
613
+ cap.add_argument("--socket", type=Path)
614
+ cap.add_argument("--credential", type=Path)
615
+ cap.add_argument("--project", required=True)
616
+ cap.add_argument("--text", help="The observation; omit to read it from stdin")
617
+ cap.add_argument("--source", default="cli", help="Where it came from, e.g. git or pytest")
618
+ cap.add_argument("--event", help="Stable event id so a rerun replays; default: a text hash")
619
+ cap.add_argument(
620
+ "--readers", help="Comma-separated principals; default everyone in the project"
621
+ )
622
+ cap.add_argument(
623
+ "--classification", default="internal", choices=("public", "internal", "restricted")
624
+ )
625
+ cap.add_argument(
626
+ "--observed-ms",
627
+ type=int,
628
+ help="Observation time in Unix ms; default is today to the day so a rerun replays",
629
+ )
630
+ rec = commands.add_parser("recall", help="Print a cited Markdown briefing for a query")
631
+ rec.add_argument("--socket", type=Path)
632
+ rec.add_argument("--credential", type=Path)
633
+ rec.add_argument("--project", required=True)
634
+ rec.add_argument("--query", required=True)
635
+ rec.add_argument("--budget", type=int, default=6000)
636
+ rec.add_argument("--task")
637
+ rec.add_argument(
638
+ "--as-of", help="Brief as the project stood then: a date, ISO date-time, or Unix ms"
639
+ )
640
+ rec.add_argument(
641
+ "--salience",
642
+ action="store_true",
643
+ help="Let your own recent use of memories nudge the ranking (bounded, reported)",
644
+ )
645
+ rec.add_argument(
646
+ "--rerank",
647
+ action="store_true",
648
+ help="Let the daemon's local cross-encoder reorder the top candidates (needs serve --reranker-model)",
649
+ )
650
+ rec.add_argument("--json", action="store_true", help="Print the structured packet instead")
651
+ dr = commands.add_parser(
652
+ "draft-proposals", help="File claim drafts from repeated evidence into the review queue"
653
+ )
654
+ dr.add_argument("--socket", type=Path)
655
+ dr.add_argument("--credential", type=Path)
656
+ dr.add_argument("--project", required=True)
657
+ dr.add_argument("--limit", type=int, default=16)
658
+ dr.add_argument("--key", help="Retry key; default: one per project and day")
659
+ dr.add_argument("--json", action="store_true")
660
+ vault = commands.add_parser(
661
+ "vault", help="Export memory as a Markdown vault for hand editing, or import one"
662
+ )
663
+ vault_commands = vault.add_subparsers(dest="vault_command", required=True)
664
+ for name, text in (
665
+ ("export", "Write every observation and claim as <project>/<source>/<name>.md"),
666
+ ("import", "Capture changed or new files as versions; claim files become proposals"),
667
+ ):
668
+ sub = vault_commands.add_parser(name, help=text)
669
+ sub.add_argument("--socket", type=Path)
670
+ sub.add_argument("--credential", type=Path)
671
+ sub.add_argument("--project", help="Default: MEMORYKING_PROJECT")
672
+ sub.add_argument("--dir", type=Path, required=True, help="The vault directory")
673
+ sub.add_argument("--json", action="store_true")
674
+ if name == "import":
675
+ sub.add_argument(
676
+ "--dry-run", action="store_true", help="Report what would change; write nothing"
677
+ )
678
+ infl = commands.add_parser(
679
+ "influence", help="Where one observation went: every record built from it and who got it"
680
+ )
681
+ infl.add_argument("observation")
682
+ infl.add_argument("--socket", type=Path)
683
+ infl.add_argument("--credential", type=Path)
684
+ infl.add_argument("--project", required=True)
685
+ infl.add_argument("--json", action="store_true", help="Print the structured report instead")
686
+ health = commands.add_parser(
687
+ "health",
688
+ help="Is memory paying for itself: feedback, empty briefings, lost evidence, backlog",
689
+ )
690
+ health.add_argument("--socket", type=Path)
691
+ health.add_argument("--credential", type=Path)
692
+ health.add_argument("--project", required=True)
693
+ health.add_argument("--days", type=int, default=30, help="Trailing window, 1 to 365 (30)")
694
+ health.add_argument("--json", action="store_true", help="Print the structured report instead")
695
+ tr = commands.add_parser("trust", help="Source trust: hold captures from untrusted sources")
696
+ tr_commands = tr.add_subparsers(dest="trust_command", required=True)
697
+ for name, text in (
698
+ ("set", "Mark a source (exact name or glob) trusted or untrusted for a project or *"),
699
+ ("list", "Show the trust rules that apply to a project"),
700
+ ("held", "List held captures awaiting review in a project"),
701
+ ("release", "Release one held capture so reads, briefings and reviews may use it"),
702
+ ):
703
+ sub = tr_commands.add_parser(name, help=text)
704
+ sub.add_argument("--socket", type=Path)
705
+ sub.add_argument("--credential", type=Path)
706
+ sub.add_argument("--project", required=True, help="Project, or * for every project on set")
707
+ sub.add_argument("--json", action="store_true")
708
+ if name == "set":
709
+ sub.add_argument("--source", required=True)
710
+ sub.add_argument("--level", required=True, choices=("trusted", "untrusted"))
711
+ sub.add_argument("--key", help="Retry key; default: derived from the rule")
712
+ if name == "release":
713
+ sub.add_argument("observation")
714
+ sub.add_argument("--key", help="Retry key; default: derived from the observation")
715
+ hk = commands.add_parser(
716
+ "hook", help="Run as a host hook: read the host's event JSON on stdin, never fail"
717
+ )
718
+ hk.add_argument("kind", choices=("session-start", "pre-compact", "session-end"))
719
+ hk.add_argument("--host", choices=("claude", "codex", "grok"), help="Host that is calling")
720
+ hk.add_argument("--socket", type=Path)
721
+ hk.add_argument("--credential", type=Path)
722
+ hk.add_argument("--project", help="Default: MEMORYKING_PROJECT")
723
+ hk.add_argument("--task", help="Resume this task at start; checkpoint it before loss")
724
+ hk.add_argument("--query", help="Briefing query at session start; default: task or project")
725
+ hk.add_argument("--budget", type=int, default=6000)
726
+ hk.add_argument(
727
+ "--strict", action="store_true", help="Exit non-zero on error instead of only logging"
728
+ )
729
+ hks = commands.add_parser("hooks", help="Install or remove the host hooks")
730
+ hks_commands = hks.add_subparsers(dest="hooks_command", required=True)
731
+ inst = hks_commands.add_parser("install", help="Write the three hooks into a host's config")
732
+ inst.add_argument("--host", required=True, choices=("claude", "codex", "grok"))
733
+ inst.add_argument("--scope", default="project", choices=("project", "user"))
734
+ inst.add_argument("--project", required=True)
735
+ inst.add_argument("--socket", type=Path)
736
+ inst.add_argument("--credential", type=Path)
737
+ inst.add_argument("--task", help="Task the hooks resume and checkpoint")
738
+ inst.add_argument("--query", help="Fixed briefing query for session start")
739
+ inst.add_argument("--cwd", type=Path, help="Project directory; default: current")
740
+ inst.add_argument("--print", action="store_true", help="Show the merged config, write nothing")
741
+ inst.add_argument("--remove", action="store_true", help="Remove MemoryKing's hooks")
742
+ rpc = commands.add_parser(
743
+ "request", help="Read a versioned operation/args JSON object from stdin"
744
+ )
745
+ rpc.add_argument("--socket", type=Path)
746
+ rpc.add_argument("--credential", type=Path)
747
+ rpc.add_argument(
748
+ "--credential-output", type=Path, help="Required for grant; saves the new secret privately"
749
+ )
750
+ login = commands.add_parser(
751
+ "dashboard-login", help="Save a one-use browser bootstrap code privately"
752
+ )
753
+ login.add_argument("--socket", type=Path)
754
+ login.add_argument("--credential", type=Path)
755
+ login.add_argument("--output", type=Path, required=True)
756
+ args = parser.parse_args()
757
+ try:
758
+ if args.command == "profile":
759
+ if args.profile_command == "add":
760
+ values: dict[str, Any] = {
761
+ "store": str(args.store.resolve()),
762
+ "control": str(args.control.resolve()),
763
+ }
764
+ for field in (
765
+ "credential",
766
+ "socket",
767
+ "embedding_model",
768
+ "reranker_model",
769
+ "backup_dir",
770
+ ):
771
+ if getattr(args, field) is not None:
772
+ values[field] = str(getattr(args, field).resolve())
773
+ for field in ("dashboard_port", "backup_every", "backup_keep"):
774
+ if getattr(args, field) is not None:
775
+ values[field] = getattr(args, field)
776
+ path = profiles.save(args.name, values, args.config)
777
+ print(json.dumps({"profile": args.name, "config": str(path)}))
778
+ elif args.profile_command == "remove":
779
+ path = profiles.remove(args.name, args.config)
780
+ print(json.dumps({"removed": args.name, "config": str(path)}))
781
+ else:
782
+ for name, values in sorted(profiles.load(args.config).items()):
783
+ print(name)
784
+ for field, value in values.items():
785
+ print(f" {field} = {value}")
786
+ return 0
787
+ profiles.apply(args, args.profile, args.config)
788
+ optional = (
789
+ {"socket", "credential"}
790
+ if args.command
791
+ in {
792
+ "doctor",
793
+ "capture",
794
+ "recall",
795
+ "hook",
796
+ "hooks",
797
+ "influence",
798
+ "trust",
799
+ "draft-proposals",
800
+ }
801
+ else set()
802
+ )
803
+ for field in ("store", "control", "socket", "credential"):
804
+ if hasattr(args, field) and getattr(args, field) is None and field not in optional:
805
+ raise LocalError(field + "_required")
806
+ if args.command == "init":
807
+ path = LocalStore.initialize(args.store, args.control, args.tenant, args.principal)
808
+ print(json.dumps({"credential_file": str(path)}))
809
+ elif args.command == "restore":
810
+ path = LocalStore.restore(
811
+ args.store,
812
+ args.control,
813
+ args.backup,
814
+ lost_anchor_journal_head=args.lost_anchor_journal_head,
815
+ )
816
+ print(json.dumps({"credential_file": str(path), "reconciliation_required": True}))
817
+ elif args.command == "dashboard-login":
818
+ private_file(args.credential)
819
+ private_dir(args.output.parent)
820
+ if args.output.exists() or args.output.is_symlink():
821
+ raise LocalError("credential_output_exists")
822
+ result = request(
823
+ args.socket, args.credential.read_text().strip(), "dashboard_bootstrap", {}
824
+ )
825
+ atomic(args.output, json.dumps(result).encode())
826
+ print(json.dumps({"bootstrap_file": str(args.output), "url": result["url"]}))
827
+ elif args.command == "embeddings":
828
+ from memoryking.adapters.local_embeddings import model_manifest
829
+ from memoryking.domain.embeddings import fingerprint
830
+
831
+ token = read_credential(args.credential)
832
+ context = request(args.socket, token, "context", {"project": args.project})
833
+ fp = fingerprint(model_manifest())
834
+
835
+ def embedding(action: str, extra: dict[str, Any], key: str | None = None) -> Any:
836
+ command: dict[str, Any] = {
837
+ "version": 1,
838
+ "incarnation": context["incarnation"],
839
+ "action": action,
840
+ "args": {"project": args.project, **extra},
841
+ }
842
+ if key:
843
+ command["key"] = key
844
+ return request(args.socket, token, "embedding", {"command": command})
845
+
846
+ if args.embeddings_command == "status":
847
+ print(json.dumps(embedding("status", {"fingerprint": fp})))
848
+ else:
849
+ try:
850
+ current = embedding("status", {"fingerprint": fp})
851
+ except LocalError as exc:
852
+ if exc.code != "embedding_partition_unavailable":
853
+ raise
854
+ current = {}
855
+ generation = int(current.get("generation") or 0)
856
+ if current.get("state") == "experimental":
857
+ print(json.dumps({**current, "already_enabled": True}))
858
+ else:
859
+ result = embedding(
860
+ "configure",
861
+ {
862
+ "model": "minilm-l6-v2-onnx",
863
+ "state": "experimental",
864
+ "expected_generation": generation,
865
+ },
866
+ key="enable-" + str(generation),
867
+ )
868
+ print(json.dumps(result))
869
+ elif args.command == "capture":
870
+ from memoryking import hooks
871
+
872
+ text = args.text if args.text is not None else sys.stdin.read()
873
+ result = hooks.capture(
874
+ text,
875
+ source=args.source,
876
+ event=args.event,
877
+ readers=args.readers.split(",") if args.readers else None,
878
+ classification=args.classification,
879
+ observed_ms=args.observed_ms,
880
+ socket=args.socket,
881
+ credential=args.credential,
882
+ project=args.project,
883
+ )
884
+ print(json.dumps({k: result[k] for k in ("observation", "position") if k in result}))
885
+ elif args.command == "recall":
886
+ from memoryking import hooks
887
+
888
+ packet = hooks.recall(
889
+ args.query,
890
+ budget=args.budget,
891
+ text=not args.json,
892
+ task=args.task,
893
+ as_of=hooks.as_of_ms(args.as_of) if args.as_of else None,
894
+ salience=args.salience,
895
+ rerank=args.rerank,
896
+ socket=args.socket,
897
+ credential=args.credential,
898
+ project=args.project,
899
+ )
900
+ if args.json:
901
+ sys.stdout.buffer.write(canonical_bytes(packet) + b"\n")
902
+ else:
903
+ print(packet["text"], end="")
904
+ elif args.command == "hook":
905
+ from memoryking import host_hooks
906
+
907
+ try:
908
+ raw = "" if sys.stdin.isatty() else sys.stdin.read()
909
+ payload = host_hooks.read_event(raw)
910
+ where = {
911
+ "socket": args.socket,
912
+ "credential": args.credential,
913
+ "project": args.project,
914
+ "profile": args.profile,
915
+ "config": args.config,
916
+ }
917
+ if args.kind == "session-start":
918
+ sys.stdout.write(
919
+ host_hooks.session_start(
920
+ payload, query=args.query, task=args.task, budget=args.budget, **where
921
+ )
922
+ )
923
+ else:
924
+ summary = host_hooks.save(
925
+ payload, args.kind, host=args.host, task=args.task, **where
926
+ )
927
+ print(json.dumps(summary), file=sys.stderr)
928
+ except (LocalError, OSError, ValueError, KeyError) as exc:
929
+ code = exc.code if isinstance(exc, LocalError) else type(exc).__name__
930
+ print(f"memoryking hook {args.kind}: {code}", file=sys.stderr)
931
+ if args.strict:
932
+ return 1
933
+ return 0
934
+ elif args.command == "hooks":
935
+ from memoryking import host_hooks
936
+
937
+ result = host_hooks.install(
938
+ host=args.host,
939
+ scope=args.scope,
940
+ project=args.project,
941
+ cwd=(args.cwd or Path.cwd()).resolve(),
942
+ home=Path.home(),
943
+ profile=args.profile,
944
+ socket=args.socket if args.profile is None else None,
945
+ credential=args.credential if args.profile is None else None,
946
+ task=args.task,
947
+ query=args.query,
948
+ remove=args.remove,
949
+ write=not args.print,
950
+ )
951
+ if args.print:
952
+ print(json.dumps(result["config"], indent=2))
953
+ else:
954
+ print(
955
+ json.dumps(
956
+ {k: result[k] for k in ("host", "path", "events", "removed", "note")}
957
+ )
958
+ )
959
+ elif args.command == "doctor":
960
+ findings = doctor(
961
+ args.store,
962
+ args.control,
963
+ args.socket,
964
+ args.credential,
965
+ args.embedding_model,
966
+ args.backup_dir,
967
+ args.backup_every,
968
+ reranker_model=args.reranker_model,
969
+ )
970
+ width = max(len(name) for _, name, _ in findings)
971
+ for level, name, detail in findings:
972
+ print(f"{level.upper():<5} {name.ljust(width)} {detail}")
973
+ failed = sum(level == "fail" for level, _, _ in findings)
974
+ print(f"{len(findings)} checks, {failed} failed")
975
+ return 1 if failed else 0
976
+ elif args.command == "credential":
977
+ credential = read_credential(args.credential)
978
+ if args.credential_command == "list":
979
+ items = request(args.socket, credential, "grants", {})["items"]
980
+ if args.json:
981
+ sys.stdout.buffer.write(canonical_bytes({"items": items}) + b"\n")
982
+ else:
983
+ print(render_grants(items))
984
+ elif args.credential_command == "revoke":
985
+ request(
986
+ args.socket,
987
+ credential,
988
+ "revoke",
989
+ {"principal": args.principal, "project": args.project},
990
+ )
991
+ print(json.dumps({"revoked": args.principal, "project": args.project}))
992
+ else:
993
+ private_dir(args.output.parent)
994
+ if args.output.exists() or args.output.is_symlink():
995
+ raise LocalError("credential_output_exists")
996
+ grant: dict[str, Any] = {
997
+ "principal": args.principal,
998
+ "project": args.project,
999
+ "capabilities": sorted(set(args.capabilities.split(","))),
1000
+ }
1001
+ if args.expires:
1002
+ grant["expires"] = int(time.time() * 1000) + duration_ms(args.expires)
1003
+ result = request(args.socket, credential, "grant", grant)
1004
+ atomic(args.output, result.pop("credential").encode())
1005
+ result.update(credential_file=str(args.output), **grant)
1006
+ print(json.dumps(result))
1007
+ elif args.command == "summarize":
1008
+ result = summarize(args)
1009
+ if args.json:
1010
+ sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
1011
+ else:
1012
+ print(result["summary"])
1013
+ print(
1014
+ f"receipt {result['receipt']} · {result['method']} · "
1015
+ f"checkpoint {result['checkpoint']} revision {result['revision']}"
1016
+ )
1017
+ elif args.command == "draft-proposals":
1018
+ token = read_credential(args.credential)
1019
+ context = request(args.socket, token, "context", {"project": args.project})
1020
+ day = int(time.time() * 1000) // 86_400_000
1021
+ report = request(
1022
+ args.socket,
1023
+ token,
1024
+ "knowledge",
1025
+ {
1026
+ "command": {
1027
+ "version": 1,
1028
+ "incarnation": context["incarnation"],
1029
+ "action": "draft",
1030
+ "key": args.key or f"draft-{args.project}-{day}",
1031
+ "args": {"project": args.project, "limit": args.limit},
1032
+ }
1033
+ },
1034
+ )
1035
+ if args.json:
1036
+ sys.stdout.buffer.write(canonical_bytes(report) + b"\n")
1037
+ else:
1038
+ for item in report["drafted"]:
1039
+ print(
1040
+ f"{item['revision']} [{item['basis']} {item['topic']}, {item['support']} sources] {item['text']}"
1041
+ )
1042
+ print(
1043
+ f"{len(report['drafted'])} draft(s) filed for review from {report['window']} observations; "
1044
+ f"skipped {json.dumps(report['skipped'], sort_keys=True)}"
1045
+ )
1046
+ elif args.command == "vault":
1047
+ from memoryking import vault as vault_module
1048
+
1049
+ client = vault_module.connect(
1050
+ socket=args.socket, credential=args.credential, project=args.project
1051
+ )
1052
+ if args.vault_command == "export":
1053
+ report = vault_module.export(args.dir, client)
1054
+ else:
1055
+ report = vault_module.import_(args.dir, client, dry_run=args.dry_run)
1056
+ if args.json:
1057
+ sys.stdout.buffer.write(canonical_bytes(report) + b"\n")
1058
+ elif args.vault_command == "export":
1059
+ print(
1060
+ f"Exported {report['observations']} file(s) from {report['versions']} "
1061
+ f"observation(s) and {report['claims']} claim(s) to {report['directory']}"
1062
+ )
1063
+ else:
1064
+ verb = "Would capture" if report["dry_run"] else "Captured"
1065
+ for item in report["captured"]:
1066
+ print(f"{verb} {item['file']} as version {item['version']}")
1067
+ for item in report["proposed"]:
1068
+ print(
1069
+ f"{verb.replace('capture', 'propose')} {item['file']} (claim {item['key']})"
1070
+ )
1071
+ for item in report["errors"]:
1072
+ print(f"Skipped {item['file']}: {item['error']}", file=sys.stderr)
1073
+ print(
1074
+ f"{len(report['captured'])} captured, {len(report['proposed'])} proposed, "
1075
+ f"{report['unchanged']} unchanged, {len(report['errors'])} skipped"
1076
+ )
1077
+ if report["errors"]:
1078
+ return 1
1079
+ elif args.command == "trust":
1080
+ token = read_credential(args.credential)
1081
+ context = request(args.socket, token, "context", {"project": args.project})
1082
+ command: dict[str, Any] = {
1083
+ "version": 1,
1084
+ "incarnation": context["incarnation"],
1085
+ "action": {
1086
+ "set": "trust",
1087
+ "list": "trust_list",
1088
+ "held": "held",
1089
+ "release": "release",
1090
+ }[args.trust_command],
1091
+ "args": {"project": args.project},
1092
+ }
1093
+ if args.trust_command == "set":
1094
+ command["args"].update(source=args.source, level=args.level)
1095
+ command["key"] = args.key or f"trust-{args.project}-{args.source}-{args.level}"
1096
+ elif args.trust_command == "release":
1097
+ command["args"]["observation"] = args.observation
1098
+ command["key"] = args.key or f"release-{args.observation}"
1099
+ report = request(args.socket, token, "inspection", {"command": command})
1100
+ if args.json:
1101
+ sys.stdout.buffer.write(canonical_bytes(report) + b"\n")
1102
+ elif args.trust_command == "list":
1103
+ for rule in report["rules"]:
1104
+ print(
1105
+ f"{rule['project']:<16} {rule['source']:<32} {rule['level']} (by {rule['decided_by']})"
1106
+ )
1107
+ if not report["rules"]:
1108
+ print("No trust rules; every source is trusted.")
1109
+ elif args.trust_command == "held":
1110
+ for item in report["held"]:
1111
+ print(
1112
+ f"{item['observation']} from {item['source']} by {item['captured_by']}: {item['preview']!r}"
1113
+ )
1114
+ if not report["held"]:
1115
+ print("No held captures.")
1116
+ else:
1117
+ print(json.dumps(report))
1118
+ elif args.command == "health":
1119
+ token = read_credential(args.credential)
1120
+ context = request(args.socket, token, "context", {"project": args.project})
1121
+ report = request(
1122
+ args.socket,
1123
+ token,
1124
+ "inspection",
1125
+ {
1126
+ "command": {
1127
+ "version": 1,
1128
+ "incarnation": context["incarnation"],
1129
+ "action": "health",
1130
+ "args": {"project": args.project, "days": args.days},
1131
+ }
1132
+ },
1133
+ )
1134
+ if args.json:
1135
+ sys.stdout.buffer.write(canonical_bytes(report) + b"\n")
1136
+ else:
1137
+ print(render_health(report), end="")
1138
+ elif args.command == "influence":
1139
+ token = read_credential(args.credential)
1140
+ context = request(args.socket, token, "context", {"project": args.project})
1141
+ report = request(
1142
+ args.socket,
1143
+ token,
1144
+ "inspection",
1145
+ {
1146
+ "command": {
1147
+ "version": 1,
1148
+ "incarnation": context["incarnation"],
1149
+ "action": "influence",
1150
+ "args": {"project": args.project, "observation": args.observation},
1151
+ }
1152
+ },
1153
+ )
1154
+ if args.json:
1155
+ sys.stdout.buffer.write(canonical_bytes(report) + b"\n")
1156
+ else:
1157
+ print(render_influence(report), end="")
1158
+ elif args.command == "egress-audit":
1159
+ result = request(
1160
+ args.socket,
1161
+ read_credential(args.credential),
1162
+ "inference",
1163
+ {
1164
+ "command": {
1165
+ "version": 1,
1166
+ "action": "audit",
1167
+ "args": {"project": args.project, "before": args.before},
1168
+ }
1169
+ },
1170
+ )
1171
+ if args.json:
1172
+ sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
1173
+ else:
1174
+ print(render_audit(result))
1175
+ elif args.command == "dashboard":
1176
+ result = request(
1177
+ args.socket, read_credential(args.credential), "dashboard_bootstrap", {}
1178
+ )
1179
+ link = result["url"] + "/#code=" + result["code"]
1180
+ if args.print_only:
1181
+ print(link)
1182
+ else:
1183
+ import webbrowser
1184
+
1185
+ opened = webbrowser.open(link)
1186
+ print(
1187
+ json.dumps(
1188
+ {
1189
+ "url": result["url"],
1190
+ "opened": opened,
1191
+ "expires_ms": result["expires_ms"],
1192
+ "note": "The one-use code is in the link fragment and expires in 60 seconds.",
1193
+ }
1194
+ )
1195
+ )
1196
+ elif args.command == "status":
1197
+ private_file(args.credential)
1198
+ result = request(
1199
+ args.socket,
1200
+ args.credential.read_text().strip(),
1201
+ "status",
1202
+ {"project": args.project},
1203
+ )
1204
+ if args.json:
1205
+ sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
1206
+ else:
1207
+ print(render_status(result, __version__))
1208
+ elif args.command == "request":
1209
+ private_file(args.credential)
1210
+ body = load_strict(sys.stdin.buffer.read(262145))
1211
+ if not isinstance(body, dict) or set(body) != {"operation", "args"}:
1212
+ raise LocalError("invalid_request")
1213
+ if body["operation"] == "grant" and args.credential_output is None:
1214
+ raise LocalError("credential_output_required")
1215
+ if body["operation"] == "grant":
1216
+ private_dir(args.credential_output.parent)
1217
+ if args.credential_output.exists() or args.credential_output.is_symlink():
1218
+ raise LocalError("credential_output_exists")
1219
+ result = request(
1220
+ args.socket, args.credential.read_text().strip(), body["operation"], body["args"]
1221
+ )
1222
+ if "credential" in result:
1223
+ atomic(args.credential_output, result.pop("credential").encode())
1224
+ result["credential_file"] = str(args.credential_output)
1225
+ sys.stdout.buffer.write(canonical_bytes(result) + b"\n")
1226
+ else:
1227
+ with LocalStore(args.store, args.control) as store:
1228
+ if args.command == "serve":
1229
+ configure(args.log_level, trace=args.trace)
1230
+ if args.egress_policy is not None:
1231
+ from memoryking.adapters.egress_policy import EgressPolicy
1232
+
1233
+ store.egress_policy = EgressPolicy.load(args.egress_policy)
1234
+ store.summary_idle_ms = (
1235
+ 0 if args.summary_idle in {"0", "off"} else duration_ms(args.summary_idle)
1236
+ )
1237
+
1238
+ def stop(signum: int, frame: object) -> None:
1239
+ raise KeyboardInterrupt
1240
+
1241
+ signal.signal(signal.SIGTERM, stop)
1242
+ dashboard = None
1243
+ embeddings = None
1244
+ if args.backup_dir is not None:
1245
+ from memoryking.backups import Policy
1246
+
1247
+ store.backup_policy = Policy(
1248
+ args.backup_dir, args.backup_every or "1d", args.backup_keep or 14
1249
+ )
1250
+ if args.embedding_model is not None:
1251
+ from memoryking.adapters.local_embeddings import LocalOnnxEmbedding
1252
+ from memoryking.embedding_loop import EmbeddingLoop
1253
+
1254
+ store.embedder = LocalOnnxEmbedding(args.embedding_model)
1255
+ if args.reranker_model is not None:
1256
+ from memoryking.adapters.local_embeddings import LocalOnnxReranker
1257
+
1258
+ store.reranker = LocalOnnxReranker(args.reranker_model)
1259
+ if args.dashboard_port is not None:
1260
+ if not 0 <= args.dashboard_port <= 65535:
1261
+ raise LocalError("invalid_dashboard_configuration")
1262
+ dashboard = Dashboard(store, args.dashboard_port)
1263
+ store.dashboard = dashboard
1264
+ dashboard.start()
1265
+ try:
1266
+ with Server(store) as server:
1267
+ print(
1268
+ json.dumps({"ready": True, "socket": str(server.path)}), flush=True
1269
+ )
1270
+ event("serve", "ready", dashboard=dashboard is not None)
1271
+ if store.embedder is not None:
1272
+ embeddings = EmbeddingLoop(
1273
+ store,
1274
+ server.path,
1275
+ args.control / "owner.credential",
1276
+ store.embedder,
1277
+ )
1278
+ embeddings.start()
1279
+ server.serve_forever(poll_interval=0.2)
1280
+ except KeyboardInterrupt:
1281
+ pass
1282
+ finally:
1283
+ if embeddings is not None:
1284
+ embeddings.stop()
1285
+ if dashboard:
1286
+ dashboard.stop()
1287
+ elif args.command == "backup":
1288
+ print(json.dumps(store.backup(args.backup)))
1289
+ elif args.command == "gc":
1290
+ print(
1291
+ json.dumps(
1292
+ {
1293
+ "expired_results": store.expire_results(),
1294
+ "orphan_blobs_removed": store.gc(),
1295
+ }
1296
+ )
1297
+ )
1298
+ elif args.command == "control-checkpoint":
1299
+ print(
1300
+ json.dumps(
1301
+ {
1302
+ "store": store.store_id,
1303
+ "incarnation": store.incarnation,
1304
+ "journal_sequence": store.anchor["journal_sequence"],
1305
+ "journal_head": store.anchor["journal_head"],
1306
+ "independent_retention_required": True,
1307
+ }
1308
+ )
1309
+ )
1310
+ return 0
1311
+ except (LocalError, ContractError) as exc:
1312
+ print(
1313
+ json.dumps(
1314
+ {"error": code, "hint": hint(code)}
1315
+ if (code := exc.code if isinstance(exc, LocalError) else "invalid_request")
1316
+ else {}
1317
+ ),
1318
+ file=sys.stderr,
1319
+ )
1320
+ return 2
1321
+ except (OSError, ValueError):
1322
+ code = "local_io_or_configuration_error"
1323
+ print(json.dumps({"error": code, "hint": hint(code)}), file=sys.stderr)
1324
+ return 2
1325
+
1326
+
1327
+ if __name__ == "__main__":
1328
+ raise SystemExit(main())