humemory 0.2.1
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/.githooks/post-commit +22 -0
- package/AGENTS.md +328 -0
- package/CHANGELOG.md +198 -0
- package/LICENSE +21 -0
- package/README.md +488 -0
- package/bin/humemory.js +19 -0
- package/dist/agent/claude-hook.d.ts +15 -0
- package/dist/agent/claude-hook.js +38 -0
- package/dist/agent/commit-closer.d.ts +60 -0
- package/dist/agent/commit-closer.js +125 -0
- package/dist/agent/learning-extractor.d.ts +10 -0
- package/dist/agent/learning-extractor.js +75 -0
- package/dist/agent/session-context.d.ts +63 -0
- package/dist/agent/session-context.js +216 -0
- package/dist/agent/session-parser.d.ts +12 -0
- package/dist/agent/session-parser.js +85 -0
- package/dist/api/dream-routes.d.ts +7 -0
- package/dist/api/dream-routes.js +40 -0
- package/dist/api/intentions-routes.d.ts +23 -0
- package/dist/api/intentions-routes.js +252 -0
- package/dist/api/memory-routes.d.ts +10 -0
- package/dist/api/memory-routes.js +277 -0
- package/dist/api/scripts-routes.d.ts +13 -0
- package/dist/api/scripts-routes.js +129 -0
- package/dist/api/server.d.ts +33 -0
- package/dist/api/server.js +157 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +798 -0
- package/dist/core/clock.d.ts +38 -0
- package/dist/core/clock.js +52 -0
- package/dist/core/cue-arg.d.ts +19 -0
- package/dist/core/cue-arg.js +72 -0
- package/dist/core/cues.d.ts +138 -0
- package/dist/core/cues.js +372 -0
- package/dist/core/decay.d.ts +49 -0
- package/dist/core/decay.js +157 -0
- package/dist/core/dreamer.d.ts +114 -0
- package/dist/core/dreamer.js +427 -0
- package/dist/core/embeddings.d.ts +79 -0
- package/dist/core/embeddings.js +133 -0
- package/dist/core/event-bus.d.ts +71 -0
- package/dist/core/event-bus.js +67 -0
- package/dist/core/hybrid.d.ts +33 -0
- package/dist/core/hybrid.js +63 -0
- package/dist/core/llm-generator.d.ts +18 -0
- package/dist/core/llm-generator.js +69 -0
- package/dist/core/sanitize.d.ts +57 -0
- package/dist/core/sanitize.js +87 -0
- package/dist/core/scripts.d.ts +55 -0
- package/dist/core/scripts.js +96 -0
- package/dist/core/search.d.ts +42 -0
- package/dist/core/search.js +173 -0
- package/dist/core/trust.d.ts +48 -0
- package/dist/core/trust.js +57 -0
- package/dist/core/types.d.ts +333 -0
- package/dist/core/types.js +1 -0
- package/dist/core/vector-clusterer.d.ts +53 -0
- package/dist/core/vector-clusterer.js +113 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +18 -0
- package/dist/mcp/server.d.ts +22 -0
- package/dist/mcp/server.js +158 -0
- package/dist/store/sqlite.d.ts +240 -0
- package/dist/store/sqlite.js +1653 -0
- package/docs/TESTING.md +244 -0
- package/package.json +95 -0
- package/public/app/galaxy-f42190mq.js +10 -0
- package/public/app/index-2cf31xxn.css +1 -0
- package/public/app/index-epqg22cp.js +1 -0
- package/public/app/index-f9h80bzq.js +12 -0
- package/public/app/index-gbfwa9vq.js +2 -0
- package/public/app/index-kvhc17mz.js +2 -0
- package/public/app/index-pbd5t4dj.js +2 -0
- package/public/app/index.html +12 -0
- package/public/app/promenade-cnzzpm73.js +4111 -0
- package/public/app/river-tyawhh8w.js +13 -0
- package/public/session.html +659 -0
- package/scripts/consolidate.js +46 -0
- package/scripts/hook-post-commit.ts +80 -0
- package/scripts/hook-session-start.ts +92 -0
- package/scripts/hook-session.ts +60 -0
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
import { DREAM_CONFIG } from './dreamer.js';
|
|
15
|
+
import { cosine, embeddableText } from './embeddings.js';
|
|
16
|
+
/** Type guard — the dreamer uses scores when the clusterer provides them. */
|
|
17
|
+
export function hasScores(c) {
|
|
18
|
+
return typeof c.clusterWithScores === 'function';
|
|
19
|
+
}
|
|
20
|
+
export class VectorClusterer {
|
|
21
|
+
embedder;
|
|
22
|
+
store;
|
|
23
|
+
threshold;
|
|
24
|
+
constructor(embedder, store,
|
|
25
|
+
/**
|
|
26
|
+
* Default: the embedder's calibrated per-model threshold
|
|
27
|
+
* (OnnxEmbedder.suggestedClusterThreshold — 7.5 round 4), falling back to
|
|
28
|
+
* DREAM_CONFIG for embedders without calibration (e.g. HashEmbedder in tests).
|
|
29
|
+
*/
|
|
30
|
+
threshold = embedder
|
|
31
|
+
.suggestedClusterThreshold ?? DREAM_CONFIG.vectorClusterThreshold) {
|
|
32
|
+
this.embedder = embedder;
|
|
33
|
+
this.store = store;
|
|
34
|
+
this.threshold = threshold;
|
|
35
|
+
}
|
|
36
|
+
async embeddingsFor(memories) {
|
|
37
|
+
const missing = [];
|
|
38
|
+
const out = [];
|
|
39
|
+
for (let i = 0; i < memories.length; i++) {
|
|
40
|
+
const row = await this.store.getEmbedding(memories[i].id);
|
|
41
|
+
if (row && row.modelId === this.embedder.modelId) {
|
|
42
|
+
out.push(row.embedding);
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
out.push(null);
|
|
46
|
+
missing.push({ index: i, text: embeddableText(memories[i]) });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (missing.length) {
|
|
50
|
+
// One batched model call for everything missing (A3: we are in a batch job).
|
|
51
|
+
const fresh = await this.embedder.embed(missing.map((m) => m.text));
|
|
52
|
+
for (let k = 0; k < missing.length; k++) {
|
|
53
|
+
out[missing[k].index] = fresh[k];
|
|
54
|
+
await this.store.setEmbedding(memories[missing[k].index].id, this.embedder.modelId, fresh[k]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
async clusterWithScores(memories) {
|
|
60
|
+
if (memories.length < 2)
|
|
61
|
+
return [];
|
|
62
|
+
const vectors = await this.embeddingsFor(memories);
|
|
63
|
+
const parent = memories.map((_, i) => i);
|
|
64
|
+
const find = (i) => {
|
|
65
|
+
while (parent[i] !== i) {
|
|
66
|
+
parent[i] = parent[parent[i]];
|
|
67
|
+
i = parent[i];
|
|
68
|
+
}
|
|
69
|
+
return i;
|
|
70
|
+
};
|
|
71
|
+
// Track the weakest accepted link per union — that is the cluster's
|
|
72
|
+
// minPairwiseSimilarity once grouping settles.
|
|
73
|
+
const sims = new Map();
|
|
74
|
+
for (let i = 0; i < memories.length; i++) {
|
|
75
|
+
for (let j = i + 1; j < memories.length; j++) {
|
|
76
|
+
const s = cosine(vectors[i], vectors[j]);
|
|
77
|
+
if (s >= this.threshold) {
|
|
78
|
+
sims.set(`${i}:${j}`, s);
|
|
79
|
+
const ri = find(i);
|
|
80
|
+
const rj = find(j);
|
|
81
|
+
if (ri !== rj)
|
|
82
|
+
parent[rj] = ri;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const groups = new Map();
|
|
87
|
+
memories.forEach((_, i) => {
|
|
88
|
+
const root = find(i);
|
|
89
|
+
if (!groups.has(root))
|
|
90
|
+
groups.set(root, []);
|
|
91
|
+
groups.get(root).push(i);
|
|
92
|
+
});
|
|
93
|
+
const clusters = [];
|
|
94
|
+
for (const idxs of groups.values()) {
|
|
95
|
+
if (idxs.length < 2)
|
|
96
|
+
continue;
|
|
97
|
+
let min = 1;
|
|
98
|
+
for (let a = 0; a < idxs.length; a++) {
|
|
99
|
+
for (let b = a + 1; b < idxs.length; b++) {
|
|
100
|
+
const key = `${Math.min(idxs[a], idxs[b])}:${Math.max(idxs[a], idxs[b])}`;
|
|
101
|
+
const s = sims.get(key) ?? cosine(vectors[idxs[a]], vectors[idxs[b]]);
|
|
102
|
+
if (s < min)
|
|
103
|
+
min = s;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
clusters.push({ members: idxs.map((i) => memories[i]), minPairwiseSimilarity: min });
|
|
107
|
+
}
|
|
108
|
+
return clusters;
|
|
109
|
+
}
|
|
110
|
+
async cluster(memories) {
|
|
111
|
+
return (await this.clusterWithScores(memories)).map((c) => c.members);
|
|
112
|
+
}
|
|
113
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
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
|
+
export { SQLiteStore } from './store/sqlite.js';
|
|
8
|
+
export { InverseSearchEngine } from './core/search.js';
|
|
9
|
+
export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
|
|
10
|
+
export { generateMemoryLevels, setLLMClient } from './core/llm-generator.js';
|
|
11
|
+
export { systemClock, FakeClock } from './core/clock.js';
|
|
12
|
+
export { InMemoryEventBus } from './core/event-bus.js';
|
|
13
|
+
export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
|
|
14
|
+
export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
|
|
15
|
+
export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
|
|
16
|
+
export { processSession } from './agent/claude-hook.js';
|
|
17
|
+
export { parseClaudeHookPayload } from './agent/session-parser.js';
|
|
18
|
+
export { extractLearnings } from './agent/learning-extractor.js';
|
|
19
|
+
export type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MergeResult, Intention, Cue, IntentionStatus, CueStatus, CueKind, TriggerSpec, TimeTriggerSpec, EventTriggerSpec, NewIntention, NewCue, IntentionStore } from './core/types.js';
|
|
20
|
+
export type { StoreOptions } from './store/sqlite.js';
|
|
21
|
+
export type { Clock } from './core/clock.js';
|
|
22
|
+
export type { CueResolver, CueResolverOptions } from './core/cues.js';
|
|
23
|
+
export type { SessionContext, SessionContextOptions } from './agent/session-context.js';
|
|
24
|
+
export type { AppEvent, AppEventType, AppEventOf, EventBus, EventHandler, Unsubscribe } from './core/event-bus.js';
|
|
25
|
+
export type { GeneratedLevels, LLMClient } from './core/llm-generator.js';
|
|
26
|
+
export type { ParsedSession, SessionMessage } from './agent/session-parser.js';
|
|
27
|
+
export type { ExtractedLearning } from './agent/learning-extractor.js';
|
|
28
|
+
export type { HookOptions, HookResult } from './agent/claude-hook.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
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
|
+
export { SQLiteStore } from './store/sqlite.js';
|
|
8
|
+
export { InverseSearchEngine } from './core/search.js';
|
|
9
|
+
export { calculateDecayLevel, calculateSaillance, calculateDecayRate, updateAllDecay, DECAY_CONFIG } from './core/decay.js';
|
|
10
|
+
export { generateMemoryLevels, setLLMClient } from './core/llm-generator.js';
|
|
11
|
+
export { systemClock, FakeClock } from './core/clock.js';
|
|
12
|
+
export { InMemoryEventBus } from './core/event-bus.js';
|
|
13
|
+
export { SqliteCueResolver, attachResolverToBus, intentionSaillance, parseCron, cronMatches, cronDueSince, eventTriggerMatches, loopId, extractLoopIds, matchIntentionByShortId } from './core/cues.js';
|
|
14
|
+
export { parseCueArg, formatTriggerSpec, CueArgError } from './core/cue-arg.js';
|
|
15
|
+
export { buildSessionContext, humanizeAge, DEFAULT_SESSION_BUDGET, DEFAULT_SAILLANCE_THRESHOLD } from './agent/session-context.js';
|
|
16
|
+
export { processSession } from './agent/claude-hook.js';
|
|
17
|
+
export { parseClaudeHookPayload } from './agent/session-parser.js';
|
|
18
|
+
export { extractLearnings } from './agent/learning-extractor.js';
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
export {};
|
|
@@ -0,0 +1,158 @@
|
|
|
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
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
23
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
import { SQLiteStore } from '../store/sqlite.js';
|
|
26
|
+
import { trustScore } from '../core/trust.js';
|
|
27
|
+
import { sanitizeTrace } from '../core/sanitize.js';
|
|
28
|
+
const store = new SQLiteStore(process.env.HUMEMORY_DB);
|
|
29
|
+
/**
|
|
30
|
+
* This process's agent identity. Not overridable per call — see the header.
|
|
31
|
+
* Register one server per agent in the client's MCP config:
|
|
32
|
+
* { "humemory": { "command": "bun", "args": ["run", "src/mcp/server.ts"],
|
|
33
|
+
* "env": { "HUMEMORY_AGENT": "claude" } } }
|
|
34
|
+
*/
|
|
35
|
+
const callingAgent = process.env.HUMEMORY_AGENT ?? 'unknown';
|
|
36
|
+
const server = new McpServer({
|
|
37
|
+
name: 'humemory',
|
|
38
|
+
version: '6.2.0',
|
|
39
|
+
});
|
|
40
|
+
/** Renders a memory for tool output — sanitized, never raw prompt material. */
|
|
41
|
+
function show(m) {
|
|
42
|
+
const trust = trustScore(m);
|
|
43
|
+
const text = sanitizeTrace(m.content, 300).text;
|
|
44
|
+
return [
|
|
45
|
+
`id: ${m.id}`,
|
|
46
|
+
`level: L${m.currentLevel} · saillance: ${m.saillance} · trust: ${trust}`,
|
|
47
|
+
`source: ${m.source ?? 'agent'}${m.agent ? ` (${m.agent})` : ''}${m.verified ? ` · verified:${m.verificationReason}` : ''}`,
|
|
48
|
+
`content: ${text}`,
|
|
49
|
+
].join('\n');
|
|
50
|
+
}
|
|
51
|
+
server.registerTool('humemory_add', {
|
|
52
|
+
description: 'Encode a new memory trace (decision, bug fix, lesson learned) into the shared store',
|
|
53
|
+
inputSchema: {
|
|
54
|
+
content: z.string().describe('What to remember'),
|
|
55
|
+
directory: z.string().optional().describe('Project path (defaults to cwd)'),
|
|
56
|
+
keywords: z.array(z.string()).optional(),
|
|
57
|
+
memoryType: z.enum(['episodic', 'semantic', 'procedural']).optional(),
|
|
58
|
+
},
|
|
59
|
+
}, async ({ content, directory, keywords, memoryType }) => {
|
|
60
|
+
const m = await store.add({
|
|
61
|
+
content,
|
|
62
|
+
directory: directory ?? process.cwd(),
|
|
63
|
+
day: new Date().toISOString().split('T')[0],
|
|
64
|
+
keywords: keywords ?? [],
|
|
65
|
+
sessionId: 'mcp',
|
|
66
|
+
memoryType: memoryType ?? 'semantic',
|
|
67
|
+
source: 'agent',
|
|
68
|
+
agent: callingAgent,
|
|
69
|
+
});
|
|
70
|
+
return { content: [{ type: 'text', text: `encoded:\n${show(m)}` }] };
|
|
71
|
+
});
|
|
72
|
+
server.registerTool('humemory_search', {
|
|
73
|
+
description: 'Inverse search — degraded layers first, like a human memory',
|
|
74
|
+
inputSchema: {
|
|
75
|
+
query: z.string(),
|
|
76
|
+
directory: z.string().optional(),
|
|
77
|
+
limit: z.number().optional(),
|
|
78
|
+
},
|
|
79
|
+
}, async ({ query, directory, limit }) => {
|
|
80
|
+
const results = await store.search({ query, directory, limit: limit ?? 5 });
|
|
81
|
+
if (!results.length)
|
|
82
|
+
return { content: [{ type: 'text', text: 'no trace' }] };
|
|
83
|
+
return {
|
|
84
|
+
content: [
|
|
85
|
+
{
|
|
86
|
+
type: 'text',
|
|
87
|
+
text: results.map((r) => `match@L${r.matchLevel} score ${r.score}\n${show(r.memory)}`).join('\n---\n'),
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
server.registerTool('humemory_recall', {
|
|
93
|
+
description: 'Recall a trace — reinforces it; a cross-agent recall earns the `reused` verification',
|
|
94
|
+
inputSchema: {
|
|
95
|
+
id: z.string(),
|
|
96
|
+
},
|
|
97
|
+
}, async ({ id }) => {
|
|
98
|
+
// identityTrusted: this agent id came from the process environment, not
|
|
99
|
+
// from the caller — so a cross-agent recall here is evidence, not a claim.
|
|
100
|
+
const m = await store.recall(id, callingAgent, { identityTrusted: true });
|
|
101
|
+
return { content: [{ type: 'text', text: `recalled:\n${show(m)}` }] };
|
|
102
|
+
});
|
|
103
|
+
server.registerTool('humemory_intent_add', {
|
|
104
|
+
description: 'Arm an open loop (prospective memory) with an optional time/event cue',
|
|
105
|
+
inputSchema: {
|
|
106
|
+
content: z.string(),
|
|
107
|
+
directory: z.string().optional(),
|
|
108
|
+
cron: z.string().optional().describe('5-field cron, e.g. "0 9 * * 1"'),
|
|
109
|
+
at: z.string().optional().describe('ISO datetime for a one-shot cue'),
|
|
110
|
+
},
|
|
111
|
+
}, async ({ content, directory, cron, at }) => {
|
|
112
|
+
const cues = [];
|
|
113
|
+
if (cron)
|
|
114
|
+
cues.push({ kind: 'time', cron });
|
|
115
|
+
else if (at)
|
|
116
|
+
cues.push({ kind: 'time', at });
|
|
117
|
+
const i = await store.addIntention({
|
|
118
|
+
content,
|
|
119
|
+
directory: directory ?? process.cwd(),
|
|
120
|
+
source: 'agent',
|
|
121
|
+
agent: callingAgent,
|
|
122
|
+
}, cues);
|
|
123
|
+
return { content: [{ type: 'text', text: `loop armed: ${i.id}\n${i.content}` }] };
|
|
124
|
+
});
|
|
125
|
+
server.registerTool('humemory_intent_close', {
|
|
126
|
+
description: 'Close an open loop by id (or short loop-XXXX id)',
|
|
127
|
+
inputSchema: { id: z.string() },
|
|
128
|
+
}, async ({ id }) => {
|
|
129
|
+
let target = await store.getIntention(id);
|
|
130
|
+
if (!target) {
|
|
131
|
+
const armed = await store.listIntentions({ status: ['armed', 'fired'], limit: 500 });
|
|
132
|
+
const { matchIntentionByShortId } = await import('../core/cues.js');
|
|
133
|
+
target = matchIntentionByShortId(armed, id.replace(/^loop-/, '')) ?? null;
|
|
134
|
+
}
|
|
135
|
+
if (!target)
|
|
136
|
+
return { content: [{ type: 'text', text: `no open loop matches ${id}` }] };
|
|
137
|
+
await store.updateIntentionStatus(target.id, 'closed', {});
|
|
138
|
+
return { content: [{ type: 'text', text: `closed: ${target.id}\n${target.content}` }] };
|
|
139
|
+
});
|
|
140
|
+
server.registerTool('humemory_dreams', {
|
|
141
|
+
description: 'List pending dream proposals (cross-session patterns awaiting human review)',
|
|
142
|
+
inputSchema: {},
|
|
143
|
+
}, async () => {
|
|
144
|
+
const pending = await store.listDreamProposals({ status: 'pending' });
|
|
145
|
+
if (!pending.length)
|
|
146
|
+
return { content: [{ type: 'text', text: 'no dream pending' }] };
|
|
147
|
+
return {
|
|
148
|
+
content: [
|
|
149
|
+
{
|
|
150
|
+
type: 'text',
|
|
151
|
+
text: pending
|
|
152
|
+
.map((p) => `[${p.kind}] ${p.id} — confidence ${p.confidence}\n${p.payload.slice(0, 400)}`)
|
|
153
|
+
.join('\n---\n'),
|
|
154
|
+
},
|
|
155
|
+
],
|
|
156
|
+
};
|
|
157
|
+
});
|
|
158
|
+
await server.connect(new StdioServerTransport());
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import type { Memory, SearchQuery, SearchResult, DecayLevel, MemoryStore, MemoryType, MergeResult, Intention, IntentionStatus, IntentionStore, NewIntention, Cue, CueKind, CueStatus, CueTargetKind, NewCue, TriggerSpec, Script, ScriptStatus, ScriptStore, NewScript, VerificationReason, Contradiction, ContradictResult, DreamProposal, DreamKind, DreamStatus } from '../core/types.js';
|
|
2
|
+
import { type LLMClient } from '../core/llm-generator.js';
|
|
3
|
+
import { type Clock } from '../core/clock.js';
|
|
4
|
+
export interface StoreOptions {
|
|
5
|
+
/** Time source. Defaults to `systemClock`; tests pass a `FakeClock`. */
|
|
6
|
+
clock?: Clock;
|
|
7
|
+
/**
|
|
8
|
+
* Encoding device id (Phase 6.0.1). Defaults to `$HUMEMORY_DEVICE`, then
|
|
9
|
+
* `os.hostname()`. Localization now; multi-device sync later.
|
|
10
|
+
*/
|
|
11
|
+
device?: string;
|
|
12
|
+
}
|
|
13
|
+
/** The only reasons a trace may be verified for — validated, never cast. */
|
|
14
|
+
export declare const VERIFICATION_REASONS: VerificationReason[];
|
|
15
|
+
export interface RecallOptions {
|
|
16
|
+
/**
|
|
17
|
+
* True when the caller's agent identity comes from the process rather than
|
|
18
|
+
* from the request — MCP stdio (one server per client, id from the env) or
|
|
19
|
+
* the CLI (a human at a terminal). The HTTP API must leave this false:
|
|
20
|
+
* `X-Humemory-Agent` is a header, and a header is a claim, not a fact.
|
|
21
|
+
* Only trusted identities can earn the `reused` verification.
|
|
22
|
+
*/
|
|
23
|
+
identityTrusted?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export declare class SQLiteStore implements MemoryStore, IntentionStore, ScriptStore {
|
|
26
|
+
private db;
|
|
27
|
+
private searchEngine;
|
|
28
|
+
private writeQueue;
|
|
29
|
+
private advisoryLock;
|
|
30
|
+
private clock;
|
|
31
|
+
/** Phase 6.0.1 — stamped on every trace/intention written by this process. */
|
|
32
|
+
readonly deviceId: string;
|
|
33
|
+
private enqueueWrite;
|
|
34
|
+
private withAdvisoryLock;
|
|
35
|
+
private enqueueWriteWithLock;
|
|
36
|
+
constructor(dbPath?: string, options?: StoreOptions);
|
|
37
|
+
private initSchema;
|
|
38
|
+
/** Snapshot the current derived levels before overwriting them (6.0.4). */
|
|
39
|
+
private revisionSnapshot;
|
|
40
|
+
/**
|
|
41
|
+
* Prospective memory schema (Phase 5.1). Idempotent: CREATE ... IF NOT EXISTS,
|
|
42
|
+
* so it replays on an existing database without a manual migration.
|
|
43
|
+
*/
|
|
44
|
+
private initProspectiveSchema;
|
|
45
|
+
private loadIntoMemory;
|
|
46
|
+
private rowToMemory;
|
|
47
|
+
private memoryToRow;
|
|
48
|
+
add(memory: Omit<Memory, 'id' | 'createdAt' | 'recallCount' | 'decayRate' | 'currentLevel' | 'saillance'>, options?: {
|
|
49
|
+
autoGenerate?: boolean;
|
|
50
|
+
}): Promise<Memory>;
|
|
51
|
+
getById(id: string): Promise<Memory | null>;
|
|
52
|
+
search(query: SearchQuery): Promise<SearchResult[]>;
|
|
53
|
+
recall(id: string, agent?: string, options?: RecallOptions): Promise<Memory>;
|
|
54
|
+
/**
|
|
55
|
+
* Phase 6.0.1 — human override verification (`pnpm cli verify <id>`).
|
|
56
|
+
* Automatic paths (reused/grounded/corroborated) set the flag directly.
|
|
57
|
+
*/
|
|
58
|
+
verify(id: string, by?: string): Promise<Memory>;
|
|
59
|
+
/**
|
|
60
|
+
* Phase 6.0.1 — negative signal without a full contradiction (6.0.2):
|
|
61
|
+
* increments refuted_count (feeds the trust score) and revokes any earned
|
|
62
|
+
* verification — a refuted trace must be re-earned, not remembered.
|
|
63
|
+
*/
|
|
64
|
+
refute(id: string, _reason?: string): Promise<Memory>;
|
|
65
|
+
updateDecay(): Promise<void>;
|
|
66
|
+
delete(id: string): Promise<void>;
|
|
67
|
+
list(options?: {
|
|
68
|
+
limit?: number;
|
|
69
|
+
level?: DecayLevel;
|
|
70
|
+
levels?: DecayLevel[];
|
|
71
|
+
type?: MemoryType;
|
|
72
|
+
directory?: string;
|
|
73
|
+
minSaillance?: number;
|
|
74
|
+
}): Promise<Memory[]>;
|
|
75
|
+
setPhotographic(id: string, value: boolean): Promise<Memory>;
|
|
76
|
+
findSimilar(id: string, options?: {
|
|
77
|
+
limit?: number;
|
|
78
|
+
threshold?: number;
|
|
79
|
+
}): Promise<SearchResult[]>;
|
|
80
|
+
merge(sourceId: string, targetId: string, options?: {
|
|
81
|
+
autoMergeContent?: boolean;
|
|
82
|
+
client?: LLMClient;
|
|
83
|
+
}): Promise<MergeResult>;
|
|
84
|
+
/**
|
|
85
|
+
* Phase 6.0.4 — revert a merge: the source trace is resurrected (level and
|
|
86
|
+
* saillance recomputed, not literally restored — decayed time does not come
|
|
87
|
+
* back), and the target gets its last revised levels back when a revision
|
|
88
|
+
* exists.
|
|
89
|
+
*/
|
|
90
|
+
unmerge(sourceId: string): Promise<{
|
|
91
|
+
source: Memory;
|
|
92
|
+
target: Memory;
|
|
93
|
+
}>;
|
|
94
|
+
/**
|
|
95
|
+
* `winnerId` contradicts `loserId`. The loser collapses (÷4, floor 5; ÷2 on
|
|
96
|
+
* further refutations, cap 3) and loses any earned verification — but is
|
|
97
|
+
* never deleted. Cycles are allowed: last write wins, no transitivity is
|
|
98
|
+
* ever inferred.
|
|
99
|
+
*/
|
|
100
|
+
contradict(winnerId: string, loserId: string, options?: {
|
|
101
|
+
reason?: string;
|
|
102
|
+
createdBy?: 'agent' | 'human' | 'dreamer';
|
|
103
|
+
agent?: string;
|
|
104
|
+
}): Promise<ContradictResult>;
|
|
105
|
+
/**
|
|
106
|
+
* Phase 8.4 — "correction kills the script": a memory contradicts a
|
|
107
|
+
* script's steps directly, and the script is archived outright rather than
|
|
108
|
+
* saillance-collapsed. Two differences from the memory-loser path:
|
|
109
|
+
*
|
|
110
|
+
* - No asymmetric-authority gate. That gate exists because a memory can be
|
|
111
|
+
* `verified` and an unverified winner shouldn't outrank it unchallenged
|
|
112
|
+
* (6.0.2). `Script` carries no `verified`/`verificationReason` field —
|
|
113
|
+
* nothing to be asymmetric *about* — so every script contradiction
|
|
114
|
+
* applies directly. If scripts grow their own verification concept
|
|
115
|
+
* later, this is the place to add the gate.
|
|
116
|
+
* - Archival, not saillance math. A script's saillance already means
|
|
117
|
+
* something else (disuse, 8.4's sweep) — collapsing it the way a
|
|
118
|
+
* memory's saillance collapses would just confuse two different scales.
|
|
119
|
+
* "Wrong" and "unused" are different failure modes with the same cure:
|
|
120
|
+
* stop injecting it.
|
|
121
|
+
*
|
|
122
|
+
* Reuses the `script_archived` notice from the disuse sweep (same kind,
|
|
123
|
+
* `payload.reason` distinguishes the two) rather than inventing a second
|
|
124
|
+
* notice type for what a human reviews identically either way.
|
|
125
|
+
*/
|
|
126
|
+
private contradictScript;
|
|
127
|
+
/**
|
|
128
|
+
* Revocation restores the trust judgment, not the automation wiring.
|
|
129
|
+
*
|
|
130
|
+
* Memory loser: saillance is recomputed, not restored to its pre-collapse
|
|
131
|
+
* literal value — decayed time does not come back (6.0.2, Kimi B10).
|
|
132
|
+
*
|
|
133
|
+
* Script loser (8.4): status flips back to `active`. Its cues stay
|
|
134
|
+
* `cancelled` — re-arming a drill's wake-ups is a deliberate act the human
|
|
135
|
+
* takes explicitly (`script activate`/cue add), not something a revoke
|
|
136
|
+
* should do silently on their behalf. A revoked-but-cueless script is
|
|
137
|
+
* visible again in `script list`; it just won't fire until re-armed.
|
|
138
|
+
*/
|
|
139
|
+
revokeContradiction(id: string): Promise<Contradiction>;
|
|
140
|
+
listContradictions(options?: {
|
|
141
|
+
loserId?: string;
|
|
142
|
+
status?: 'active' | 'revoked';
|
|
143
|
+
}): Promise<Contradiction[]>;
|
|
144
|
+
private rowToContradiction;
|
|
145
|
+
private rowToDream;
|
|
146
|
+
fileDreamProposal(p: {
|
|
147
|
+
kind: DreamKind;
|
|
148
|
+
payload: string;
|
|
149
|
+
payloadHash: string;
|
|
150
|
+
confidence?: number;
|
|
151
|
+
expiresAt?: Date;
|
|
152
|
+
}): Promise<boolean>;
|
|
153
|
+
listDreamProposals(options?: {
|
|
154
|
+
status?: DreamStatus;
|
|
155
|
+
includeExpired?: boolean;
|
|
156
|
+
}): Promise<DreamProposal[]>;
|
|
157
|
+
resolveDreamProposal(id: string, status: 'approved' | 'rejected', resolvedBy?: string): Promise<DreamProposal>;
|
|
158
|
+
expireDreamProposals(): Promise<number>;
|
|
159
|
+
setEmbedding(memoryId: string, modelId: string, embedding: Float32Array): Promise<void>;
|
|
160
|
+
getEmbedding(memoryId: string): Promise<{
|
|
161
|
+
modelId: string;
|
|
162
|
+
embedding: Float32Array;
|
|
163
|
+
} | null>;
|
|
164
|
+
/** All stored embeddings, optionally filtered. The dreamer brute-forces over these. */
|
|
165
|
+
listEmbeddings(options?: {
|
|
166
|
+
modelId?: string;
|
|
167
|
+
}): Promise<{
|
|
168
|
+
memoryId: string;
|
|
169
|
+
embedding: Float32Array;
|
|
170
|
+
}[]>;
|
|
171
|
+
/** Traces with no embedding for this model (or a stale one) — the backfill queue. */
|
|
172
|
+
listMissingEmbeddings(modelId: string, limit?: number): Promise<Memory[]>;
|
|
173
|
+
/** A4 — the ONLY correct response to a level mutation: delete; next batch re-embeds. */
|
|
174
|
+
deleteEmbeddings(memoryIds: string[]): Promise<void>;
|
|
175
|
+
private rowToIntention;
|
|
176
|
+
private rowToCue;
|
|
177
|
+
/**
|
|
178
|
+
* Arms an intention, and optionally its cues in the same breath — both writes
|
|
179
|
+
* go through the same lock, so an intention can never be observed without the
|
|
180
|
+
* cues meant to wake it.
|
|
181
|
+
*/
|
|
182
|
+
addIntention(intention: NewIntention, cues?: TriggerSpec[]): Promise<Intention>;
|
|
183
|
+
private insertCueRow;
|
|
184
|
+
getIntention(id: string): Promise<Intention | null>;
|
|
185
|
+
listIntentions(options?: {
|
|
186
|
+
status?: IntentionStatus | IntentionStatus[];
|
|
187
|
+
directory?: string;
|
|
188
|
+
limit?: number;
|
|
189
|
+
}): Promise<Intention[]>;
|
|
190
|
+
/**
|
|
191
|
+
* Status transitions. Timestamps come from the injected clock: `fired` sets
|
|
192
|
+
* `fired_at`, `closed` sets `closed_at` (plus the SHA when given). `expired` is
|
|
193
|
+
* a soft delete — the row stays, for the record.
|
|
194
|
+
*/
|
|
195
|
+
updateIntentionStatus(id: string, status: IntentionStatus, options?: {
|
|
196
|
+
closedByCommit?: string;
|
|
197
|
+
}): Promise<Intention>;
|
|
198
|
+
/** Deletes the intention and its cues — explicit since Phase 8.1 (the generic
|
|
199
|
+
* target can no longer carry a single-table FK cascade). */
|
|
200
|
+
deleteIntention(id: string): Promise<void>;
|
|
201
|
+
addCue(cue: NewCue): Promise<Cue>;
|
|
202
|
+
getCue(id: string): Promise<Cue | null>;
|
|
203
|
+
listCues(options?: {
|
|
204
|
+
intentionId?: string;
|
|
205
|
+
targetKind?: CueTargetKind;
|
|
206
|
+
targetId?: string;
|
|
207
|
+
status?: CueStatus | CueStatus[];
|
|
208
|
+
kind?: CueKind;
|
|
209
|
+
limit?: number;
|
|
210
|
+
}): Promise<Cue[]>;
|
|
211
|
+
/**
|
|
212
|
+
* Marks a cue as fired. `rearm: true` leaves it `armed` while still recording
|
|
213
|
+
* `fired_at` — what a recurring (cron) cue needs: without it, a recurrence would
|
|
214
|
+
* be a one-shot in disguise.
|
|
215
|
+
*/
|
|
216
|
+
markCueFired(id: string, options?: {
|
|
217
|
+
rearm?: boolean;
|
|
218
|
+
}): Promise<Cue>;
|
|
219
|
+
updateCueStatus(id: string, status: CueStatus): Promise<Cue>;
|
|
220
|
+
private rowToScript;
|
|
221
|
+
addScript(script: NewScript, cues?: TriggerSpec[]): Promise<Script>;
|
|
222
|
+
getScript(id: string): Promise<Script | null>;
|
|
223
|
+
getScriptByName(name: string, directory: string): Promise<Script | null>;
|
|
224
|
+
listScripts(options?: {
|
|
225
|
+
status?: ScriptStatus | ScriptStatus[];
|
|
226
|
+
directory?: string;
|
|
227
|
+
limit?: number;
|
|
228
|
+
}): Promise<Script[]>;
|
|
229
|
+
updateScriptStatus(id: string, status: ScriptStatus): Promise<Script>;
|
|
230
|
+
updateScript(id: string, patch: {
|
|
231
|
+
name?: string;
|
|
232
|
+
description?: string;
|
|
233
|
+
steps?: string[];
|
|
234
|
+
pinned?: boolean;
|
|
235
|
+
}): Promise<Script>;
|
|
236
|
+
/** Firing a drill: fire_count +1, last_fired_at, saillance +5 capped at 100 (8.2). */
|
|
237
|
+
markScriptFired(id: string): Promise<Script>;
|
|
238
|
+
deleteScript(id: string): Promise<void>;
|
|
239
|
+
close(): void;
|
|
240
|
+
}
|