humemory 0.2.7 → 0.2.9
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.
- package/AGENTS.md +14 -7
- package/CHANGELOG.md +23 -0
- package/README.md +66 -12
- package/dist/agent/kimi-import.d.ts +19 -0
- package/dist/agent/kimi-import.js +111 -0
- package/dist/agent/kimi-session-parser.d.ts +3 -0
- package/dist/agent/kimi-session-parser.js +102 -0
- package/dist/agent/maintenance-queue.d.ts +2 -1
- package/dist/agent/maintenance-queue.js +36 -62
- package/dist/agent/maintenance-runner.d.ts +17 -4
- package/dist/agent/maintenance-runner.js +45 -10
- package/dist/agent/mcp-client-setup.d.ts +16 -0
- package/dist/agent/mcp-client-setup.js +108 -0
- package/dist/agent/opencode-import.d.ts +22 -0
- package/dist/agent/opencode-import.js +71 -0
- package/dist/agent/opencode-session-parser.d.ts +3 -0
- package/dist/agent/opencode-session-parser.js +35 -0
- package/dist/agent/session-parser.d.ts +8 -0
- package/dist/agent/session-parser.js +18 -0
- package/dist/agent/source-registry.js +1 -1
- package/dist/api/memory-routes.js +1 -1
- package/dist/api/server.js +3 -2
- package/dist/cli/index.js +117 -6
- package/dist/core/cues.d.ts +1 -0
- package/dist/core/cues.js +19 -7
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +320 -0
- package/dist/core/embeddings.d.ts +0 -10
- package/dist/core/embeddings.js +2 -1
- package/dist/core/hybrid.d.ts +7 -3
- package/dist/core/hybrid.js +7 -3
- package/dist/core/llm-generator.d.ts +2 -10
- package/dist/core/paths.d.ts +12 -0
- package/dist/core/paths.js +36 -0
- package/dist/core/project-path.d.ts +3 -0
- package/dist/core/project-path.js +14 -0
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.js +7 -9
- package/dist/core/types.d.ts +13 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/store/sqlite.d.ts +37 -0
- package/dist/store/sqlite.js +94 -42
- package/docs/PORTABILITY.md +84 -0
- package/package.json +5 -3
- package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
- package/public/app/index.html +1 -1
- package/scripts/consolidate.js +4 -4
- package/scripts/hook-post-commit.ts +2 -1
- package/scripts/hook-session-start.ts +2 -1
- package/scripts/hook-session.ts +2 -1
- package/scripts/maintenance-worker.ts +7 -2
- package/src/agent/claude-hook.ts +126 -0
- package/src/agent/codex-import.ts +129 -0
- package/src/agent/codex-rollout-parser.ts +121 -0
- package/src/agent/commit-closer.ts +173 -0
- package/src/agent/kimi-import.ts +128 -0
- package/src/agent/kimi-session-parser.ts +127 -0
- package/src/agent/learning-extractor.ts +128 -0
- package/src/agent/maintenance-queue.ts +544 -0
- package/src/agent/maintenance-runner.ts +322 -0
- package/src/agent/maintenance-state.ts +168 -0
- package/src/agent/mcp-client-setup.ts +125 -0
- package/src/agent/opencode-import.ts +96 -0
- package/src/agent/opencode-session-parser.ts +53 -0
- package/src/agent/session-context.ts +302 -0
- package/src/agent/session-parser.ts +155 -0
- package/src/agent/source-registry.ts +135 -0
- package/src/api/cors.ts +42 -0
- package/src/api/dream-routes.ts +46 -0
- package/src/api/errors.ts +45 -0
- package/src/api/intentions-routes.ts +348 -0
- package/src/api/limits.ts +90 -0
- package/src/api/maintenance-routes.ts +73 -0
- package/src/api/memory-routes.ts +391 -0
- package/src/api/scripts-routes.ts +176 -0
- package/src/api/security-headers.ts +54 -0
- package/src/api/server.ts +292 -0
- package/src/cli/index.ts +1195 -0
- package/src/core/clock.ts +64 -0
- package/src/core/cue-arg.ts +79 -0
- package/src/core/cues.ts +511 -0
- package/src/core/decay.ts +198 -0
- package/src/core/doctor.ts +362 -0
- package/src/core/dreamer.ts +494 -0
- package/src/core/embeddings.ts +157 -0
- package/src/core/event-bus.ts +100 -0
- package/src/core/hybrid.ts +82 -0
- package/src/core/llm-cli-client.ts +118 -0
- package/src/core/llm-generator.ts +90 -0
- package/src/core/paths.ts +38 -0
- package/src/core/project-path.ts +14 -0
- package/src/core/sanitize.ts +116 -0
- package/src/core/scripts.ts +112 -0
- package/src/core/search.ts +189 -0
- package/src/core/trust.ts +67 -0
- package/src/core/types.ts +393 -0
- package/src/core/vector-clusterer.ts +131 -0
- package/src/index.ts +40 -0
- package/src/mcp/HTTP_TRANSPORT.md +359 -0
- package/src/mcp/server.ts +202 -0
- package/src/store/sqlite.ts +1958 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VectorClusterer — Phase 7.3.
|
|
3
|
+
*
|
|
4
|
+
* Same union-find shape as KeywordClusterer, on cosine similarity over stored
|
|
5
|
+
* embeddings instead of Jaccard over tokens. Missing embeddings are embedded
|
|
6
|
+
* on the spot BY THE BATCH JOB (A3 — this class only ever runs inside
|
|
7
|
+
* `pnpm dream` / backfill, never on the add() path).
|
|
8
|
+
*
|
|
9
|
+
* Implements `ScoredClusterer`: the dreamer needs the cluster's minimum
|
|
10
|
+
* pairwise similarity to gate `corroborated` verification on the STRICTER
|
|
11
|
+
* threshold (A1). Grouping tolerates noise — a human reviews proposals;
|
|
12
|
+
* verification does not — nobody reviews it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Memory } from './types.js';
|
|
16
|
+
import { DREAM_CONFIG, type Clusterer } from './dreamer.js';
|
|
17
|
+
import { cosine, embeddableText, type Embedder } from './embeddings.js';
|
|
18
|
+
|
|
19
|
+
export interface ScoredCluster {
|
|
20
|
+
members: Memory[];
|
|
21
|
+
/** Weakest link that holds the cluster together. */
|
|
22
|
+
minPairwiseSimilarity: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ScoredClusterer extends Clusterer {
|
|
26
|
+
clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Type guard — the dreamer uses scores when the clusterer provides them. */
|
|
30
|
+
export function hasScores(c: Clusterer): c is ScoredClusterer {
|
|
31
|
+
return typeof (c as ScoredClusterer).clusterWithScores === 'function';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface EmbeddingStore {
|
|
35
|
+
getEmbedding(memoryId: string): Promise<{ modelId: string; embedding: Float32Array } | null>;
|
|
36
|
+
setEmbedding(memoryId: string, modelId: string, embedding: Float32Array): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class VectorClusterer implements ScoredClusterer {
|
|
40
|
+
constructor(
|
|
41
|
+
private embedder: Embedder,
|
|
42
|
+
private store: EmbeddingStore,
|
|
43
|
+
/**
|
|
44
|
+
* Default: the embedder's calibrated per-model threshold
|
|
45
|
+
* (OnnxEmbedder.suggestedClusterThreshold — 7.5 round 4), falling back to
|
|
46
|
+
* DREAM_CONFIG for embedders without calibration (e.g. HashEmbedder in tests).
|
|
47
|
+
*/
|
|
48
|
+
private threshold: number = (embedder as { suggestedClusterThreshold?: number })
|
|
49
|
+
.suggestedClusterThreshold ?? DREAM_CONFIG.vectorClusterThreshold
|
|
50
|
+
) {}
|
|
51
|
+
|
|
52
|
+
private async embeddingsFor(memories: Memory[]): Promise<Float32Array[]> {
|
|
53
|
+
const missing: { index: number; text: string }[] = [];
|
|
54
|
+
const out: (Float32Array | null)[] = [];
|
|
55
|
+
|
|
56
|
+
for (let i = 0; i < memories.length; i++) {
|
|
57
|
+
const row = await this.store.getEmbedding(memories[i].id);
|
|
58
|
+
if (row && row.modelId === this.embedder.modelId) {
|
|
59
|
+
out.push(row.embedding);
|
|
60
|
+
} else {
|
|
61
|
+
out.push(null);
|
|
62
|
+
missing.push({ index: i, text: embeddableText(memories[i]) });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (missing.length) {
|
|
67
|
+
// One batched model call for everything missing (A3: we are in a batch job).
|
|
68
|
+
const fresh = await this.embedder.embed(missing.map((m) => m.text));
|
|
69
|
+
for (let k = 0; k < missing.length; k++) {
|
|
70
|
+
out[missing[k].index] = fresh[k];
|
|
71
|
+
await this.store.setEmbedding(memories[missing[k].index].id, this.embedder.modelId, fresh[k]);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return out as Float32Array[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async clusterWithScores(memories: Memory[]): Promise<ScoredCluster[]> {
|
|
79
|
+
if (memories.length < 2) return [];
|
|
80
|
+
const vectors = await this.embeddingsFor(memories);
|
|
81
|
+
|
|
82
|
+
const parent = memories.map((_, i) => i);
|
|
83
|
+
const find = (i: number): number => {
|
|
84
|
+
while (parent[i] !== i) {
|
|
85
|
+
parent[i] = parent[parent[i]];
|
|
86
|
+
i = parent[i];
|
|
87
|
+
}
|
|
88
|
+
return i;
|
|
89
|
+
};
|
|
90
|
+
// Track the weakest accepted link per union — that is the cluster's
|
|
91
|
+
// minPairwiseSimilarity once grouping settles.
|
|
92
|
+
const sims = new Map<string, number>();
|
|
93
|
+
for (let i = 0; i < memories.length; i++) {
|
|
94
|
+
for (let j = i + 1; j < memories.length; j++) {
|
|
95
|
+
const s = cosine(vectors[i], vectors[j]);
|
|
96
|
+
if (s >= this.threshold) {
|
|
97
|
+
sims.set(`${i}:${j}`, s);
|
|
98
|
+
const ri = find(i);
|
|
99
|
+
const rj = find(j);
|
|
100
|
+
if (ri !== rj) parent[rj] = ri;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const groups = new Map<number, number[]>();
|
|
106
|
+
memories.forEach((_, i) => {
|
|
107
|
+
const root = find(i);
|
|
108
|
+
if (!groups.has(root)) groups.set(root, []);
|
|
109
|
+
groups.get(root)!.push(i);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const clusters: ScoredCluster[] = [];
|
|
113
|
+
for (const idxs of groups.values()) {
|
|
114
|
+
if (idxs.length < 2) continue;
|
|
115
|
+
let min = 1;
|
|
116
|
+
for (let a = 0; a < idxs.length; a++) {
|
|
117
|
+
for (let b = a + 1; b < idxs.length; b++) {
|
|
118
|
+
const key = `${Math.min(idxs[a], idxs[b])}:${Math.max(idxs[a], idxs[b])}`;
|
|
119
|
+
const s = sims.get(key) ?? cosine(vectors[idxs[a]], vectors[idxs[b]]);
|
|
120
|
+
if (s < min) min = s;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
clusters.push({ members: idxs.map((i) => memories[i]), minPairwiseSimilarity: min });
|
|
124
|
+
}
|
|
125
|
+
return clusters;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async cluster(memories: Memory[]): Promise<Memory[][]> {
|
|
129
|
+
return (await this.clusterWithScores(memories)).map((c) => c.members);
|
|
130
|
+
}
|
|
131
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* humemory — Human-like memory system
|
|
3
|
+
*
|
|
4
|
+
* Stores memories with progressive decay and inverse search
|
|
5
|
+
* (degraded layers first, escalating to full detail)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export { SQLiteStore } from './store/sqlite.js';
|
|
9
|
+
export { InverseSearchEngine } from './core/search.js';
|
|
10
|
+
export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
|
|
11
|
+
export { generateMemoryLevels, generateMemoryLevelsDeterministic, setLLMClient } from './core/llm-generator.js';
|
|
12
|
+
export { systemClock, FakeClock } from './core/clock.js';
|
|
13
|
+
export { InMemoryEventBus } from './core/event-bus.js';
|
|
14
|
+
export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
|
|
15
|
+
export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
|
|
16
|
+
export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
|
|
17
|
+
export { processSession } from './agent/claude-hook.js';
|
|
18
|
+
export { parseClaudeHookPayload } from './agent/session-parser.js';
|
|
19
|
+
export { parseKimiSession } from './agent/kimi-session-parser.js';
|
|
20
|
+
export { importKimiSessions, defaultKimiHome, KIMI_SOURCE } from './agent/kimi-import.js';
|
|
21
|
+
export { parseOpenCodeExport } from './agent/opencode-session-parser.js';
|
|
22
|
+
export { importOpenCodeSessions, defaultOpenCodeCommand, OPENCODE_SOURCE } from './agent/opencode-import.js';
|
|
23
|
+
export { setupHumemoryMcpClients } from './agent/mcp-client-setup.js';
|
|
24
|
+
export { extractLearnings, extractLearningsDeterministic } from './agent/learning-extractor.js';
|
|
25
|
+
export { enqueueSession, processMaintenanceQueue } from './agent/maintenance-queue.js';
|
|
26
|
+
export { discoverLocalAgentSources, KNOWN_AGENT_SOURCES } from './agent/source-registry.js';
|
|
27
|
+
export type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MergeResult,
|
|
28
|
+
Intention, Cue, IntentionStatus, CueStatus, CueKind, TriggerSpec, TimeTriggerSpec, EventTriggerSpec,
|
|
29
|
+
NewIntention, NewCue, IntentionStore } from './core/types.js';
|
|
30
|
+
export type { StoreOptions } from './store/sqlite.js';
|
|
31
|
+
export type { Clock } from './core/clock.js';
|
|
32
|
+
export type { CueResolver, CueResolverOptions } from './core/cues.js';
|
|
33
|
+
export type { SessionContext, SessionContextOptions } from './agent/session-context.js';
|
|
34
|
+
export type { AppEvent, AppEventType, AppEventOf, EventBus, EventHandler, Unsubscribe } from './core/event-bus.js';
|
|
35
|
+
export type { GeneratedLevels, LLMClient } from './core/llm-generator.js';
|
|
36
|
+
export type { ParsedSession, SessionMessage } from './agent/session-parser.js';
|
|
37
|
+
export type { ExtractedLearning } from './agent/learning-extractor.js';
|
|
38
|
+
export type { HookOptions, HookResult } from './agent/claude-hook.js';
|
|
39
|
+
export type { MaintenanceJob, EnqueueOptions, QueueResult, WorkerOptions, WorkerResult } from './agent/maintenance-queue.js';
|
|
40
|
+
export type { AgentSourceDefinition, AgentSourceId, DiscoveredAgentSource, DiscoveryOptions } from './agent/source-registry.js';
|
|
@@ -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.
|