@fabersep/memory 0.1.0 → 0.2.1

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/cli.js CHANGED
@@ -4,13 +4,23 @@ import * as path from 'node:path';
4
4
  import * as readline from 'node:readline';
5
5
  import { compileGlobalL0 } from './compiler.js';
6
6
  import { generateUuid, getCompiledL0Path, getDefaultPersonalPath, getHomeDir, loadConfig, saveConfig, } from './config.js';
7
- import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, isGitRepo, } from './git.js';
7
+ import { formatDoctorReport, runDoctor } from './doctor.js';
8
+ import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, gitSync, isGitRepo, } from './git.js';
8
9
  import { runImport } from './importer.js';
9
- import { formatUnifiedDiff, planOrApplyInit } from './init.js';
10
+ import { formatPlanBeforeAfter, planOrApplyInit } from './init.js';
10
11
  import { FaberMemoryMcpServer } from './mcp.js';
11
12
  import { approveProposalsBatch, findProposalById, reconcileAwaitingCommitProposals, rejectProposal, saveProposal, } from './proposals.js';
13
+ import { buildShareableBenchmark, computeStats, formatShareableMarkdown, formatStatsReport, validateDaysArg, } from './stats.js';
12
14
  import { loadAllScopes, resolveProjectRoot } from './store.js';
13
15
  import { syncAllRoots } from './sync.js';
16
+ import { getPackageVersion } from './version.js';
17
+ import { c, hr, inferErrorAnchor, normalizeTeamUrl, troubleshootingLink, } from './ui.js';
18
+ // Flags that never take a value, so `init --preview ~/notes` keeps ~/notes as a positional.
19
+ const BOOLEAN_FLAGS = new Set([
20
+ 'apply', 'undo', 'preview', 'dry-run', 'check', 'json', 'strict', 'cache', 'share', 'yes',
21
+ 'all', 'approve', 'approve-all', 'split-headings', 'normalize-paths', 'project-hint',
22
+ 'include-personal-repo', 'help',
23
+ ]);
14
24
  function parseFlags(args) {
15
25
  const positional = [];
16
26
  const flags = {};
@@ -24,7 +34,7 @@ function parseFlags(args) {
24
34
  else {
25
35
  const key = arg.slice(2);
26
36
  const next = args[i + 1];
27
- if (next && !next.startsWith('--')) {
37
+ if (next && !next.startsWith('--') && !BOOLEAN_FLAGS.has(key)) {
28
38
  flags[key] = next;
29
39
  i++;
30
40
  }
@@ -39,11 +49,60 @@ function parseFlags(args) {
39
49
  }
40
50
  return { positional, flags };
41
51
  }
52
+ async function promptLine(question) {
53
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
54
+ try {
55
+ return await new Promise((resolve) => {
56
+ rl.question(question, (ans) => resolve(ans.trim()));
57
+ });
58
+ }
59
+ finally {
60
+ rl.close();
61
+ }
62
+ }
63
+ function printErrorWithHelp(errMsg) {
64
+ console.error(c.red(`Error: ${errMsg}`));
65
+ const anchor = inferErrorAnchor(errMsg);
66
+ if (anchor) {
67
+ console.error(c.dim(` Details: ${troubleshootingLink(anchor)}`));
68
+ }
69
+ }
70
+ function createPersonalRoot(config, personalPath, homeDir) {
71
+ const existed = isGitRepo(personalPath);
72
+ gitInitSoloRepo(personalPath, 'main');
73
+ config.roots.personal = {
74
+ uuid: config.roots.personal?.uuid || generateUuid(),
75
+ path: personalPath,
76
+ scope: 'personal',
77
+ defaultBranch: existed ? getDefaultBranch(personalPath) : 'main',
78
+ };
79
+ saveConfig(config, homeDir);
80
+ }
81
+ // Notes already in a chosen folder are not active until they are in Git HEAD.
82
+ function printUncommittedNotesHint(dir) {
83
+ let count = 0;
84
+ try {
85
+ const res = gitSync(['--no-optional-locks', '-C', dir, 'status', '--porcelain', '-uall']);
86
+ if (!res.ok)
87
+ return;
88
+ count = res.stdout.split('\n').filter((l) => /\.md"?$/i.test(l.trim())).length;
89
+ }
90
+ catch {
91
+ return;
92
+ }
93
+ if (count > 0) {
94
+ console.log(c.yellow(`Found ${count} Markdown file(s) in ${dir} that are not committed yet; memory only reads committed notes. Commit them, or bring them in for review with: faber-memory import --from markdown-dir ${dir}`));
95
+ }
96
+ }
42
97
  async function main() {
43
98
  const argv = process.argv.slice(2);
44
99
  const cmd = argv[0];
45
100
  const { positional, flags } = parseFlags(argv.slice(1));
46
101
  const homeDir = getHomeDir();
102
+ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
103
+ console.log(getPackageVersion());
104
+ return 0;
105
+ }
47
106
  if (!cmd || cmd === '--help' || cmd === '-h') {
48
107
  printHelp();
49
108
  return 0;
@@ -56,7 +115,11 @@ async function main() {
56
115
  if (cmd === 'setup') {
57
116
  const config = loadConfig(homeDir);
58
117
  if (flags.team) {
59
- const url = String(flags.team);
118
+ const rawUrl = String(flags.team);
119
+ const { url, normalized } = normalizeTeamUrl(rawUrl);
120
+ if (normalized) {
121
+ console.log(c.dim(`Normalized team URL: ${rawUrl} -> ${url}`));
122
+ }
60
123
  const dest = typeof flags.path === 'string'
61
124
  ? path.resolve(flags.path)
62
125
  : path.join(homeDir, 'clones', 'team');
@@ -73,7 +136,7 @@ async function main() {
73
136
  submitMode,
74
137
  };
75
138
  saveConfig(config, homeDir);
76
- console.log(`Configured team root at ${dest} (branch: ${defaultBranch}, uuid: ${config.roots.team.uuid})`);
139
+ console.log(c.green(`Configured team root at ${dest} (branch: ${defaultBranch}, uuid: ${config.roots.team.uuid})`));
77
140
  return 0;
78
141
  }
79
142
  const personalPath = typeof flags.path === 'string'
@@ -81,15 +144,9 @@ async function main() {
81
144
  : positional[0]
82
145
  ? path.resolve(positional[0])
83
146
  : getDefaultPersonalPath();
84
- gitInitSoloRepo(personalPath, 'main');
85
- config.roots.personal = {
86
- uuid: config.roots.personal?.uuid || generateUuid(),
87
- path: personalPath,
88
- scope: 'personal',
89
- defaultBranch: 'main',
90
- };
91
- saveConfig(config, homeDir);
92
- console.log(`Initialized personal memory root at ${personalPath} (uuid: ${config.roots.personal.uuid})`);
147
+ createPersonalRoot(config, personalPath, homeDir);
148
+ console.log(c.green(`Initialized personal memory root at ${personalPath} (uuid: ${config.roots.personal.uuid})`));
149
+ printUncommittedNotesHint(personalPath);
93
150
  return 0;
94
151
  }
95
152
  if (cmd === 'config') {
@@ -109,7 +166,7 @@ async function main() {
109
166
  }
110
167
  root.path = path.resolve(newPath);
111
168
  saveConfig(config, homeDir);
112
- console.log(`Updated ${scope} root path to ${root.path} (uuid preserved: ${root.uuid})`);
169
+ console.log(c.green(`Updated ${scope} root path to ${root.path} (uuid preserved: ${root.uuid})`));
113
170
  return 0;
114
171
  }
115
172
  if (sub === 'set-submit-mode') {
@@ -120,7 +177,23 @@ async function main() {
120
177
  }
121
178
  config.roots.team.submitMode = mode;
122
179
  saveConfig(config, homeDir);
123
- console.log(`Updated team submit mode to ${mode}`);
180
+ console.log(c.green(`Updated team submit mode to ${mode}`));
181
+ return 0;
182
+ }
183
+ if (sub === 'unset') {
184
+ const scope = positional[1];
185
+ if (!scope || !['personal', 'team'].includes(scope)) {
186
+ console.error('Usage: faber-memory config unset <personal|team>');
187
+ return 1;
188
+ }
189
+ const existing = config.roots[scope];
190
+ if (!existing) {
191
+ console.log(`Root "${scope}" is not configured.`);
192
+ return 0;
193
+ }
194
+ delete config.roots[scope];
195
+ saveConfig(config, homeDir);
196
+ console.log(c.green(`Disconnected ${scope} root from config (files on disk at ${existing.path} were kept intact).`));
124
197
  return 0;
125
198
  }
126
199
  console.log(JSON.stringify(config, null, 2));
@@ -138,17 +211,17 @@ async function main() {
138
211
  standaloneRepoDir,
139
212
  });
140
213
  for (const w of res.warnings)
141
- console.warn(`Warning: ${w}`);
214
+ console.warn(c.yellow(`Warning: ${w}`));
142
215
  if (!res.ok) {
143
216
  for (const e of res.errors)
144
- console.error(`Error: ${e}`);
217
+ printErrorWithHelp(e);
145
218
  return 1;
146
219
  }
147
220
  if (checkOnly) {
148
- console.log(`OK: compile --check passed (${res.estimatedTokens}/${res.budget} estimated tokens).`);
221
+ console.log(c.green(`OK: compile --check passed (${res.estimatedTokens}/${res.budget} estimated tokens).`));
149
222
  }
150
223
  else {
151
- console.log(`Compiled L0 to ${res.outputPath} (${res.estimatedTokens}/${res.budget} estimated tokens).`);
224
+ console.log(c.green(`Compiled L0 to ${res.outputPath} (${res.estimatedTokens}/${res.budget} estimated tokens).`));
152
225
  }
153
226
  return 0;
154
227
  }
@@ -157,15 +230,15 @@ async function main() {
157
230
  const timeoutMs = typeof flags.timeout === 'string' ? Number(flags.timeout) : 5000;
158
231
  const res = await syncAllRoots(config, { homeDir, timeoutMs, recompile: true });
159
232
  for (const w of res.warnings)
160
- console.warn(`Warning: ${w}`);
233
+ console.warn(c.yellow(`Warning: ${w}`));
161
234
  if (!res.ok) {
162
235
  for (const e of res.errors)
163
- console.error(`Error: ${e}`);
236
+ printErrorWithHelp(e);
164
237
  return 1;
165
238
  }
166
- console.log(res.advanced
239
+ console.log(c.green(res.advanced
167
240
  ? 'Synced remote updates and recompiled L0.'
168
- : 'Already up to date; L0 compiled.');
241
+ : 'Already up to date; L0 compiled.'));
169
242
  return 0;
170
243
  }
171
244
  if (cmd === 'approve') {
@@ -179,7 +252,7 @@ async function main() {
179
252
  for (const id of ids) {
180
253
  const p = findProposalById(id, homeDir);
181
254
  if (!p) {
182
- console.error(`Error: Proposal "${id}" not found.`);
255
+ console.error(c.red(`Error: Proposal "${id}" not found.`));
183
256
  return 1;
184
257
  }
185
258
  proposals.push(p);
@@ -193,27 +266,82 @@ async function main() {
193
266
  console.log(m);
194
267
  if (!outcome.ok) {
195
268
  for (const e of outcome.errors)
196
- console.error(`Error: ${e}`);
269
+ printErrorWithHelp(e);
197
270
  return 1;
198
271
  }
199
272
  return 0;
200
273
  }
201
274
  if (cmd === 'reject') {
275
+ if (flags.all) {
276
+ const proposals = reconcileAwaitingCommitProposals(homeDir);
277
+ if (proposals.length === 0) {
278
+ console.log('No pending proposals to reject.');
279
+ return 0;
280
+ }
281
+ if (!flags.yes) {
282
+ const ans = (await promptLine(c.yellow(`Reject and delete all ${proposals.length} pending proposal(s)? [y/N]: `))).toLowerCase();
283
+ if (ans !== 'y' && ans !== 'yes') {
284
+ console.log('Cancelled. No proposals were removed.');
285
+ return 0;
286
+ }
287
+ }
288
+ for (const p of proposals) {
289
+ rejectProposal(p.id, homeDir);
290
+ }
291
+ console.log(c.green(`Rejected and removed ${proposals.length} pending proposal(s).`));
292
+ return 0;
293
+ }
202
294
  const id = positional[0];
203
295
  if (!id) {
204
- console.error('Usage: faber-memory reject <proposal-id>');
296
+ console.error('Usage: faber-memory reject <proposal-id> | faber-memory reject --all [--yes]');
205
297
  return 1;
206
298
  }
207
299
  try {
208
300
  const removed = rejectProposal(id, homeDir);
209
- console.log(`Rejected and removed proposal ${removed.id}.`);
301
+ console.log(c.green(`Rejected and removed proposal ${removed.id}.`));
210
302
  return 0;
211
303
  }
212
304
  catch (err) {
213
- console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
305
+ printErrorWithHelp(err instanceof Error ? err.message : String(err));
214
306
  return 1;
215
307
  }
216
308
  }
309
+ if (cmd === 'reset') {
310
+ const config = loadConfig(homeDir);
311
+ const includePersonal = Boolean(flags['include-personal-repo']);
312
+ const personalPath = config.roots.personal?.path;
313
+ console.log(c.bold(c.yellow('FaberSEP Memory Reset')));
314
+ console.log('This will:');
315
+ console.log(' 1. Undo agent wiring (remove faber-memory blocks & MCP entries).');
316
+ console.log(` 2. Delete local state directory: ${homeDir} (config, compiled L0, pre-memory, metrics.jsonl, team clone).`);
317
+ if (includePersonal && personalPath) {
318
+ console.log(c.red(` 3. Delete personal memory Git repository: ${personalPath}`));
319
+ }
320
+ else if (personalPath) {
321
+ console.log(c.dim(` (Personal Git repo at ${personalPath} will be kept. Pass --include-personal-repo to delete it too.)`));
322
+ }
323
+ if (!flags.yes) {
324
+ const ans = (await promptLine(c.yellow('Continue with reset? [y/N]: '))).toLowerCase();
325
+ if (ans !== 'y' && ans !== 'yes') {
326
+ console.log('Reset cancelled.');
327
+ return 0;
328
+ }
329
+ }
330
+ try {
331
+ planOrApplyInit(config, { undo: true, homeDir });
332
+ }
333
+ catch {
334
+ // Best-effort undo even if config is partial
335
+ }
336
+ if (fs.existsSync(homeDir)) {
337
+ fs.rmSync(homeDir, { recursive: true, force: true });
338
+ }
339
+ if (includePersonal && personalPath && fs.existsSync(personalPath)) {
340
+ fs.rmSync(personalPath, { recursive: true, force: true });
341
+ }
342
+ console.log(c.green('Reset complete.'));
343
+ return 0;
344
+ }
217
345
  if (cmd === 'review') {
218
346
  const config = loadConfig(homeDir);
219
347
  const proposals = reconcileAwaitingCommitProposals(homeDir).filter((p) => p.status !== 'awaiting_commit');
@@ -221,50 +349,126 @@ async function main() {
221
349
  console.log('No pending proposals to review.');
222
350
  return 0;
223
351
  }
224
- const toApprove = [];
352
+ const decisions = new Map();
225
353
  if (flags['approve-all']) {
226
- toApprove.push(...proposals);
354
+ for (const p of proposals)
355
+ decisions.set(p.id, 'approve');
227
356
  }
228
357
  else {
229
358
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
359
+ let interrupted = false;
360
+ rl.on('SIGINT', () => {
361
+ interrupted = true;
362
+ console.log(c.yellow('\nInterrupted — saving decisions made so far...'));
363
+ rl.close();
364
+ });
230
365
  const lineIter = rl[Symbol.asyncIterator]();
231
366
  const ask = async (q) => {
232
367
  process.stdout.write(q);
233
368
  const next = await lineIter.next();
234
- return next.done ? '' : String(next.value);
369
+ if (next.done)
370
+ return null;
371
+ return String(next.value);
235
372
  };
373
+ const MAX_PREVIEW_LINES = 12;
236
374
  try {
237
- for (const p of proposals) {
238
- console.log(`\n=== Proposal ${p.id} [${p.scope} / ${p.action}] ===`);
239
- console.log(`Entry ID: ${p.entryId}${p.targetId ? ` (target: ${p.targetId})` : ''}`);
240
- console.log(`Type: ${p.type} | Summary: ${p.summary}`);
375
+ let idx = 0;
376
+ let showFull = false;
377
+ while (idx < proposals.length && !interrupted) {
378
+ const p = proposals[idx];
379
+ const approvedCount = [...decisions.values()].filter((d) => d === 'approve').length;
380
+ const rejectedCount = [...decisions.values()].filter((d) => d === 'reject').length;
381
+ const skippedCount = [...decisions.values()].filter((d) => d === 'skip').length;
382
+ const prevDecision = decisions.get(p.id);
383
+ console.log(`\n${c.dim(hr('═', 68))}`);
384
+ console.log(`${c.bold(c.cyan(`[ ${idx + 1} / ${proposals.length} ]`))} ` +
385
+ `${c.green(`Approved: ${approvedCount}`)} | ` +
386
+ `${c.red(`Rejected: ${rejectedCount}`)} | ` +
387
+ `${c.yellow(`Skipped: ${skippedCount}`)}` +
388
+ (prevDecision ? c.dim(` (current: ${prevDecision})`) : ''));
389
+ console.log(c.dim(hr('─', 68)));
390
+ console.log(`${c.bold('ID:')} ${c.cyan(p.entryId)} ` +
391
+ `${c.bold('Scope:')} ${c.magenta(p.scope)} ` +
392
+ `${c.bold('Type:')} ${p.type} ` +
393
+ `${c.bold('Action:')} ${p.action}` +
394
+ (p.targetId ? ` (target: ${p.targetId})` : ''));
395
+ console.log(`${c.bold('Summary:')} ${p.summary}`);
241
396
  if (p.forceNew && p.reason) {
242
- console.log(`force_new reason: ${p.reason}`);
397
+ console.log(`${c.yellow('force_new reason:')} ${p.reason}`);
398
+ }
399
+ console.log(c.dim(hr('─', 68)));
400
+ const bodyLines = p.body.split('\n');
401
+ if (!showFull && bodyLines.length > MAX_PREVIEW_LINES) {
402
+ console.log(bodyLines.slice(0, MAX_PREVIEW_LINES).join('\n'));
403
+ console.log(c.dim(`... (+${bodyLines.length - MAX_PREVIEW_LINES} more lines — press [v] to view full body)`));
404
+ }
405
+ else {
406
+ console.log(p.body);
243
407
  }
244
- console.log(`Body:\n${p.body}\n`);
245
- const answer = (await ask('Action? [a]pprove / [e]dit / [r]eject / [s]kip: '))
246
- .trim()
247
- .toLowerCase();
408
+ console.log(c.dim(hr('─', 68)));
409
+ const navHints = [
410
+ c.green('[a]pprove'),
411
+ c.cyan('[e]dit'),
412
+ c.red('[r]eject'),
413
+ c.yellow('[s]kip'),
414
+ ...(!showFull && bodyLines.length > MAX_PREVIEW_LINES ? ['[v]iew full'] : []),
415
+ ...(idx > 0 ? ['[b]ack'] : []),
416
+ c.dim('[q]uit & save'),
417
+ ].join(' ');
418
+ const rawAns = await ask(`${navHints}\n> `);
419
+ if (rawAns === null)
420
+ break;
421
+ const answer = rawAns.trim().toLowerCase();
422
+ if (answer === 'v' || answer === 'view') {
423
+ showFull = true;
424
+ continue;
425
+ }
426
+ if (answer === 'b' || answer === 'back') {
427
+ if (idx > 0) {
428
+ idx--;
429
+ showFull = false;
430
+ }
431
+ else {
432
+ console.log(c.dim('Already at the first proposal.'));
433
+ }
434
+ continue;
435
+ }
436
+ if (answer === 'q' || answer === 'quit') {
437
+ break;
438
+ }
439
+ showFull = false;
248
440
  if (answer === 'a' || answer === 'approve') {
249
- toApprove.push(p);
441
+ decisions.set(p.id, 'approve');
442
+ idx++;
250
443
  }
251
444
  else if (answer === 'e' || answer === 'edit') {
252
- const newBody = (await ask('New body (single line or leave empty to keep): ')).trim();
445
+ const newBodyRaw = await ask('New body (single line or leave empty to keep): ');
446
+ if (newBodyRaw === null)
447
+ break;
448
+ const newBody = newBodyRaw.trim();
253
449
  if (newBody) {
254
450
  p.body = newBody;
255
451
  saveProposal(p, homeDir);
256
452
  }
257
- const confirm = (await ask('Approve edited proposal? [y/N]: ')).trim().toLowerCase();
453
+ const confirmRaw = await ask('Approve edited proposal? [y/N]: ');
454
+ if (confirmRaw === null)
455
+ break;
456
+ const confirm = confirmRaw.trim().toLowerCase();
258
457
  if (confirm === 'y' || confirm === 'yes') {
259
- toApprove.push(p);
458
+ decisions.set(p.id, 'approve');
459
+ }
460
+ else {
461
+ decisions.set(p.id, 'skip');
260
462
  }
463
+ idx++;
261
464
  }
262
465
  else if (answer === 'r' || answer === 'reject') {
263
- rejectProposal(p.id, homeDir);
264
- console.log(`Rejected ${p.id}.`);
466
+ decisions.set(p.id, 'reject');
467
+ idx++;
265
468
  }
266
469
  else {
267
- console.log(`Skipped ${p.id}.`);
470
+ decisions.set(p.id, 'skip');
471
+ idx++;
268
472
  }
269
473
  }
270
474
  }
@@ -272,25 +476,45 @@ async function main() {
272
476
  rl.close();
273
477
  }
274
478
  }
479
+ const toApprove = [];
480
+ const toReject = [];
481
+ for (const p of proposals) {
482
+ const d = decisions.get(p.id);
483
+ if (d === 'approve')
484
+ toApprove.push(p);
485
+ else if (d === 'reject')
486
+ toReject.push(p);
487
+ }
488
+ for (const p of toReject) {
489
+ rejectProposal(p.id, homeDir);
490
+ }
491
+ let exitCode = 0;
275
492
  if (toApprove.length > 0) {
276
493
  const outcome = await approveProposalsBatch(config, toApprove, { homeDir });
277
494
  for (const m of outcome.messages)
278
495
  console.log(m);
279
496
  if (!outcome.ok) {
280
497
  for (const e of outcome.errors)
281
- console.error(`Error: ${e}`);
282
- return 1;
498
+ printErrorWithHelp(e);
499
+ exitCode = 1;
283
500
  }
284
501
  }
285
- return 0;
502
+ const remainingCount = proposals.length - toApprove.length - toReject.length;
503
+ console.log(`\n${c.bold('Review summary:')} ` +
504
+ `${c.green(`${toApprove.length} approved`)} | ` +
505
+ `${c.red(`${toReject.length} rejected`)} | ` +
506
+ `${c.yellow(`${remainingCount} remaining in pre-memory`)}`);
507
+ return exitCode;
286
508
  }
287
509
  if (cmd === 'status') {
288
510
  const config = loadConfig(homeDir);
289
511
  const projectRes = resolveProjectRoot(undefined, process.cwd());
290
512
  const loaded = loadAllScopes(config, projectRes);
291
513
  const proposals = reconcileAwaitingCommitProposals(homeDir);
292
- console.log('FaberSEP Memory Status');
293
- console.log(` Compiled L0: ${getCompiledL0Path(homeDir)} (${fs.existsSync(getCompiledL0Path(homeDir)) ? 'present' : 'missing'})`);
514
+ console.log(c.bold('FaberSEP Memory Status'));
515
+ const l0Path = getCompiledL0Path(homeDir);
516
+ const l0Present = fs.existsSync(l0Path);
517
+ console.log(` Compiled L0: ${l0Path} (${l0Present ? c.green('present') : c.yellow('missing')})`);
294
518
  if (config.roots.team) {
295
519
  console.log(` Team root: ${config.roots.team.path} (HEAD: ${getHeadSha(config.roots.team.path)?.slice(0, 8) || 'none'}, mode: ${config.roots.team.submitMode || 'auto'})`);
296
520
  }
@@ -299,7 +523,7 @@ async function main() {
299
523
  }
300
524
  console.log(` Project root: ${projectRes.projectRoot || 'none'} (source: ${projectRes.source})`);
301
525
  if (loaded.uncommittedWarnings.length > 0) {
302
- console.log('Warnings:');
526
+ console.log(c.yellow('Warnings:'));
303
527
  for (const w of loaded.uncommittedWarnings)
304
528
  console.log(` - ${w}`);
305
529
  }
@@ -317,7 +541,7 @@ async function main() {
317
541
  console.log(` file: ${p.targetFilePath} — run "git add ${p.targetFilePath} && git commit" to activate`);
318
542
  }
319
543
  if (p.status === 'push_failed' && p.error) {
320
- console.log(` push error: ${p.error}`);
544
+ console.log(c.red(` push error: ${p.error}`));
321
545
  }
322
546
  }
323
547
  return 0;
@@ -327,7 +551,7 @@ async function main() {
327
551
  const from = flags.from;
328
552
  const sourcePath = positional[0];
329
553
  if (!from || !sourcePath) {
330
- console.error('Usage: faber-memory import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--split-headings] [--approve]');
554
+ console.error('Usage: faber-memory import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]');
331
555
  return 1;
332
556
  }
333
557
  try {
@@ -336,40 +560,100 @@ async function main() {
336
560
  sourcePath: path.resolve(sourcePath),
337
561
  scope: typeof flags.scope === 'string' ? flags.scope : 'personal',
338
562
  splitHeadings: Boolean(flags['split-headings']),
563
+ normalizePaths: Boolean(flags['normalize-paths']),
339
564
  approve: Boolean(flags.approve),
340
565
  homeDir,
341
566
  cwd: process.cwd(),
342
567
  });
343
- console.log(`Staged ${res.staged.length} proposal(s) in pre-memory.`);
568
+ console.log(c.green(`Staged ${res.staged.length} proposal(s) in pre-memory.`));
344
569
  if (res.approvedIds.length > 0) {
345
- console.log(`Approved ${res.approvedIds.length} proposal(s) in solo mode.`);
570
+ console.log(c.green(`Approved ${res.approvedIds.length} proposal(s) in solo mode.`));
571
+ }
572
+ if (res.normalizedPaths.length > 0) {
573
+ console.log(c.cyan(`Normalized machine paths to ~/ in ${res.normalizedPaths.length} file(s):`));
574
+ for (const n of res.normalizedPaths) {
575
+ console.log(` - ${n.source} (${n.replacements} replacement(s))`);
576
+ }
577
+ }
578
+ if (res.skippedIndex.length > 0) {
579
+ console.log(c.dim(`Index files skipped (${res.skippedIndex.length}) — faber-memory compiles its own L0 MEMORY.md index:`));
580
+ for (const f of res.skippedIndex) {
581
+ console.log(c.dim(` - ${f}`));
582
+ }
583
+ console.log(c.dim(` Details: ${troubleshootingLink('index-files')}`));
346
584
  }
347
585
  if (res.duplicates.length > 0) {
348
- console.log(`Duplicates skipped (${res.duplicates.length}):`);
586
+ console.log(c.yellow(`Duplicates skipped (${res.duplicates.length}):`));
349
587
  for (const d of res.duplicates) {
350
588
  console.log(` - ${d.source} matches "${d.matchedId}" (${d.summary})`);
351
589
  }
352
590
  }
353
591
  if (res.skippedHygiene.length > 0) {
354
- console.log(`Hygiene skipped (${res.skippedHygiene.length}):`);
592
+ console.log(c.yellow(`Hygiene skipped (${res.skippedHygiene.length}):`));
355
593
  for (const s of res.skippedHygiene) {
356
594
  console.log(` - ${s.source}: ${s.reason}`);
595
+ if (s.snippet) {
596
+ console.log(c.dim(` snippet: ${s.snippet}`));
597
+ }
598
+ if (s.anchor === 'machine-specific-paths') {
599
+ console.log(c.cyan(' hint: Replace /Users/<name>/ or /home/<name>/ with ~/, or re-run with --normalize-paths.'));
600
+ }
601
+ else {
602
+ console.log(c.cyan(' hint: Remove the secret/token and reference an env var name instead.'));
603
+ }
604
+ console.log(c.dim(` details: ${troubleshootingLink(s.anchor)}`));
357
605
  }
358
606
  }
607
+ if (res.skippedHygiene.length > 0) {
608
+ console.log(c.yellow(`NOT imported: ${res.skippedHygiene.length} item(s) were left out because of the hygiene check above. Fix them (or add --normalize-paths for paths) and run import again; already staged items are not duplicated.`));
609
+ }
359
610
  for (const n of res.notes)
360
611
  console.log(n);
361
612
  return 0;
362
613
  }
363
614
  catch (err) {
364
- console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
615
+ printErrorWithHelp(err instanceof Error ? err.message : String(err));
365
616
  return 1;
366
617
  }
367
618
  }
368
619
  if (cmd === 'init') {
369
620
  const config = loadConfig(homeDir);
370
- const apply = Boolean(flags.apply);
371
621
  const undo = Boolean(flags.undo);
622
+ // init applies by default; --preview (alias --dry-run) only shows the diff.
623
+ // --apply is kept as a no-op alias for older docs and scripts.
624
+ const preview = Boolean(flags.preview || flags['dry-run']);
625
+ if (preview && flags.apply) {
626
+ printErrorWithHelp('Use either --preview or --apply, not both.');
627
+ return 1;
628
+ }
629
+ const apply = !undo && !preview;
372
630
  const projectHint = Boolean(flags['project-hint']);
631
+ // init also creates the personal memory folder, so `setup` is optional:
632
+ // `init <folder>` picks the folder; plain `init` uses ~/.faber/memory when
633
+ // no personal or team root is configured yet.
634
+ if (!undo) {
635
+ const requested = positional[0] ? path.resolve(positional[0]) : undefined;
636
+ const current = config.roots.personal?.path;
637
+ if (requested && current && path.resolve(current) !== requested) {
638
+ printErrorWithHelp(`Personal memory is already at ${current}. To move it, run: faber-memory config set-path personal ${requested}`);
639
+ return 1;
640
+ }
641
+ const target = requested && !current
642
+ ? requested
643
+ : !current && !config.roots.team
644
+ ? getDefaultPersonalPath()
645
+ : undefined;
646
+ if (target) {
647
+ if (preview) {
648
+ console.log(c.cyan(`Would create your personal memory folder at ${target}.`));
649
+ }
650
+ else {
651
+ createPersonalRoot(config, target, homeDir);
652
+ console.log(c.green(`Created your personal memory folder at ${target}.`));
653
+ printUncommittedNotesHint(target);
654
+ }
655
+ }
656
+ }
373
657
  const engines = typeof flags.engine === 'string'
374
658
  ? flags.engine.split(',').map((e) => e.trim())
375
659
  : undefined;
@@ -382,26 +666,78 @@ async function main() {
382
666
  homeDir,
383
667
  });
384
668
  for (const n of res.notes)
385
- console.log(n);
669
+ console.log(c.yellow(n));
386
670
  for (const p of res.plans) {
387
- console.log(formatUnifiedDiff(p));
671
+ console.log(formatPlanBeforeAfter(p));
388
672
  }
389
- if (undo && res.backups.length > 0) {
390
- console.log(`Backup files preserved (not auto-restored): ${res.backups.join(', ')}`);
673
+ if (undo) {
674
+ console.log(c.cyan('\nRemoved agent wiring only. Your memory repos and pending pre-memory proposals were kept intact. (Use "faber-memory reset" to wipe local state.)'));
675
+ if (res.backups.length > 0) {
676
+ console.log(c.dim(`Backup files preserved (not auto-restored): ${res.backups.join(', ')}`));
677
+ }
391
678
  }
392
679
  if (res.projectHint) {
393
680
  console.log(`Project hint: ${res.projectHint}`);
394
681
  }
395
- if (!apply && !undo) {
396
- console.log('\nDry-run only. Re-run with --apply to write changes.');
682
+ if (preview) {
683
+ console.log(c.yellow('\nPreview only. Run "faber-memory init" to write these changes.'));
684
+ }
685
+ else if (apply) {
686
+ const wired = [...new Set(res.plans.map((p) => p.engine))];
687
+ console.log(c.green(`\nConnected: ${wired.join(', ') || 'nothing to change'}. Backups are saved as .bak; undo any time with "faber-memory init --undo". Start a new chat in your assistant to use memory.`));
397
688
  }
398
689
  return 0;
399
690
  }
400
691
  catch (err) {
401
- console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
692
+ printErrorWithHelp(err instanceof Error ? err.message : String(err));
402
693
  return 1;
403
694
  }
404
695
  }
696
+ if (cmd === 'stats') {
697
+ const daysCheck = validateDaysArg(flags.days);
698
+ if (!daysCheck.ok) {
699
+ printErrorWithHelp(daysCheck.error);
700
+ return 1;
701
+ }
702
+ const report = computeStats({
703
+ days: daysCheck.days,
704
+ includeCache: Boolean(flags.cache),
705
+ engine: typeof flags.engine === 'string' ? flags.engine : undefined,
706
+ logDir: typeof flags['log-dir'] === 'string' ? path.resolve(flags['log-dir']) : undefined,
707
+ homeDir,
708
+ cwd: process.cwd(),
709
+ });
710
+ if (flags.share) {
711
+ const card = buildShareableBenchmark(report);
712
+ if (flags.json) {
713
+ console.log(JSON.stringify(card, null, 2));
714
+ }
715
+ else {
716
+ console.log(formatShareableMarkdown(card));
717
+ }
718
+ return 0;
719
+ }
720
+ if (flags.json) {
721
+ console.log(JSON.stringify(report, null, 2));
722
+ return 0;
723
+ }
724
+ console.log(formatStatsReport(report));
725
+ return 0;
726
+ }
727
+ if (cmd === 'doctor') {
728
+ const report = runDoctor({
729
+ strict: Boolean(flags.strict),
730
+ homeDir,
731
+ cwd: process.cwd(),
732
+ });
733
+ if (flags.json) {
734
+ console.log(JSON.stringify(report, null, 2));
735
+ }
736
+ else {
737
+ console.log(formatDoctorReport(report));
738
+ }
739
+ return report.exitCode;
740
+ }
405
741
  console.error(`Unknown command: ${cmd}`);
406
742
  printHelp();
407
743
  return 1;
@@ -410,17 +746,23 @@ function printHelp() {
410
746
  console.log(`@fabersep/memory (faber-memory)
411
747
 
412
748
  Commands:
413
- setup [path] [--team <git-url> --path <dir> --submit-mode auto|pr]
414
- config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr>]
415
- init [--apply | --undo] [--engine claude-code,antigravity,cursor,codex] [--project-hint]
749
+ setup [path] [--team <git-url|org/repo> --path <dir> --submit-mode auto|pr]
750
+ config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | unset <personal|team>]
751
+ init [folder] [--preview | --undo] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
416
752
  compile [--check] [--repo <dir>]
417
753
  sync [--timeout <ms>]
418
754
  status
755
+ stats [--days 1..90] [--json] [--cache] [--engine claude-code|antigravity|all] [--log-dir <path>] [--share]
756
+ doctor [--json] [--strict]
419
757
  review [--approve-all]
420
758
  approve <proposal-id> [...] [--mode auto|pr]
421
- reject <proposal-id>
422
- import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--split-headings] [--approve]
759
+ reject <proposal-id> | reject --all [--yes]
760
+ reset [--include-personal-repo] [--yes]
761
+ import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]
423
762
  serve
763
+ --version
764
+
765
+ Docs: https://github.com/fabersep/memory#readme
424
766
  `);
425
767
  }
426
768
  main()
@@ -429,6 +771,6 @@ main()
429
771
  process.exit(code);
430
772
  })
431
773
  .catch((err) => {
432
- console.error(err instanceof Error ? err.message : String(err));
774
+ printErrorWithHelp(err instanceof Error ? err.message : String(err));
433
775
  process.exit(1);
434
776
  });