@fabersep/memory 0.0.0-stage → 0.1.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.
@@ -0,0 +1,128 @@
1
+ interface JsonRpcRequest {
2
+ jsonrpc: '2.0';
3
+ id?: string | number | null;
4
+ method: string;
5
+ params?: Record<string, unknown>;
6
+ }
7
+ export declare class FaberMemoryMcpServer {
8
+ private readonly homeDir;
9
+ private readonly cwd;
10
+ private readonly startupPullTimeoutMs;
11
+ private mcpRoots;
12
+ private index;
13
+ private lastHeadSignature;
14
+ private lastLoaded;
15
+ private startupWarnings;
16
+ private startupPullPromise;
17
+ constructor(options?: {
18
+ homeDir?: string;
19
+ cwd?: string;
20
+ mcpRoots?: string[];
21
+ startupPullTimeoutMs?: number;
22
+ });
23
+ startNonBlockingSync(): void;
24
+ waitForStartupSyncForTest(): Promise<void>;
25
+ setMcpRoots(roots: string[]): void;
26
+ private refreshIndexIfNeeded;
27
+ private drainWarnings;
28
+ listTools(): readonly [{
29
+ readonly name: "memory_search";
30
+ readonly description: "Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.";
31
+ readonly inputSchema: {
32
+ readonly type: "object";
33
+ readonly properties: {
34
+ readonly query: {
35
+ readonly type: "string";
36
+ readonly description: "Keyword query; empty lists all.";
37
+ };
38
+ readonly scope: {
39
+ readonly type: "string";
40
+ readonly enum: readonly ["team", "personal", "project"];
41
+ };
42
+ readonly type: {
43
+ readonly type: "string";
44
+ readonly enum: readonly ["rule", "decision", "lesson", "preference", "reference"];
45
+ };
46
+ readonly include_pending: {
47
+ readonly type: "boolean";
48
+ readonly default: false;
49
+ };
50
+ };
51
+ };
52
+ }, {
53
+ readonly name: "memory_get";
54
+ readonly description: "Fetch full L2 Markdown body, frontmatter metadata, and links for one or more IDs.";
55
+ readonly inputSchema: {
56
+ readonly type: "object";
57
+ readonly properties: {
58
+ readonly ids: {
59
+ readonly type: "array";
60
+ readonly items: {
61
+ readonly type: "string";
62
+ };
63
+ readonly minItems: 1;
64
+ };
65
+ };
66
+ readonly required: readonly ["ids"];
67
+ };
68
+ }, {
69
+ readonly name: "memory_propose";
70
+ readonly description: "Submit a create, update, or supersede proposal to pre-memory for human approval.";
71
+ readonly inputSchema: {
72
+ readonly type: "object";
73
+ readonly properties: {
74
+ readonly action: {
75
+ readonly type: "string";
76
+ readonly enum: readonly ["create", "update", "supersede"];
77
+ };
78
+ readonly scope: {
79
+ readonly type: "string";
80
+ readonly enum: readonly ["team", "personal", "project"];
81
+ };
82
+ readonly summary: {
83
+ readonly type: "string";
84
+ };
85
+ readonly type: {
86
+ readonly type: "string";
87
+ readonly enum: readonly ["rule", "decision", "lesson", "preference", "reference"];
88
+ };
89
+ readonly body: {
90
+ readonly type: "string";
91
+ };
92
+ readonly target_id: {
93
+ readonly type: "string";
94
+ };
95
+ readonly entry_id: {
96
+ readonly type: "string";
97
+ };
98
+ readonly tags: {
99
+ readonly type: "array";
100
+ readonly items: {
101
+ readonly type: "string";
102
+ };
103
+ };
104
+ readonly l0: {
105
+ readonly type: "string";
106
+ readonly enum: readonly ["none", "line", "body"];
107
+ };
108
+ readonly force_new: {
109
+ readonly type: "boolean";
110
+ };
111
+ readonly reason: {
112
+ readonly type: "string";
113
+ };
114
+ };
115
+ readonly required: readonly ["action", "scope", "summary", "type", "body"];
116
+ };
117
+ }];
118
+ handleToolCall(name: string, args?: Record<string, unknown>): {
119
+ content: {
120
+ type: 'text';
121
+ text: string;
122
+ }[];
123
+ isError?: boolean;
124
+ };
125
+ handleJsonRpc(req: JsonRpcRequest): Record<string, unknown> | null;
126
+ serveStdio(): void;
127
+ }
128
+ export {};
@@ -0,0 +1,381 @@
1
+ import * as fs from 'node:fs';
2
+ import * as readline from 'node:readline';
3
+ import { BM25Index, findNearDuplicates } from './bm25.js';
4
+ import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
5
+ import { compileGlobalL0 } from './compiler.js';
6
+ import { getHeadSha } from './git.js';
7
+ import { formatHygieneErrors, scanHygiene } from './hygiene.js';
8
+ import { createProposal, reconcileAwaitingCommitProposals } from './proposals.js';
9
+ import { loadAllScopes, resolveProjectRoot } from './store.js';
10
+ import { syncAllRoots } from './sync.js';
11
+ import { VALID_TYPES, } from './types.js';
12
+ const MCP_TOOLS = [
13
+ {
14
+ name: 'memory_search',
15
+ description: 'Search or list memory entries (L0/L1 summaries only). Empty query lists active entries.',
16
+ inputSchema: {
17
+ type: 'object',
18
+ properties: {
19
+ query: { type: 'string', description: 'Keyword query; empty lists all.' },
20
+ scope: { type: 'string', enum: ['team', 'personal', 'project'] },
21
+ type: { type: 'string', enum: ['rule', 'decision', 'lesson', 'preference', 'reference'] },
22
+ include_pending: { type: 'boolean', default: false },
23
+ },
24
+ },
25
+ },
26
+ {
27
+ name: 'memory_get',
28
+ description: 'Fetch full L2 Markdown body, frontmatter metadata, and links for one or more IDs.',
29
+ inputSchema: {
30
+ type: 'object',
31
+ properties: {
32
+ ids: { type: 'array', items: { type: 'string' }, minItems: 1 },
33
+ },
34
+ required: ['ids'],
35
+ },
36
+ },
37
+ {
38
+ name: 'memory_propose',
39
+ description: 'Submit a create, update, or supersede proposal to pre-memory for human approval.',
40
+ inputSchema: {
41
+ type: 'object',
42
+ properties: {
43
+ action: { type: 'string', enum: ['create', 'update', 'supersede'] },
44
+ scope: { type: 'string', enum: ['team', 'personal', 'project'] },
45
+ summary: { type: 'string' },
46
+ type: { type: 'string', enum: ['rule', 'decision', 'lesson', 'preference', 'reference'] },
47
+ body: { type: 'string' },
48
+ target_id: { type: 'string' },
49
+ entry_id: { type: 'string' },
50
+ tags: { type: 'array', items: { type: 'string' } },
51
+ l0: { type: 'string', enum: ['none', 'line', 'body'] },
52
+ force_new: { type: 'boolean' },
53
+ reason: { type: 'string' },
54
+ },
55
+ required: ['action', 'scope', 'summary', 'type', 'body'],
56
+ },
57
+ },
58
+ ];
59
+ export class FaberMemoryMcpServer {
60
+ homeDir;
61
+ cwd;
62
+ startupPullTimeoutMs;
63
+ mcpRoots;
64
+ index = new BM25Index();
65
+ lastHeadSignature = '';
66
+ lastLoaded = null;
67
+ startupWarnings = [];
68
+ startupPullPromise = null;
69
+ constructor(options = {}) {
70
+ this.homeDir = options.homeDir || getHomeDir();
71
+ this.cwd = options.cwd || process.cwd();
72
+ this.mcpRoots = options.mcpRoots;
73
+ this.startupPullTimeoutMs = options.startupPullTimeoutMs ?? 5000;
74
+ }
75
+ startNonBlockingSync() {
76
+ const config = loadConfig(this.homeDir);
77
+ // Ensure compiled L0 exists on startup if missing
78
+ if (!fs.existsSync(getCompiledL0Path(this.homeDir))) {
79
+ compileGlobalL0(config, { homeDir: this.homeDir });
80
+ }
81
+ this.startupPullPromise = syncAllRoots(config, {
82
+ homeDir: this.homeDir,
83
+ timeoutMs: this.startupPullTimeoutMs,
84
+ recompile: true,
85
+ })
86
+ .then((res) => {
87
+ if (res.warnings.length > 0) {
88
+ this.startupWarnings.push(...res.warnings);
89
+ }
90
+ })
91
+ .catch((err) => {
92
+ this.startupWarnings.push(`Startup sync failed: ${err instanceof Error ? err.message : String(err)}`);
93
+ });
94
+ }
95
+ async waitForStartupSyncForTest() {
96
+ if (this.startupPullPromise) {
97
+ await this.startupPullPromise;
98
+ }
99
+ }
100
+ setMcpRoots(roots) {
101
+ this.mcpRoots = roots;
102
+ this.lastHeadSignature = '';
103
+ }
104
+ refreshIndexIfNeeded() {
105
+ const config = loadConfig(this.homeDir);
106
+ const projectRes = resolveProjectRoot(this.mcpRoots, this.cwd);
107
+ const pending = reconcileAwaitingCommitProposals(this.homeDir);
108
+ const teamSha = config.roots.team ? getHeadSha(config.roots.team.path) : '';
109
+ const personalSha = config.roots.personal ? getHeadSha(config.roots.personal.path) : '';
110
+ const projectSha = projectRes.source !== 'none' && projectRes.projectRoot
111
+ ? getHeadSha(projectRes.projectRoot)
112
+ : '';
113
+ const pendingSig = pending.map((p) => `${p.id}:${p.status}`).join(',');
114
+ const sig = `${teamSha}|${personalSha}|${projectSha}|${projectRes.source}|${pendingSig}`;
115
+ if (sig !== this.lastHeadSignature || !this.lastLoaded) {
116
+ this.lastLoaded = loadAllScopes(config, projectRes);
117
+ this.index.rebuild(this.lastLoaded.activeEntries, pending);
118
+ this.lastHeadSignature = sig;
119
+ }
120
+ return { config, loaded: this.lastLoaded };
121
+ }
122
+ drainWarnings(loaded) {
123
+ const warnings = [...this.startupWarnings, ...loaded.uncommittedWarnings, ...loaded.shadowWarnings];
124
+ this.startupWarnings = [];
125
+ return warnings;
126
+ }
127
+ listTools() {
128
+ return MCP_TOOLS;
129
+ }
130
+ handleToolCall(name, args = {}) {
131
+ if (name === 'memory_search') {
132
+ const { loaded } = this.refreshIndexIfNeeded();
133
+ const query = typeof args.query === 'string' ? args.query : '';
134
+ const scope = typeof args.scope === 'string' ? args.scope : undefined;
135
+ const type = typeof args.type === 'string' ? args.type : undefined;
136
+ const includePending = Boolean(args.include_pending);
137
+ const results = this.index.search(query, { scope, type, includePending });
138
+ const warnings = this.drainWarnings(loaded);
139
+ const payload = {
140
+ results,
141
+ metadata: {
142
+ project_root_source: loaded.projectResolution.source,
143
+ warnings,
144
+ },
145
+ };
146
+ return {
147
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
148
+ };
149
+ }
150
+ if (name === 'memory_get') {
151
+ const { loaded } = this.refreshIndexIfNeeded();
152
+ const ids = Array.isArray(args.ids) ? args.ids.map(String) : [];
153
+ if (ids.length === 0) {
154
+ return {
155
+ isError: true,
156
+ content: [{ type: 'text', text: JSON.stringify({ error: 'ids array is required' }) }],
157
+ };
158
+ }
159
+ const found = [];
160
+ const notFound = [];
161
+ for (const id of ids) {
162
+ const matches = loaded.allEntries.filter((e) => e.id === id);
163
+ if (matches.length === 0) {
164
+ notFound.push(id);
165
+ }
166
+ else {
167
+ for (const e of matches) {
168
+ found.push({
169
+ id: e.id,
170
+ scope: e.scope,
171
+ type: e.type,
172
+ summary: e.summary,
173
+ tags: e.tags,
174
+ status: e.status,
175
+ superseded_by: e.superseded_by,
176
+ l0: e.l0,
177
+ last_verified: e.last_verified,
178
+ body: e.body,
179
+ links: e.links,
180
+ shadowed: e.shadowed,
181
+ shadow_warning: e.shadowWarning,
182
+ });
183
+ }
184
+ }
185
+ }
186
+ const warnings = this.drainWarnings(loaded);
187
+ return {
188
+ content: [
189
+ {
190
+ type: 'text',
191
+ text: JSON.stringify({ entries: found, not_found: notFound, warnings }, null, 2),
192
+ },
193
+ ],
194
+ };
195
+ }
196
+ if (name === 'memory_propose') {
197
+ const { config, loaded } = this.refreshIndexIfNeeded();
198
+ const action = String(args.action || '');
199
+ const scope = String(args.scope || '');
200
+ const summary = typeof args.summary === 'string' ? args.summary.trim() : '';
201
+ const type = String(args.type || '');
202
+ const body = typeof args.body === 'string' ? args.body.trim() : '';
203
+ const targetId = typeof args.target_id === 'string' ? args.target_id.trim() : undefined;
204
+ const entryId = typeof args.entry_id === 'string' ? args.entry_id.trim() : undefined;
205
+ const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
206
+ const l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
207
+ const forceNew = Boolean(args.force_new);
208
+ const reason = typeof args.reason === 'string' ? args.reason.trim() : undefined;
209
+ if (!['create', 'update', 'supersede'].includes(action)) {
210
+ return errorResponse('Invalid action; expected create, update, or supersede.');
211
+ }
212
+ if (!['team', 'personal', 'project'].includes(scope)) {
213
+ return errorResponse('Invalid scope; expected team, personal, or project.');
214
+ }
215
+ if (!summary) {
216
+ return errorResponse('summary is required.');
217
+ }
218
+ if (!VALID_TYPES.includes(type)) {
219
+ return errorResponse(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
220
+ }
221
+ if (!body) {
222
+ return errorResponse('body is required.');
223
+ }
224
+ // Validate target_id for update / supersede (AC-08c1, AC-08c2)
225
+ if (action === 'update' || action === 'supersede') {
226
+ if (!targetId) {
227
+ return errorResponse(`target_id is required when action is "${action}".`);
228
+ }
229
+ const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
230
+ loaded.activeEntries.some((e) => e.id === targetId);
231
+ if (!exists) {
232
+ return errorResponse(`Target entry "${targetId}" not found in active memory.`);
233
+ }
234
+ }
235
+ // Hygiene scan (AC-20a)
236
+ const hygieneFindings = scanHygiene(`${summary}\n${body}`);
237
+ if (hygieneFindings.length > 0) {
238
+ return errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings });
239
+ }
240
+ // Near-duplicate check on create (AC-10, AC-11)
241
+ if (action === 'create') {
242
+ if (forceNew && !reason) {
243
+ return errorResponse('A non-empty "reason" is required when force_new is true.');
244
+ }
245
+ if (!forceNew) {
246
+ const pending = reconcileAwaitingCommitProposals(this.homeDir);
247
+ const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
248
+ if (matches.length > 0) {
249
+ return errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
250
+ matches: matches.map((m) => ({
251
+ id: m.id,
252
+ scope: m.scope,
253
+ summary: m.summary,
254
+ pending: m.pending,
255
+ similarity: m.similarity,
256
+ })),
257
+ });
258
+ }
259
+ }
260
+ }
261
+ try {
262
+ const proposal = createProposal(config, {
263
+ scope,
264
+ action,
265
+ entryId,
266
+ targetId,
267
+ summary,
268
+ type,
269
+ tags,
270
+ l0,
271
+ body,
272
+ forceNew,
273
+ reason,
274
+ projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
275
+ }, this.homeDir);
276
+ this.lastHeadSignature = '';
277
+ const warnings = this.drainWarnings(loaded);
278
+ return {
279
+ content: [
280
+ {
281
+ type: 'text',
282
+ text: JSON.stringify({
283
+ status: 'staged',
284
+ proposal_id: proposal.id,
285
+ entry_id: proposal.entryId,
286
+ scope: proposal.scope,
287
+ warnings,
288
+ }, null, 2),
289
+ },
290
+ ],
291
+ };
292
+ }
293
+ catch (err) {
294
+ return errorResponse(err instanceof Error ? err.message : String(err));
295
+ }
296
+ }
297
+ return errorResponse(`Unknown tool: ${name}`);
298
+ }
299
+ handleJsonRpc(req) {
300
+ if (req.method === 'initialize') {
301
+ return {
302
+ jsonrpc: '2.0',
303
+ id: req.id ?? null,
304
+ result: {
305
+ protocolVersion: '2024-11-05',
306
+ capabilities: {
307
+ tools: { listChanged: false },
308
+ },
309
+ serverInfo: {
310
+ name: '@fabersep/memory',
311
+ version: '0.1.0',
312
+ },
313
+ },
314
+ };
315
+ }
316
+ if (req.method === 'notifications/initialized') {
317
+ return null;
318
+ }
319
+ if (req.method === 'ping') {
320
+ return { jsonrpc: '2.0', id: req.id ?? null, result: {} };
321
+ }
322
+ if (req.method === 'tools/list') {
323
+ return {
324
+ jsonrpc: '2.0',
325
+ id: req.id ?? null,
326
+ result: { tools: this.listTools() },
327
+ };
328
+ }
329
+ if (req.method === 'tools/call') {
330
+ const params = req.params || {};
331
+ const toolName = String(params.name || '');
332
+ const toolArgs = params.arguments || {};
333
+ const res = this.handleToolCall(toolName, toolArgs);
334
+ return {
335
+ jsonrpc: '2.0',
336
+ id: req.id ?? null,
337
+ result: res,
338
+ };
339
+ }
340
+ if (req.id === undefined)
341
+ return null;
342
+ return {
343
+ jsonrpc: '2.0',
344
+ id: req.id,
345
+ error: { code: -32601, message: `Method not found: ${req.method}` },
346
+ };
347
+ }
348
+ serveStdio() {
349
+ this.startNonBlockingSync();
350
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
351
+ rl.on('line', (line) => {
352
+ const trimmed = line.trim();
353
+ if (!trimmed)
354
+ return;
355
+ try {
356
+ const req = JSON.parse(trimmed);
357
+ const resp = this.handleJsonRpc(req);
358
+ if (resp) {
359
+ process.stdout.write(JSON.stringify(resp) + '\n');
360
+ }
361
+ }
362
+ catch (err) {
363
+ const errResp = {
364
+ jsonrpc: '2.0',
365
+ id: null,
366
+ error: {
367
+ code: -32700,
368
+ message: `Parse error: ${err instanceof Error ? err.message : String(err)}`,
369
+ },
370
+ };
371
+ process.stdout.write(JSON.stringify(errResp) + '\n');
372
+ }
373
+ });
374
+ }
375
+ }
376
+ function errorResponse(message, extra) {
377
+ return {
378
+ isError: true,
379
+ content: [{ type: 'text', text: JSON.stringify({ error: message, ...extra }, null, 2) }],
380
+ };
381
+ }
@@ -0,0 +1,34 @@
1
+ import { EntryType, L0Mode, Proposal, ProposalAction, Scope, TeamSubmitMode, UserConfig } from './types.js';
2
+ export declare const CACHE_GUIDANCE_NOTE = "Note: Updated L0 applies to new sessions; batching reviews at session end maximizes prompt-cache reuse.";
3
+ export declare function saveProposal(proposal: Proposal, homeDir?: string): string;
4
+ export declare function deleteProposal(proposal: Proposal, homeDir?: string): void;
5
+ export declare function listAllProposals(homeDir?: string): Proposal[];
6
+ export declare function reconcileAwaitingCommitProposals(homeDir?: string): Proposal[];
7
+ export declare function findProposalById(id: string, homeDir?: string): Proposal | null;
8
+ export declare function createProposal(config: UserConfig, input: {
9
+ scope: Scope;
10
+ action: ProposalAction;
11
+ entryId?: string;
12
+ targetId?: string;
13
+ summary: string;
14
+ type: EntryType;
15
+ tags?: string[];
16
+ l0?: L0Mode;
17
+ body: string;
18
+ forceNew?: boolean;
19
+ reason?: string;
20
+ projectRootPath?: string;
21
+ }, homeDir?: string): Proposal;
22
+ export declare function rejectProposal(id: string, homeDir?: string): Proposal;
23
+ export interface ApproveOutcome {
24
+ ok: boolean;
25
+ approvedIds: string[];
26
+ messages: string[];
27
+ errors: string[];
28
+ compareUrl?: string;
29
+ recompiledL0?: boolean;
30
+ }
31
+ export declare function approveProposalsBatch(config: UserConfig, proposals: Proposal[], options?: {
32
+ homeDir?: string;
33
+ teamSubmitModeOverride?: TeamSubmitMode;
34
+ }): Promise<ApproveOutcome>;