@fabersep/memory 0.3.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/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
- const { config, loaded } = this.refreshIndexIfNeeded();
234
- const action = String(args.action || '');
235
- const scope = String(args.scope || '');
236
- const summary = typeof args.summary === 'string' ? args.summary.trim() : '';
237
- const type = String(args.type || '');
238
- const body = typeof args.body === 'string' ? args.body.trim() : '';
239
- const targetId = typeof args.target_id === 'string' ? args.target_id.trim() : undefined;
240
- const entryId = typeof args.entry_id === 'string' ? args.entry_id.trim() : undefined;
241
- const tags = Array.isArray(args.tags) ? args.tags.map(String) : [];
242
- const l0 = typeof args.l0 === 'string' ? args.l0 : undefined;
243
- const forceNew = Boolean(args.force_new);
244
- const reason = typeof args.reason === 'string' ? args.reason.trim() : undefined;
245
- const metricScope = ['team', 'personal', 'project'].includes(scope)
246
- ? scope
247
- : 'personal';
248
- const metricAction = ['create', 'update', 'supersede'].includes(action)
249
- ? action
250
- : 'create';
251
- const recordPropose = (outcome, hygieneCategory) => {
252
- appendMetric({
253
- type: 'propose',
254
- ts: new Date().toISOString(),
255
- source: 'mcp',
256
- scope: metricScope,
257
- action: metricAction,
258
- outcome,
259
- ...(hygieneCategory ? { hygiene_category: hygieneCategory } : {}),
260
- }, this.homeDir);
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
- if (!['create', 'update', 'supersede'].includes(action)) {
263
- recordPropose('validation_error');
264
- return errorResponse('Invalid action; expected create, update, or supersede.');
265
- }
266
- if (!['team', 'personal', 'project'].includes(scope)) {
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
- // Near-duplicate check on create (AC-10, AC-11)
307
- if (action === 'create') {
308
- if (forceNew && !reason) {
309
- recordPropose('validation_error');
310
- return errorResponse('A non-empty "reason" is required when force_new is true.');
311
- }
312
- if (!forceNew) {
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
- try {
330
- const proposal = createProposal(config, {
331
- scope,
332
- action,
333
- entryId,
334
- targetId,
335
- summary,
336
- type,
337
- tags,
338
- l0,
339
- body,
340
- forceNew,
341
- reason,
342
- projectRootPath: scope === 'project' ? loaded.projectResolution.projectRoot : undefined,
343
- }, this.homeDir);
344
- recordPropose('staged');
345
- // 01 FR-04 amendment: say what the similarity check found, without blocking.
346
- const similar = action === 'create'
347
- ? 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 }))
348
- : [];
349
- this.lastHeadSignature = '';
350
- const warnings = this.drainWarnings(loaded);
351
- return {
352
- content: [
353
- {
354
- type: 'text',
355
- text: JSON.stringify({
356
- status: 'staged',
357
- proposal_id: proposal.id,
358
- entry_id: proposal.entryId,
359
- scope: proposal.scope,
360
- ...(action === 'create'
361
- ? {
362
- similar,
363
- ...(similar.length > 0
364
- ? { similar_note: 'a related entry exists; prefer update if it is the same fact' }
365
- : {}),
366
- }
367
- : {}),
368
- warnings,
369
- }, null, 2),
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
- catch (err) {
375
- recordPropose('validation_error');
376
- return errorResponse(err instanceof Error ? err.message : String(err));
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
- return errorResponse(`Unknown tool: ${name}`);
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
- const resp = this.handleJsonRpc(req);
440
- if (resp) {
441
- process.stdout.write(JSON.stringify(resp) + '\n');
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
+ }
@@ -1,8 +1,8 @@
1
1
  import { ProposalAction, Scope } from './types.js';
2
2
  export type CompileTrigger = 'cli' | 'sync' | 'mcp-startup' | 'approve' | 'init';
3
3
  export type ProposeSource = 'mcp' | 'import';
4
- export type ProposeOutcome = 'staged' | 'duplicate_blocked' | 'hygiene_blocked' | 'validation_error';
5
- export type ReviewOutcome = 'approved_committed' | 'approved_pushed' | 'approved_pr' | 'push_failed' | 'awaiting_commit' | 'rejected';
4
+ export type ProposeOutcome = 'staged' | 'direct_saved' | 'duplicate_blocked' | 'hygiene_blocked' | 'validation_error';
5
+ export type ReviewOutcome = 'approved_committed' | 'approved_pushed' | 'approved_pr' | 'push_failed' | 'awaiting_commit' | 'rejected' | 'undone';
6
6
  export interface CompileMetricEvent {
7
7
  type: 'compile';
8
8
  ts: string;
@@ -40,6 +40,8 @@ export interface ProposeMetricEvent {
40
40
  action: ProposalAction;
41
41
  outcome: ProposeOutcome;
42
42
  hygiene_category?: 'secret' | 'machine-path';
43
+ /** 06 FR-08: who asked for it; absent in older events means "agent". */
44
+ origin?: 'user' | 'agent';
43
45
  }
44
46
  export interface ReviewOutcomeMetricEvent {
45
47
  type: 'review_outcome';
@@ -1,11 +1,11 @@
1
- import { EntryType, L0Mode, Proposal, ProposalAction, Scope, TeamSubmitMode, UserConfig } from './types.js';
1
+ import { EntryType, L0Mode, Proposal, ProposalAction, ProposalSource, StagedReason, Scope, TeamSubmitMode, UserConfig } from './types.js';
2
2
  export declare const CACHE_GUIDANCE_NOTE = "Note: Updated L0 applies to new sessions; batching reviews at session end maximizes prompt-cache reuse.";
3
3
  export declare function saveProposal(proposal: Proposal, homeDir?: string): string;
4
4
  export declare function deleteProposal(proposal: Proposal, homeDir?: string): void;
5
5
  export declare function listAllProposals(homeDir?: string): Proposal[];
6
6
  export declare function reconcileAwaitingCommitProposals(homeDir?: string): Proposal[];
7
7
  export declare function findProposalById(id: string, homeDir?: string): Proposal | null;
8
- export declare function createProposal(config: UserConfig, input: {
8
+ export interface ProposalInput {
9
9
  scope: Scope;
10
10
  action: ProposalAction;
11
11
  entryId?: string;
@@ -18,8 +18,15 @@ export declare function createProposal(config: UserConfig, input: {
18
18
  forceNew?: boolean;
19
19
  reason?: string;
20
20
  projectRootPath?: string;
21
- }, homeDir?: string): Proposal;
21
+ source?: ProposalSource;
22
+ userQuote?: string;
23
+ stagedReason?: StagedReason;
24
+ }
25
+ export declare function createProposal(config: UserConfig, input: ProposalInput, homeDir?: string): Proposal;
26
+ /** Builds a proposal record without writing it (06 FR-02 uses it for a direct save). */
27
+ export declare function buildProposal(config: UserConfig, input: ProposalInput): Proposal;
22
28
  export declare function rejectProposal(id: string, homeDir?: string): Proposal;
29
+ export declare function applyProposalFilesToDir(repoDir: string, subDir: string, proposal: Proposal): string[];
23
30
  export interface ApproveOutcome {
24
31
  ok: boolean;
25
32
  approvedIds: string[];
@@ -66,6 +66,12 @@ export function findProposalById(id, homeDir = getHomeDir()) {
66
66
  return all.find((p) => p.id === id) || null;
67
67
  }
68
68
  export function createProposal(config, input, homeDir = getHomeDir()) {
69
+ const proposal = buildProposal(config, input);
70
+ saveProposal(proposal, homeDir);
71
+ return proposal;
72
+ }
73
+ /** Builds a proposal record without writing it (06 FR-02 uses it for a direct save). */
74
+ export function buildProposal(config, input) {
69
75
  let rootUuid;
70
76
  if (input.scope === 'personal') {
71
77
  if (!config.roots.personal) {
@@ -107,8 +113,14 @@ export function createProposal(config, input, homeDir = getHomeDir()) {
107
113
  status: 'pending',
108
114
  createdAt: new Date().toISOString(),
109
115
  projectRootPath: input.projectRootPath,
116
+ ...(input.source === 'user'
117
+ ? {
118
+ source: 'user',
119
+ userQuote: input.userQuote,
120
+ ...(input.stagedReason ? { stagedReason: input.stagedReason } : {}),
121
+ }
122
+ : {}),
110
123
  };
111
- saveProposal(proposal, homeDir);
112
124
  return proposal;
113
125
  }
114
126
  export function rejectProposal(id, homeDir = getHomeDir()) {
@@ -125,7 +137,7 @@ export function rejectProposal(id, homeDir = getHomeDir()) {
125
137
  }, homeDir);
126
138
  return proposal;
127
139
  }
128
- function applyProposalFilesToDir(repoDir, subDir, proposal) {
140
+ export function applyProposalFilesToDir(repoDir, subDir, proposal) {
129
141
  const touched = [];
130
142
  const targetDir = subDir ? path.join(repoDir, subDir) : repoDir;
131
143
  fs.mkdirSync(targetDir, { recursive: true });
@@ -94,6 +94,12 @@ export interface StatsReport {
94
94
  awaitingCommit: number;
95
95
  rejected: number;
96
96
  };
97
+ /** 06 FR-08: memories the user dictated. */
98
+ userDictated: {
99
+ directSaved: number;
100
+ staged: number;
101
+ undone: number;
102
+ };
97
103
  };
98
104
  cache?: CacheAnalysisResult;
99
105
  }
@@ -137,6 +143,8 @@ export interface ShareableBenchmarkJson {
137
143
  pushFailed: number;
138
144
  awaitingCommit: number;
139
145
  rejected: number;
146
+ directSaved: number;
147
+ userDictatedStaged: number;
140
148
  };
141
149
  cache?: Partial<Record<'claude-code' | 'antigravity', {
142
150
  sessions: number;