@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.
@@ -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;
package/dist/src/stats.js CHANGED
@@ -97,6 +97,7 @@ export function computeStats(options = {}) {
97
97
  awaitingCommit: 0,
98
98
  rejected: 0,
99
99
  },
100
+ userDictated: { directSaved: 0, staged: 0, undone: 0 },
100
101
  },
101
102
  };
102
103
  }
@@ -224,12 +225,17 @@ export function computeStats(options = {}) {
224
225
  awaitingCommit: 0,
225
226
  rejected: 0,
226
227
  },
228
+ userDictated: { directSaved: 0, staged: 0, undone: 0 },
227
229
  };
228
230
  for (const ev of windowEvents) {
229
231
  if (ev.type === 'propose') {
230
232
  const p = ev;
231
233
  const bucket = p.source === 'import' ? funnel.bySource.import : funnel.bySource.mcp;
232
- if (p.outcome === 'staged')
234
+ if (p.origin === 'user' && p.outcome === 'staged')
235
+ funnel.userDictated.staged++;
236
+ if (p.outcome === 'direct_saved')
237
+ funnel.userDictated.directSaved++;
238
+ else if (p.outcome === 'staged')
233
239
  bucket.staged++;
234
240
  else if (p.outcome === 'duplicate_blocked')
235
241
  bucket.duplicateBlocked++;
@@ -256,6 +262,8 @@ export function computeStats(options = {}) {
256
262
  funnel.reviewOutcomes.awaitingCommit++;
257
263
  else if (r.outcome === 'rejected')
258
264
  funnel.reviewOutcomes.rejected++;
265
+ else if (r.outcome === 'undone')
266
+ funnel.userDictated.undone++;
259
267
  }
260
268
  }
261
269
  let cache;
@@ -330,7 +338,8 @@ export function computeStats(options = {}) {
330
338
  export function buildShareableBenchmark(report) {
331
339
  const mcpSrc = report.funnel.bySource.mcp;
332
340
  const impSrc = report.funnel.bySource.import;
333
- const proposedMcp = mcpSrc.staged +
341
+ const proposedMcp = report.funnel.userDictated.directSaved +
342
+ mcpSrc.staged +
334
343
  mcpSrc.duplicateBlocked +
335
344
  mcpSrc.hygieneBlockedSecret +
336
345
  mcpSrc.hygieneBlockedMachinePath +
@@ -380,6 +389,8 @@ export function buildShareableBenchmark(report) {
380
389
  pushFailed: report.funnel.reviewOutcomes.pushFailed,
381
390
  awaitingCommit: report.funnel.reviewOutcomes.awaitingCommit,
382
391
  rejected: report.funnel.reviewOutcomes.rejected,
392
+ directSaved: report.funnel.userDictated.directSaved,
393
+ userDictatedStaged: report.funnel.userDictated.staged,
383
394
  },
384
395
  };
385
396
  if (report.cache && report.cache.engines.length > 0) {
@@ -421,6 +432,7 @@ export function formatShareableMarkdown(card) {
421
432
  lines.push(`| Retrieval (searches / get-per-search / zero-result) | ${card.retrieval.nonEmptySearches} / ${card.retrieval.getCallsPerSearch} / ${card.retrieval.zeroResultPct}% |`);
422
433
  lines.push(`| Median BM25 search latency | ${card.retrieval.medianBm25LatencyMs !== null ? `${card.retrieval.medianBm25LatencyMs} ms` : 'n/a'} |`);
423
434
  lines.push(`| Pre-memory funnel (staged / dupes / hygiene) | ${card.funnel.staged} / ${card.funnel.duplicateBlocked} / ${card.funnel.hygieneBlockedSecret + card.funnel.hygieneBlockedMachinePath} |`);
435
+ lines.push(`| Direct saves (user asked) | ${card.funnel.directSaved} |`);
424
436
  if (card.cache) {
425
437
  for (const engineKey of ['claude-code', 'antigravity']) {
426
438
  const eng = card.cache[engineKey];
@@ -516,6 +528,8 @@ export function formatStatsReport(report) {
516
528
  lines.push(` Import proposals: staged=${imp.staged}, duplicate_blocked=${imp.duplicateBlocked}, hygiene_blocked(secret=${imp.hygieneBlockedSecret}, machine-path=${imp.hygieneBlockedMachinePath}), validation_error=${imp.validationError}`);
517
529
  const ro = report.funnel.reviewOutcomes;
518
530
  lines.push(` Review outcomes: approved_committed=${ro.approvedCommitted}, approved_pushed=${ro.approvedPushed}, approved_pr=${ro.approvedPr}, push_failed=${ro.pushFailed}, awaiting_commit=${ro.awaitingCommit}, rejected=${ro.rejected}`);
531
+ const ud = report.funnel.userDictated;
532
+ lines.push(` User asked: direct_saved=${ud.directSaved}, staged=${ud.staged} (counted in MCP staged above), undone=${ud.undone}`);
519
533
  // Cache report
520
534
  if (report.cache) {
521
535
  lines.push('');
@@ -6,6 +6,10 @@ export type TeamSubmitMode = 'auto' | 'pr';
6
6
  export type PushMode = 'ask' | 'auto' | 'never';
7
7
  export type ProposalAction = 'create' | 'update' | 'supersede';
8
8
  export type ProposalStatus = 'pending' | 'awaiting_commit' | 'push_failed';
9
+ /** 06 FR-01: who asked for a memory. */
10
+ export type ProposalSource = 'agent' | 'user';
11
+ /** 06 FR-04: why a user-dictated proposal was staged instead of saved directly. */
12
+ export type StagedReason = 'scope' | 'disabled' | 'session_cap' | 'l0_budget' | 'compile_error';
9
13
  export type ProjectRootSource = 'mcp-roots' | 'cwd' | 'none';
10
14
  export declare const COMPILER_VERSION: string;
11
15
  export declare const DEFAULT_TOKEN_BUDGET = 1500;
@@ -33,6 +37,8 @@ export interface UserConfig {
33
37
  tokenBudget: number;
34
38
  staleDays: number;
35
39
  similarityThreshold: number;
40
+ /** 06 FR-05: save user-dictated personal memories directly (default true). */
41
+ directUserSave?: boolean;
36
42
  /** Lower bound for the related-entry notice on a staged create (01 FR-04 amendment). */
37
43
  similarityHintFloor?: number;
38
44
  roots: {
@@ -89,6 +95,12 @@ export interface Proposal {
89
95
  error?: string;
90
96
  projectRootPath?: string;
91
97
  targetFilePath?: string;
98
+ /** 06 FR-04: set to "user" when the user dictated this memory. */
99
+ source?: ProposalSource;
100
+ /** 06 FR-04: the user's verbatim words. */
101
+ userQuote?: string;
102
+ /** 06 FR-04: why it was staged instead of saved directly. */
103
+ stagedReason?: StagedReason;
92
104
  }
93
105
  export interface ProjectRootResolution {
94
106
  source: ProjectRootSource;
@@ -378,6 +378,7 @@ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); f
378
378
  font-size: 11.5px; font-weight: 600; padding: 2px 8px; border-radius: 999px;
379
379
  }
380
380
  .pill-muted { background: var(--surface-subtle); color: var(--text-muted); }
381
+ .pill-direct { background: var(--ok-soft); color: var(--ok); }
381
382
  .pill-ok { background: var(--ok-soft); color: var(--ok); }
382
383
  .pill-warn { background: var(--warn-soft); color: var(--warn); }
383
384
  .pill-danger { background: var(--danger-soft); color: var(--danger); }
@@ -479,6 +480,7 @@ kbd {
479
480
  .alert { padding: 9px 12px; border-radius: 8px; font-size: 13px; margin: 8px 0; }
480
481
  .alert-warn { background: var(--warn-soft); color: var(--warn); }
481
482
  .alert-danger { background: var(--danger-soft); color: var(--danger); }
483
+ .alert-ok { background: var(--ok-soft); color: var(--ok); }
482
484
 
483
485
  .browse-controls { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }
484
486
  .input, .select, .textarea {
@@ -799,6 +801,9 @@ export function getWebClientJs() {
799
801
  const reasonHtml = p.forceNew && p.reason
800
802
  ? '<div class="alert alert-warn"><strong>Reason for new entry:</strong> ' + escapeHtml(p.reason) + '</div>'
801
803
  : '';
804
+ const userHtml = p.source === 'user'
805
+ ? '<div class="alert alert-ok"><strong>User asked:</strong> &ldquo;' + escapeHtml(p.userQuote || '') + '&rdquo;</div>'
806
+ : '';
802
807
  const errHtml = p.error
803
808
  ? '<div class="alert alert-danger"><strong>Previous error:</strong> ' + escapeHtml(p.error) + '</div>'
804
809
  : '';
@@ -841,6 +846,7 @@ export function getWebClientJs() {
841
846
  '</div>' +
842
847
  '</div>' +
843
848
  '<div class="proposal-summary">' + escapeHtml(p.summary) + '</div>' +
849
+ userHtml +
844
850
  reasonHtml +
845
851
  errHtml +
846
852
  bodyHtml +
@@ -968,6 +974,24 @@ export function getWebClientJs() {
968
974
  }
969
975
  }
970
976
 
977
+ async function undoDirectSave(e) {
978
+ if (state.readOnly) return;
979
+ try {
980
+ const res = await apiPost('/api/memories/personal/' + encodeURIComponent(e.id) + '/undo', {});
981
+ state.selectedMemoryKey = null;
982
+ state.selectedMemoryEntry = null;
983
+ $('memory-detail').innerHTML = '<div class="empty-state">Select a memory entry to inspect, edit, or delete it.</div>';
984
+ if (res.pushResult && !res.pushResult.ok) {
985
+ showBanner('warn', (res.message || 'Undone.') + ' ' + res.pushResult.message);
986
+ } else {
987
+ showBanner('ok', res.message || 'Undone.');
988
+ }
989
+ await Promise.all([loadMemories(), loadHealth()]);
990
+ } catch (err) {
991
+ showBanner('danger', err.message);
992
+ }
993
+ }
994
+
971
995
  async function confirmDeleteMemory() {
972
996
  if (!state.deleteTarget || state.readOnly) return;
973
997
  const { scope, id } = state.deleteTarget;
@@ -1089,6 +1113,7 @@ export function getWebClientJs() {
1089
1113
  '<div class="memory-item-head">' +
1090
1114
  '<span class="mono-id">' + escapeHtml(m.id) + '</span>' +
1091
1115
  scopePill(m.scope) +
1116
+ (m.addedDirectly ? '<span class="pill pill-direct" title="Saved on your word, without review">added directly</span>' : '') +
1092
1117
  '</div>' +
1093
1118
  '<div class="memory-item-summary">' + escapeHtml(m.summary) + '</div>' +
1094
1119
  '</button>'
@@ -1114,9 +1139,14 @@ export function getWebClientJs() {
1114
1139
  const linksHtml = (e.links || []).length > 0
1115
1140
  ? '<div style="margin-top:12px;"><strong>Links:</strong> ' + e.links.map((l) => '<span class="pill pill-muted">' + escapeHtml(l) + '</span>').join(' ') + '</div>'
1116
1141
  : '';
1142
+ const ds = data.directSave;
1143
+ const directHtml = ds
1144
+ ? '<div class="alert alert-ok"><strong>Added directly</strong> on your word (' + escapeHtml(ds.ts.slice(0, 10)) + '): &ldquo;' + escapeHtml(ds.quote) + '&rdquo;</div>'
1145
+ : '';
1117
1146
  const actionsHtml = state.readOnly
1118
1147
  ? '<span class="pill pill-muted">Read-only</span>'
1119
1148
  : '<div class="proposal-actions">' +
1149
+ (ds ? '<button id="btn-mem-undo" class="btn btn-secondary" title="Revert the commit that saved it">Undo</button>' : '') +
1120
1150
  '<button id="btn-mem-edit" class="btn btn-secondary">Edit</button>' +
1121
1151
  '<button id="btn-mem-delete" class="btn btn-reject">Delete</button>' +
1122
1152
  '</div>';
@@ -1133,6 +1163,7 @@ export function getWebClientJs() {
1133
1163
  actionsHtml +
1134
1164
  '</div>' +
1135
1165
  '<div class="proposal-summary">' + escapeHtml(e.summary) + '</div>' +
1166
+ directHtml +
1136
1167
  shadowHtml +
1137
1168
  '<div class="meta-grid">' +
1138
1169
  '<div class="meta-kv"><span class="meta-k">File</span><span class="meta-v">' + escapeHtml(e.filePath) + '</span></div>' +
@@ -1147,6 +1178,8 @@ export function getWebClientJs() {
1147
1178
  const delBtn = $('btn-mem-delete');
1148
1179
  if (editBtn) editBtn.addEventListener('click', () => openMemoryEditModal(e));
1149
1180
  if (delBtn) delBtn.addEventListener('click', () => openDeleteModal(e));
1181
+ const undoBtn = $('btn-mem-undo');
1182
+ if (undoBtn) undoBtn.addEventListener('click', () => undoDirectSave(e));
1150
1183
  } catch (err) {
1151
1184
  detail.innerHTML = '<div class="alert alert-danger">' + escapeHtml(err.message) + '</div>';
1152
1185
  }
package/dist/src/web.js CHANGED
@@ -6,6 +6,7 @@ import * as path from 'node:path';
6
6
  import { BM25Index } from './bm25.js';
7
7
  import { compileGlobalL0, estimateTokens } from './compiler.js';
8
8
  import { getCompiledL0Path, getHomeDir, loadConfig } from './config.js';
9
+ import { getActiveDirectSaves, undoDirectSave } from './direct-save.js';
9
10
  import { runDoctor } from './doctor.js';
10
11
  import { serializeEntryMarkdown } from './frontmatter.js';
11
12
  import { buildCompareUrl, createThrowawayWorktree, getDefaultBranch, getRemoteUrl, gitCommitFiles, gitPullFfOnly, gitSync, isBranchProtectionRejection, removeThrowawayWorktree, } from './git.js';
@@ -529,8 +530,10 @@ export async function startWebServer(options = {}) {
529
530
  return false;
530
531
  return true;
531
532
  });
533
+ const direct = getActiveDirectSaves(homeDir);
532
534
  sendJson(res, 200, {
533
535
  entries: entries.map((e) => ({
536
+ addedDirectly: e.scope === 'personal' && direct.has(e.id),
534
537
  id: e.id,
535
538
  scope: e.scope,
536
539
  type: e.type,
@@ -559,6 +562,7 @@ export async function startWebServer(options = {}) {
559
562
  type: typeFilter && isValidType(typeFilter) ? typeFilter : undefined,
560
563
  limit: 100,
561
564
  });
565
+ const direct = getActiveDirectSaves(homeDir);
562
566
  const entryByKey = new Map();
563
567
  for (const e of loaded.activeEntries) {
564
568
  entryByKey.set(`${e.scope}:${e.id}`, e);
@@ -568,6 +572,7 @@ export async function startWebServer(options = {}) {
568
572
  const full = entryByKey.get(`${r.scope}:${r.id}`);
569
573
  return {
570
574
  ...r,
575
+ addedDirectly: r.scope === 'personal' && direct.has(r.id),
571
576
  status: full?.status || 'active',
572
577
  l0: full?.l0 || 'line',
573
578
  };
@@ -848,6 +853,35 @@ export async function startWebServer(options = {}) {
848
853
  return;
849
854
  }
850
855
  // GET /api/memories/:scope/:id
856
+ // POST /api/memories/personal/:id/undo (06 FR-06)
857
+ const undoMatch = pathname.match(/^\/api\/memories\/personal\/([^/]+)\/undo$/);
858
+ if (method === 'POST' && undoMatch) {
859
+ const ro = effectiveReadOnly();
860
+ if (ro.readOnly) {
861
+ sendJson(res, 403, { error: ro.reason });
862
+ return;
863
+ }
864
+ const config = loadConfig(homeDir);
865
+ const result = undoDirectSave(config, decodeURIComponent(undoMatch[1]), homeDir);
866
+ if (!result.ok) {
867
+ sendJson(res, 400, { error: result.errors.join('\n'), messages: result.messages });
868
+ return;
869
+ }
870
+ let pushResult = null;
871
+ const root = config.roots.personal;
872
+ if (root && getPushMode(root) === 'auto') {
873
+ const aheadNow = getAheadInfo(root.path);
874
+ if (aheadNow.hasRemote && aheadNow.ahead > 0)
875
+ pushResult = await pushPersonalRoot(root, homeDir);
876
+ }
877
+ sendJson(res, 200, {
878
+ ok: true,
879
+ message: result.messages.join(' '),
880
+ pushResult,
881
+ unpushedReminder: getUnpushedReminder(config, homeDir),
882
+ });
883
+ return;
884
+ }
851
885
  const detailMatch = pathname.match(/^\/api\/memories\/([^/]+)\/([^/]+)$/);
852
886
  if (method === 'GET' && detailMatch) {
853
887
  const scope = decodeURIComponent(detailMatch[1]);
@@ -863,7 +897,11 @@ export async function startWebServer(options = {}) {
863
897
  sendJson(res, 404, { error: `Memory entry "${scope}/${id}" not found.` });
864
898
  return;
865
899
  }
866
- sendJson(res, 200, { entry });
900
+ const rec = scope === 'personal' ? getActiveDirectSaves(homeDir).get(id) : undefined;
901
+ sendJson(res, 200, {
902
+ entry,
903
+ directSave: rec ? { quote: rec.quote || '', ts: rec.ts, commit: rec.commit.slice(0, 7) } : null,
904
+ });
867
905
  return;
868
906
  }
869
907
  // GET /api/health
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabersep/memory",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "private": false,
5
5
  "description": "Prefix-cache-first, Git-backed Markdown memory MCP server, pre-memory staging, and import CLI for AI coding agents.",
6
6
  "license": "Apache-2.0",