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/mcp.py ADDED
@@ -0,0 +1,1046 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ honcho-mcp - Model Context Protocol server for the omp-memory system.
4
+
5
+ One codebase, two transports:
6
+
7
+ stdio (default) an agent spawns this per session; single-user local.
8
+ http self-hosted; many users, bearer-token auth, per-token
9
+ database isolation under <data-dir>/users/<hash>/.
10
+
11
+ Why this exists: the storage layer answers "where do memories live"; the MCP
12
+ server is what makes an agent actually *use* them. Without it, memories are a
13
+ file that grows and is never read.
14
+
15
+ Tools
16
+ recall Search memory before acting. Ranked by lexical match,
17
+ confidence, heat and type prior.
18
+ remember Persist a fact/decision/correction learned this session.
19
+ reinforce Confirm or refute an existing memory after observing reality.
20
+ forget Retire a memory that is provably wrong.
21
+ stats Inspect what the agent has learned.
22
+
23
+ Environment
24
+ OMP_MEMORY_DB explicit DB path (wins over all else)
25
+ HONCHO_HOME data root (default ~/.omp/profiles/<profile>/agent/honcho)
26
+ HONCHO_TRANSPORT stdio | http (default stdio)
27
+ HONCHO_HOST/PORT http bind (default 127.0.0.1:8765)
28
+ HONCHO_TOKENS comma-separated bearer tokens for http mode
29
+ HONCHO_MAX_RECALL default recall limit (default 8)
30
+ HONCHO_EXTRA_TOOLS os.pathsep list of adapter directories
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import hmac
35
+ import json
36
+ import os
37
+ import secrets
38
+ import sqlite3
39
+ import sys
40
+ import threading
41
+ import traceback
42
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
43
+ from pathlib import Path
44
+ from typing import Any, Dict, List, Optional
45
+
46
+ from . import db
47
+ from . import __version__
48
+ from .context import _neutralize_fence
49
+
50
+ SERVER_NAME = "honcho"
51
+ # Single source of truth: the distribution version. A hardcoded string here
52
+ # drifted from pyproject (0.2.0) and reported 2.0.0 to every MCP client.
53
+ SERVER_VERSION = __version__
54
+ PROTOCOL_VERSION = "2024-11-05"
55
+
56
+ MAX_CONTENT = 4000
57
+ MAX_RECALL_DEFAULT = db.env_int("HONCHO_MAX_RECALL", 8, 1, 50)
58
+
59
+ # The source of every write that comes through this server, generated here
60
+ # rather than accepted from the agent. An agent-supplied source string let one
61
+ # agent present as two corroborating sources ("sessA", "sessB") and promote its
62
+ # own inference to FACT. One process is one source; HTTP mode keys per token.
63
+ _SERVER_SOURCE = "mcp:" + secrets.token_urlsafe(8)
64
+ _SERVER_SOURCES: Dict[str, str] = {}
65
+
66
+
67
+ def _server_source(user: str = "") -> str:
68
+ """The write source for this connection. Same caller, same source."""
69
+ if not user:
70
+ return _SERVER_SOURCE
71
+ src = _SERVER_SOURCES.get(user)
72
+ if src is None:
73
+ src = _SERVER_SOURCES[user] = "mcp:" + secrets.token_urlsafe(8)
74
+ return src
75
+
76
+ # Last recall result per user ("" for single-tenant). Reinforce without an id
77
+ # targets these: the agent that just used a recalled memory does not always
78
+ # know which record it came from, but it does know the recall it acted on.
79
+ _last_recall: Dict[str, List[str]] = {}
80
+ _recalled_users: set = set()
81
+
82
+
83
+ # --------------------------------------------------------------------------
84
+ # Paths and connection
85
+ # --------------------------------------------------------------------------
86
+
87
+ def _default_home() -> Path:
88
+ explicit = os.environ.get("HONCHO_HOME")
89
+ if explicit:
90
+ return Path(explicit).expanduser()
91
+ agent_dir = os.environ.get("PI_CODING_AGENT_DIR")
92
+ if agent_dir:
93
+ return Path(agent_dir) / "honcho"
94
+ profile = os.environ.get("OMP_PROFILE") or "default"
95
+ return Path.home() / ".omp" / "profiles" / profile / "agent" / "honcho"
96
+
97
+
98
+ def resolve_db_path(user: str = "") -> Path:
99
+ """Per-user database path. Empty user -> single-tenant layout."""
100
+ explicit = os.environ.get("OMP_MEMORY_DB")
101
+ home = _default_home()
102
+ if user:
103
+ # Token identities must never collide, and must not leak into a path
104
+ # name a filesystem dislikes; hash them.
105
+ return home / "users" / db.sha(f"user:{user}") / "memory.db"
106
+ if explicit:
107
+ return Path(explicit).expanduser()
108
+ return home / "memory.db"
109
+
110
+ _writer_lock = threading.RLock()
111
+ _local = threading.local()
112
+
113
+
114
+ def _stale_schema(conn) -> bool:
115
+ """True when the cached connection is pinned to a dead schema.
116
+
117
+ A migration rebuilds the records table (new inode on some filesystems),
118
+ but the already-open connection keeps the old schema in its schema
119
+ cookie, so every later statement fails with "malformed database schema".
120
+ A cheap probe statement is the detection: it costs a parse, not a scan.
121
+ """
122
+ try:
123
+ conn.execute("SELECT 1 FROM records LIMIT 1").fetchone()
124
+ return False
125
+ except sqlite3.DatabaseError as exc:
126
+ # Only the stale-cache signature. "database disk image is malformed"
127
+ # (page corruption) also contains "malformed" but is a file problem:
128
+ # a reopen fixes nothing, and init_db's auto-repair would swap the
129
+ # live DB for a backup on every call.
130
+ return str(exc).lower().startswith("malformed database schema")
131
+
132
+
133
+ def get_conn(user: str = ""):
134
+ """Open one sqlite connection per calling thread.
135
+
136
+ sqlite3 connections are not thread-safe by default: sharing one across the
137
+ ThreadingHTTPServer worker threads made the second request fail with
138
+ ProgrammingError, and the failure was permanent for the process. Each
139
+ thread opens its own connection; WAL plus the busy timeout lets them
140
+ coexist. init_db() runs under the writer lock so concurrent first touches
141
+ cannot race the migration.
142
+
143
+ A cached connection whose schema cookie is stale (the file was migrated
144
+ by another process while this one held the old handle) is closed and
145
+ reopened once: the old handle would otherwise fail every tool call
146
+ forever, because the error lives in the connection, not the file.
147
+ """
148
+ conns = getattr(_local, "conns", None)
149
+ if conns is None:
150
+ conns = _local.conns = {}
151
+ key = str(resolve_db_path(user))
152
+ conn = conns.get(key)
153
+ if conn is not None:
154
+ if _stale_schema(conn):
155
+ try:
156
+ conn.close()
157
+ except sqlite3.Error:
158
+ pass
159
+ conns.pop(key, None)
160
+ else:
161
+ return conn
162
+ path = Path(key)
163
+ path.parent.mkdir(parents=True, exist_ok=True)
164
+ with _writer_lock:
165
+ conn = db.connect(key)
166
+ # init_db() returns None in this API; it migrates in place.
167
+ db.init_db(conn, key)
168
+ conns[key] = conn
169
+ return conn
170
+
171
+
172
+ def with_conn(user: str = "", fn=None):
173
+ """Run a tool body under the single-writer lock and return its result.
174
+
175
+ Write work (remember/reinforce/forget) is serialised so concurrent HTTP
176
+ callers cannot interleave the read-modify-write of a merge. Read work also
177
+ takes the lock: it is cheaper than teaching every tool which statements
178
+ need it, and recall under load is not the bottleneck.
179
+ """
180
+ def run(body):
181
+ with _writer_lock:
182
+ return body(get_conn(user))
183
+ if fn is not None:
184
+ return run(fn)
185
+ return run
186
+
187
+
188
+ # --------------------------------------------------------------------------
189
+ # Tool implementations
190
+ # --------------------------------------------------------------------------
191
+
192
+ def _as_float(value, default: float) -> float:
193
+ """Tolerant numeric parse for MCP arguments.
194
+
195
+ A client can send "abc" or a null for a numeric field; float() would
196
+ raise and kill the whole tool call. Bad input is clamped to the default
197
+ rather than crashing the server.
198
+ """
199
+ if value is None:
200
+ return default
201
+ try:
202
+ parsed = float(value)
203
+ except (TypeError, ValueError):
204
+ return default
205
+ if parsed != parsed: # NaN
206
+ return default
207
+ return parsed
208
+
209
+
210
+ def _one_line(text: str, limit: int) -> str:
211
+ """Collapse newlines so evidence cannot fabricate extra listing lines.
212
+
213
+ A bare newline is not the only spoof: a line that starts like a result row
214
+ ("- [FACT] ... confidence=1.00 verified") reads as one even inside a
215
+ sentence. The bracket is defused so it cannot be mistaken for the tool's
216
+ own output format.
217
+ """
218
+ import re as _re
219
+ flat = " ".join((text or "").splitlines())
220
+ flat = _re.sub(r"-\s*\[", "- (", flat)
221
+ return _clip(flat, limit)
222
+
223
+
224
+ def _clip(text: str, limit: int = MAX_CONTENT) -> str:
225
+ text = (text or "").strip()
226
+ return text if len(text) <= limit else text[: limit - 3] + "..."
227
+
228
+
229
+ _MEM_TOOLS = {"recall", "remember", "reinforce", "forget", "stats", "handoff", "maintenance", "capture"}
230
+
231
+
232
+ def _auto_recall_block(user: str, tool_name: str, args: Dict[str, Any]) -> str:
233
+ """Run one recall for the session's first mem tool call, return its text."""
234
+ query = " ".join(
235
+ str(v) for v in [tool_name] + list(args.values()) if v
236
+ ).strip()[:200]
237
+ try:
238
+ conn = get_conn(user)
239
+ try:
240
+ rows = db.recall(conn, query, limit=4, full=True)
241
+ finally:
242
+ conn.close()
243
+ except Exception: # noqa: BLE001 - injection must never break the tool
244
+ return ""
245
+ if not rows:
246
+ return ""
247
+ _recalled_users.add(user)
248
+ out = ["[Auto-recall] matching memories for this session's first call:"]
249
+ for r in rows:
250
+ out.append(
251
+ f"- [{r['type']}] {_clip(r['content'], 300)} "
252
+ f"(id={r['id']} conf={float(r['confidence']):.2f})"
253
+ )
254
+ out.append("Use mcp__mem_recall for more, reinforce after relying on one.")
255
+ return "\n".join(out) + "\n\n"
256
+
257
+
258
+ def tool_recall(args: Dict[str, Any], user: str = "") -> str:
259
+ def body(conn):
260
+ query = str(args.get("query") or "").strip()
261
+ if not query:
262
+ return "recall: query is required"
263
+ limit = int(_as_float(args.get("limit"), MAX_RECALL_DEFAULT))
264
+ limit = max(1, min(limit, 50))
265
+ rtype = args.get("type")
266
+ project = args.get("project")
267
+ session = args.get("session")
268
+ verified_only = bool(args.get("verified_only"))
269
+ min_confidence = _as_float(args.get("min_confidence"), 0.0)
270
+ about_peer = args.get("about_peer")
271
+ # recall() reranks and takes the same confidence filters, so every
272
+ # query path keeps the same ranking instead of silently downgrading
273
+ # filtered queries to plain lexical order.
274
+ rows = db.recall(conn, query, limit=limit, full=True,
275
+ rtype=rtype, project_id=project,
276
+ session_id=session,
277
+ verified_only=verified_only,
278
+ min_confidence=min_confidence,
279
+ about_peer=about_peer, as_of=args.get("as_of"))
280
+ if not rows:
281
+ return f"No memory matched: {query!r}"
282
+ _last_recall[user] = [r["id"] for r in rows]
283
+ # Retrieval practice: the act of recalling is itself a learning
284
+ # event. Logged as a zero-delta signal so it starts the spacing
285
+ # clock and feeds consolidation without moving confidence.
286
+ db.log_retrieval(conn, _last_recall[user],
287
+ session_id=str(args.get("session") or ""),
288
+ channel="digest" if args.get("brief") else "recall",
289
+ query=query)
290
+ if args.get("brief"):
291
+ # L0 progressive disclosure: index only, token cost visible.
292
+ out = [f"Recalled {len(rows)} record(s) for {query!r} (brief index):"]
293
+ for r in rows:
294
+ first = next((l for l in r["content"].splitlines() if l.strip()), "")
295
+ out.append(f"- {r['id']} [{r['type']}] {first[:100]} "
296
+ f"(conf {float(r['confidence']):.2f})")
297
+ body = "\n".join(out)
298
+ out.append(f"~{len(body) // 4} tokens. Detail: recall with a narrower "
299
+ "query, or remember the id and ask for it specifically.")
300
+ return "\n".join(out)
301
+ out = [f"Recalled {len(rows)} memory record(s) for {query!r}:"]
302
+ for r in rows:
303
+ flag = "verified" if r["verified"] else "unverified"
304
+ trust = db.effective_trust(r)
305
+ out.append(
306
+ f"- [{r['type']}] {_clip(r['content'], 500)}\n"
307
+ f" id={r['id']} confidence={float(r['confidence']):.2f} {flag}"
308
+ f" trust={trust}"
309
+ + (f" evidence={_one_line(r['evidence'], 200)}"
310
+ if r["evidence"] else "")
311
+ )
312
+ cf = db.conflicts(conn, [r["id"] for r in rows])
313
+ if cf:
314
+ out.append("Possible contradictions (judge, do not auto-merge):")
315
+ for c in cf:
316
+ out.append(f"- {c['a']} vs {c['b']} ({c['kind']}, "
317
+ f"overlap {c['overlap']})")
318
+ stale = [r["id"] for r in rows if r.get("stale")]
319
+ if stale:
320
+ out.append(f"Stale anchors (source file changed, re-verify): {', '.join(stale)}")
321
+ out.append("Say reinforce {id, signal} after using one of these: success when it "
322
+ "held, failure when it did not, correction when the right answer was "
323
+ "different. The signal feeds confidence and heat.")
324
+ return "\n".join(out)
325
+ return with_conn(user, body)
326
+
327
+
328
+ def tool_digest(args: Dict[str, Any], user: str = "") -> str:
329
+ def body(conn):
330
+ budget = max(200, min(int(_as_float(args.get("budget"), 2000)), 20000))
331
+ d = db.digest(conn, budget=budget, project_id=args.get("project"))
332
+ return d["text"]
333
+ return with_conn(user, body)
334
+
335
+ def tool_handoff(args: Dict[str, Any], user: str = "") -> str:
336
+ """Pull the working-context brief for one session.
337
+
338
+ Pull-only by nature: the host must ask for it. For omp the extension
339
+ pushes it automatically on a model switch; for every other agent this tool
340
+ is the only way to get the same brief, so it accepts the session file the
341
+ host knows about and falls back to the newest one.
342
+ """
343
+ from . import handoff as _handoff
344
+
345
+ session = str(args.get("session") or "").strip()
346
+ budget = int(_as_float(args.get("chars"), _handoff.DEFAULT_CHARS))
347
+ try:
348
+ result = _handoff.build(budget, session or None)
349
+ except Exception as exc: # a brief failure must not kill the tool call
350
+ return f"handoff: {exc}"
351
+ if result.get("error"):
352
+ return f"handoff: {result['error']}"
353
+ text = (result.get("text") or "").strip()
354
+ if not text:
355
+ return "handoff: no evidence in that session yet"
356
+ return text
357
+
358
+
359
+ def tool_remember(args: Dict[str, Any], user: str = "") -> str:
360
+ def body(conn):
361
+ content = _neutralize_fence(str(args.get("content") or "").strip())
362
+ if not content:
363
+ return "remember: content is required"
364
+ rtype = str(args.get("type") or "FACT").upper()
365
+ if rtype not in db.VALID_TYPES:
366
+ return f"remember: invalid type {rtype}; use one of {sorted(db.VALID_TYPES)}"
367
+ leaked = _scan_secret(content + " " + str(args.get("evidence") or ""))
368
+ if leaked:
369
+ return f"remember: refused, possible secret detected ({leaked})"
370
+ if rtype in ("RULE", "PROCEDURAL"):
371
+ from . import capture
372
+ danger = capture.dangerous_instructions(content)
373
+ if danger:
374
+ # A rule an agent wrote that runs commands is an execution
375
+ # path, not a memory. Park it for the operator's review.
376
+ pid = db.stage_write(conn, {
377
+ "rtype": rtype, "content": _clip(content),
378
+ "evidence": _clip(str(args.get("evidence") or "")),
379
+ "confidence": min(_as_float(args.get("confidence"), 0.6),
380
+ db.CLAIMED_CONFIDENCE_CAP),
381
+ "source": _server_source(user),
382
+ "tags": str(args.get("tags") or ""),
383
+ "session_id": str(args.get("session") or ""),
384
+ "project_id": str(args.get("project") or "")})
385
+ return (f"remember: quarantined as pending write {pid} "
386
+ f"({danger[0][0]}); an operator must approve it with: "
387
+ f"omp-memory maintenance approve --pending-id {pid}")
388
+ # Trust boundary: an agent cannot verify itself, name its own source,
389
+ # or self-assign high confidence. `verified` from the arguments is
390
+ # dropped (reported below), the source is this server's, and the store
391
+ # caps a claimed confidence.
392
+ wanted_verified = bool(args.get("verified"))
393
+ result = db.remember(
394
+ conn,
395
+ rtype=rtype,
396
+ content=_clip(content),
397
+ evidence=_clip(_neutralize_fence(str(args.get("evidence") or ""))),
398
+ verified=0,
399
+ confidence=_as_float(args.get("confidence"), 0.6),
400
+ trust=db.TRUST_CLAIMED,
401
+ source=_server_source(user),
402
+ tags=str(args.get("tags") or ""),
403
+ session_id=str(args.get("session") or ""),
404
+ project_id=str(args.get("project") or ""),
405
+ about_peer=str(args.get("about_peer") or ""),
406
+ importance=_as_float(args.get("importance"), 0.5),
407
+ cue=str(args.get("cue") or ""),
408
+ )
409
+ rid = result["id"]
410
+ # Temporal validity + code anchor (v15): set after the write so the
411
+ # content identity path stays untouched. anchor_sha defaults to the
412
+ # file's current hash so check_anchors has a baseline.
413
+ anchor_path = str(args.get("anchor_path") or "")
414
+ valid_from = str(args.get("valid_from") or "")
415
+ valid_until = str(args.get("valid_until") or "")
416
+ if valid_from or valid_until:
417
+ # Re-apply on the same id only updates the window, but the second
418
+ # call supplied no evidence/verified/confidence, so it would have
419
+ # rewritten those to their defaults on the same row.
420
+ db.set_validity(conn, rid, valid_from=valid_from,
421
+ valid_until=valid_until)
422
+ if anchor_path:
423
+ import hashlib
424
+ try:
425
+ with open(anchor_path, "rb") as f:
426
+ sha = hashlib.sha256(f.read()).hexdigest()
427
+ except OSError:
428
+ return f"remember: anchor_path not readable: {anchor_path}"
429
+ conn.execute(
430
+ "UPDATE records SET anchor_path=?, anchor_sha=? WHERE id=?",
431
+ (anchor_path, sha, rid))
432
+ conn.commit()
433
+ rec = db.get_record(conn, rid) or {}
434
+ out = (
435
+ f"Stored {rtype} id={rid} confidence={float(rec.get('confidence', 0)):.2f} "
436
+ f"trust={rec.get('trust', 'claimed')} ({result['applied']})"
437
+ )
438
+ if wanted_verified:
439
+ out += ("\nverified=True was ignored: an agent cannot verify its own "
440
+ "record. Ask the operator to run: omp-memory attest " + rid)
441
+ # Near-duplicates were reported, not merged; the caller should read this.
442
+ if result.get("advisory"):
443
+ out += f"\n{result['advisory']}"
444
+ return out
445
+ return with_conn(user, body)
446
+
447
+
448
+ def tool_reinforce(args: Dict[str, Any], user: str = "") -> str:
449
+ def body(conn):
450
+ rid = str(args.get("id") or "").strip()
451
+ if not rid:
452
+ # No explicit id: the agent is confirming the recall it just used.
453
+ ids = _last_recall.get(user) or []
454
+ if not ids:
455
+ return "reinforce: id is required (or call recall first)"
456
+ if len(ids) > 1:
457
+ return ("reinforce: id is required; the last recall returned multiple "
458
+ "records, so name the one you used")
459
+ rid = ids[0]
460
+ signal = str(args.get("signal") or "").strip().lower()
461
+ if signal not in db.VALID_SIGNALS:
462
+ return f"reinforce: invalid signal {signal}; use one of {sorted(db.VALID_SIGNALS)}"
463
+ content = _neutralize_fence(str(args.get("content") or "").strip())
464
+ evidence = _neutralize_fence(str(args.get("evidence") or "").strip())
465
+ if content:
466
+ leaked = _scan_secret(content + " " + evidence)
467
+ if leaked:
468
+ return f"reinforce: {leaked} detected in correction content"
469
+ try:
470
+ new_conf = db.reinforce(conn, rid, signal,
471
+ content=content or None,
472
+ evidence=evidence,
473
+ source=_server_source(user))
474
+ except ValueError as exc:
475
+ return f"reinforce: {exc}"
476
+ out = f"Reinforced {rid} with {signal} -> confidence {new_conf:.2f}"
477
+ promo = db.last_promotion()
478
+ if promo:
479
+ out += f"\nPromoted to {promo['to_type']} (heat {float(promo['heat']):.2f})"
480
+ return out
481
+ return with_conn(user, body)
482
+
483
+
484
+ def tool_forget(args: Dict[str, Any], user: str = "") -> str:
485
+ def body(conn):
486
+ rid = str(args.get("id") or "").strip()
487
+ if not rid:
488
+ return "forget: id is required"
489
+ rec = db.get_record(conn, rid)
490
+ if not rec:
491
+ return f"forget: no record {rid}"
492
+ # reinforcement rows hold an FK to records; delete children first or the
493
+ # parent delete fails with FOREIGN KEY constraint failed. The graveyard
494
+ # row is written before the delete so a crash leaves an audit trail
495
+ # instead of a silently missing record, matching forget_cold(). REPLACE
496
+ # because the same content can be forgotten, re-created and forgotten
497
+ # again; a plain INSERT would then fail on the PRIMARY KEY.
498
+ conn.execute(
499
+ "INSERT OR REPLACE INTO forgotten_graveyard (id, type, content, reason, ts)"
500
+ " SELECT id, type, content, 'forgotten via MCP', ? FROM records WHERE id=?",
501
+ (db.now_iso(), rid),
502
+ )
503
+ conn.execute("DELETE FROM reinforcement WHERE record_id=?", (rid,))
504
+ conn.execute("DELETE FROM records WHERE id=?", (rid,))
505
+ conn.commit()
506
+ # secure_delete scrubs ordinary pages; the FTS index needs its own
507
+ # rewrite or the forgotten text stays readable in the db file.
508
+ db.purge_fts_free_pages(conn)
509
+ conn.commit()
510
+ return f"Forgot {rid} ({rec['type']})"
511
+ return with_conn(user, body)
512
+
513
+
514
+ def tool_stats(args: Dict[str, Any], user: str = "") -> str:
515
+ def body(conn):
516
+ return json.dumps(db.stats(conn), indent=2, sort_keys=True)
517
+ return with_conn(user, body)
518
+
519
+
520
+ def tool_maintenance(args: Dict[str, Any], user: str = "") -> str:
521
+ def body(conn):
522
+ op = str(args.get("op") or "decay").strip().lower()
523
+ if op == "decay":
524
+ report = {"decayed": db.apply_decay(conn),
525
+ "consolidated": db.consolidate(conn)}
526
+ return json.dumps(report, indent=2, sort_keys=True)
527
+ if op == "sleep":
528
+ report = db.sleep_pass(conn, apply=bool(args.get("apply", True)))
529
+ report["anchors"] = db.check_anchors(conn, apply=bool(args.get("apply", True)))
530
+ return json.dumps(report, indent=2, sort_keys=True)
531
+ if op == "forget_cold":
532
+ report = db.forget_cold(conn, apply=bool(args.get("apply")))
533
+ return json.dumps(report, indent=2, sort_keys=True)
534
+ if op == "promote":
535
+ return json.dumps({"promotion": db.promote_hot(conn)}, indent=2, sort_keys=True)
536
+ if op == "reflect":
537
+ from . import experience
538
+ report = experience.reflect(conn, apply=bool(args.get("apply", True)))
539
+ return json.dumps(report, indent=2, sort_keys=True)
540
+ if op == "capture":
541
+ # Lazy import: capture reads harness session logs, which are not
542
+ # the storage layer's concern.
543
+ from . import capture
544
+ report = capture.capture_session(
545
+ db, conn, apply=bool(args.get("apply")),
546
+ reflect=bool(args.get("reflect")),
547
+ staging=bool(args.get("staging")),
548
+ session_id=str(args.get("session") or ""))
549
+ return json.dumps(report, indent=2, sort_keys=True)
550
+ if op == "ingest_md":
551
+ # omp's `learn` tool appends to memories/**/learned.md after a
552
+ # tombstone that says memory moved here. Nothing read those files
553
+ # after the one-time reclaim, so recent lessons existed only on
554
+ # disk. This op closes that fork incrementally (mtime+size+sha).
555
+ from . import md_ingest
556
+ report = md_ingest.ingest_md(conn, db, apply=bool(args.get("apply")))
557
+ return json.dumps(report, indent=2, sort_keys=True)
558
+ if op == "review":
559
+ # Hermes background-review without our own LLM: return the
560
+ # review contract + recent candidates; the host agent (already
561
+ # an LLM) executes it and writes back via remember/correction.
562
+ from . import capture
563
+ report = capture.capture_session(db, conn, apply=False)
564
+ return json.dumps({"review_prompt": capture.REVIEW_PROMPT,
565
+ "candidates": report.get("candidates", [])},
566
+ indent=2, sort_keys=True)
567
+ if op == "pending":
568
+ rows = db.list_pending(conn)
569
+ return json.dumps(rows, indent=2, sort_keys=True)
570
+ if op in ("approve", "reject"):
571
+ pid = args.get("pending_id")
572
+ if pid is None:
573
+ return f"maintenance: {op} needs pending_id (see op=pending)"
574
+ try:
575
+ result = db.decide_pending(conn, int(pid), approve=(op == "approve"))
576
+ except (KeyError, db.NotFound):
577
+ return f"maintenance: pending {pid} not found"
578
+ except ValueError as e:
579
+ return f"maintenance: {e}"
580
+ return json.dumps(result, indent=2, sort_keys=True)
581
+ if op == "not_conflict":
582
+ a, b = args.get("a"), args.get("b")
583
+ if not a or not b:
584
+ return "maintenance: not_conflict needs a and b (record ids)"
585
+ return json.dumps(db.mark_not_conflict(conn, str(a), str(b)),
586
+ indent=2, sort_keys=True)
587
+ return (f"maintenance: unknown op {op}; use decay | sleep | reflect | "
588
+ "forget_cold | promote | capture | ingest_md | review | pending"
589
+ " | approve | reject | not_conflict")
590
+ return with_conn(user, body)
591
+ def _scan_secret(text: str) -> Optional[str]:
592
+ # One pattern list for every write door (capture, MCP, web).
593
+ from .capture import scan_text
594
+ hits = scan_text(text)
595
+ return hits[0][0] if hits else None
596
+
597
+ TOOLS: List[Dict[str, Any]] = [
598
+ {
599
+ "name": "recall",
600
+ "description": (
601
+ "Search persistent memory from previous sessions before starting work. "
602
+ "Returns ranked records with type, confidence and evidence. Call this when a "
603
+ "task may depend on prior decisions, corrections, project conventions or "
604
+ "hard-won debugging facts."
605
+ ),
606
+ "inputSchema": {
607
+ "type": "object",
608
+ "properties": {
609
+ "query": {"type": "string", "description": "Keywords describing what you need."},
610
+ "limit": {"type": "integer", "description": "Max results (1-50).", "default": 8},
611
+ "type": {"type": "string", "enum": sorted(db.VALID_TYPES)},
612
+ "project": {"type": "string", "description": "Scope to a project id."},
613
+ "session": {"type": "string", "description": "Scope to one session's records."},
614
+ "verified_only": {"type": "boolean"},
615
+ "min_confidence": {"type": "number"},
616
+ "brief": {"type": "boolean",
617
+ "description": "L0 index only: id + one line + confidence, "
618
+ "with token cost. Fetch detail via recall full "
619
+ "or a narrower query."},
620
+ "as_of": {"type": "string",
621
+ "description": "ISO timestamp: what was true then "
622
+ "(bi-temporal validity filter)."},
623
+ "explain": {"type": "boolean", "default": False,
624
+ "description": "Attach the score decomposition; the "
625
+ "terms sum exactly to the score."},
626
+ "expand": {"type": "integer", "default": 0,
627
+ "description": "Window size (0 = off). Each hit gains a "
628
+ "`window` of temporally adjacent records, "
629
+ "for answers that span several turns."},
630
+ },
631
+ "required": ["query"],
632
+ },
633
+ },
634
+ {
635
+ "name": "remember",
636
+ "description": (
637
+ "Persist something learned that will matter in future sessions: a decision, "
638
+ "a root cause, a project convention, a correction. Use FACT only when verified; "
639
+ "otherwise INFERENCE or ASSUMPTION. Keep content short and self-contained."
640
+ ),
641
+ "inputSchema": {
642
+ "type": "object",
643
+ "properties": {
644
+ "content": {"type": "string", "description": "One self-contained statement."},
645
+ "type": {"type": "string", "enum": sorted(db.VALID_TYPES), "default": "FACT"},
646
+ "evidence": {"type": "string", "description": "How this was verified."},
647
+ "verified": {"type": "boolean", "default": False},
648
+ "confidence": {"type": "number", "minimum": 0, "maximum": 1, "default": 0.6},
649
+ "tags": {"type": "string"},
650
+ "project": {"type": "string"},
651
+ "source": {"type": "string"},
652
+ "session": {"type": "string"},
653
+ "importance": {"type": "number", "minimum": 0, "maximum": 1, "default": 0.5,
654
+ "description": "How much this intent matters (INTENT records)."},
655
+ "cue": {"type": "string", "description": "Trigger phrase that surfaces an INTENT on recall."},
656
+ "anchor_path": {"type": "string",
657
+ "description": "File this lesson describes; its sha is "
658
+ "recorded so a later change flags the record stale."},
659
+ "valid_from": {"type": "string", "description": "ISO: valid from this moment."},
660
+ "valid_until": {"type": "string", "description": "ISO: expires at this moment."},
661
+ },
662
+ "required": ["content"],
663
+ },
664
+ },
665
+ {
666
+ "name": "reinforce",
667
+ "description": (
668
+ "Adjust a memory's confidence after observing reality. signal=success when it "
669
+ "held, failure when it did not, correction when you learned the right answer, "
670
+ "decay to fade it. This is how memory stays calibrated instead of trusting stale "
671
+ "notes. Omit id to confirm the single record from your last recall."
672
+ ),
673
+ "inputSchema": {
674
+ "type": "object",
675
+ "properties": {
676
+ "id": {"type": "string",
677
+ "description": "record id; defaults to the last single-hit recall"},
678
+ "signal": {"type": "string", "enum": sorted(db.VALID_SIGNALS)},
679
+ "source": {"type": "string"},
680
+ "content": {"type": "string",
681
+ "description": ("correction only: the corrected "
682
+ "statement; requires evidence or a "
683
+ "verified record")},
684
+ "evidence": {"type": "string",
685
+ "description": "why the correction is true"},
686
+ },
687
+ "required": ["signal"],
688
+ },
689
+ },
690
+ {
691
+ "name": "forget",
692
+ "description": ("Delete a memory record that is provably wrong. "
693
+ "Prefer reinforce(failure) when merely uncertain."),
694
+ "inputSchema": {"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]},
695
+ },
696
+ {
697
+ "name": "stats",
698
+ "description": "Counts of stored memory by type, plus verified totals.",
699
+ "inputSchema": {"type": "object", "properties": {}},
700
+ },
701
+ {
702
+ "name": "maintenance",
703
+ "description": ("Housekeeping: op=decay ages confidence, op=sleep runs "
704
+ "the consolidation pass + anchor check + backup, op=reflect "
705
+ "abstracts cross-session patterns, op=forget_cold reports "
706
+ "(or with apply=true deletes) untouched cold records, "
707
+ "op=promote reconsiders hot INFERENCE/ASSUMPTION, "
708
+ "op=capture extracts lessons (staging=true parks them for "
709
+ "review), op=ingest_md imports omp's builtin "
710
+ "memories/**/*.md incrementally, op=pending lists staged "
711
+ "writes, op=approve/reject "
712
+ "decides one by pending_id, op=not_conflict records an "
713
+ "adjudicated compatible pair (a, b) so it never resurfaces."),
714
+ "inputSchema": {
715
+ "type": "object",
716
+ "properties": {
717
+ "op": {"type": "string",
718
+ "enum": ["decay", "sleep", "reflect", "forget_cold",
719
+ "promote", "capture", "review", "pending", "approve",
720
+ "reject", "not_conflict"]},
721
+ "apply": {"type": "boolean",
722
+ "description": "forget_cold: actually delete; capture/reflect: write"},
723
+ "staging": {"type": "boolean",
724
+ "description": "capture: park candidates for approve/reject"},
725
+ "pending_id": {"type": "integer",
726
+ "description": "approve/reject: which staged write"},
727
+ "a": {"type": "string", "description": "not_conflict: first record id"},
728
+ "b": {"type": "string", "description": "not_conflict: second record id"},
729
+ },
730
+ },
731
+ },
732
+ {
733
+ "name": "digest",
734
+ "description": (
735
+ "The always-in-context memory block: top verified rules, decisions and "
736
+ "facts rendered into a char budget, stable across calls so prefix caches "
737
+ "survive. Inject once at session start; use recall for task-specific hits."
738
+ ),
739
+ "inputSchema": {
740
+ "type": "object",
741
+ "properties": {
742
+ "budget": {"type": "integer", "description": "Char budget.", "default": 2000},
743
+ "project": {"type": "string", "description": "Scope to a project id."},
744
+ },
745
+ },
746
+ },
747
+ {
748
+ "name": "handoff",
749
+ "description": (
750
+ "Return the working-context brief for a session: the operator's "
751
+ "verbatim requests, decisions from memory, observed failures and "
752
+ "files touched, assembled from the transcript rather than "
753
+ "paraphrased. Call it after a model switch or when resuming."
754
+ ),
755
+ "inputSchema": {
756
+ "type": "object",
757
+ "properties": {
758
+ "session": {
759
+ "type": "string",
760
+ "description": (
761
+ "Session transcript path. Omit to use the newest one."
762
+ ),
763
+ },
764
+ "chars": {
765
+ "type": "integer",
766
+ "description": "Character budget for the brief.",
767
+ },
768
+ },
769
+ },
770
+ },
771
+ ]
772
+
773
+ _HANDLERS: Dict[str, Any] = {
774
+ "recall": tool_recall,
775
+ "remember": tool_remember,
776
+ "reinforce": tool_reinforce,
777
+ "forget": tool_forget,
778
+ "maintenance": tool_maintenance,
779
+ "stats": tool_stats,
780
+ "digest": tool_digest,
781
+ "handoff": tool_handoff,
782
+ }
783
+
784
+
785
+ def _load_extensions() -> None:
786
+ """Merge optional tools from HONCHO_EXTRA_TOOLS directories.
787
+
788
+ Some capabilities are inherently harness-specific. A session-transcript
789
+ reader, for example, only works where the transcript format is known, and
790
+ those formats are undocumented and change without notice. Shipping one in
791
+ the package would mean advertising a feature that silently breaks.
792
+
793
+ Instead an operator can drop a module into a directory and point
794
+ HONCHO_EXTRA_TOOLS at it. Each module exposes `TOOLS` (a list of MCP tool
795
+ definitions) and `call(args, user) -> str`. Failures are reported on stderr
796
+ and never prevent the core tools from loading.
797
+ """
798
+ raw = os.environ.get("HONCHO_EXTRA_TOOLS", "")
799
+ for entry in [p for p in raw.split(os.pathsep) if p]:
800
+ d = Path(entry).expanduser()
801
+ if not d.is_dir():
802
+ continue
803
+ if str(d) not in sys.path:
804
+ sys.path.insert(0, str(d))
805
+ for mod_path in sorted(d.glob("*.py")):
806
+ name = mod_path.stem
807
+ if name.startswith("_"):
808
+ continue
809
+ # Only modules that opt in as adapters are loaded; a helper module
810
+ # dropped in the same directory must not be imported for side effects.
811
+ if not mod_path.name.startswith("local_") and not mod_path.name.startswith("adapter_"):
812
+ continue
813
+ try:
814
+ import importlib
815
+ mod = importlib.import_module(name)
816
+ except Exception as exc: # noqa: BLE001
817
+ sys.stderr.write(f"[honcho] extension {name} failed: {exc}\n")
818
+ continue
819
+ mod_tools = getattr(mod, "TOOLS", None)
820
+ call = getattr(mod, "call", None)
821
+ if not mod_tools or not callable(call):
822
+ continue
823
+ for spec in mod_tools:
824
+ tool_name = spec.get("name")
825
+ if not tool_name or tool_name in _HANDLERS:
826
+ continue
827
+ TOOLS.append(spec)
828
+ _HANDLERS[tool_name] = _make_extension_handler(call)
829
+ sys.stderr.write(f"[honcho] extension tool loaded: {tool_name}\n")
830
+
831
+
832
+ def _make_extension_handler(call):
833
+ def handler(args: Dict[str, Any], user: str = "") -> str:
834
+ return call(args, user)
835
+ return handler
836
+
837
+
838
+ _load_extensions()
839
+
840
+
841
+ INSTRUCTIONS = (
842
+ "honcho memory is your persistent memory across sessions and model switches. "
843
+ "Three habits, every session, no exceptions. "
844
+ "(1) Before any non-trivial work, call `recall` with keywords about the task; "
845
+ "prior decisions and corrections are usually more reliable than re-deriving them. "
846
+ "(2) After a recalled record proves right or wrong in this session, call `reinforce` "
847
+ "with success/failure for the id you used, so confidence stays calibrated and hot "
848
+ "records get promoted while stale ones decay. When you learn something durable "
849
+ "(a root cause, a convention, a verified fact), call `remember` with an honest type. "
850
+ "(3) At the end of a session, call maintenance {op: capture, apply: true} to persist "
851
+ "lessons from the transcript as low-confidence candidates. When you suspect you are "
852
+ "a continuation after a model switch or context reset, call `handoff` before asking "
853
+ "the operator anything. Never store secrets."
854
+ )
855
+
856
+
857
+ # --------------------------------------------------------------------------
858
+ # JSON-RPC dispatch (shared by both transports)
859
+ # --------------------------------------------------------------------------
860
+
861
+ def _result(req_id: Any, result: Dict[str, Any]) -> Dict[str, Any]:
862
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
863
+
864
+
865
+ def _error(req_id: Any, code: int, message: str) -> Dict[str, Any]:
866
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
867
+
868
+
869
+ def handle_message(msg: Any, user: str = "") -> Optional[Dict[str, Any]]:
870
+ """Handle one JSON-RPC message. Returns None for notifications."""
871
+ if not isinstance(msg, dict):
872
+ return _error(None, -32600, "invalid request: message must be an object")
873
+ try:
874
+ return _handle_message(msg, user)
875
+ except Exception: # noqa: BLE001 - one bad message must not kill the loop
876
+ traceback.print_exc(file=sys.stderr)
877
+ req_id = msg.get("id") if isinstance(msg, dict) else None
878
+ if req_id is None:
879
+ return None
880
+ return _error(req_id, -32603, "internal error handling message")
881
+
882
+
883
+ def _handle_message(msg: Dict[str, Any], user: str = "") -> Optional[Dict[str, Any]]:
884
+ method = msg.get("method")
885
+ req_id = msg.get("id")
886
+ params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
887
+
888
+ if method == "initialize":
889
+ return _result(req_id, {
890
+ "protocolVersion": PROTOCOL_VERSION,
891
+ "capabilities": {"tools": {"listChanged": False}},
892
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
893
+ "instructions": INSTRUCTIONS,
894
+ })
895
+
896
+ if method in ("notifications/initialized", "initialized"):
897
+ return None
898
+
899
+ if method == "ping":
900
+ return _result(req_id, {})
901
+
902
+ if method == "tools/list":
903
+ return _result(req_id, {"tools": TOOLS})
904
+
905
+ if method == "tools/call":
906
+ name = params.get("name")
907
+ args = params.get("arguments") or {}
908
+ handler = _HANDLERS.get(name)
909
+ if handler is None:
910
+ return _error(req_id, -32602, f"unknown tool: {name}")
911
+ try:
912
+ text = handler(args, user)
913
+ if name not in _MEM_TOOLS and user not in _recalled_users:
914
+ block = _auto_recall_block(user, name, args)
915
+ if block:
916
+ text = block + text
917
+ return _result(req_id, {"content": [{"type": "text", "text": text}]})
918
+ except Exception as exc: # noqa: BLE001 - surface, never crash the server
919
+ traceback.print_exc(file=sys.stderr)
920
+ return _result(req_id, {
921
+ "content": [{"type": "text", "text": f"tool {name} failed: {exc}"}],
922
+ "isError": True,
923
+ })
924
+
925
+ if method in ("resources/list", "prompts/list"):
926
+ return _result(req_id, {"resources": []} if "resources" in method else {"prompts": []})
927
+
928
+ if req_id is None:
929
+ return None
930
+ return _error(req_id, -32601, f"method not found: {method}")
931
+
932
+
933
+ # --------------------------------------------------------------------------
934
+ # Transport: stdio
935
+ # --------------------------------------------------------------------------
936
+
937
+ def serve_stdio() -> None:
938
+ """Newline-delimited JSON-RPC on stdin/stdout, as MCP stdio expects."""
939
+ for raw in sys.stdin:
940
+ raw = raw.strip()
941
+ if not raw:
942
+ continue
943
+ try:
944
+ msg = json.loads(raw)
945
+ except json.JSONDecodeError:
946
+ continue
947
+ if isinstance(msg, list):
948
+ out = [r for r in (handle_message(m) for m in msg) if r is not None]
949
+ if out:
950
+ sys.stdout.write(json.dumps(out) + "\n")
951
+ else:
952
+ resp = handle_message(msg)
953
+ if resp is not None:
954
+ sys.stdout.write(json.dumps(resp) + "\n")
955
+ sys.stdout.flush()
956
+
957
+
958
+ # --------------------------------------------------------------------------
959
+ # Transport: http (streamable single-POST JSON-RPC, bearer auth)
960
+ # --------------------------------------------------------------------------
961
+
962
+ class _Handler(BaseHTTPRequestHandler):
963
+ tokens: set = set()
964
+
965
+ def log_message(self, fmt: str, *args) -> None: # quieter default logging
966
+ sys.stderr.write("[honcho-http] " + (fmt % args) + "\n")
967
+
968
+ def _user(self) -> Optional[str]:
969
+ if not self.tokens:
970
+ return ""
971
+ header = self.headers.get("Authorization", "").strip()
972
+ if not header.lower().startswith("bearer "):
973
+ return None
974
+ token = header[7:].strip()
975
+ # Constant-time compare: `in` short-circuits on the first differing
976
+ # byte, which leaks token prefixes to a caller that can time us.
977
+ for known in self.tokens:
978
+ if hmac.compare_digest(token, known):
979
+ return known
980
+ return None
981
+
982
+ def _send(self, code: int, payload: Any) -> None:
983
+ body = json.dumps(payload).encode()
984
+ self.send_response(code)
985
+ self.send_header("Content-Type", "application/json")
986
+ self.send_header("Content-Length", str(len(body)))
987
+ self.end_headers()
988
+ self.wfile.write(body)
989
+
990
+ def do_GET(self):
991
+ if self.path.rstrip("/") in ("/health", "/healthz"):
992
+ self._send(200, {"ok": True, "server": SERVER_NAME, "version": SERVER_VERSION})
993
+ return
994
+ self._send(404, {"error": "not found"})
995
+
996
+ def do_POST(self):
997
+ user = self._user()
998
+ if user is None:
999
+ self._send(401, {"error": "unauthorized"})
1000
+ return
1001
+ length = int(self.headers.get("Content-Length") or 0)
1002
+ if length > 1_000_000:
1003
+ self._send(413, {"error": "payload too large"})
1004
+ return
1005
+ try:
1006
+ msg = json.loads(self.rfile.read(length) or b"{}")
1007
+ except json.JSONDecodeError:
1008
+ self._send(400, {"error": "invalid json"})
1009
+ return
1010
+ if isinstance(msg, list):
1011
+ out = [r for r in (handle_message(m, user) for m in msg) if r is not None]
1012
+ self._send(200, out)
1013
+ else:
1014
+ resp = handle_message(msg, user)
1015
+ self._send(200, resp or {})
1016
+ return
1017
+
1018
+
1019
+ def serve_http() -> None:
1020
+ host = os.environ.get("HONCHO_HOST", "127.0.0.1")
1021
+ port = db.env_int("HONCHO_PORT", 8765, 1, 65535)
1022
+ tokens = {t.strip() for t in os.environ.get("HONCHO_TOKENS", "").split(",") if t.strip()}
1023
+ _Handler.tokens = tokens
1024
+ if host not in ("127.0.0.1", "localhost", "::1") and not tokens:
1025
+ sys.stderr.write(
1026
+ "[honcho-http] refusing to bind a public interface without HONCHO_TOKENS\n"
1027
+ )
1028
+ raise SystemExit(2)
1029
+ srv = ThreadingHTTPServer((host, port), _Handler)
1030
+ sys.stderr.write(
1031
+ f"[honcho-http] listening on http://{host}:{port} "
1032
+ f"({'token auth' if tokens else 'no auth, loopback only'})\n"
1033
+ )
1034
+ srv.serve_forever()
1035
+
1036
+
1037
+ def main() -> None:
1038
+ transport = os.environ.get("HONCHO_TRANSPORT", "stdio").lower()
1039
+ if transport == "http":
1040
+ serve_http()
1041
+ else:
1042
+ serve_stdio()
1043
+
1044
+
1045
+ if __name__ == "__main__":
1046
+ main()