agent-working-memory 0.3.1 → 0.4.0
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/README.md +84 -72
- package/dist/api/routes.d.ts.map +1 -1
- package/dist/api/routes.js +3 -1
- package/dist/api/routes.js.map +1 -1
- package/dist/cli.js +106 -28
- package/dist/cli.js.map +1 -1
- package/dist/core/logger.d.ts +12 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +32 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/salience.d.ts +14 -0
- package/dist/core/salience.d.ts.map +1 -1
- package/dist/core/salience.js +51 -5
- package/dist/core/salience.js.map +1 -1
- package/dist/hooks/sidecar.d.ts +27 -0
- package/dist/hooks/sidecar.d.ts.map +1 -0
- package/dist/hooks/sidecar.js +188 -0
- package/dist/hooks/sidecar.js.map +1 -0
- package/dist/mcp.js +632 -417
- package/dist/mcp.js.map +1 -1
- package/package.json +1 -1
- package/src/api/routes.ts +4 -1
- package/src/cli.ts +113 -28
- package/src/core/logger.ts +34 -0
- package/src/core/salience.ts +51 -5
- package/src/hooks/sidecar.ts +231 -0
- package/src/mcp.ts +275 -25
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook Sidecar — lightweight HTTP server that runs alongside the MCP process.
|
|
3
|
+
*
|
|
4
|
+
* Claude Code hooks (PreCompact, SessionEnd, etc.) send POST requests here.
|
|
5
|
+
* Since we share the same process as the MCP server, there's zero SQLite
|
|
6
|
+
* contention — we use the same store/engines directly.
|
|
7
|
+
*
|
|
8
|
+
* Endpoints:
|
|
9
|
+
* POST /hooks/checkpoint — auto-checkpoint (called by PreCompact, SessionEnd hooks)
|
|
10
|
+
* GET /health — health check
|
|
11
|
+
*
|
|
12
|
+
* Security:
|
|
13
|
+
* - Binds to 127.0.0.1 only (localhost)
|
|
14
|
+
* - Bearer token auth via AWM_HOOK_SECRET
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
18
|
+
import { readFileSync } from 'node:fs';
|
|
19
|
+
import type { EngramStore } from '../storage/sqlite.js';
|
|
20
|
+
import type { ConsciousState } from '../types/checkpoint.js';
|
|
21
|
+
import { log } from '../core/logger.js';
|
|
22
|
+
|
|
23
|
+
export interface SidecarDeps {
|
|
24
|
+
store: EngramStore;
|
|
25
|
+
agentId: string;
|
|
26
|
+
secret: string | null;
|
|
27
|
+
port: number;
|
|
28
|
+
onConsolidate?: (agentId: string, reason: string) => void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface HookInput {
|
|
32
|
+
session_id?: string;
|
|
33
|
+
transcript_path?: string;
|
|
34
|
+
hook_event_name?: string;
|
|
35
|
+
cwd?: string;
|
|
36
|
+
tool_name?: string;
|
|
37
|
+
tool_input?: Record<string, unknown>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface TranscriptContext {
|
|
41
|
+
currentTask: string;
|
|
42
|
+
activeFiles: string[];
|
|
43
|
+
recentTools: string[];
|
|
44
|
+
lastUserMessage: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Parse the Claude Code transcript to extract context for auto-checkpointing.
|
|
49
|
+
* Reads the JSONL transcript file and extracts recent tool calls, files, and user messages.
|
|
50
|
+
*/
|
|
51
|
+
function parseTranscript(transcriptPath: string): TranscriptContext {
|
|
52
|
+
const ctx: TranscriptContext = {
|
|
53
|
+
currentTask: '',
|
|
54
|
+
activeFiles: [],
|
|
55
|
+
recentTools: [],
|
|
56
|
+
lastUserMessage: '',
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const raw = readFileSync(transcriptPath, 'utf-8');
|
|
61
|
+
const lines = raw.trim().split('\n').filter(Boolean);
|
|
62
|
+
|
|
63
|
+
const files = new Set<string>();
|
|
64
|
+
const tools: string[] = [];
|
|
65
|
+
let lastUserMsg = '';
|
|
66
|
+
|
|
67
|
+
// Parse last 100 lines max to avoid huge transcripts
|
|
68
|
+
const recent = lines.slice(-100);
|
|
69
|
+
|
|
70
|
+
for (const line of recent) {
|
|
71
|
+
try {
|
|
72
|
+
const entry = JSON.parse(line);
|
|
73
|
+
|
|
74
|
+
// Extract user messages
|
|
75
|
+
if (entry.role === 'user' && typeof entry.content === 'string') {
|
|
76
|
+
lastUserMsg = entry.content.slice(0, 200);
|
|
77
|
+
}
|
|
78
|
+
if (entry.role === 'user' && Array.isArray(entry.content)) {
|
|
79
|
+
for (const part of entry.content) {
|
|
80
|
+
if (part.type === 'text' && typeof part.text === 'string') {
|
|
81
|
+
lastUserMsg = part.text.slice(0, 200);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Extract tool uses
|
|
87
|
+
if (entry.role === 'assistant' && Array.isArray(entry.content)) {
|
|
88
|
+
for (const part of entry.content) {
|
|
89
|
+
if (part.type === 'tool_use') {
|
|
90
|
+
tools.push(part.name);
|
|
91
|
+
// Extract file paths from tool inputs
|
|
92
|
+
const input = part.input;
|
|
93
|
+
if (input?.file_path) files.add(String(input.file_path));
|
|
94
|
+
if (input?.path) files.add(String(input.path));
|
|
95
|
+
if (input?.command && typeof input.command === 'string') {
|
|
96
|
+
// Try to extract file paths from bash commands
|
|
97
|
+
const pathMatch = input.command.match(/["']?([A-Z]:[/\\][^"'\s]+|\/[^\s"']+\.\w+)["']?/g);
|
|
98
|
+
if (pathMatch) pathMatch.forEach((p: string) => files.add(p.replace(/["']/g, '')));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
// Skip malformed lines
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
ctx.lastUserMessage = lastUserMsg;
|
|
109
|
+
ctx.activeFiles = [...files].slice(-20); // Last 20 unique files
|
|
110
|
+
ctx.recentTools = tools.slice(-30); // Last 30 tool calls
|
|
111
|
+
ctx.currentTask = lastUserMsg || 'Unknown task (auto-checkpoint)';
|
|
112
|
+
} catch {
|
|
113
|
+
ctx.currentTask = 'Auto-checkpoint (transcript unavailable)';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return ctx;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readBody(req: IncomingMessage): Promise<string> {
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
const chunks: Buffer[] = [];
|
|
122
|
+
req.on('data', (chunk: Buffer) => chunks.push(chunk));
|
|
123
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString()));
|
|
124
|
+
req.on('error', reject);
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function json(res: ServerResponse, status: number, body: Record<string, unknown>) {
|
|
129
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
130
|
+
res.end(JSON.stringify(body));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function startSidecar(deps: SidecarDeps): { close: () => void } {
|
|
134
|
+
const { store, agentId, secret, port, onConsolidate } = deps;
|
|
135
|
+
|
|
136
|
+
const server = createServer(async (req, res) => {
|
|
137
|
+
// CORS preflight
|
|
138
|
+
if (req.method === 'OPTIONS') {
|
|
139
|
+
res.writeHead(204);
|
|
140
|
+
res.end();
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Health check — no auth required
|
|
145
|
+
if (req.url === '/health' && req.method === 'GET') {
|
|
146
|
+
json(res, 200, { status: 'ok', sidecar: true, agentId });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Auth check
|
|
151
|
+
if (secret) {
|
|
152
|
+
const auth = req.headers.authorization;
|
|
153
|
+
if (auth !== `Bearer ${secret}`) {
|
|
154
|
+
json(res, 401, { error: 'Unauthorized' });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// POST /hooks/checkpoint — auto-checkpoint from hook events
|
|
160
|
+
if (req.url === '/hooks/checkpoint' && req.method === 'POST') {
|
|
161
|
+
try {
|
|
162
|
+
const body = await readBody(req);
|
|
163
|
+
const hookInput: HookInput = body ? JSON.parse(body) : {};
|
|
164
|
+
const event = hookInput.hook_event_name ?? 'unknown';
|
|
165
|
+
|
|
166
|
+
// Parse transcript for rich context
|
|
167
|
+
let ctx: TranscriptContext | null = null;
|
|
168
|
+
if (hookInput.transcript_path) {
|
|
169
|
+
ctx = parseTranscript(hookInput.transcript_path);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Build checkpoint state
|
|
173
|
+
const state: ConsciousState = {
|
|
174
|
+
currentTask: ctx?.currentTask ?? `Auto-checkpoint (${event})`,
|
|
175
|
+
decisions: [],
|
|
176
|
+
activeFiles: ctx?.activeFiles ?? [],
|
|
177
|
+
nextSteps: [],
|
|
178
|
+
relatedMemoryIds: [],
|
|
179
|
+
notes: `Auto-saved by ${event} hook.${ctx?.recentTools.length ? ` Recent tools: ${[...new Set(ctx.recentTools)].join(', ')}` : ''}`,
|
|
180
|
+
episodeId: null,
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
store.saveCheckpoint(agentId, state);
|
|
184
|
+
log(agentId, `hook:${event}`, `auto-checkpoint files=${state.activeFiles.length} task="${state.currentTask.slice(0, 80)}"`);
|
|
185
|
+
|
|
186
|
+
// On SessionEnd: run full consolidation (sleep cycle) before process dies
|
|
187
|
+
let consolidated = false;
|
|
188
|
+
if (event === 'SessionEnd' && onConsolidate) {
|
|
189
|
+
try {
|
|
190
|
+
onConsolidate(agentId, `SessionEnd hook (graceful exit)`);
|
|
191
|
+
consolidated = true;
|
|
192
|
+
log(agentId, 'consolidation', 'full sleep cycle on graceful exit');
|
|
193
|
+
} catch { /* consolidation failure is non-fatal */ }
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Return context for Claude (stdout from hooks is visible)
|
|
197
|
+
json(res, 200, {
|
|
198
|
+
status: 'checkpointed',
|
|
199
|
+
event,
|
|
200
|
+
task: state.currentTask,
|
|
201
|
+
files: state.activeFiles.length,
|
|
202
|
+
consolidated,
|
|
203
|
+
});
|
|
204
|
+
} catch (err) {
|
|
205
|
+
json(res, 500, { error: 'Checkpoint failed', detail: String(err) });
|
|
206
|
+
}
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// 404
|
|
211
|
+
json(res, 404, { error: 'Not found' });
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
server.listen(port, '127.0.0.1', () => {
|
|
215
|
+
console.error(`AWM hook sidecar listening on 127.0.0.1:${port}`);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
server.on('error', (err: NodeJS.ErrnoException) => {
|
|
219
|
+
if (err.code === 'EADDRINUSE') {
|
|
220
|
+
console.error(`AWM hook sidecar: port ${port} in use, hooks disabled`);
|
|
221
|
+
} else {
|
|
222
|
+
console.error('AWM hook sidecar error:', err.message);
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
close: () => {
|
|
228
|
+
server.close();
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
package/src/mcp.ts
CHANGED
|
@@ -51,17 +51,41 @@ import { RetractionEngine } from './engine/retraction.js';
|
|
|
51
51
|
import { EvalEngine } from './engine/eval.js';
|
|
52
52
|
import { ConsolidationEngine } from './engine/consolidation.js';
|
|
53
53
|
import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
|
|
54
|
-
import { evaluateSalience } from './core/salience.js';
|
|
54
|
+
import { evaluateSalience, computeNovelty } from './core/salience.js';
|
|
55
55
|
import type { ConsciousState } from './types/checkpoint.js';
|
|
56
56
|
import type { SalienceEventType } from './core/salience.js';
|
|
57
57
|
import type { TaskStatus, TaskPriority } from './types/engram.js';
|
|
58
58
|
import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
|
|
59
59
|
import { embed } from './core/embeddings.js';
|
|
60
|
+
import { startSidecar } from './hooks/sidecar.js';
|
|
61
|
+
import { initLogger, log, getLogPath } from './core/logger.js';
|
|
62
|
+
|
|
63
|
+
// --- Incognito Mode ---
|
|
64
|
+
// When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
|
|
65
|
+
// No DB, no engines, no sidecar — just a bare MCP server that exposes nothing.
|
|
66
|
+
|
|
67
|
+
const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
|
|
68
|
+
|
|
69
|
+
if (INCOGNITO) {
|
|
70
|
+
console.error('AWM: incognito mode — all memory tools disabled, nothing will be recorded');
|
|
71
|
+
const server = new McpServer({ name: 'agent-working-memory', version: '0.4.0' });
|
|
72
|
+
const transport = new StdioServerTransport();
|
|
73
|
+
server.connect(transport).catch(err => {
|
|
74
|
+
console.error('MCP server failed:', err);
|
|
75
|
+
process.exit(1);
|
|
76
|
+
});
|
|
77
|
+
// No tools registered — Claude won't see any memory_* tools
|
|
78
|
+
} else {
|
|
60
79
|
|
|
61
80
|
// --- Setup ---
|
|
62
81
|
|
|
63
82
|
const DB_PATH = process.env.AWM_DB_PATH ?? 'memory.db';
|
|
64
83
|
const AGENT_ID = process.env.AWM_AGENT_ID ?? 'claude-code';
|
|
84
|
+
const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
|
|
85
|
+
const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
|
|
86
|
+
|
|
87
|
+
initLogger(DB_PATH);
|
|
88
|
+
log(AGENT_ID, 'startup', `MCP server starting (db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
|
|
65
89
|
|
|
66
90
|
const store = new EngramStore(DB_PATH);
|
|
67
91
|
const activationEngine = new ActivationEngine(store);
|
|
@@ -78,7 +102,7 @@ consolidationScheduler.start();
|
|
|
78
102
|
|
|
79
103
|
const server = new McpServer({
|
|
80
104
|
name: 'agent-working-memory',
|
|
81
|
-
version: '0.
|
|
105
|
+
version: '0.4.0',
|
|
82
106
|
});
|
|
83
107
|
|
|
84
108
|
// --- Tools ---
|
|
@@ -87,11 +111,12 @@ server.tool(
|
|
|
87
111
|
'memory_write',
|
|
88
112
|
`Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
|
|
89
113
|
|
|
90
|
-
|
|
91
|
-
-
|
|
92
|
-
-
|
|
93
|
-
-
|
|
94
|
-
-
|
|
114
|
+
CALL THIS PROACTIVELY — do not wait to be asked. Write memories when you:
|
|
115
|
+
- Discover something about the codebase, bugs, or architecture
|
|
116
|
+
- Make a decision and want to remember why
|
|
117
|
+
- Encounter and resolve an error
|
|
118
|
+
- Learn a user preference or project pattern
|
|
119
|
+
- Complete a significant piece of work
|
|
95
120
|
|
|
96
121
|
The concept should be a short label (3-8 words). The content should be the full detail.`,
|
|
97
122
|
{
|
|
@@ -111,6 +136,9 @@ The concept should be a short label (3-8 words). The content should be the full
|
|
|
111
136
|
.describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
|
|
112
137
|
},
|
|
113
138
|
async (params) => {
|
|
139
|
+
// Check novelty — is this new information or a duplicate?
|
|
140
|
+
const novelty = computeNovelty(store, AGENT_ID, params.concept, params.content);
|
|
141
|
+
|
|
114
142
|
const salience = evaluateSalience({
|
|
115
143
|
content: params.content,
|
|
116
144
|
eventType: params.event_type as SalienceEventType,
|
|
@@ -118,13 +146,15 @@ The concept should be a short label (3-8 words). The content should be the full
|
|
|
118
146
|
decisionMade: params.decision_made,
|
|
119
147
|
causalDepth: params.causal_depth,
|
|
120
148
|
resolutionEffort: params.resolution_effort,
|
|
149
|
+
novelty,
|
|
121
150
|
});
|
|
122
151
|
|
|
123
152
|
if (salience.disposition === 'discard') {
|
|
153
|
+
log(AGENT_ID, 'write:discard', `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)}`);
|
|
124
154
|
return {
|
|
125
155
|
content: [{
|
|
126
156
|
type: 'text' as const,
|
|
127
|
-
text: `Memory discarded (salience ${salience.score.toFixed(2)} below threshold). Not worth storing.`,
|
|
157
|
+
text: `Memory discarded (salience ${salience.score.toFixed(2)} below threshold, novelty ${novelty.toFixed(1)}). Not worth storing.`,
|
|
128
158
|
}],
|
|
129
159
|
};
|
|
130
160
|
}
|
|
@@ -154,6 +184,8 @@ The concept should be a short label (3-8 words). The content should be the full
|
|
|
154
184
|
// Auto-checkpoint: track write
|
|
155
185
|
try { store.updateAutoCheckpointWrite(AGENT_ID, engram.id); } catch { /* non-fatal */ }
|
|
156
186
|
|
|
187
|
+
log(AGENT_ID, `write:${salience.disposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
|
|
188
|
+
|
|
157
189
|
return {
|
|
158
190
|
content: [{
|
|
159
191
|
type: 'text' as const,
|
|
@@ -165,16 +197,19 @@ The concept should be a short label (3-8 words). The content should be the full
|
|
|
165
197
|
|
|
166
198
|
server.tool(
|
|
167
199
|
'memory_recall',
|
|
168
|
-
`Recall memories relevant to a
|
|
200
|
+
`Recall memories relevant to a query. Uses cognitive activation — not keyword search.
|
|
169
201
|
|
|
170
|
-
|
|
171
|
-
- Starting a
|
|
202
|
+
ALWAYS call this when:
|
|
203
|
+
- Starting work on a project or topic (recall what you know)
|
|
172
204
|
- Debugging (recall similar errors and solutions)
|
|
173
205
|
- Making decisions (recall past decisions and outcomes)
|
|
206
|
+
- The user mentions a topic you might have stored memories about
|
|
174
207
|
|
|
175
|
-
|
|
208
|
+
Accepts either "query" or "context" parameter — both work identically.
|
|
209
|
+
Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`,
|
|
176
210
|
{
|
|
177
|
-
|
|
211
|
+
query: z.string().optional().describe('What to search for — describe the situation, question, or topic'),
|
|
212
|
+
context: z.string().optional().describe('Alias for query (either works)'),
|
|
178
213
|
limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
|
|
179
214
|
min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
|
|
180
215
|
include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
|
|
@@ -182,9 +217,18 @@ Returns the most relevant memories ranked by a composite score of text relevance
|
|
|
182
217
|
use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
|
|
183
218
|
},
|
|
184
219
|
async (params) => {
|
|
220
|
+
const queryText = params.query ?? params.context;
|
|
221
|
+
if (!queryText) {
|
|
222
|
+
return {
|
|
223
|
+
content: [{
|
|
224
|
+
type: 'text' as const,
|
|
225
|
+
text: 'Error: provide either "query" or "context" parameter with your search text.',
|
|
226
|
+
}],
|
|
227
|
+
};
|
|
228
|
+
}
|
|
185
229
|
const results = await activationEngine.activate({
|
|
186
230
|
agentId: AGENT_ID,
|
|
187
|
-
context:
|
|
231
|
+
context: queryText,
|
|
188
232
|
limit: params.limit,
|
|
189
233
|
minScore: params.min_score,
|
|
190
234
|
includeStaging: params.include_staging,
|
|
@@ -195,9 +239,11 @@ Returns the most relevant memories ranked by a composite score of text relevance
|
|
|
195
239
|
// Auto-checkpoint: track recall
|
|
196
240
|
try {
|
|
197
241
|
const ids = results.map(r => r.engram.id);
|
|
198
|
-
store.updateAutoCheckpointRecall(AGENT_ID,
|
|
242
|
+
store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
|
|
199
243
|
} catch { /* non-fatal */ }
|
|
200
244
|
|
|
245
|
+
log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" → ${results.length} results`);
|
|
246
|
+
|
|
201
247
|
if (results.length === 0) {
|
|
202
248
|
return {
|
|
203
249
|
content: [{
|
|
@@ -286,10 +332,12 @@ Use this when you discover a memory contains incorrect information.`,
|
|
|
286
332
|
|
|
287
333
|
server.tool(
|
|
288
334
|
'memory_stats',
|
|
289
|
-
`Get memory health stats — how many memories, confidence levels, association count, and system performance
|
|
335
|
+
`Get memory health stats — how many memories, confidence levels, association count, and system performance.
|
|
336
|
+
Also shows the activity log path so the user can tail it to see what's happening.`,
|
|
290
337
|
{},
|
|
291
338
|
async () => {
|
|
292
339
|
const metrics = evalEngine.computeMetrics(AGENT_ID);
|
|
340
|
+
const checkpoint = store.getCheckpoint(AGENT_ID);
|
|
293
341
|
const lines = [
|
|
294
342
|
`Agent: ${AGENT_ID}`,
|
|
295
343
|
`Active memories: ${metrics.activeEngramCount}`,
|
|
@@ -300,6 +348,14 @@ server.tool(
|
|
|
300
348
|
`Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
|
|
301
349
|
`Activations (24h): ${metrics.activationCount}`,
|
|
302
350
|
`Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
|
|
351
|
+
``,
|
|
352
|
+
`Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
|
|
353
|
+
`Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
|
|
354
|
+
`Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
|
|
355
|
+
`Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
|
|
356
|
+
``,
|
|
357
|
+
`Activity log: ${getLogPath() ?? 'not configured'}`,
|
|
358
|
+
`Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
|
|
303
359
|
];
|
|
304
360
|
|
|
305
361
|
return {
|
|
@@ -317,12 +373,12 @@ server.tool(
|
|
|
317
373
|
'memory_checkpoint',
|
|
318
374
|
`Save your current execution state so you can recover after context compaction.
|
|
319
375
|
|
|
320
|
-
|
|
321
|
-
-
|
|
322
|
-
-
|
|
323
|
-
-
|
|
376
|
+
ALWAYS call this before:
|
|
377
|
+
- Long operations (multi-file generation, large refactors, overnight work)
|
|
378
|
+
- Anything that might fill the context window
|
|
379
|
+
- Switching to a different task
|
|
324
380
|
|
|
325
|
-
The state is saved per-agent and overwrites any previous checkpoint.`,
|
|
381
|
+
Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`,
|
|
326
382
|
{
|
|
327
383
|
current_task: z.string().describe('What you are currently working on'),
|
|
328
384
|
decisions: z.array(z.string()).optional().default([])
|
|
@@ -350,6 +406,7 @@ The state is saved per-agent and overwrites any previous checkpoint.`,
|
|
|
350
406
|
};
|
|
351
407
|
|
|
352
408
|
store.saveCheckpoint(AGENT_ID, state);
|
|
409
|
+
log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
|
|
353
410
|
|
|
354
411
|
return {
|
|
355
412
|
content: [{
|
|
@@ -414,18 +471,44 @@ Use this at the start of every session or after compaction to pick up where you
|
|
|
414
471
|
} catch { /* recall failure is non-fatal */ }
|
|
415
472
|
}
|
|
416
473
|
|
|
417
|
-
//
|
|
474
|
+
// Consolidation on restore:
|
|
475
|
+
// - If idle >5min but last consolidation was recent (graceful exit ran it), skip
|
|
476
|
+
// - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
|
|
418
477
|
const MINI_IDLE_MS = 5 * 60_000;
|
|
478
|
+
const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min — if last consolidation was longer ago, run full
|
|
419
479
|
let miniConsolidationTriggered = false;
|
|
480
|
+
let fullConsolidationTriggered = false;
|
|
481
|
+
|
|
420
482
|
if (idleMs > MINI_IDLE_MS) {
|
|
421
|
-
|
|
422
|
-
|
|
483
|
+
const sinceLastConsolidation = checkpoint?.lastConsolidationAt
|
|
484
|
+
? now - checkpoint.lastConsolidationAt.getTime()
|
|
485
|
+
: Infinity;
|
|
486
|
+
|
|
487
|
+
if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
|
|
488
|
+
// No recent consolidation — graceful exit didn't happen, run full cycle
|
|
489
|
+
fullConsolidationTriggered = true;
|
|
490
|
+
try {
|
|
491
|
+
const result = consolidationEngine.consolidate(AGENT_ID);
|
|
492
|
+
store.markConsolidation(AGENT_ID, false);
|
|
493
|
+
log(AGENT_ID, 'consolidation', `full sleep cycle on restore (no graceful exit, idle ${Math.round(idleMs / 60_000)}min, last consolidation ${Math.round(sinceLastConsolidation / 60_000)}min ago) — ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
|
|
494
|
+
} catch { /* consolidation failure is non-fatal */ }
|
|
495
|
+
} else {
|
|
496
|
+
// Recent consolidation exists — graceful exit already handled it, just do mini
|
|
497
|
+
miniConsolidationTriggered = true;
|
|
498
|
+
consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => {});
|
|
499
|
+
}
|
|
423
500
|
}
|
|
424
501
|
|
|
425
502
|
// Format response
|
|
426
503
|
const parts: string[] = [];
|
|
427
504
|
const idleMin = Math.round(idleMs / 60_000);
|
|
428
|
-
|
|
505
|
+
const consolidationNote = fullConsolidationTriggered
|
|
506
|
+
? ' (full consolidation — no graceful exit detected)'
|
|
507
|
+
: miniConsolidationTriggered
|
|
508
|
+
? ' (mini-consolidation triggered)'
|
|
509
|
+
: '';
|
|
510
|
+
log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
|
|
511
|
+
parts.push(`Idle: ${idleMin}min${consolidationNote}`);
|
|
429
512
|
|
|
430
513
|
if (checkpoint?.executionState) {
|
|
431
514
|
const s = checkpoint.executionState;
|
|
@@ -437,6 +520,7 @@ Use this at the start of every session or after compaction to pick up where you
|
|
|
437
520
|
if (checkpoint.checkpointAt) parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
|
|
438
521
|
} else {
|
|
439
522
|
parts.push('\nNo explicit checkpoint saved.');
|
|
523
|
+
parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
|
|
440
524
|
}
|
|
441
525
|
|
|
442
526
|
if (lastWrite) {
|
|
@@ -620,16 +704,182 @@ Use this when you finish a task or need to decide what to do next.`,
|
|
|
620
704
|
}
|
|
621
705
|
);
|
|
622
706
|
|
|
707
|
+
// --- Task Bracket Tools ---
|
|
708
|
+
|
|
709
|
+
server.tool(
|
|
710
|
+
'memory_task_begin',
|
|
711
|
+
`Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
|
|
712
|
+
|
|
713
|
+
CALL THIS when starting:
|
|
714
|
+
- A multi-step operation (doc generation, large refactor, migration)
|
|
715
|
+
- Work on a new topic or project area
|
|
716
|
+
- Anything that might fill the context window
|
|
717
|
+
|
|
718
|
+
This ensures your state is saved before you start, and primes recall with relevant context.`,
|
|
719
|
+
{
|
|
720
|
+
topic: z.string().describe('What task are you starting? (3-15 words)'),
|
|
721
|
+
files: z.array(z.string()).optional().default([])
|
|
722
|
+
.describe('Files you expect to work with'),
|
|
723
|
+
notes: z.string().optional().default('')
|
|
724
|
+
.describe('Any additional context'),
|
|
725
|
+
},
|
|
726
|
+
async (params) => {
|
|
727
|
+
// 1. Checkpoint current state
|
|
728
|
+
const checkpoint = store.getCheckpoint(AGENT_ID);
|
|
729
|
+
const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
|
|
730
|
+
|
|
731
|
+
store.saveCheckpoint(AGENT_ID, {
|
|
732
|
+
currentTask: params.topic,
|
|
733
|
+
decisions: [],
|
|
734
|
+
activeFiles: params.files,
|
|
735
|
+
nextSteps: [],
|
|
736
|
+
relatedMemoryIds: [],
|
|
737
|
+
notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
|
|
738
|
+
episodeId: null,
|
|
739
|
+
});
|
|
740
|
+
|
|
741
|
+
// 2. Auto-recall relevant memories
|
|
742
|
+
let recalledSummary = '';
|
|
743
|
+
try {
|
|
744
|
+
const results = await activationEngine.activate({
|
|
745
|
+
agentId: AGENT_ID,
|
|
746
|
+
context: params.topic,
|
|
747
|
+
limit: 5,
|
|
748
|
+
minScore: 0.05,
|
|
749
|
+
useReranker: true,
|
|
750
|
+
useExpansion: true,
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
if (results.length > 0) {
|
|
754
|
+
const lines = results.map((r, i) => {
|
|
755
|
+
const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
|
|
756
|
+
return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
|
|
757
|
+
});
|
|
758
|
+
recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
|
|
759
|
+
|
|
760
|
+
// Track recall
|
|
761
|
+
store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
|
|
762
|
+
}
|
|
763
|
+
} catch { /* recall failure is non-fatal */ }
|
|
764
|
+
|
|
765
|
+
log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
|
|
766
|
+
|
|
767
|
+
return {
|
|
768
|
+
content: [{
|
|
769
|
+
type: 'text' as const,
|
|
770
|
+
text: `Task started: ${params.topic}\nCheckpoint saved (previous: ${prevTask}).${params.files.length ? `\nFiles: ${params.files.join(', ')}` : ''}${recalledSummary}`,
|
|
771
|
+
}],
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
);
|
|
775
|
+
|
|
776
|
+
server.tool(
|
|
777
|
+
'memory_task_end',
|
|
778
|
+
`Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
|
|
779
|
+
|
|
780
|
+
CALL THIS when you finish:
|
|
781
|
+
- A multi-step operation
|
|
782
|
+
- Before switching to a different topic
|
|
783
|
+
- At the end of a work session
|
|
784
|
+
|
|
785
|
+
This captures what was accomplished so future sessions can recall it.`,
|
|
786
|
+
{
|
|
787
|
+
summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
|
|
788
|
+
tags: z.array(z.string()).optional().default([])
|
|
789
|
+
.describe('Tags for the summary memory'),
|
|
790
|
+
},
|
|
791
|
+
async (params) => {
|
|
792
|
+
// 1. Write summary as a memory
|
|
793
|
+
const salience = evaluateSalience({
|
|
794
|
+
content: params.summary,
|
|
795
|
+
eventType: 'decision',
|
|
796
|
+
surprise: 0.3,
|
|
797
|
+
decisionMade: true,
|
|
798
|
+
causalDepth: 0.5,
|
|
799
|
+
resolutionEffort: 0.5,
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
const engram = store.createEngram({
|
|
803
|
+
agentId: AGENT_ID,
|
|
804
|
+
concept: 'Task completed',
|
|
805
|
+
content: params.summary,
|
|
806
|
+
tags: [...params.tags, 'task-summary'],
|
|
807
|
+
salience: Math.max(salience.score, 0.7), // Always high salience for task summaries
|
|
808
|
+
salienceFeatures: salience.features,
|
|
809
|
+
reasonCodes: [...salience.reasonCodes, 'task-end'],
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
connectionEngine.enqueue(engram.id);
|
|
813
|
+
|
|
814
|
+
// Generate embedding asynchronously
|
|
815
|
+
embed(`Task completed: ${params.summary}`).then(vec => {
|
|
816
|
+
store.updateEmbedding(engram.id, vec);
|
|
817
|
+
}).catch(() => {});
|
|
818
|
+
|
|
819
|
+
// 2. Update checkpoint to reflect completion
|
|
820
|
+
const checkpoint = store.getCheckpoint(AGENT_ID);
|
|
821
|
+
const completedTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
|
|
822
|
+
|
|
823
|
+
store.saveCheckpoint(AGENT_ID, {
|
|
824
|
+
currentTask: `Completed: ${completedTask}`,
|
|
825
|
+
decisions: checkpoint?.executionState?.decisions ?? [],
|
|
826
|
+
activeFiles: [],
|
|
827
|
+
nextSteps: [],
|
|
828
|
+
relatedMemoryIds: [engram.id],
|
|
829
|
+
notes: `Task completed. Summary memory: ${engram.id}`,
|
|
830
|
+
episodeId: null,
|
|
831
|
+
});
|
|
832
|
+
|
|
833
|
+
store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
|
|
834
|
+
log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)}`);
|
|
835
|
+
|
|
836
|
+
return {
|
|
837
|
+
content: [{
|
|
838
|
+
type: 'text' as const,
|
|
839
|
+
text: `Task completed and saved.\nSummary memory: ${engram.id}\nSalience: ${salience.score.toFixed(2)}\nCheckpoint updated.`,
|
|
840
|
+
}],
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
);
|
|
844
|
+
|
|
623
845
|
// --- Start ---
|
|
624
846
|
|
|
625
847
|
async function main() {
|
|
626
848
|
const transport = new StdioServerTransport();
|
|
627
849
|
await server.connect(transport);
|
|
850
|
+
|
|
851
|
+
// Start hook sidecar (lightweight HTTP for Claude Code hooks)
|
|
852
|
+
const sidecar = startSidecar({
|
|
853
|
+
store,
|
|
854
|
+
agentId: AGENT_ID,
|
|
855
|
+
secret: HOOK_SECRET,
|
|
856
|
+
port: HOOK_PORT,
|
|
857
|
+
onConsolidate: (agentId, reason) => {
|
|
858
|
+
console.error(`[mcp] consolidation triggered: ${reason}`);
|
|
859
|
+
const result = consolidationEngine.consolidate(agentId);
|
|
860
|
+
store.markConsolidation(agentId, false);
|
|
861
|
+
console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
|
|
862
|
+
},
|
|
863
|
+
});
|
|
864
|
+
|
|
628
865
|
// Log to stderr (stdout is reserved for MCP protocol)
|
|
629
866
|
console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
|
|
867
|
+
console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
|
|
868
|
+
|
|
869
|
+
// Clean shutdown
|
|
870
|
+
const cleanup = () => {
|
|
871
|
+
sidecar.close();
|
|
872
|
+
consolidationScheduler.stop();
|
|
873
|
+
stagingBuffer.stop();
|
|
874
|
+
store.close();
|
|
875
|
+
};
|
|
876
|
+
process.on('SIGINT', () => { cleanup(); process.exit(0); });
|
|
877
|
+
process.on('SIGTERM', () => { cleanup(); process.exit(0); });
|
|
630
878
|
}
|
|
631
879
|
|
|
632
880
|
main().catch(err => {
|
|
633
881
|
console.error('MCP server failed:', err);
|
|
634
882
|
process.exit(1);
|
|
635
883
|
});
|
|
884
|
+
|
|
885
|
+
} // end else (non-incognito)
|