omp-memory 0.2.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.
- omp_memory/__init__.py +188 -0
- omp_memory/__main__.py +8 -0
- omp_memory/capture.py +658 -0
- omp_memory/cli.py +1045 -0
- omp_memory/context.py +187 -0
- omp_memory/db.py +4638 -0
- omp_memory/experience.py +309 -0
- omp_memory/handoff.py +468 -0
- omp_memory/hooks.py +162 -0
- omp_memory/mcp.py +1046 -0
- omp_memory/md_ingest.py +268 -0
- omp_memory/outcomes.py +58 -0
- omp_memory/provider.py +129 -0
- omp_memory/watch.py +163 -0
- omp_memory/web/dist/assets/index-BMXPmOzw.js +216 -0
- omp_memory/web/dist/assets/index-qca123ar.css +1 -0
- omp_memory/web/dist/index.html +13 -0
- omp_memory/web.py +879 -0
- omp_memory-0.2.0.dist-info/METADATA +506 -0
- omp_memory-0.2.0.dist-info/RECORD +24 -0
- omp_memory-0.2.0.dist-info/WHEEL +5 -0
- omp_memory-0.2.0.dist-info/entry_points.txt +3 -0
- omp_memory-0.2.0.dist-info/licenses/LICENSE.md +19 -0
- omp_memory-0.2.0.dist-info/top_level.txt +1 -0
omp_memory/handoff.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
"""Working-context handoff: build a brief a successor model can act on.
|
|
2
|
+
|
|
3
|
+
Why this lives in the repository: the first version of this file existed only
|
|
4
|
+
as a script outside the repo, imported by a test that skipped whenever the
|
|
5
|
+
machine lacked it -- so CI never exercised it, and it imported a pre-v18 fork
|
|
6
|
+
of the engine. The logic is the same; the placement is what changed.
|
|
7
|
+
|
|
8
|
+
Contract:
|
|
9
|
+
* The brief is assembled from transcript evidence (verbatim operator turns,
|
|
10
|
+
recorded decisions, observed failures, files), never from a model's
|
|
11
|
+
paraphrase.
|
|
12
|
+
* Truncation drops whole low-priority sections instead of slicing the tail,
|
|
13
|
+
so a fenced block is never half-written.
|
|
14
|
+
* `build()` returns `usable`, and the CLI exits 2 when a small budget left
|
|
15
|
+
no room for content. A caller must skip injection rather than inject a
|
|
16
|
+
header with no body.
|
|
17
|
+
* `model_state()` counts only `role == "default"` switches: omp also records
|
|
18
|
+
retry-fallback hops and prewalk promotions as model_change rows, and those
|
|
19
|
+
are the harness moving traffic, not the operator choosing a model.
|
|
20
|
+
|
|
21
|
+
The harness-specific parts (session path layout, entry shapes) are the only
|
|
22
|
+
things OMP-shaped here; everything else is plain JSON handling.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import sys
|
|
30
|
+
from collections import OrderedDict
|
|
31
|
+
from datetime import datetime, timezone
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
DEFAULT_CHARS = 24_000 # ~6k tokens: detailed but never dominating the window
|
|
36
|
+
MAX_USER_TURNS = 12
|
|
37
|
+
MAX_TOOLS = 40
|
|
38
|
+
MAX_CMD_OUTPUT = 400
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---------------------------------------------------------------- discovery
|
|
42
|
+
|
|
43
|
+
def agent_dir() -> Path:
|
|
44
|
+
explicit = os.environ.get("PI_CODING_AGENT_DIR")
|
|
45
|
+
if explicit:
|
|
46
|
+
return Path(explicit)
|
|
47
|
+
profile = os.environ.get("OMP_PROFILE") or "default"
|
|
48
|
+
return Path.home() / ".omp" / "profiles" / profile / "agent"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def sessions_dir() -> Path:
|
|
52
|
+
return agent_dir() / "sessions"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def latest_session() -> Path | None:
|
|
56
|
+
root = sessions_dir()
|
|
57
|
+
if not root.is_dir():
|
|
58
|
+
return None
|
|
59
|
+
files = [p for p in root.rglob("*.jsonl") if p.is_file()]
|
|
60
|
+
if not files:
|
|
61
|
+
return None
|
|
62
|
+
return max(files, key=lambda p: p.stat().st_mtime)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def read_entries(path: Path) -> list[dict]:
|
|
66
|
+
out = []
|
|
67
|
+
try:
|
|
68
|
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
|
69
|
+
for line in fh:
|
|
70
|
+
line = line.strip()
|
|
71
|
+
if not line:
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
out.append(json.loads(line))
|
|
75
|
+
except json.JSONDecodeError:
|
|
76
|
+
continue
|
|
77
|
+
except OSError:
|
|
78
|
+
pass
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---------------------------------------------------------------- detection
|
|
83
|
+
|
|
84
|
+
class ModelState:
|
|
85
|
+
"""Current model plus whether it differs from the previous distinct model."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, current: str = "", previous: str = "", changes: int = 0,
|
|
88
|
+
switched_at: str = ""):
|
|
89
|
+
self.current = current
|
|
90
|
+
self.previous = previous
|
|
91
|
+
self.changes = changes
|
|
92
|
+
self.switched_at = switched_at
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def switched(self) -> bool:
|
|
96
|
+
return bool(self.previous) and self.previous != self.current
|
|
97
|
+
|
|
98
|
+
def to_dict(self) -> dict:
|
|
99
|
+
return {
|
|
100
|
+
"current": self.current,
|
|
101
|
+
"previous": self.previous,
|
|
102
|
+
"changes": self.changes,
|
|
103
|
+
"switched": self.switched,
|
|
104
|
+
"switched_at": self.switched_at,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def model_state(entries: list[dict]) -> ModelState:
|
|
109
|
+
"""Collapse consecutive duplicate model_change rows into real switches.
|
|
110
|
+
|
|
111
|
+
omp writes several model_change rows seconds apart for one logical switch
|
|
112
|
+
(role resolution etc.), so only a change of the *name* counts.
|
|
113
|
+
"""
|
|
114
|
+
# Role matters. omp records retry-fallback hops (role="fallback") and
|
|
115
|
+
# prewalk/prompt-tier promotions (role="prewalk"/"temporary") as
|
|
116
|
+
# model_change rows too. Those are the harness moving traffic inside one
|
|
117
|
+
# operator turn, not the operator choosing a different model. Counting
|
|
118
|
+
# them overstated this session as 18 switches when the log holds 14 real
|
|
119
|
+
# ones (verified: 25 rows -> 14 default + 11 temporary). omp's own
|
|
120
|
+
# lastModelChangeRole(skipEphemeral) skips the same roles.
|
|
121
|
+
names: list[tuple[str, str]] = []
|
|
122
|
+
for e in entries:
|
|
123
|
+
if e.get("type") != "model_change" or not e.get("model"):
|
|
124
|
+
continue
|
|
125
|
+
if str(e.get("role") or "default") != "default":
|
|
126
|
+
continue
|
|
127
|
+
name = str(e["model"])
|
|
128
|
+
if not names or names[-1][0] != name:
|
|
129
|
+
names.append((name, str(e.get("timestamp") or "")))
|
|
130
|
+
if not names:
|
|
131
|
+
return ModelState()
|
|
132
|
+
current = names[-1][0]
|
|
133
|
+
previous = names[-2][0] if len(names) > 1 else ""
|
|
134
|
+
return ModelState(current, previous, max(0, len(names) - 1), names[-1][1])
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def detect(session_path=None) -> dict:
|
|
138
|
+
path = Path(session_path) if session_path else latest_session()
|
|
139
|
+
if path is None:
|
|
140
|
+
return {"error": "no session files", "session": None}
|
|
141
|
+
st = model_state(read_entries(path))
|
|
142
|
+
return {"session": str(path), **st.to_dict()}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---------------------------------------------------------------- extraction
|
|
146
|
+
|
|
147
|
+
def _text_of(message: dict) -> str:
|
|
148
|
+
content = message.get("content")
|
|
149
|
+
if isinstance(content, str):
|
|
150
|
+
return content
|
|
151
|
+
if isinstance(content, list):
|
|
152
|
+
parts = []
|
|
153
|
+
for block in content:
|
|
154
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
155
|
+
parts.append(str(block.get("text") or ""))
|
|
156
|
+
return "\n".join(parts)
|
|
157
|
+
return ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _clip(s: str, n: int) -> str:
|
|
161
|
+
s = " ".join(str(s).split())
|
|
162
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def extract(entries: list[dict]) -> dict:
|
|
166
|
+
"""Pull the evidence a successor actually needs out of the transcript."""
|
|
167
|
+
user_turns: list[str] = []
|
|
168
|
+
files_touched: "OrderedDict[str, int]" = OrderedDict()
|
|
169
|
+
commands: list[tuple[str, str]] = []
|
|
170
|
+
failures: list[str] = []
|
|
171
|
+
tool_counts: "OrderedDict[str, int]" = OrderedDict()
|
|
172
|
+
started = ""
|
|
173
|
+
|
|
174
|
+
for e in entries:
|
|
175
|
+
t = e.get("type")
|
|
176
|
+
ts = e.get("timestamp")
|
|
177
|
+
if not started and ts:
|
|
178
|
+
started = str(ts)
|
|
179
|
+
|
|
180
|
+
if t == "message":
|
|
181
|
+
msg = e.get("message") or {}
|
|
182
|
+
role = msg.get("role")
|
|
183
|
+
if role == "user":
|
|
184
|
+
txt = _text_of(msg).strip()
|
|
185
|
+
# Skip harness-injected control text.
|
|
186
|
+
if txt and not txt.startswith(("[HANDOFF]", "[System note]")) \
|
|
187
|
+
and "recalled memory context" not in txt.lower():
|
|
188
|
+
user_turns.append(txt)
|
|
189
|
+
elif role == "toolResult":
|
|
190
|
+
name = str(msg.get("toolName") or "")
|
|
191
|
+
if name:
|
|
192
|
+
tool_counts[name] = tool_counts.get(name, 0) + 1
|
|
193
|
+
body = _text_of(msg)
|
|
194
|
+
low = body.lower()
|
|
195
|
+
if any(k in low for k in ("error", "traceback", "failed", "exception",
|
|
196
|
+
"exit code 1", "not found", "malformed")):
|
|
197
|
+
failures.append(f"{name}: {_clip(body, 220)}")
|
|
198
|
+
if name == "bash":
|
|
199
|
+
commands.append((_clip(body, MAX_CMD_OUTPUT), "bash"))
|
|
200
|
+
|
|
201
|
+
# Some builds record tool calls as custom entries.
|
|
202
|
+
if t == "custom":
|
|
203
|
+
payload = e.get("custom") or e.get("data") or {}
|
|
204
|
+
if isinstance(payload, dict):
|
|
205
|
+
nm = payload.get("toolName") or payload.get("name")
|
|
206
|
+
if nm:
|
|
207
|
+
tool_counts[str(nm)] = tool_counts.get(str(nm), 0) + 1
|
|
208
|
+
|
|
209
|
+
for e in entries:
|
|
210
|
+
for key in ("path", "file_path", "filePath"):
|
|
211
|
+
p = (e.get(key) if isinstance(e, dict) else None)
|
|
212
|
+
if isinstance(p, str) and "/" in p:
|
|
213
|
+
files_touched[p] = files_touched.get(p, 0) + 1
|
|
214
|
+
payload = e.get("input") if isinstance(e, dict) else None
|
|
215
|
+
if isinstance(payload, dict):
|
|
216
|
+
p = payload.get("path") or payload.get("file_path")
|
|
217
|
+
if isinstance(p, str):
|
|
218
|
+
files_touched[p] = files_touched.get(p, 0) + 1
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
"started": started,
|
|
222
|
+
"user_turns": user_turns[-MAX_USER_TURNS:],
|
|
223
|
+
"files": list(files_touched.items())[-MAX_TOOLS:],
|
|
224
|
+
"commands": commands[-12:],
|
|
225
|
+
"failures": failures[-12:],
|
|
226
|
+
"tools": list(tool_counts.items()),
|
|
227
|
+
"total_entries": len(entries),
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _memory_module():
|
|
232
|
+
"""This module ships with the engine, so it is always the engine."""
|
|
233
|
+
from . import db as engine_db # noqa: PLC0415
|
|
234
|
+
return engine_db, "omp_memory"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _memories(limit: int = 6) -> list[dict]:
|
|
238
|
+
"""Latest honcho records, used as the decision log section."""
|
|
239
|
+
try:
|
|
240
|
+
db, _engine = _memory_module()
|
|
241
|
+
path = os.environ.get("OMP_MEMORY_DB") or str(agent_dir() / "honcho" / "memory.db")
|
|
242
|
+
if not Path(path).exists():
|
|
243
|
+
return []
|
|
244
|
+
conn = db.connect(path)
|
|
245
|
+
# init_db returns None (it migrates in place); assigning its result
|
|
246
|
+
# used to replace the connection with None and the whole section was
|
|
247
|
+
# silently dropped by the except below.
|
|
248
|
+
db.init_db(conn, path)
|
|
249
|
+
rows = conn.execute(
|
|
250
|
+
"SELECT type, content, confidence, verified FROM records "
|
|
251
|
+
"WHERE type IN ('DECISION','CORRECTION','RULE') "
|
|
252
|
+
"ORDER BY updated_at DESC LIMIT ?", (limit,)
|
|
253
|
+
).fetchall()
|
|
254
|
+
conn.close()
|
|
255
|
+
return [dict(r) for r in rows]
|
|
256
|
+
except Exception as exc:
|
|
257
|
+
# Returning [] silently hid a real failure (the fixture's DB was not
|
|
258
|
+
# the one being read). Keep the brief working, but leave a trace that
|
|
259
|
+
# OMP_HANDOFF_DEBUG surfaces instead of guessing later.
|
|
260
|
+
if os.environ.get("OMP_HANDOFF_DEBUG"):
|
|
261
|
+
print(f"handoff: memory section skipped: {type(exc).__name__}: {exc}",
|
|
262
|
+
file=sys.stderr)
|
|
263
|
+
return []
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# Section priority when the brief does not fit. Order is deliberate: the
|
|
267
|
+
# operator's own words and the recorded decisions change what the successor
|
|
268
|
+
# does; tool counts and raw command output only add flavour. The old code cut
|
|
269
|
+
# the tail blindly, so the section it always destroyed first was "Recent
|
|
270
|
+
# command output" -- which is also the only one that can truncate mid
|
|
271
|
+
# code-fence and produce malformed text.
|
|
272
|
+
_SECTION_PRIORITY = (
|
|
273
|
+
"## What the operator asked for",
|
|
274
|
+
"## Decisions and corrections",
|
|
275
|
+
"## Observed failures",
|
|
276
|
+
"## Files referenced",
|
|
277
|
+
"## Tool usage",
|
|
278
|
+
"## Recent command output",
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _split_sections(lines: list[str]) -> tuple[list[str], list[tuple[str, list[str]]]]:
|
|
283
|
+
"""Split the brief into its preamble and its `## ` sections, in order."""
|
|
284
|
+
head: list[str] = []
|
|
285
|
+
sections: list[tuple[str, list[str]]] = []
|
|
286
|
+
for line in lines:
|
|
287
|
+
if line.startswith("## "):
|
|
288
|
+
sections.append((line, [line]))
|
|
289
|
+
elif sections:
|
|
290
|
+
sections[-1][1].append(line)
|
|
291
|
+
else:
|
|
292
|
+
head.append(line)
|
|
293
|
+
return head, sections
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _trim_to_budget(lines: list[str], max_chars: int) -> tuple[str, bool]:
|
|
297
|
+
"""Fit the brief into max_chars by dropping whole low-priority sections.
|
|
298
|
+
|
|
299
|
+
Never slices mid-line, so a fenced block is either present or absent, not
|
|
300
|
+
half-written. The header (session, model, switch, entry count) is always
|
|
301
|
+
kept: without it the block is unreadable.
|
|
302
|
+
"""
|
|
303
|
+
head, sections = _split_sections(lines)
|
|
304
|
+
order = {name: i for i, name in enumerate(_SECTION_PRIORITY)}
|
|
305
|
+
|
|
306
|
+
def rank(item: tuple[str, list[str]]) -> int:
|
|
307
|
+
title = item[0]
|
|
308
|
+
for name in _SECTION_PRIORITY:
|
|
309
|
+
if title.startswith(name):
|
|
310
|
+
return order[name]
|
|
311
|
+
return len(_SECTION_PRIORITY) # unknown sections go last
|
|
312
|
+
|
|
313
|
+
kept = sorted(sections, key=rank)
|
|
314
|
+
head_text = "\n".join(head).rstrip()
|
|
315
|
+
while True:
|
|
316
|
+
# Check emptiness FIRST. After the last section is popped the joined
|
|
317
|
+
# text trivially fits the budget, so the size check would return a
|
|
318
|
+
# header-only "brief" as if it succeeded -- which is exactly how the
|
|
319
|
+
# earlier version reported usable=True for 411 characters of header.
|
|
320
|
+
if not kept:
|
|
321
|
+
return (head_text + "\n[handoff has no room for content at this "
|
|
322
|
+
"budget; increase --chars or skip injection]", False)
|
|
323
|
+
text = "\n".join(head + [ln for _, body in kept for ln in body])
|
|
324
|
+
if len(text) <= max_chars:
|
|
325
|
+
dropped = len(sections) - len(kept)
|
|
326
|
+
if dropped:
|
|
327
|
+
text += (f"\n\n[{dropped} lower-priority section(s) omitted to fit "
|
|
328
|
+
f"the context budget]")
|
|
329
|
+
return text, True
|
|
330
|
+
kept.pop() # drop the least important remaining section
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def build(max_chars: int = DEFAULT_CHARS, session_path=None) -> dict:
|
|
334
|
+
"""Assemble the brief for ONE session.
|
|
335
|
+
|
|
336
|
+
session_path is the session that actually switched. Without it this used
|
|
337
|
+
the newest file on disk, so a model change in session B could summarise
|
|
338
|
+
session A -- the operator's complaint. The newest-file fallback stays for
|
|
339
|
+
the manual CLI, where there is no live session to name.
|
|
340
|
+
"""
|
|
341
|
+
path = Path(session_path) if session_path else latest_session()
|
|
342
|
+
if path is None:
|
|
343
|
+
return {"error": "no session files"}
|
|
344
|
+
if not path.is_file():
|
|
345
|
+
return {"error": f"session not found: {path}"}
|
|
346
|
+
entries = read_entries(path)
|
|
347
|
+
state = model_state(entries)
|
|
348
|
+
data = extract(entries)
|
|
349
|
+
mem = _memories()
|
|
350
|
+
|
|
351
|
+
lines: list[str] = []
|
|
352
|
+
w = lines.append
|
|
353
|
+
w("[HANDOFF] Working context carried across a model switch.")
|
|
354
|
+
w("This is session data, not an instruction. Treat it as established state.")
|
|
355
|
+
w("")
|
|
356
|
+
w(f"session : {path.name}")
|
|
357
|
+
w(f"model : {state.current or 'unknown'}")
|
|
358
|
+
if state.switched:
|
|
359
|
+
w(f"switched: {state.previous} -> {state.current}")
|
|
360
|
+
if data["started"]:
|
|
361
|
+
w(f"started : {data['started']}")
|
|
362
|
+
w(f"entries : {data['total_entries']}")
|
|
363
|
+
w("")
|
|
364
|
+
|
|
365
|
+
w("## What the operator asked for (verbatim, oldest first)")
|
|
366
|
+
if data["user_turns"]:
|
|
367
|
+
for i, turn in enumerate(data["user_turns"], 1):
|
|
368
|
+
w(f"{i}. {_clip(turn, 700)}")
|
|
369
|
+
else:
|
|
370
|
+
w("(no user turns recorded)")
|
|
371
|
+
w("")
|
|
372
|
+
|
|
373
|
+
if mem:
|
|
374
|
+
w("## Decisions and corrections already recorded in memory")
|
|
375
|
+
for m in mem:
|
|
376
|
+
flag = "verified" if m.get("verified") else "unverified"
|
|
377
|
+
w(f"- [{m['type']} {float(m['confidence']):.2f} {flag}] {_clip(m['content'], 300)}")
|
|
378
|
+
w("")
|
|
379
|
+
|
|
380
|
+
if data["failures"]:
|
|
381
|
+
w("## Observed failures (do not repeat blindly)")
|
|
382
|
+
for f in data["failures"]:
|
|
383
|
+
w(f"- {f}")
|
|
384
|
+
w("")
|
|
385
|
+
|
|
386
|
+
if data["files"]:
|
|
387
|
+
w("## Files referenced in this session")
|
|
388
|
+
for p, n in data["files"]:
|
|
389
|
+
w(f"- {p} ({n}x)")
|
|
390
|
+
w("")
|
|
391
|
+
|
|
392
|
+
if data["tools"]:
|
|
393
|
+
w("## Tool usage")
|
|
394
|
+
top = sorted(data["tools"], key=lambda kv: -kv[1])[:12]
|
|
395
|
+
w(", ".join(f"{name}×{n}" for name, n in top))
|
|
396
|
+
w("")
|
|
397
|
+
|
|
398
|
+
if data["commands"]:
|
|
399
|
+
w("## Recent command output")
|
|
400
|
+
for out, _ in data["commands"]:
|
|
401
|
+
w(f"```\n{out}\n```")
|
|
402
|
+
|
|
403
|
+
text = "\n".join(lines)
|
|
404
|
+
usable = True
|
|
405
|
+
if len(text) > max_chars:
|
|
406
|
+
text, usable = _trim_to_budget(lines, max_chars)
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
"text": text,
|
|
410
|
+
"chars": len(text),
|
|
411
|
+
# Machine-readable verdict so the caller can skip injection instead of
|
|
412
|
+
# parsing prose. A brief whose body is empty must not be injected.
|
|
413
|
+
"usable": bool(text) and usable,
|
|
414
|
+
"session": str(path),
|
|
415
|
+
"model": state.to_dict(),
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# ---------------------------------------------------------------- CLI
|
|
420
|
+
|
|
421
|
+
def main() -> int:
|
|
422
|
+
ap = argparse.ArgumentParser()
|
|
423
|
+
ap.add_argument("cmd", choices=["detect", "build", "watch"])
|
|
424
|
+
ap.add_argument("--chars", type=int, default=DEFAULT_CHARS)
|
|
425
|
+
ap.add_argument("--json", action="store_true")
|
|
426
|
+
ap.add_argument("--interval", type=float, default=5.0)
|
|
427
|
+
ap.add_argument("--session", default=None,
|
|
428
|
+
help="session file that switched; omit to use the newest")
|
|
429
|
+
args = ap.parse_args()
|
|
430
|
+
|
|
431
|
+
if args.cmd == "detect":
|
|
432
|
+
out = detect(args.session)
|
|
433
|
+
elif args.cmd == "build":
|
|
434
|
+
out = build(args.chars, args.session)
|
|
435
|
+
else:
|
|
436
|
+
return _watch(args)
|
|
437
|
+
|
|
438
|
+
if args.json:
|
|
439
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
440
|
+
else:
|
|
441
|
+
print(out.get("text") or json.dumps(out, indent=2, ensure_ascii=False))
|
|
442
|
+
# Exit 2 = built but not usable (no room for content). A caller that only
|
|
443
|
+
# checks exit status then skips injection instead of injecting a header.
|
|
444
|
+
if out.get("usable") is False:
|
|
445
|
+
return 2
|
|
446
|
+
return 0
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _watch(args) -> int:
|
|
450
|
+
"""Print a brief whenever the active model changes.
|
|
451
|
+
|
|
452
|
+
Intended for a background process: `handoff.py watch > /tmp/handoff.log`.
|
|
453
|
+
"""
|
|
454
|
+
import time
|
|
455
|
+
seen = ""
|
|
456
|
+
while True:
|
|
457
|
+
st = detect()
|
|
458
|
+
if st.get("current") and st["current"] != seen:
|
|
459
|
+
if seen:
|
|
460
|
+
print(f"\n=== model switch {seen} -> {st['current']} at "
|
|
461
|
+
f"{datetime.now(timezone.utc).isoformat()} ===", flush=True)
|
|
462
|
+
print(build(args.chars)["text"], flush=True)
|
|
463
|
+
seen = st["current"]
|
|
464
|
+
time.sleep(args.interval)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
if __name__ == "__main__":
|
|
468
|
+
raise SystemExit(main())
|
omp_memory/hooks.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Install and run agent hooks that push memory in and capture lessons out.
|
|
2
|
+
|
|
3
|
+
Claude Code documents two things this relies on: hooks are configured in
|
|
4
|
+
settings.json, and a hook receives JSON on stdin including `transcript_path`
|
|
5
|
+
and `session_id`. Its transcript FORMAT is explicitly internal and changes
|
|
6
|
+
between releases, so parsing is best-effort and only ever runs on a file the
|
|
7
|
+
host itself pointed at. Nothing here guesses a path.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import db
|
|
18
|
+
|
|
19
|
+
HOOK_EVENTS = (("SessionStart", "session-start"), ("SessionEnd", "session-end"))
|
|
20
|
+
_BACKUP_SUFFIX = ".omp-backup"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def settings_path() -> Path:
|
|
24
|
+
"""`~/.claude/settings.json`, relocated when CLAUDE_CONFIG_DIR is set."""
|
|
25
|
+
root = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
26
|
+
base = Path(root) if root else Path.home() / ".claude"
|
|
27
|
+
return base / "settings.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _command(action: str) -> str:
|
|
31
|
+
# The CLI subcommand, not a generated shell script: one code path, no
|
|
32
|
+
# quoting to get wrong, and it works on every platform Python runs on.
|
|
33
|
+
return f"{sys.executable} -m omp_memory hook {action}"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _groups(settings: dict, event: str) -> list:
|
|
37
|
+
return settings.setdefault("hooks", {}).setdefault(event, [])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _has_command(settings: dict, event: str, command: str) -> bool:
|
|
41
|
+
for group in _groups(settings, event):
|
|
42
|
+
for handler in group.get("hooks", []):
|
|
43
|
+
if handler.get("command") == command:
|
|
44
|
+
return True
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _remove_command(settings: dict, event: str, command: str) -> bool:
|
|
49
|
+
removed = False
|
|
50
|
+
groups = _groups(settings, event)
|
|
51
|
+
for group in list(groups):
|
|
52
|
+
handlers = [h for h in group.get("hooks", [])
|
|
53
|
+
if h.get("command") != command]
|
|
54
|
+
if len(handlers) != len(group.get("hooks", [])):
|
|
55
|
+
removed = True
|
|
56
|
+
if handlers:
|
|
57
|
+
group["hooks"] = handlers
|
|
58
|
+
else:
|
|
59
|
+
groups.remove(group)
|
|
60
|
+
if not groups:
|
|
61
|
+
settings.get("hooks", {}).pop(event, None)
|
|
62
|
+
if settings.get("hooks") == {}:
|
|
63
|
+
settings.pop("hooks", None)
|
|
64
|
+
return removed
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def install_claude_code(dry_run: bool = False, uninstall: bool = False) -> dict:
|
|
68
|
+
"""Merge or remove our two hooks, touching nothing else in the file."""
|
|
69
|
+
path = settings_path()
|
|
70
|
+
backup = path.with_name(path.name + _BACKUP_SUFFIX)
|
|
71
|
+
original_text = path.read_text(encoding="utf-8") if path.is_file() else ""
|
|
72
|
+
try:
|
|
73
|
+
settings = json.loads(original_text) if original_text.strip() else {}
|
|
74
|
+
except json.JSONDecodeError as exc:
|
|
75
|
+
return {"error": f"{path} is not valid JSON: {exc}", "path": str(path)}
|
|
76
|
+
|
|
77
|
+
changed = False
|
|
78
|
+
if uninstall:
|
|
79
|
+
for event, action in HOOK_EVENTS:
|
|
80
|
+
if _remove_command(settings, event, _command(action)):
|
|
81
|
+
changed = True
|
|
82
|
+
plan = "remove the two memory hooks"
|
|
83
|
+
else:
|
|
84
|
+
for event, action in HOOK_EVENTS:
|
|
85
|
+
command = _command(action)
|
|
86
|
+
if not _has_command(settings, event, command):
|
|
87
|
+
_groups(settings, event).append(
|
|
88
|
+
{"hooks": [{"type": "command", "command": command}]})
|
|
89
|
+
changed = True
|
|
90
|
+
plan = "add SessionStart (push digest) and SessionEnd (capture)"
|
|
91
|
+
|
|
92
|
+
new_text = json.dumps(settings, indent=2) + "\n"
|
|
93
|
+
result = {"path": str(path), "changed": changed, "plan": plan,
|
|
94
|
+
"dry_run": dry_run}
|
|
95
|
+
if dry_run:
|
|
96
|
+
result["before"] = original_text
|
|
97
|
+
result["after"] = new_text
|
|
98
|
+
return result
|
|
99
|
+
if not changed:
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
103
|
+
if uninstall:
|
|
104
|
+
if backup.is_file():
|
|
105
|
+
# Restore the exact bytes we replaced, so an uninstall really is
|
|
106
|
+
# an undo rather than a re-serialisation that may reorder keys.
|
|
107
|
+
shutil.copyfile(backup, path)
|
|
108
|
+
backup.unlink()
|
|
109
|
+
return result
|
|
110
|
+
elif not backup.is_file() and original_text:
|
|
111
|
+
backup.write_text(original_text, encoding="utf-8")
|
|
112
|
+
path.write_text(new_text, encoding="utf-8")
|
|
113
|
+
return result
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def read_payload(stream=None) -> dict:
|
|
117
|
+
"""Hook stdin as a dict; an empty or invalid payload is not fatal."""
|
|
118
|
+
stream = stream or sys.stdin
|
|
119
|
+
try:
|
|
120
|
+
text = stream.read()
|
|
121
|
+
except (OSError, ValueError):
|
|
122
|
+
return {}
|
|
123
|
+
if not text.strip():
|
|
124
|
+
return {}
|
|
125
|
+
try:
|
|
126
|
+
value = json.loads(text)
|
|
127
|
+
except json.JSONDecodeError:
|
|
128
|
+
return {}
|
|
129
|
+
return value if isinstance(value, dict) else {}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def session_start(payload: dict) -> str:
|
|
133
|
+
"""The digest, printed to stdout: SessionStart output enters the context."""
|
|
134
|
+
try:
|
|
135
|
+
conn = db.connect()
|
|
136
|
+
db.init_db(conn)
|
|
137
|
+
try:
|
|
138
|
+
block = db.digest(conn)
|
|
139
|
+
finally:
|
|
140
|
+
conn.close()
|
|
141
|
+
except Exception as exc: # a hook must never break the host session
|
|
142
|
+
return f"[honcho] memory unavailable: {exc}"
|
|
143
|
+
return block.get("text") or ""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def session_end(payload: dict) -> dict:
|
|
147
|
+
"""Capture lessons from the transcript the host named, if it named one."""
|
|
148
|
+
raw = str(payload.get("transcript_path") or "")
|
|
149
|
+
if not raw:
|
|
150
|
+
return {"skipped": "no transcript_path in hook payload"}
|
|
151
|
+
path = Path(raw)
|
|
152
|
+
if not path.is_file():
|
|
153
|
+
return {"skipped": f"transcript not found: {raw}"}
|
|
154
|
+
from . import capture
|
|
155
|
+
conn = db.connect()
|
|
156
|
+
db.init_db(conn)
|
|
157
|
+
try:
|
|
158
|
+
return capture.capture_session(
|
|
159
|
+
db, conn, session_path=path, apply=True,
|
|
160
|
+
session_id=str(payload.get("session_id") or ""))
|
|
161
|
+
finally:
|
|
162
|
+
conn.close()
|