@fabersep/memory 0.4.0 → 0.5.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/CHANGELOG.md +7 -0
- package/README.md +62 -110
- package/dist/src/cli.js +41 -1
- package/dist/src/config.js +1 -0
- package/dist/src/direct-save.d.ts +53 -0
- package/dist/src/direct-save.js +226 -0
- package/dist/src/doctor.js +4 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/init.d.ts +1 -1
- package/dist/src/init.js +1 -1
- package/dist/src/mcp.d.ts +45 -2
- package/dist/src/mcp.js +281 -142
- package/dist/src/metrics.d.ts +4 -2
- package/dist/src/proposals.d.ts +10 -3
- package/dist/src/proposals.js +14 -2
- package/dist/src/stats.d.ts +8 -0
- package/dist/src/stats.js +16 -2
- package/dist/src/types.d.ts +12 -0
- package/dist/src/web-assets.js +33 -0
- package/dist/src/web.js +39 -1
- package/package.json +1 -1
package/dist/src/doctor.js
CHANGED
|
@@ -8,6 +8,7 @@ import { BLOCK_END, BLOCK_START, getEngineSpecs, getUserHome } from './init.js';
|
|
|
8
8
|
import { readMetrics } from './metrics.js';
|
|
9
9
|
import { getAheadInfo, getUnpushedReminder, readPersonalRemoteState } from './personal-remote.js';
|
|
10
10
|
import { listAllProposals } from './proposals.js';
|
|
11
|
+
import { countRecentDirectSaves, DIRECT_SAVE_RECENT_DAYS, isDirectUserSaveOn } from './direct-save.js';
|
|
11
12
|
import { L0_CHURN_WARN_THRESHOLD } from './stats.js';
|
|
12
13
|
import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
|
|
13
14
|
import { c, hr } from './ui.js';
|
|
@@ -412,6 +413,9 @@ export function runDoctor(options = {}) {
|
|
|
412
413
|
queueStatus = 'WARN';
|
|
413
414
|
queueDetails.push(`${awaitingCommitCount} project proposal(s) awaiting git commit.`);
|
|
414
415
|
}
|
|
416
|
+
// 06 FR-06: direct saves are information, never a failure.
|
|
417
|
+
const recentDirect = countRecentDirectSaves(homeDir);
|
|
418
|
+
queueDetails.push(`Direct save is ${config && !isDirectUserSaveOn(config) ? 'off' : 'on'}; ${recentDirect} memor${recentDirect === 1 ? 'y' : 'ies'} added directly on the user's word in the last ${DIRECT_SAVE_RECENT_DAYS} days.`);
|
|
415
419
|
if (queueStatus === 'WARN') {
|
|
416
420
|
queueHint = 'Run "faber-memory status" and "faber-memory review" to resolve queued proposals.';
|
|
417
421
|
}
|
package/dist/src/index.d.ts
CHANGED
package/dist/src/index.js
CHANGED
package/dist/src/init.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { UserConfig } from './types.js';
|
|
2
2
|
export declare const BLOCK_START = "<!-- faber-memory:start -->";
|
|
3
3
|
export declare const BLOCK_END = "<!-- faber-memory:end -->";
|
|
4
|
-
export declare const TOOL_GUIDANCE_LINE = "Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).";
|
|
4
|
+
export declare const TOOL_GUIDANCE_LINE = "Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly). When the user explicitly asks you to remember something, call memory_propose with source \"user\" and their exact words in user_quote; it is saved at once.";
|
|
5
5
|
export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
|
|
6
6
|
export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
|
|
7
7
|
export interface EngineSpec {
|
package/dist/src/init.js
CHANGED
|
@@ -6,7 +6,7 @@ import { compileGlobalL0 } from './compiler.js';
|
|
|
6
6
|
import { c, hr, shouldUseColor } from './ui.js';
|
|
7
7
|
export const BLOCK_START = '<!-- faber-memory:start -->';
|
|
8
8
|
export const BLOCK_END = '<!-- faber-memory:end -->';
|
|
9
|
-
export const TOOL_GUIDANCE_LINE = 'Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly).';
|
|
9
|
+
export const TOOL_GUIDANCE_LINE = 'Use the faber-memory MCP tools: memory_search and memory_get for the details behind these lines; when you learn a durable rule, decision, lesson or preference, call memory_propose (the user approves it later; never edit memory files directly). When the user explicitly asks you to remember something, call memory_propose with source "user" and their exact words in user_quote; it is saved at once.';
|
|
10
10
|
export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
|
|
11
11
|
export function getEngineSpecs() {
|
|
12
12
|
return {
|
package/dist/src/mcp.d.ts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
type ToolResponse = {
|
|
2
|
+
content: {
|
|
3
|
+
type: 'text';
|
|
4
|
+
text: string;
|
|
5
|
+
}[];
|
|
6
|
+
isError?: boolean;
|
|
7
|
+
};
|
|
1
8
|
interface JsonRpcRequest {
|
|
2
9
|
jsonrpc: '2.0';
|
|
3
10
|
id?: string | number | null;
|
|
@@ -46,7 +53,7 @@ export declare const MCP_TOOLS: readonly [{
|
|
|
46
53
|
};
|
|
47
54
|
}, {
|
|
48
55
|
readonly name: "memory_propose";
|
|
49
|
-
readonly description:
|
|
56
|
+
readonly description: string;
|
|
50
57
|
readonly inputSchema: {
|
|
51
58
|
readonly type: "object";
|
|
52
59
|
readonly properties: {
|
|
@@ -90,6 +97,15 @@ export declare const MCP_TOOLS: readonly [{
|
|
|
90
97
|
readonly reason: {
|
|
91
98
|
readonly type: "string";
|
|
92
99
|
};
|
|
100
|
+
readonly source: {
|
|
101
|
+
readonly type: "string";
|
|
102
|
+
readonly enum: readonly ["agent", "user"];
|
|
103
|
+
readonly default: "agent";
|
|
104
|
+
};
|
|
105
|
+
readonly user_quote: {
|
|
106
|
+
readonly type: "string";
|
|
107
|
+
readonly description: "The user's exact words asking for this memory (required when source is \"user\").";
|
|
108
|
+
};
|
|
93
109
|
};
|
|
94
110
|
readonly required: readonly ["action", "scope", "summary", "type", "body"];
|
|
95
111
|
};
|
|
@@ -105,6 +121,9 @@ export declare class FaberMemoryMcpServer {
|
|
|
105
121
|
private startupWarnings;
|
|
106
122
|
private unpushedReminderShown;
|
|
107
123
|
private startupPullPromise;
|
|
124
|
+
private directSaveCount;
|
|
125
|
+
/** Keeps stdio responses in request order while a direct save awaits pull/push. */
|
|
126
|
+
private queue;
|
|
108
127
|
constructor(options?: {
|
|
109
128
|
homeDir?: string;
|
|
110
129
|
cwd?: string;
|
|
@@ -158,7 +177,7 @@ export declare class FaberMemoryMcpServer {
|
|
|
158
177
|
};
|
|
159
178
|
}, {
|
|
160
179
|
readonly name: "memory_propose";
|
|
161
|
-
readonly description:
|
|
180
|
+
readonly description: string;
|
|
162
181
|
readonly inputSchema: {
|
|
163
182
|
readonly type: "object";
|
|
164
183
|
readonly properties: {
|
|
@@ -202,6 +221,15 @@ export declare class FaberMemoryMcpServer {
|
|
|
202
221
|
readonly reason: {
|
|
203
222
|
readonly type: "string";
|
|
204
223
|
};
|
|
224
|
+
readonly source: {
|
|
225
|
+
readonly type: "string";
|
|
226
|
+
readonly enum: readonly ["agent", "user"];
|
|
227
|
+
readonly default: "agent";
|
|
228
|
+
};
|
|
229
|
+
readonly user_quote: {
|
|
230
|
+
readonly type: "string";
|
|
231
|
+
readonly description: "The user's exact words asking for this memory (required when source is \"user\").";
|
|
232
|
+
};
|
|
205
233
|
};
|
|
206
234
|
readonly required: readonly ["action", "scope", "summary", "type", "body"];
|
|
207
235
|
};
|
|
@@ -213,6 +241,21 @@ export declare class FaberMemoryMcpServer {
|
|
|
213
241
|
}[];
|
|
214
242
|
isError?: boolean;
|
|
215
243
|
};
|
|
244
|
+
/**
|
|
245
|
+
* 06 FR-01..FR-08 (and 01 FR-05): validate, then stage in pre-memory, or, for a
|
|
246
|
+
* user-dictated personal memory, save it directly. Pull and push are done by
|
|
247
|
+
* `handleToolCallAsync`; this synchronous path keeps a direct save local.
|
|
248
|
+
*/
|
|
249
|
+
private handlePropose;
|
|
250
|
+
/** 06 FR-02/FR-05/FR-06: why a user-dictated call must be staged, or undefined when it can be saved directly. */
|
|
251
|
+
private directSaveBlocker;
|
|
252
|
+
/**
|
|
253
|
+
* Like `handleToolCall`, but a user-dictated personal save pulls before it commits
|
|
254
|
+
* (03 FR-04) and pushes per `pushMode` after (03 FR-02, 06 FR-02).
|
|
255
|
+
*/
|
|
256
|
+
handleToolCallAsync(name: string, args?: Record<string, unknown>): Promise<ToolResponse>;
|
|
257
|
+
/** JSON-RPC entry for stdio: like `handleJsonRpc`, with `tools/call` via `handleToolCallAsync`. */
|
|
258
|
+
handleJsonRpcAsync(req: JsonRpcRequest): Promise<Record<string, unknown> | null>;
|
|
216
259
|
handleJsonRpc(req: JsonRpcRequest): Record<string, unknown> | null;
|
|
217
260
|
serveStdio(): void;
|
|
218
261
|
}
|
package/dist/src/mcp.js
CHANGED
|
@@ -5,13 +5,21 @@ import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
|
|
|
5
5
|
import { compileGlobalL0 } from './compiler.js';
|
|
6
6
|
import { getHeadSha } from './git.js';
|
|
7
7
|
import { formatHygieneErrors, scanHygiene } from './hygiene.js';
|
|
8
|
-
import { getUnpushedReminder, isReadOnlyRoot, READ_ONLY_MESSAGE } from './personal-remote.js';
|
|
8
|
+
import { getAheadInfo, getPushMode, getUnpushedReminder, isReadOnlyRoot, pullRebaseBeforeCommit, pushPersonalRoot, READ_ONLY_MESSAGE, } from './personal-remote.js';
|
|
9
9
|
import { appendMetric, MAX_GET_FOUND_IDS } from './metrics.js';
|
|
10
|
-
import { createProposal, reconcileAwaitingCommitProposals } from './proposals.js';
|
|
10
|
+
import { buildProposal, CACHE_GUIDANCE_NOTE, createProposal, reconcileAwaitingCommitProposals, } from './proposals.js';
|
|
11
|
+
import { DIRECT_SAVE_SESSION_CAP, directSavePersonal, followRebasedDirectSave, isDirectUserSaveOn, MAX_USER_QUOTE_CHARS, } from './direct-save.js';
|
|
11
12
|
import { loadAllScopes, resolveProjectRoot } from './store.js';
|
|
12
13
|
import { syncAllRoots } from './sync.js';
|
|
13
14
|
import { getPackageVersion } from './version.js';
|
|
14
15
|
import { DEFAULT_SIMILARITY_HINT_FLOOR, VALID_TYPES, } from './types.js';
|
|
16
|
+
const STAGED_REASON_TEXT = {
|
|
17
|
+
scope: 'only personal memories are saved directly; this one waits for review',
|
|
18
|
+
disabled: 'direct save is off (faber-memory config set-direct-save on); this one waits for review',
|
|
19
|
+
session_cap: 'the direct-save limit for this session is reached; this one waits for review',
|
|
20
|
+
l0_budget: 'the startup index is full; trim it, then approve this one',
|
|
21
|
+
compile_error: 'the startup index did not compile with this entry; it waits for review',
|
|
22
|
+
};
|
|
15
23
|
export const MCP_TOOLS = [
|
|
16
24
|
{
|
|
17
25
|
name: 'memory_search',
|
|
@@ -39,7 +47,8 @@ export const MCP_TOOLS = [
|
|
|
39
47
|
},
|
|
40
48
|
{
|
|
41
49
|
name: 'memory_propose',
|
|
42
|
-
description: 'Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory.'
|
|
50
|
+
description: 'Propose a durable rule, decision, lesson or preference you learned (or a fix to an existing entry). Goes to pre-memory for human approval; never edits active memory. ' +
|
|
51
|
+
'Only when the user explicitly asks you to remember or add something, pass source "user" and their exact words in user_quote: a personal memory is then saved at once and listed in the startup index from the next session; tell the user what was saved. Things you decide to save yourself use the default source.',
|
|
43
52
|
inputSchema: {
|
|
44
53
|
type: 'object',
|
|
45
54
|
properties: {
|
|
@@ -54,6 +63,8 @@ export const MCP_TOOLS = [
|
|
|
54
63
|
l0: { type: 'string', enum: ['none', 'line', 'body'] },
|
|
55
64
|
force_new: { type: 'boolean' },
|
|
56
65
|
reason: { type: 'string' },
|
|
66
|
+
source: { type: 'string', enum: ['agent', 'user'], default: 'agent' },
|
|
67
|
+
user_quote: { type: 'string', description: 'The user\'s exact words asking for this memory (required when source is "user").' },
|
|
57
68
|
},
|
|
58
69
|
required: ['action', 'scope', 'summary', 'type', 'body'],
|
|
59
70
|
},
|
|
@@ -70,6 +81,9 @@ export class FaberMemoryMcpServer {
|
|
|
70
81
|
startupWarnings = [];
|
|
71
82
|
unpushedReminderShown = false;
|
|
72
83
|
startupPullPromise = null;
|
|
84
|
+
directSaveCount = 0;
|
|
85
|
+
/** Keeps stdio responses in request order while a direct save awaits pull/push. */
|
|
86
|
+
queue = Promise.resolve();
|
|
73
87
|
constructor(options = {}) {
|
|
74
88
|
this.homeDir = options.homeDir || getHomeDir();
|
|
75
89
|
this.cwd = options.cwd || process.cwd();
|
|
@@ -124,10 +138,10 @@ export class FaberMemoryMcpServer {
|
|
|
124
138
|
}
|
|
125
139
|
return { config, loaded: this.lastLoaded };
|
|
126
140
|
}
|
|
127
|
-
drainWarnings(loaded) {
|
|
141
|
+
drainWarnings(loaded, withReminder = true) {
|
|
128
142
|
const warnings = [...this.startupWarnings, ...loaded.uncommittedWarnings, ...loaded.shadowWarnings];
|
|
129
143
|
this.startupWarnings = [];
|
|
130
|
-
if (!this.unpushedReminderShown) {
|
|
144
|
+
if (withReminder && !this.unpushedReminderShown) {
|
|
131
145
|
// Feature 03 FR-03: once per server process, never in L0 or the tool list.
|
|
132
146
|
this.unpushedReminderShown = true;
|
|
133
147
|
const reminder = getUnpushedReminder(loadConfig(this.homeDir), this.homeDir);
|
|
@@ -230,91 +244,111 @@ export class FaberMemoryMcpServer {
|
|
|
230
244
|
};
|
|
231
245
|
}
|
|
232
246
|
if (name === 'memory_propose') {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
247
|
+
return this.handlePropose(args).response;
|
|
248
|
+
}
|
|
249
|
+
return errorResponse(`Unknown tool: ${name}`);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* 06 FR-01..FR-08 (and 01 FR-05): validate, then stage in pre-memory, or, for a
|
|
253
|
+
* user-dictated personal memory, save it directly. Pull and push are done by
|
|
254
|
+
* `handleToolCallAsync`; this synchronous path keeps a direct save local.
|
|
255
|
+
*/
|
|
256
|
+
handlePropose(args, extraWarnings = [], checkOnly = false) {
|
|
257
|
+
const { config, loaded } = this.refreshIndexIfNeeded();
|
|
258
|
+
const action = String(args.action || '');
|
|
259
|
+
const scope = String(args.scope || '');
|
|
260
|
+
const summary = typeof args.summary === 'string' ? args.summary.trim() : '';
|
|
261
|
+
const type = String(args.type || '');
|
|
262
|
+
const body = typeof args.body === 'string' ? args.body.trim() : '';
|
|
263
|
+
const targetId = typeof args.target_id === 'string' ? args.target_id.trim() : undefined;
|
|
264
|
+
const entryId = typeof args.entry_id === 'string' ? args.entry_id.trim() : undefined;
|
|
265
|
+
const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
|
|
266
|
+
let l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
|
|
267
|
+
const forceNew = Boolean(args.force_new);
|
|
268
|
+
const reason = typeof args.reason === 'string' ? args.reason.trim() : undefined;
|
|
269
|
+
const rawSource = args.source === undefined || args.source === null ? 'agent' : String(args.source);
|
|
270
|
+
const source = rawSource === 'user' ? 'user' : 'agent';
|
|
271
|
+
const userQuote = source === 'user' && typeof args.user_quote === 'string' ? args.user_quote.trim() : '';
|
|
272
|
+
const metricScope = ['team', 'personal', 'project'].includes(scope)
|
|
273
|
+
? scope
|
|
274
|
+
: 'personal';
|
|
275
|
+
const metricAction = ['create', 'update', 'supersede'].includes(action)
|
|
276
|
+
? action
|
|
277
|
+
: 'create';
|
|
278
|
+
const recordPropose = (outcome, hygieneCategory) => {
|
|
279
|
+
// A check-only pass (before the pull) records nothing; the real pass does.
|
|
280
|
+
if (checkOnly)
|
|
281
|
+
return;
|
|
282
|
+
appendMetric({
|
|
283
|
+
type: 'propose',
|
|
284
|
+
ts: new Date().toISOString(),
|
|
285
|
+
source: 'mcp',
|
|
286
|
+
scope: metricScope,
|
|
287
|
+
action: metricAction,
|
|
288
|
+
outcome,
|
|
289
|
+
...(hygieneCategory ? { hygiene_category: hygieneCategory } : {}),
|
|
290
|
+
origin: source,
|
|
291
|
+
}, this.homeDir);
|
|
292
|
+
};
|
|
293
|
+
const fail = (message, extra) => {
|
|
294
|
+
recordPropose('validation_error');
|
|
295
|
+
return { response: errorResponse(message, extra) };
|
|
296
|
+
};
|
|
297
|
+
if (rawSource !== 'agent' && rawSource !== 'user') {
|
|
298
|
+
return fail('Invalid source; expected "agent" or "user".');
|
|
299
|
+
}
|
|
300
|
+
if (source === 'user' && !userQuote) {
|
|
301
|
+
return fail('user_quote is required when source is "user": pass the user\'s exact words.');
|
|
302
|
+
}
|
|
303
|
+
if (userQuote.length > MAX_USER_QUOTE_CHARS) {
|
|
304
|
+
return fail(`user_quote is too long (max ${MAX_USER_QUOTE_CHARS} characters).`);
|
|
305
|
+
}
|
|
306
|
+
if (!['create', 'update', 'supersede'].includes(action)) {
|
|
307
|
+
return fail('Invalid action; expected create, update, or supersede.');
|
|
308
|
+
}
|
|
309
|
+
if (!['team', 'personal', 'project'].includes(scope)) {
|
|
310
|
+
return fail('Invalid scope; expected team, personal, or project.');
|
|
311
|
+
}
|
|
312
|
+
if (!summary)
|
|
313
|
+
return fail('summary is required.');
|
|
314
|
+
if (!VALID_TYPES.includes(type)) {
|
|
315
|
+
return fail(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
|
|
316
|
+
}
|
|
317
|
+
if (!body)
|
|
318
|
+
return fail('body is required.');
|
|
319
|
+
if (scope === 'personal' && isReadOnlyRoot(config.roots.personal)) {
|
|
320
|
+
return fail(READ_ONLY_MESSAGE);
|
|
321
|
+
}
|
|
322
|
+
// Validate target_id for update / supersede (AC-08c1, AC-08c2)
|
|
323
|
+
if (action === 'update' || action === 'supersede') {
|
|
324
|
+
if (!targetId)
|
|
325
|
+
return fail(`target_id is required when action is "${action}".`);
|
|
326
|
+
const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
|
|
327
|
+
loaded.activeEntries.some((e) => e.id === targetId);
|
|
328
|
+
if (!exists)
|
|
329
|
+
return fail(`Target entry "${targetId}" not found in active memory.`);
|
|
330
|
+
}
|
|
331
|
+
// Hygiene scan (AC-20a; 06 FR-02 adds the quote)
|
|
332
|
+
const hygieneFindings = scanHygiene(`${summary}\n${body}${userQuote ? `\n${userQuote}` : ''}`);
|
|
333
|
+
if (hygieneFindings.length > 0) {
|
|
334
|
+
const hasSecret = hygieneFindings.some((f) => f.category === 'secret');
|
|
335
|
+
recordPropose('hygiene_blocked', hasSecret ? 'secret' : 'machine-path');
|
|
336
|
+
return {
|
|
337
|
+
response: errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings }),
|
|
261
338
|
};
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
recordPropose('validation_error');
|
|
268
|
-
return errorResponse('Invalid scope; expected team, personal, or project.');
|
|
269
|
-
}
|
|
270
|
-
if (!summary) {
|
|
271
|
-
recordPropose('validation_error');
|
|
272
|
-
return errorResponse('summary is required.');
|
|
273
|
-
}
|
|
274
|
-
if (!VALID_TYPES.includes(type)) {
|
|
275
|
-
recordPropose('validation_error');
|
|
276
|
-
return errorResponse(`Invalid type; expected one of: ${VALID_TYPES.join(', ')}`);
|
|
277
|
-
}
|
|
278
|
-
if (!body) {
|
|
279
|
-
recordPropose('validation_error');
|
|
280
|
-
return errorResponse('body is required.');
|
|
281
|
-
}
|
|
282
|
-
if (scope === 'personal' && isReadOnlyRoot(config.roots.personal)) {
|
|
283
|
-
recordPropose('validation_error');
|
|
284
|
-
return errorResponse(READ_ONLY_MESSAGE);
|
|
285
|
-
}
|
|
286
|
-
// Validate target_id for update / supersede (AC-08c1, AC-08c2)
|
|
287
|
-
if (action === 'update' || action === 'supersede') {
|
|
288
|
-
if (!targetId) {
|
|
289
|
-
recordPropose('validation_error');
|
|
290
|
-
return errorResponse(`target_id is required when action is "${action}".`);
|
|
291
|
-
}
|
|
292
|
-
const exists = loaded.activeEntries.some((e) => e.id === targetId && e.scope === scope) ||
|
|
293
|
-
loaded.activeEntries.some((e) => e.id === targetId);
|
|
294
|
-
if (!exists) {
|
|
295
|
-
recordPropose('validation_error');
|
|
296
|
-
return errorResponse(`Target entry "${targetId}" not found in active memory.`);
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
// Hygiene scan (AC-20a)
|
|
300
|
-
const hygieneFindings = scanHygiene(`${summary}\n${body}`);
|
|
301
|
-
if (hygieneFindings.length > 0) {
|
|
302
|
-
const hasSecret = hygieneFindings.some((f) => f.category === 'secret');
|
|
303
|
-
recordPropose('hygiene_blocked', hasSecret ? 'secret' : 'machine-path');
|
|
304
|
-
return errorResponse(`Hygiene scan rejected proposal:\n${formatHygieneErrors(hygieneFindings)}`, { findings: hygieneFindings });
|
|
339
|
+
}
|
|
340
|
+
// Near-duplicate check on create (AC-10, AC-11)
|
|
341
|
+
if (action === 'create') {
|
|
342
|
+
if (forceNew && !reason) {
|
|
343
|
+
return fail('A non-empty "reason" is required when force_new is true.');
|
|
305
344
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const pending = reconcileAwaitingCommitProposals(this.homeDir);
|
|
314
|
-
const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
|
|
315
|
-
if (matches.length > 0) {
|
|
316
|
-
recordPropose('duplicate_blocked');
|
|
317
|
-
return errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
|
|
345
|
+
if (!forceNew) {
|
|
346
|
+
const pending = reconcileAwaitingCommitProposals(this.homeDir);
|
|
347
|
+
const matches = findNearDuplicates(summary, body, loaded.activeEntries, pending, config.similarityThreshold);
|
|
348
|
+
if (matches.length > 0) {
|
|
349
|
+
recordPropose('duplicate_blocked');
|
|
350
|
+
return {
|
|
351
|
+
response: errorResponse('Near-duplicate entry found. Use action "update" or "supersede", or pass force_new: true with a reason.', {
|
|
318
352
|
matches: matches.map((m) => ({
|
|
319
353
|
id: m.id,
|
|
320
354
|
scope: m.scope,
|
|
@@ -322,61 +356,158 @@ export class FaberMemoryMcpServer {
|
|
|
322
356
|
pending: m.pending,
|
|
323
357
|
similarity: m.similarity,
|
|
324
358
|
})),
|
|
325
|
-
})
|
|
326
|
-
}
|
|
359
|
+
}),
|
|
360
|
+
};
|
|
327
361
|
}
|
|
328
362
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
363
|
+
}
|
|
364
|
+
// 06 FR-03: a rule the user dictates always reaches the startup index.
|
|
365
|
+
let l0Note;
|
|
366
|
+
if (source === 'user' && scope !== 'project' && l0 !== 'body' && l0 !== 'line') {
|
|
367
|
+
l0Note = `l0 set to "line" (was ${l0 ? `"${l0}"` : 'not set'}): a memory the user asks for is listed in the startup index.`;
|
|
368
|
+
l0 = 'line';
|
|
369
|
+
}
|
|
370
|
+
let stagedReason;
|
|
371
|
+
if (source === 'user') {
|
|
372
|
+
stagedReason = this.directSaveBlocker(config, scope);
|
|
373
|
+
}
|
|
374
|
+
if (checkOnly) {
|
|
375
|
+
return { response: jsonResponse({}), checksPassed: true, directEligible: source === 'user' && !stagedReason };
|
|
376
|
+
}
|
|
377
|
+
const input = {
|
|
378
|
+
scope,
|
|
379
|
+
action,
|
|
380
|
+
entryId,
|
|
381
|
+
targetId,
|
|
382
|
+
summary,
|
|
383
|
+
type,
|
|
384
|
+
tags,
|
|
385
|
+
l0,
|
|
386
|
+
body,
|
|
387
|
+
forceNew,
|
|
388
|
+
reason,
|
|
389
|
+
projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
|
|
390
|
+
...(source === 'user' ? { source, userQuote } : {}),
|
|
391
|
+
};
|
|
392
|
+
try {
|
|
393
|
+
let stagedErrors = [];
|
|
394
|
+
if (source === 'user' && !stagedReason) {
|
|
395
|
+
const proposal = buildProposal(config, input);
|
|
396
|
+
const saved = directSavePersonal(config, proposal, this.homeDir);
|
|
397
|
+
if (saved.ok) {
|
|
398
|
+
this.directSaveCount++;
|
|
399
|
+
recordPropose('direct_saved');
|
|
400
|
+
this.lastHeadSignature = '';
|
|
401
|
+
// The unpushed reminder is decided after the push step (03 FR-03, 06 FR-02).
|
|
402
|
+
const warnings = [...extraWarnings, ...this.drainWarnings(loaded, false)];
|
|
403
|
+
this.unpushedReminderShown = false;
|
|
404
|
+
const payload = {
|
|
405
|
+
status: 'saved',
|
|
406
|
+
entry_id: proposal.entryId,
|
|
407
|
+
scope: 'personal',
|
|
408
|
+
commit: saved.commit.slice(0, 7),
|
|
409
|
+
l0: proposal.l0,
|
|
410
|
+
...(l0Note ? { l0_note: l0Note } : {}),
|
|
411
|
+
push: 'local',
|
|
412
|
+
note: CACHE_GUIDANCE_NOTE,
|
|
413
|
+
tell_user: `Saved to your personal memory: "${proposal.summary}". It is in the startup index from your next session. ` +
|
|
414
|
+
`To undo: faber-memory undo ${proposal.entryId}`,
|
|
415
|
+
warnings,
|
|
416
|
+
};
|
|
417
|
+
return { response: jsonResponse(payload), payload, directSaved: true, commit: saved.commit };
|
|
418
|
+
}
|
|
419
|
+
stagedReason = saved.stagedReason;
|
|
420
|
+
stagedErrors = saved.errors;
|
|
373
421
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
422
|
+
const proposal = createProposal(config, { ...input, ...(stagedReason ? { stagedReason } : {}) }, this.homeDir);
|
|
423
|
+
recordPropose('staged');
|
|
424
|
+
// 01 FR-04 amendment: say what the similarity check found, without blocking.
|
|
425
|
+
const similar = action === 'create'
|
|
426
|
+
? findRelatedEntries(summary, body, loaded.activeEntries, reconcileAwaitingCommitProposals(this.homeDir).filter((p) => p.id !== proposal.id), config.similarityHintFloor ?? DEFAULT_SIMILARITY_HINT_FLOOR, config.similarityThreshold).map((m) => ({ id: m.id, scope: m.scope, summary: m.summary, pending: m.pending, similarity: m.similarity }))
|
|
427
|
+
: [];
|
|
428
|
+
this.lastHeadSignature = '';
|
|
429
|
+
const warnings = [...extraWarnings, ...stagedErrors, ...this.drainWarnings(loaded)];
|
|
430
|
+
const payload = {
|
|
431
|
+
status: 'staged',
|
|
432
|
+
proposal_id: proposal.id,
|
|
433
|
+
entry_id: proposal.entryId,
|
|
434
|
+
scope: proposal.scope,
|
|
435
|
+
...(stagedReason ? { staged_reason: stagedReason, staged_note: STAGED_REASON_TEXT[stagedReason] } : {}),
|
|
436
|
+
...(l0Note ? { l0_note: l0Note } : {}),
|
|
437
|
+
...(action === 'create'
|
|
438
|
+
? {
|
|
439
|
+
similar,
|
|
440
|
+
...(similar.length > 0
|
|
441
|
+
? { similar_note: 'a related entry exists; prefer update if it is the same fact' }
|
|
442
|
+
: {}),
|
|
443
|
+
}
|
|
444
|
+
: {}),
|
|
445
|
+
warnings,
|
|
446
|
+
};
|
|
447
|
+
return { response: jsonResponse(payload), payload };
|
|
448
|
+
}
|
|
449
|
+
catch (err) {
|
|
450
|
+
return fail(err instanceof Error ? err.message : String(err));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/** 06 FR-02/FR-05/FR-06: why a user-dictated call must be staged, or undefined when it can be saved directly. */
|
|
454
|
+
directSaveBlocker(config, scope) {
|
|
455
|
+
if (scope !== 'personal' || !config.roots.personal)
|
|
456
|
+
return 'scope';
|
|
457
|
+
if (!isDirectUserSaveOn(config))
|
|
458
|
+
return 'disabled';
|
|
459
|
+
if (this.directSaveCount >= DIRECT_SAVE_SESSION_CAP)
|
|
460
|
+
return 'session_cap';
|
|
461
|
+
return undefined;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Like `handleToolCall`, but a user-dictated personal save pulls before it commits
|
|
465
|
+
* (03 FR-04) and pushes per `pushMode` after (03 FR-02, 06 FR-02).
|
|
466
|
+
*/
|
|
467
|
+
async handleToolCallAsync(name, args = {}) {
|
|
468
|
+
if (name !== 'memory_propose' || args.source !== 'user') {
|
|
469
|
+
return this.handleToolCall(name, args);
|
|
470
|
+
}
|
|
471
|
+
const config = loadConfig(this.homeDir);
|
|
472
|
+
const root = config.roots.personal;
|
|
473
|
+
const extraWarnings = [];
|
|
474
|
+
// 06 FR-02: validate, scan and check duplicates first; pull only for a call that will be saved.
|
|
475
|
+
const check = this.handlePropose(args, [], true);
|
|
476
|
+
if (check.checksPassed && check.directEligible && root) {
|
|
477
|
+
// Never pull while the startup sync may still be writing the same repository.
|
|
478
|
+
if (this.startupPullPromise)
|
|
479
|
+
await this.startupPullPromise;
|
|
480
|
+
const pullWarning = await pullRebaseBeforeCommit(root);
|
|
481
|
+
if (pullWarning)
|
|
482
|
+
extraWarnings.push(pullWarning);
|
|
483
|
+
this.lastHeadSignature = '';
|
|
484
|
+
}
|
|
485
|
+
const handled = this.handlePropose(args, extraWarnings);
|
|
486
|
+
if (!handled.directSaved || !handled.payload || !root || !handled.commit)
|
|
487
|
+
return handled.response;
|
|
488
|
+
let push = 'local';
|
|
489
|
+
if (getPushMode(root) === 'auto' && getAheadInfo(root.path).hasRemote) {
|
|
490
|
+
const res = await pushPersonalRoot(root, this.homeDir);
|
|
491
|
+
push = res.ok ? 'pushed' : 'push_failed';
|
|
492
|
+
if (!res.ok)
|
|
493
|
+
handled.payload.warnings.push(res.message);
|
|
494
|
+
// A push may rebase the save onto origin: keep the log, the result and L0 in step.
|
|
495
|
+
const moved = followRebasedDirectSave(config, handled.commit, this.homeDir);
|
|
496
|
+
if (moved) {
|
|
497
|
+
handled.payload.commit = moved.slice(0, 7);
|
|
498
|
+
this.lastHeadSignature = '';
|
|
377
499
|
}
|
|
378
500
|
}
|
|
379
|
-
|
|
501
|
+
handled.payload.push = push;
|
|
502
|
+
return jsonResponse(handled.payload);
|
|
503
|
+
}
|
|
504
|
+
/** JSON-RPC entry for stdio: like `handleJsonRpc`, with `tools/call` via `handleToolCallAsync`. */
|
|
505
|
+
async handleJsonRpcAsync(req) {
|
|
506
|
+
if (req.method !== 'tools/call')
|
|
507
|
+
return this.handleJsonRpc(req);
|
|
508
|
+
const params = req.params || {};
|
|
509
|
+
const res = await this.handleToolCallAsync(String(params.name || ''), params.arguments || {});
|
|
510
|
+
return { jsonrpc: '2.0', id: req.id ?? null, result: res };
|
|
380
511
|
}
|
|
381
512
|
handleJsonRpc(req) {
|
|
382
513
|
if (req.method === 'initialize') {
|
|
@@ -436,10 +567,15 @@ export class FaberMemoryMcpServer {
|
|
|
436
567
|
return;
|
|
437
568
|
try {
|
|
438
569
|
const req = JSON.parse(trimmed);
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
570
|
+
this.queue = this.queue.then(async () => {
|
|
571
|
+
const resp = await this.handleJsonRpcAsync(req).catch((err) => ({
|
|
572
|
+
jsonrpc: '2.0',
|
|
573
|
+
id: req.id ?? null,
|
|
574
|
+
error: { code: -32603, message: err instanceof Error ? err.message : String(err) },
|
|
575
|
+
}));
|
|
576
|
+
if (resp)
|
|
577
|
+
process.stdout.write(JSON.stringify(resp) + '\n');
|
|
578
|
+
});
|
|
443
579
|
}
|
|
444
580
|
catch (err) {
|
|
445
581
|
const errResp = {
|
|
@@ -461,3 +597,6 @@ function errorResponse(message, extra) {
|
|
|
461
597
|
content: [{ type: 'text', text: JSON.stringify({ error: message, ...extra }, null, 2) }],
|
|
462
598
|
};
|
|
463
599
|
}
|
|
600
|
+
function jsonResponse(payload) {
|
|
601
|
+
return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
|
|
602
|
+
}
|