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,454 @@
1
+ """Host hooks: memory that loads itself at session start and saves itself before loss.
2
+
3
+ Claude Code, Codex and Grok all run command hooks at the same three moments: when a
4
+ session starts or resumes (including right after compaction), before the transcript is
5
+ compacted, and when the session ends. Each hook receives one JSON object on stdin and
6
+ MemoryKing turns it into an ordinary authorized call:
7
+
8
+ - `session-start` prints a cited Markdown briefing (and the task's resume packet when
9
+ a task is named). Claude Code and Codex add a session-start hook's stdout to the
10
+ model's context; Grok ignores hook stdout, so there the briefing goes nowhere unless
11
+ the host's own instructions read it from a file.
12
+ - `pre-compact` captures the tail of the transcript as an observation before the host
13
+ compresses it, and saves a minimal checkpoint when a task is named.
14
+ - `session-end` captures the transcript tail (or the host's last assistant message)
15
+ so the final state survives the session.
16
+
17
+ A hook never fails the host: every error is reported on stderr and the exit code stays
18
+ zero. Captures use deterministic event ids, so a hook that fires twice replays.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import sys
26
+ import time
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from memoryking import hooks
31
+ from memoryking.adapters.local_ipc import request
32
+ from memoryking.domain.checkpoint import complete
33
+ from memoryking.domain.local import LocalError
34
+
35
+ HOSTS = ("claude", "codex", "grok")
36
+ KINDS = ("session-start", "pre-compact", "session-end")
37
+ TAIL_BYTES = 262_144
38
+ TAIL_CHARS = 16_384
39
+ STATE_CHARS = 2_000
40
+ EVENT_KINDS = {
41
+ "SessionStart": "session-start",
42
+ "PreCompact": "pre-compact",
43
+ "SessionEnd": "session-end",
44
+ "Stop": "session-end",
45
+ }
46
+
47
+
48
+ def read_event(raw: str | bytes, environ: dict[str, str] | None = None) -> dict[str, Any]:
49
+ """Normalize a host's hook payload: snake_case (Claude Code, Codex) or camelCase (Grok).
50
+
51
+ Missing stdin is an empty event; the environment supplies what Grok exports."""
52
+ env = os.environ if environ is None else environ
53
+ text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else raw
54
+ data: dict[str, Any] = {}
55
+ if text.strip():
56
+ try:
57
+ loaded = json.loads(text)
58
+ except ValueError as exc:
59
+ raise LocalError("hook_event_invalid") from exc
60
+ if not isinstance(loaded, dict):
61
+ raise LocalError("hook_event_invalid")
62
+ data = loaded
63
+
64
+ def pick(*names: str) -> Any:
65
+ for name in names:
66
+ value = data.get(name)
67
+ if value is not None:
68
+ return value
69
+ return None
70
+
71
+ host = (
72
+ "grok"
73
+ if "hookEventName" in data or "GROK_HOOK_EVENT" in env
74
+ else "claude"
75
+ if "scratchpad_dir" in data or "prompt_id" in data or "CLAUDE_PROJECT_DIR" in env
76
+ else "codex"
77
+ if "turn_id" in data or "model" in data
78
+ else None
79
+ )
80
+ name = pick("hook_event_name", "hookEventName") or env.get("GROK_HOOK_EVENT")
81
+ return {
82
+ "host": host,
83
+ "event": name,
84
+ "kind": EVENT_KINDS.get(str(name), None),
85
+ "session": str(pick("session_id", "sessionId") or env.get("GROK_SESSION_ID") or ""),
86
+ "cwd": str(
87
+ pick("cwd")
88
+ or env.get("GROK_WORKSPACE_ROOT")
89
+ or env.get("CLAUDE_PROJECT_DIR")
90
+ or os.getcwd()
91
+ ),
92
+ "transcript": pick("transcript_path", "transcriptPath"),
93
+ "source": pick("source"),
94
+ "trigger": pick("trigger"),
95
+ "instructions": pick("custom_instructions"),
96
+ "last_message": pick("last_assistant_message"),
97
+ }
98
+
99
+
100
+ def _texts(value: Any, out: list[str], assistant: bool) -> None:
101
+ """Collect assistant text from any transcript line shape, bounded by the caller."""
102
+ if isinstance(value, dict):
103
+ role = value.get("role") or value.get("type")
104
+ mine = assistant or role == "assistant"
105
+ for key, item in value.items():
106
+ if key in ("text", "content") and isinstance(item, str) and mine:
107
+ if item.strip():
108
+ out.append(item)
109
+ else:
110
+ _texts(item, out, mine)
111
+ elif isinstance(value, list):
112
+ for item in value:
113
+ _texts(item, out, assistant)
114
+
115
+
116
+ def transcript_tail(path: str | Path | None, limit: int = TAIL_CHARS) -> str:
117
+ """The last assistant text in a JSONL transcript, or the raw tail of any text file.
118
+
119
+ Reads at most the last 256 KiB and returns at most `limit` characters; a missing
120
+ or unreadable transcript is an empty string, never an error."""
121
+ if not path:
122
+ return ""
123
+ try:
124
+ file = Path(path)
125
+ size = file.stat().st_size
126
+ with file.open("rb") as handle:
127
+ if size > TAIL_BYTES:
128
+ handle.seek(size - TAIL_BYTES)
129
+ handle.readline() # drop the torn first line
130
+ raw = handle.read(TAIL_BYTES).decode("utf-8", "replace")
131
+ except OSError:
132
+ return ""
133
+ pieces: list[str] = []
134
+ parsed = False
135
+ for line in raw.splitlines():
136
+ line = line.strip()
137
+ if not line.startswith("{"):
138
+ continue
139
+ try:
140
+ value = json.loads(line)
141
+ except ValueError:
142
+ continue
143
+ parsed = True
144
+ _texts(value, pieces, False)
145
+ text = "\n\n".join(pieces) if parsed else raw
146
+ return text[-limit:].strip()
147
+
148
+
149
+ def session_start(
150
+ event: dict[str, Any],
151
+ *,
152
+ query: str | None = None,
153
+ task: str | None = None,
154
+ budget: int = 6000,
155
+ **where: Any,
156
+ ) -> str:
157
+ """Cited Markdown for the model: the task's resume packet first, then a briefing."""
158
+ socket, token, project = hooks.connection(**where)
159
+ parts: list[str] = []
160
+ if task:
161
+ context = request(socket, token, "context", {"project": project})
162
+ try:
163
+ packet = request(
164
+ socket,
165
+ token,
166
+ "working",
167
+ {
168
+ "command": {
169
+ "version": 1,
170
+ "incarnation": context["incarnation"],
171
+ "action": "resume",
172
+ "args": {
173
+ "project": project,
174
+ "task": task,
175
+ "run": None,
176
+ "checkpoint": None,
177
+ "bindings": [{}],
178
+ "max_output_tokens": budget,
179
+ "tokenizer": "utf8-byte-estimate-v1",
180
+ "format": "text",
181
+ },
182
+ }
183
+ },
184
+ )
185
+ parts.append(str(packet.get("text", "")).rstrip())
186
+ except LocalError as exc:
187
+ if exc.code != "checkpoint_unavailable":
188
+ raise
189
+ packet = hooks.recall(
190
+ query or task or project,
191
+ budget=budget,
192
+ text=True,
193
+ task=task,
194
+ socket=socket,
195
+ credential=Path(where["credential"]) if where.get("credential") else None,
196
+ project=project,
197
+ profile=where.get("profile"),
198
+ config=where.get("config"),
199
+ )
200
+ parts.append(str(packet.get("text", "")).rstrip())
201
+ return "\n\n".join(p for p in parts if p) + "\n"
202
+
203
+
204
+ def _save_state(
205
+ socket: Path,
206
+ token: str,
207
+ project: str,
208
+ task: str,
209
+ session: str,
210
+ text: str,
211
+ observation: str | None,
212
+ ) -> dict[str, Any]:
213
+ context = request(socket, token, "context", {"project": project})
214
+ # Day-granular like hook captures: a hook that fires twice sends identical bytes
215
+ # under its stable retry key and replays instead of conflicting.
216
+ observed = int(time.time() * 1000) // hooks.DAY_MS * hooks.DAY_MS
217
+ body = complete(
218
+ {
219
+ "objective": f"Session {session[:12] or 'unknown'} on {project}",
220
+ "current_state": text[:STATE_CHARS],
221
+ "references": [{"kind": "observation", "id": observation}] if observation else [],
222
+ },
223
+ observed,
224
+ )
225
+ return request(
226
+ socket,
227
+ token,
228
+ "working",
229
+ {
230
+ "command": {
231
+ "version": 1,
232
+ "incarnation": context["incarnation"],
233
+ "action": "save",
234
+ "key": hooks.event_id("hook-checkpoint", text, f"{project}\n{task}\n{session}"),
235
+ "args": {
236
+ "project": project,
237
+ "task": task,
238
+ "run": None,
239
+ "readers": None,
240
+ "expected_revision": None,
241
+ "checkpoint": body,
242
+ },
243
+ }
244
+ },
245
+ )
246
+
247
+
248
+ def save(
249
+ event: dict[str, Any],
250
+ kind: str,
251
+ *,
252
+ host: str | None = None,
253
+ task: str | None = None,
254
+ **where: Any,
255
+ ) -> dict[str, Any]:
256
+ """Capture what the host is about to lose; with a task, also save a checkpoint.
257
+
258
+ `pre-compact` captures the transcript tail (plus the user's compaction instructions
259
+ when the host passes them); `session-end` captures the host's last assistant message
260
+ when given, else the transcript tail. The event id covers host, session and text, so
261
+ the same moment replays and a later compaction is a new observation."""
262
+ socket, token, project = hooks.connection(**where)
263
+ name = host or event.get("host") or "host"
264
+ text = ""
265
+ if kind == "session-end" and event.get("last_message"):
266
+ text = str(event["last_message"])
267
+ else:
268
+ text = transcript_tail(event.get("transcript"))
269
+ if kind == "pre-compact" and event.get("instructions"):
270
+ text = f"Compaction instructions: {event['instructions']}\n\n{text}".strip()
271
+ if not text.strip():
272
+ return {"captured": False, "reason": "nothing_to_capture"}
273
+ source = f"{name}-{'compact' if kind == 'pre-compact' else 'session'}"
274
+ salt = f"{event.get('session', '')}\n{event.get('trigger') or event.get('source') or ''}"
275
+ result = hooks.capture(
276
+ text,
277
+ source=source,
278
+ event=hooks.event_id(source, text, salt),
279
+ socket=socket,
280
+ credential=Path(where["credential"]) if where.get("credential") else None,
281
+ project=project,
282
+ profile=where.get("profile"),
283
+ config=where.get("config"),
284
+ )
285
+ summary: dict[str, Any] = {
286
+ "captured": True,
287
+ "observation": result.get("observation"),
288
+ "source": source,
289
+ }
290
+ if task:
291
+ saved = _save_state(
292
+ socket,
293
+ token,
294
+ project,
295
+ task,
296
+ str(event.get("session", "")),
297
+ text,
298
+ result.get("observation"),
299
+ )
300
+ summary["checkpoint"] = saved.get("checkpoint")
301
+ summary["revision"] = saved.get("revision")
302
+ return summary
303
+
304
+
305
+ # --- Installation -------------------------------------------------------------------
306
+
307
+ MARK = "memoryking"
308
+
309
+
310
+ def hook_command(
311
+ kind: str,
312
+ *,
313
+ host: str,
314
+ project: str,
315
+ profile: str | None,
316
+ socket: Path | None,
317
+ credential: Path | None,
318
+ task: str | None,
319
+ query: str | None,
320
+ ) -> str:
321
+ """The shell command a host runs; absolute paths so it works without the shell env."""
322
+ parts = [json.dumps(sys.executable), "-m", "memoryking"]
323
+ if profile:
324
+ parts += ["--profile", profile]
325
+ parts += ["hook", kind, "--host", host, "--project", project]
326
+ if socket is not None:
327
+ parts += ["--socket", json.dumps(str(socket))]
328
+ if credential is not None:
329
+ parts += ["--credential", json.dumps(str(credential))]
330
+ if task:
331
+ parts += ["--task", task]
332
+ if query and kind == "session-start":
333
+ parts += ["--query", json.dumps(query)]
334
+ return " ".join(parts)
335
+
336
+
337
+ def config_path(host: str, scope: str, cwd: Path, home: Path) -> Path:
338
+ if host not in HOSTS:
339
+ raise LocalError("host_unsupported")
340
+ if scope not in ("project", "user"):
341
+ raise LocalError("invalid_request")
342
+ base = cwd if scope == "project" else home
343
+ return {
344
+ "claude": base / ".claude/settings.json",
345
+ "codex": base / ".codex/hooks.json",
346
+ "grok": base / ".grok/hooks/memoryking.json",
347
+ }[host]
348
+
349
+
350
+ def _entries(host: str, commands: dict[str, str]) -> dict[str, list[dict[str, Any]]]:
351
+ """Hook entries per event, in the shape all three hosts read."""
352
+ timeout = {"claude": 30, "codex": 30, "grok": 20}[host]
353
+ status = {"session-start": "Loading MemoryKing briefing", "pre-compact": "Saving to MemoryKing"}
354
+
355
+ def entry(kind: str, matcher: str | None, seconds: int) -> dict[str, Any]:
356
+ hook: dict[str, Any] = {"type": "command", "command": commands[kind], "timeout": seconds}
357
+ if host == "codex" and kind in status:
358
+ hook["statusMessage"] = status[kind]
359
+ value: dict[str, Any] = {"hooks": [hook]}
360
+ if matcher:
361
+ value["matcher"] = matcher
362
+ return value
363
+
364
+ return {
365
+ "SessionStart": [entry("session-start", "startup|resume|compact", timeout)],
366
+ "PreCompact": [entry("pre-compact", None, timeout)],
367
+ "SessionEnd": [entry("session-end", None, 10 if host == "claude" else timeout)],
368
+ }
369
+
370
+
371
+ def _ours(group: dict[str, Any]) -> bool:
372
+ return any(
373
+ isinstance(h, dict)
374
+ and MARK in str(h.get("command", ""))
375
+ and " hook " in str(h.get("command", ""))
376
+ for h in group.get("hooks", [])
377
+ )
378
+
379
+
380
+ def merge(
381
+ existing: dict[str, Any], entries: dict[str, list[dict[str, Any]]], *, remove: bool
382
+ ) -> dict[str, Any]:
383
+ """Add or replace MemoryKing's entries, leaving every other hook untouched."""
384
+ value = dict(existing)
385
+ section = dict(value.get("hooks") or {})
386
+ for event, ours in entries.items():
387
+ groups = [g for g in section.get(event, []) if isinstance(g, dict) and not _ours(g)]
388
+ if not remove:
389
+ groups.extend(ours)
390
+ if groups:
391
+ section[event] = groups
392
+ else:
393
+ section.pop(event, None)
394
+ if section:
395
+ value["hooks"] = section
396
+ else:
397
+ value.pop("hooks", None)
398
+ return value
399
+
400
+
401
+ def install(
402
+ *,
403
+ host: str,
404
+ scope: str,
405
+ project: str,
406
+ cwd: Path,
407
+ home: Path,
408
+ profile: str | None = None,
409
+ socket: Path | None = None,
410
+ credential: Path | None = None,
411
+ task: str | None = None,
412
+ query: str | None = None,
413
+ remove: bool = False,
414
+ write: bool = True,
415
+ ) -> dict[str, Any]:
416
+ """Merge MemoryKing's three hooks into the host's config file (or show the result)."""
417
+ path = config_path(host, scope, cwd, home)
418
+ commands = {
419
+ kind: hook_command(
420
+ kind,
421
+ host=host,
422
+ project=project,
423
+ profile=profile,
424
+ socket=socket,
425
+ credential=credential,
426
+ task=task,
427
+ query=query,
428
+ )
429
+ for kind in KINDS
430
+ }
431
+ existing: dict[str, Any] = {}
432
+ if path.exists():
433
+ try:
434
+ loaded = json.loads(path.read_text())
435
+ except ValueError as exc:
436
+ raise LocalError("hook_config_invalid") from exc
437
+ if not isinstance(loaded, dict):
438
+ raise LocalError("hook_config_invalid")
439
+ existing = loaded
440
+ merged = merge(existing, _entries(host, commands), remove=remove)
441
+ if write:
442
+ path.parent.mkdir(parents=True, exist_ok=True)
443
+ path.write_text(json.dumps(merged, indent=2) + "\n")
444
+ return {
445
+ "host": host,
446
+ "path": str(path),
447
+ "written": write,
448
+ "removed": remove,
449
+ "events": sorted(_entries(host, commands)) if not remove else [],
450
+ "config": merged,
451
+ "note": "Grok ignores hook stdout, so the session-start briefing is not injected there."
452
+ if host == "grok"
453
+ else None,
454
+ }