humemory 0.2.7 → 0.2.8

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 (94) hide show
  1. package/AGENTS.md +8 -4
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -0
  9. package/dist/agent/maintenance-queue.js +36 -61
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/server.js +3 -2
  22. package/dist/cli/index.js +96 -4
  23. package/dist/core/cues.d.ts +1 -0
  24. package/dist/core/cues.js +19 -7
  25. package/dist/core/embeddings.d.ts +0 -10
  26. package/dist/core/embeddings.js +2 -1
  27. package/dist/core/llm-generator.d.ts +2 -10
  28. package/dist/core/paths.d.ts +5 -0
  29. package/dist/core/paths.js +27 -0
  30. package/dist/core/project-path.d.ts +3 -0
  31. package/dist/core/project-path.js +14 -0
  32. package/dist/core/search.d.ts +1 -1
  33. package/dist/core/search.js +7 -9
  34. package/dist/core/types.d.ts +13 -1
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +5 -0
  37. package/dist/store/sqlite.d.ts +37 -0
  38. package/dist/store/sqlite.js +94 -42
  39. package/package.json +4 -3
  40. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  41. package/public/app/index.html +1 -1
  42. package/scripts/consolidate.js +4 -4
  43. package/scripts/hook-post-commit.ts +2 -1
  44. package/scripts/hook-session-start.ts +2 -1
  45. package/scripts/hook-session.ts +2 -1
  46. package/src/agent/claude-hook.ts +126 -0
  47. package/src/agent/codex-import.ts +129 -0
  48. package/src/agent/codex-rollout-parser.ts +121 -0
  49. package/src/agent/commit-closer.ts +173 -0
  50. package/src/agent/kimi-import.ts +128 -0
  51. package/src/agent/kimi-session-parser.ts +127 -0
  52. package/src/agent/learning-extractor.ts +128 -0
  53. package/src/agent/maintenance-queue.ts +546 -0
  54. package/src/agent/maintenance-runner.ts +322 -0
  55. package/src/agent/maintenance-state.ts +168 -0
  56. package/src/agent/mcp-client-setup.ts +125 -0
  57. package/src/agent/opencode-import.ts +96 -0
  58. package/src/agent/opencode-session-parser.ts +53 -0
  59. package/src/agent/session-context.ts +302 -0
  60. package/src/agent/session-parser.ts +155 -0
  61. package/src/agent/source-registry.ts +135 -0
  62. package/src/api/cors.ts +42 -0
  63. package/src/api/dream-routes.ts +46 -0
  64. package/src/api/errors.ts +45 -0
  65. package/src/api/intentions-routes.ts +348 -0
  66. package/src/api/limits.ts +90 -0
  67. package/src/api/maintenance-routes.ts +73 -0
  68. package/src/api/memory-routes.ts +391 -0
  69. package/src/api/scripts-routes.ts +176 -0
  70. package/src/api/security-headers.ts +54 -0
  71. package/src/api/server.ts +292 -0
  72. package/src/cli/index.ts +1175 -0
  73. package/src/core/clock.ts +64 -0
  74. package/src/core/cue-arg.ts +79 -0
  75. package/src/core/cues.ts +511 -0
  76. package/src/core/decay.ts +198 -0
  77. package/src/core/dreamer.ts +494 -0
  78. package/src/core/embeddings.ts +157 -0
  79. package/src/core/event-bus.ts +100 -0
  80. package/src/core/hybrid.ts +78 -0
  81. package/src/core/llm-cli-client.ts +118 -0
  82. package/src/core/llm-generator.ts +90 -0
  83. package/src/core/paths.ts +28 -0
  84. package/src/core/project-path.ts +14 -0
  85. package/src/core/sanitize.ts +116 -0
  86. package/src/core/scripts.ts +112 -0
  87. package/src/core/search.ts +189 -0
  88. package/src/core/trust.ts +67 -0
  89. package/src/core/types.ts +393 -0
  90. package/src/core/vector-clusterer.ts +131 -0
  91. package/src/index.ts +40 -0
  92. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  93. package/src/mcp/server.ts +202 -0
  94. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,359 @@
1
+ # HTTP transport + OAuth for the humemory MCP server
2
+
3
+ Status: **design note, not a plan of record.** Nothing here is scheduled. It exists
4
+ so the multi-user / multi-machine target does not get designed by accident, one
5
+ convenient shortcut at a time.
6
+
7
+ Colocated with [`server.ts`](./server.ts) because it is about that file.
8
+
9
+ ---
10
+
11
+ ## 1. What the protocol actually offers
12
+
13
+ MCP defines two transports. That is the whole menu.
14
+
15
+ | | **stdio** | **Streamable HTTP** |
16
+ |---|---|---|
17
+ | Process model | one server process per client, spawned by the client | one server, N clients |
18
+ | Identity | the process environment (`env` in the client's MCP config) | the HTTP layer — i.e. OAuth, or nothing |
19
+ | Auth | none needed; the OS already isolated you | OAuth 2.1, server acts as a **resource server** |
20
+ | Session | implicit (= the process lifetime) | explicit, `Mcp-Session-Id` header |
21
+ | Reach | local machine only | anywhere |
22
+
23
+ The old HTTP+SSE transport (two endpoints, `/sse` + `/messages`) is **deprecated**.
24
+ Do not implement it. Streamable HTTP is a single endpoint that handles `POST`,
25
+ `GET` and `DELETE`, with the server free to answer a POST either as one JSON
26
+ response or as an SSE stream.
27
+
28
+ Key mechanics of Streamable HTTP, since they drive the design below:
29
+
30
+ - One route, three methods. `POST /mcp` carries JSON-RPC in; `GET /mcp` opens the
31
+ server→client notification stream; `DELETE /mcp` ends the session.
32
+ - `POST` requests must send `Content-Type: application/json` and an `Accept`
33
+ containing **both** `application/json` and `text/event-stream`. The transport
34
+ rejects anything else with 415 / 406.
35
+ - Sessions are a transport concern. Pass `sessionIdGenerator` to create one; the
36
+ id then rides on the `Mcp-Session-Id` response header, and the client echoes it
37
+ on every subsequent request. Omit `sessionIdGenerator` and the server is
38
+ stateless (each POST fully self-contained).
39
+ - `OPTIONS` is *not* handled by the transport — it returns 405. CORS preflight is
40
+ the framework's job (Hono's `cors()` middleware, already mounted in
41
+ `src/api/server.ts`).
42
+
43
+ ---
44
+
45
+ ## 2. Why humemory can't just flip the switch
46
+
47
+ ### 2.1 The identity problem — this is the real blocker
48
+
49
+ Read the header of [`server.ts`](./server.ts) before anything else. The current
50
+ design is deliberate:
51
+
52
+ ```ts
53
+ const callingAgent = process.env.HUMEMORY_AGENT ?? 'unknown';
54
+ ```
55
+
56
+ `callingAgent` is a **module-level constant**, sourced from the process
57
+ environment, never from a tool argument. The rationale, verbatim from the file:
58
+ the model filling in its own name is a claim, and in an injection scenario the
59
+ model is precisely the untrusted party. stdio gives a real identity per process.
60
+
61
+ Everything downstream leans on that:
62
+
63
+ - `humemory_recall` passes `{ identityTrusted: true }` to `store.recall()`. That
64
+ flag is what makes a cross-agent recall count as **evidence** rather than a
65
+ self-assertion, and it is what earns the `reused` verification
66
+ (`VerificationReason` in `src/core/types.ts`).
67
+ - The trust layer (`src/core/trust.ts`) and the dreamer's cross-agent recurrence
68
+ mining both consume that verification.
69
+
70
+ Move to HTTP with a shared process and `callingAgent` becomes a constant across
71
+ all callers. `identityTrusted: true` becomes a lie told at every call site. The
72
+ trust layer does not break loudly — it degrades silently into noise, which is
73
+ worse.
74
+
75
+ **Therefore: OAuth is not an optional add-on to HTTP transport here. It is the
76
+ thing that restores the invariant HTTP breaks.** Ship them together or not at
77
+ all. If you ever need a staging shortcut, make the shortcut explicit — see §6.
78
+
79
+ ### 2.2 The tenancy problem
80
+
81
+ There is no `userId`, `tenantId`, `ownerId` or `workspace` anywhere in `src/`
82
+ (grep returns zero). `Memory`, `Intention`, `Cue`, `Script`, `DreamProposal` are
83
+ all scoped by `directory` (the "lieu mental") and nothing else. `directory` is a
84
+ filesystem path on *someone's* machine — meaningless as an isolation boundary
85
+ across users, and actively misleading across machines where two people both have
86
+ `D:\dev\api`.
87
+
88
+ Multi-user means a schema migration and a store-level scope that cannot be
89
+ forgotten. That is a bigger job than the transport itself.
90
+
91
+ ### 2.3 The store problem
92
+
93
+ `SQLiteStore` is a single local file with WAL plus a file-based `AdvisoryLock`
94
+ for cross-process writes. That design assumes *one filesystem*. Multi-machine
95
+ means either a network-reachable server owning the only SQLite file (fine — the
96
+ lock becomes unnecessary, the write queue does the work) or a different store
97
+ backend. The first is much cheaper and should be the default assumption.
98
+
99
+ ---
100
+
101
+ ## 3. Target shape
102
+
103
+ ```
104
+ ┌────────────────────────────────────────────┐
105
+ Claude ────┤ POST/GET/DELETE /mcp │
106
+ Codex ────┤ ├─ Bearer token (OAuth 2.1) │
107
+ Kimi ────┤ ├─ resolve subject → agentIdentity │
108
+ │ └─ StreamableHTTPServerTransport │
109
+ │ └─ McpServer (per session) │
110
+ │ └─ tools, scoped by tenant │
111
+ ├────────────────────────────────────────────┤
112
+ │ GET /.well-known/oauth-protected-resource │
113
+ ├────────────────────────────────────────────┤
114
+ │ existing Hono API (:3456), dashboard │
115
+ └──────────────────┬─────────────────────────┘
116
+ │
117
+ SQLiteStore (single owner)
118
+ ```
119
+
120
+ One process. The MCP endpoint mounts on the **existing Hono app** in
121
+ `src/api/server.ts` rather than standing up a second server — same port, same
122
+ CORS policy, same store instance, one thing to deploy.
123
+
124
+ ---
125
+
126
+ ## 4. Implementation paths
127
+
128
+ Four steps, in dependency order. Each is independently shippable and independently
129
+ testable. Do not reorder — step 2 before step 1 is exactly the silent-degradation
130
+ failure of §2.1.
131
+
132
+ ### Step 0 — prerequisite: make `callingAgent` a parameter
133
+
134
+ Pure refactor, no behaviour change, doable today, and it is the whole reason the
135
+ rest is tractable.
136
+
137
+ Today `server.ts` is a top-level script: it builds one `McpServer`, closes over
138
+ `callingAgent`, and connects a `StdioServerTransport` at module scope.
139
+
140
+ Change to a factory:
141
+
142
+ ```ts
143
+ export interface CallerIdentity {
144
+ /** Agent name — 'claude', 'codex'. Trusted: derived from env or a token, never from a tool arg. */
145
+ agent: string;
146
+ /** Null until §4.3 lands. Once non-null, every store call must be scoped by it. */
147
+ tenantId: string | null;
148
+ }
149
+
150
+ export function createHumemoryServer(store: MemoryStore, caller: CallerIdentity): McpServer {
151
+ // ... the six registerTool calls, reading `caller.agent` instead of the const
152
+ }
153
+ ```
154
+
155
+ Then `src/mcp/stdio.ts` becomes the four-line entry point that `pnpm mcp` runs:
156
+
157
+ ```ts
158
+ const store = new SQLiteStore(process.env.HUMEMORY_DB);
159
+ const server = createHumemoryServer(store, {
160
+ agent: process.env.HUMEMORY_AGENT ?? 'unknown',
161
+ tenantId: null,
162
+ });
163
+ await server.connect(new StdioServerTransport());
164
+ ```
165
+
166
+ Nothing else changes. `tests/mcp.test.ts` gets easier — it can build a server
167
+ against a temp-file store with an explicit identity, no env juggling, which is
168
+ what `docs/TESTING.md` demands anyway.
169
+
170
+ **Do this step whether or not HTTP ever ships.** It is a strict improvement.
171
+
172
+ ### Step 1 — Streamable HTTP transport, localhost only, still one identity
173
+
174
+ Goal: prove the transport works, before touching auth. Bind to `127.0.0.1`, keep
175
+ `HUMEMORY_AGENT` from the env, and **refuse to start on a non-loopback bind
176
+ without step 2**. Explicit guard, not a comment:
177
+
178
+ ```ts
179
+ if (bindHost !== '127.0.0.1' && !oauthEnabled) {
180
+ throw new Error('MCP over HTTP on a non-loopback address requires OAuth (see src/mcp/HTTP_TRANSPORT.md §2.1)');
181
+ }
182
+ ```
183
+
184
+ Session routing, mounted on the existing Hono app. One transport per session, one
185
+ `McpServer` per transport:
186
+
187
+ ```ts
188
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
189
+
190
+ async function handleMcp(c: Context) {
191
+ const sessionId = c.req.header('mcp-session-id');
192
+ const body = c.req.method === 'POST' ? await c.req.json() : undefined;
193
+
194
+ if (sessionId && sessions.has(sessionId)) {
195
+ return sessions.get(sessionId)!.handleRequest(c.req.raw, body);
196
+ }
197
+ if (!sessionId && isInitializeRequest(body)) {
198
+ const transport = new StreamableHTTPServerTransport({
199
+ sessionIdGenerator: () => randomUUID(),
200
+ onsessioninitialized: (id) => sessions.set(id, transport),
201
+ });
202
+ transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
203
+ await createHumemoryServer(store, callerFor(c)).connect(transport);
204
+ return transport.handleRequest(c.req.raw, body);
205
+ }
206
+ // unknown session → 404 -32001; no session on a non-init request → 400 -32000
207
+ }
208
+
209
+ app.post('/mcp', handleMcp);
210
+ app.get('/mcp', handleMcp);
211
+ app.delete('/mcp', handleMcp);
212
+ ```
213
+
214
+ Watch out for:
215
+
216
+ - **Hono's runtime.** The SDK's Node transport wants `IncomingMessage`/
217
+ `ServerResponse`; the Fetch-API transport wants a `Request`. The project runs
218
+ under bun but serves via `@hono/node-server`, so check which surface the
219
+ installed `@modelcontextprotocol/sdk` (^1.30) exposes before writing the glue.
220
+ If only the Node flavour exists, mount the MCP route with
221
+ `@hono/node-server`'s raw handle rather than fighting the adapter.
222
+ - **CORS.** The existing policy allows credentialed localhost origins. An MCP
223
+ endpoint reachable from a browser origin is a DNS-rebinding target. Give `/mcp`
224
+ its own stricter CORS (no `*`, explicit allowlist) and validate the `Origin`
225
+ header — do not inherit the dashboard's policy.
226
+ - **Session memory.** `sessions` is an unbounded `Map`. Add a TTL sweep; a client
227
+ that dies without `DELETE` leaks a transport and an `McpServer` forever.
228
+
229
+ At the end of this step you have a working remote MCP server that is only safe on
230
+ loopback. Do not deploy it. Go to step 2.
231
+
232
+ ### Step 2 — OAuth 2.1, server as resource server
233
+
234
+ The spec's requirements, non-negotiable:
235
+
236
+ - The MCP server is an **OAuth 2.1 resource server**, not an authorization
237
+ server. Do not write an auth server. Use an existing IdP.
238
+ - It **must** implement OAuth 2.0 Protected Resource Metadata —
239
+ `GET /.well-known/oauth-protected-resource` — pointing at the authorization
240
+ server. This is how clients discover where to authenticate.
241
+ - It **must** validate that the token's audience is this server, and reject
242
+ tokens issued for anyone else. Rejecting on signature alone is not enough — a
243
+ valid token for a *different* resource is a confused-deputy attack.
244
+ - On a missing or invalid token, return `401` with a `WWW-Authenticate` header
245
+ carrying the metadata URL:
246
+
247
+ ```http
248
+ HTTP/1.1 401 Unauthorized
249
+ WWW-Authenticate: Bearer resource_metadata="https://mem.example.com/.well-known/oauth-protected-resource",
250
+ scope="humemory:read"
251
+ ```
252
+
253
+ Insufficient scope is `403` with `error="insufficient_scope"`, not `401`.
254
+ - Never forward a received token upstream. If humemory ever calls an upstream API
255
+ on the user's behalf, it obtains its own token.
256
+
257
+ Then the payoff — `callerFor(c)` becomes real:
258
+
259
+ ```ts
260
+ function callerFor(c: Context): CallerIdentity {
261
+ const claims = c.get('tokenClaims'); // set by the auth middleware
262
+ return {
263
+ agent: claims.client_id, // which agent app — the OAuth client, not a self-report
264
+ tenantId: claims.sub, // which human
265
+ };
266
+ }
267
+ ```
268
+
269
+ `agent` now comes from the OAuth client identity and `tenantId` from the token
270
+ subject. Both are attested by the IdP. `{ identityTrusted: true }` in
271
+ `humemory_recall` is honest again, and it means something *stronger* than the
272
+ stdio version: cross-agent recall is now cross-agent *within one user*, which is
273
+ exactly the signal the dreamer wants.
274
+
275
+ Scopes worth defining early, mapped to the six tools:
276
+
277
+ | scope | tools |
278
+ |---|---|
279
+ | `humemory:read` | `humemory_search`, `humemory_recall`, `humemory_dreams` |
280
+ | `humemory:write` | `humemory_add`, `humemory_intent_add`, `humemory_intent_close` |
281
+
282
+ Split read/write from day one. Widening a scope later is easy; narrowing one
283
+ breaks every issued token.
284
+
285
+ ### Step 3 — tenancy in the store
286
+
287
+ The largest step, and the one with a migration.
288
+
289
+ 1. Add `tenantId TEXT NOT NULL` to `memories`, `intentions`, `cues`, `scripts`,
290
+ `dream_proposals`. Backfill existing rows with a single `'local'` tenant.
291
+ 2. Index every table on `(tenantId, directory)` — the current `directory` indexes
292
+ become the wrong shape the moment a second tenant exists.
293
+ 3. Make the scope impossible to forget. Do **not** add an optional `tenantId` to
294
+ every `MemoryStore` method — someone will omit it and read another user's
295
+ memories. Either:
296
+ - **(a) Scoped store wrapper** — `store.forTenant(id)` returns a façade whose
297
+ methods inject the predicate. The MCP session holds the façade and cannot
298
+ reach the raw store. Cheap, type-safe, recommended.
299
+ - **(b) Required parameter** on every method. Verbose, touches every call
300
+ site (CLI, API, hooks, dreamer, maintenance worker), but the compiler
301
+ enforces it.
302
+
303
+ (a) is the better trade here — the CLI and hooks keep using the unscoped store
304
+ with an implicit `'local'` tenant, so single-user local use is untouched.
305
+ 4. Audit the cross-cutting jobs: the dreamer, the decay sweep, `scripts/
306
+ maintenance-worker.ts` and `pnpm consolidate` all iterate over everything.
307
+ Decay is per-trace and tenant-agnostic — fine. **Merging, contradiction
308
+ detection and dream mining are not**: they correlate traces across rows, and
309
+ must never correlate across tenants. That is a data-leak bug, not a
310
+ correctness nit.
311
+ 5. Tests, per `docs/TESTING.md`: a two-tenant fixture where tenant A's search,
312
+ recall, dream list and contradiction set never surface tenant B's rows. This
313
+ suite is the one that justifies the whole step.
314
+
315
+ ---
316
+
317
+ ## 5. Testing
318
+
319
+ The `docs/TESTING.md` constraints hold — hermetic, deterministic, network-free,
320
+ never touching `data/humemory.db`, injected clock, stubbed `LLMClient`.
321
+
322
+ Additions for this work:
323
+
324
+ - **Transport tests** use an in-process client over an ephemeral port; no fixed
325
+ `:3456`, tests must be able to run in parallel.
326
+ - **Token validation tests** use a locally-generated key pair and hand-minted
327
+ JWTs. No live IdP, no network. Cases that must fail: expired, wrong audience,
328
+ wrong issuer, bad signature, missing scope, `none` algorithm.
329
+ - **Tenancy isolation** as in §4.3 step 5 — the load-bearing suite.
330
+ - **Session lifecycle**: init → tool call → `DELETE` → the id is gone from
331
+ `sessions`; and TTL expiry evicts an abandoned session.
332
+
333
+ ---
334
+
335
+ ## 6. Decision record
336
+
337
+ - Streamable HTTP, single endpoint. Never the deprecated HTTP+SSE pair.
338
+ - The MCP route mounts on the existing Hono app, not a second server.
339
+ - HTTP and OAuth ship together. A non-loopback bind without OAuth is a startup
340
+ error, not a warning — see the guard in §4.2.
341
+ - humemory is a resource server. It does not become an authorization server.
342
+ - stdio remains the default and the local path. `pnpm mcp` keeps working with
343
+ zero config, forever. HTTP is opt-in.
344
+ - Step 0 (identity as a parameter) is worth doing on its own merits, now.
345
+
346
+ ## 7. Open questions
347
+
348
+ - Which IdP? Self-hosted (Keycloak, Ory Hydra, Zitadel) vs hosted (Auth0,
349
+ Clerk, WorkOS). Drives whether Dynamic Client Registration is available, which
350
+ in turn decides how painful it is for an arbitrary MCP client to connect.
351
+ - Is `directory` still meaningful across machines, or does a tenant need an
352
+ explicit project/workspace entity that `directory` merely maps into? Leaning
353
+ toward: `directory` stays as a local hint, a new `workspace` becomes the real
354
+ conceptual scope. That is a Phase-level decision, not a transport one.
355
+ - Does the dashboard (`public/`, `web/`) get the same auth, or stay local-only?
356
+ Two auth models in one process is a maintenance cost worth avoiding.
357
+ - Embeddings and the LLM generator run server-side. Multi-tenant means someone's
358
+ Anthropic key pays for everyone's summaries — needs a quota story before this
359
+ is a product.
@@ -0,0 +1,202 @@
1
+ /**
2
+ * MCP server — Phase 6.2.
3
+ *
4
+ * Exposes the shared humemory store over the Model Context Protocol so any
5
+ * MCP-capable agent (Claude, Codex, Kimi, OpenCode) encodes, searches and
6
+ * recalls against the SAME database, with the same decay curve — one unified
7
+ * memory instead of one memory per tool.
8
+ *
9
+ * Attribution: every write path carries the calling agent, taken from
10
+ * `$HUMEMORY_AGENT` in this process's environment — set by the client's MCP
11
+ * config, one server process per client. It is deliberately NOT a tool
12
+ * argument: the model filling in its own name is a claim, and in an injection
13
+ * scenario the model is precisely the untrusted party. stdio gives us a real
14
+ * identity per process; using it is the whole point of doing attribution at
15
+ * this boundary.
16
+ *
17
+ * That identity feeds the Phase 6.0.1 trust layer: cross-agent recall earns
18
+ * the `reused` verification, cross-agent recurrence feeds the dreamer.
19
+ *
20
+ * Run: `pnpm mcp` (stdio transport — register it in the client's MCP config).
21
+ */
22
+
23
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
24
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
25
+ import { z } from 'zod';
26
+ import { SQLiteStore } from '../store/sqlite.js';
27
+ import { trustScore } from '../core/trust.js';
28
+ import { sanitizeTrace, wrapUntrusted } from '../core/sanitize.js';
29
+
30
+ const store = new SQLiteStore(process.env.HUMEMORY_DB);
31
+
32
+ /**
33
+ * This process's agent identity. Not overridable per call — see the header.
34
+ * Register one server per agent in the client's MCP config:
35
+ * { "humemory": { "command": "bun", "args": ["run", "src/mcp/server.ts"],
36
+ * "env": { "HUMEMORY_AGENT": "claude" } } }
37
+ */
38
+ const callingAgent = process.env.HUMEMORY_AGENT ?? 'unknown';
39
+
40
+ const server = new McpServer({
41
+ name: 'humemory',
42
+ version: '6.2.0',
43
+ });
44
+
45
+ /** Renders a memory for tool output — sanitized, never raw prompt material. */
46
+ function show(m: any): string {
47
+ const trust = trustScore(m);
48
+ const text = sanitizeTrace(m.content, 300).text;
49
+ return [
50
+ `id: ${m.id}`,
51
+ `level: L${m.currentLevel} · saillance: ${m.saillance} · trust: ${trust}`,
52
+ `source: ${m.source ?? 'agent'}${m.agent ? ` (${m.agent})` : ''}${m.verified ? ` · verified:${m.verificationReason}` : ''}`,
53
+ `content: ${text}`,
54
+ ].join('\n');
55
+ }
56
+
57
+ server.registerTool(
58
+ 'humemory_add',
59
+ {
60
+ description: 'Encode a new memory trace (decision, bug fix, lesson learned) into the shared store',
61
+ inputSchema: {
62
+ content: z.string().describe('What to remember'),
63
+ directory: z.string().optional().describe('Project path (defaults to cwd)'),
64
+ keywords: z.array(z.string()).optional(),
65
+ memoryType: z.enum(['episodic', 'semantic', 'procedural']).optional(),
66
+ },
67
+ },
68
+ async ({ content, directory, keywords, memoryType }) => {
69
+ const m = await store.add({
70
+ content,
71
+ directory: directory ?? process.cwd(),
72
+ day: new Date().toISOString().split('T')[0],
73
+ keywords: keywords ?? [],
74
+ sessionId: 'mcp',
75
+ memoryType: memoryType ?? 'semantic',
76
+ source: 'agent',
77
+ agent: callingAgent,
78
+ });
79
+ return { content: [{ type: 'text', text: `encoded:\n${show(m)}` }] };
80
+ }
81
+ );
82
+
83
+ server.registerTool(
84
+ 'humemory_search',
85
+ {
86
+ description: 'Inverse search — degraded layers first, like a human memory',
87
+ inputSchema: {
88
+ query: z.string(),
89
+ directory: z.string().optional(),
90
+ limit: z.number().optional(),
91
+ },
92
+ },
93
+ async ({ query, directory, limit }) => {
94
+ const results = await store.search({ query, directory, limit: limit ?? 5 });
95
+ if (!results.length) return { content: [{ type: 'text', text: 'no trace' }] };
96
+ return {
97
+ content: [
98
+ {
99
+ type: 'text',
100
+ text: results.map((r) => `match@L${r.matchLevel} score ${r.score}\n${show(r.memory)}`).join('\n---\n'),
101
+ },
102
+ ],
103
+ };
104
+ }
105
+ );
106
+
107
+ server.registerTool(
108
+ 'humemory_recall',
109
+ {
110
+ description: 'Recall a trace — reinforces it; a cross-agent recall earns the `reused` verification',
111
+ inputSchema: {
112
+ id: z.string(),
113
+ },
114
+ },
115
+ async ({ id }) => {
116
+ // identityTrusted: this agent id came from the process environment, not
117
+ // from the caller — so a cross-agent recall here is evidence, not a claim.
118
+ const m = await store.recall(id, callingAgent, { identityTrusted: true });
119
+ return { content: [{ type: 'text', text: `recalled:\n${show(m)}` }] };
120
+ }
121
+ );
122
+
123
+ server.registerTool(
124
+ 'humemory_intent_add',
125
+ {
126
+ description: 'Arm an open loop (prospective memory) with an optional time/event cue',
127
+ inputSchema: {
128
+ content: z.string(),
129
+ directory: z.string().optional(),
130
+ cron: z.string().optional().describe('5-field cron, e.g. "0 9 * * 1"'),
131
+ at: z.string().optional().describe('ISO datetime for a one-shot cue'),
132
+ },
133
+ },
134
+ async ({ content, directory, cron, at }) => {
135
+ const cues = [];
136
+ if (cron) cues.push({ kind: 'time' as const, cron });
137
+ else if (at) cues.push({ kind: 'time' as const, at });
138
+ const i = await store.addIntention(
139
+ {
140
+ content,
141
+ directory: directory ?? process.cwd(),
142
+ source: 'agent',
143
+ agent: callingAgent,
144
+ },
145
+ cues
146
+ );
147
+ // Echoes the caller's own content back into the tool result, which lands
148
+ // in the agent's context like any other tool output — sanitized the same
149
+ // way a recalled trace would be (SECURITY_AUDIT.md H-03).
150
+ const s = sanitizeTrace(i.content);
151
+ return { content: [{ type: 'text', text: `loop armed: ${i.id}\n${s.text}` }] };
152
+ }
153
+ );
154
+
155
+ server.registerTool(
156
+ 'humemory_intent_close',
157
+ {
158
+ description: 'Close an open loop by id (or short loop-XXXX id)',
159
+ inputSchema: { id: z.string() },
160
+ },
161
+ async ({ id }) => {
162
+ let target = await store.getIntention(id);
163
+ if (!target) {
164
+ const armed = await store.listIntentions({ status: ['armed', 'fired'], limit: 500 });
165
+ const { matchIntentionByShortId } = await import('../core/cues.js');
166
+ target = matchIntentionByShortId(armed, id.replace(/^loop-/, '')) ?? null;
167
+ }
168
+ if (!target) return { content: [{ type: 'text', text: `no open loop matches ${id}` }] };
169
+ await store.updateIntentionStatus(target.id, 'closed', {});
170
+ return { content: [{ type: 'text', text: `closed: ${target.id}\n${target.content}` }] };
171
+ }
172
+ );
173
+
174
+ server.registerTool(
175
+ 'humemory_dreams',
176
+ {
177
+ description: 'List pending dream proposals (cross-session patterns awaiting human review)',
178
+ inputSchema: {},
179
+ },
180
+ async () => {
181
+ const pending = await store.listDreamProposals({ status: 'pending' });
182
+ if (!pending.length) return { content: [{ type: 'text', text: 'no dream pending' }] };
183
+ // Dream proposals are synthesized cross-session patterns, never
184
+ // human-verified at this stage — wrapped like any other unverified
185
+ // recalled content (SECURITY_AUDIT.md H-03), not returned raw.
186
+ return {
187
+ content: [
188
+ {
189
+ type: 'text',
190
+ text: pending
191
+ .map((p) => {
192
+ const s = sanitizeTrace(p.payload.slice(0, 400));
193
+ return `[${p.kind}] ${p.id} — confidence ${p.confidence}\n${wrapUntrusted(s.text, { id: p.id })}`;
194
+ })
195
+ .join('\n---\n'),
196
+ },
197
+ ],
198
+ };
199
+ }
200
+ );
201
+
202
+ await server.connect(new StdioServerTransport());