@fabersep/memory 0.2.0 → 0.3.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/cli.js CHANGED
@@ -5,7 +5,7 @@ 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
7
  import { formatDoctorReport, runDoctor } from './doctor.js';
8
- import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, isGitRepo, } from './git.js';
8
+ import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, gitSync, isGitRepo, } from './git.js';
9
9
  import { runImport } from './importer.js';
10
10
  import { formatPlanBeforeAfter, planOrApplyInit } from './init.js';
11
11
  import { FaberMemoryMcpServer } from './mcp.js';
@@ -13,7 +13,15 @@ import { approveProposalsBatch, findProposalById, reconcileAwaitingCommitProposa
13
13
  import { buildShareableBenchmark, computeStats, formatShareableMarkdown, formatStatsReport, validateDaysArg, } from './stats.js';
14
14
  import { loadAllScopes, resolveProjectRoot } from './store.js';
15
15
  import { syncAllRoots } from './sync.js';
16
+ import { addPersonalRemote, DEFAULT_READ_ONLY_PATH, getAheadInfo, getPushMode, getUnpushedReminder, isReadOnlyRoot, pushPersonalRoot, READ_ONLY_MESSAGE, removePersonalRemote, } from './personal-remote.js';
17
+ import { getPackageVersion } from './version.js';
16
18
  import { c, hr, inferErrorAnchor, normalizeTeamUrl, troubleshootingLink, } from './ui.js';
19
+ // Flags that never take a value, so `init --preview ~/notes` keeps ~/notes as a positional.
20
+ const BOOLEAN_FLAGS = new Set([
21
+ 'apply', 'undo', 'preview', 'dry-run', 'check', 'json', 'strict', 'cache', 'share', 'yes',
22
+ 'all', 'approve', 'approve-all', 'split-headings', 'normalize-paths', 'project-hint',
23
+ 'include-personal-repo', 'help', 'allow-public',
24
+ ]);
17
25
  function parseFlags(args) {
18
26
  const positional = [];
19
27
  const flags = {};
@@ -27,7 +35,7 @@ function parseFlags(args) {
27
35
  else {
28
36
  const key = arg.slice(2);
29
37
  const next = args[i + 1];
30
- if (next && !next.startsWith('--')) {
38
+ if (next && !next.startsWith('--') && !BOOLEAN_FLAGS.has(key)) {
31
39
  flags[key] = next;
32
40
  i++;
33
41
  }
@@ -60,11 +68,72 @@ function printErrorWithHelp(errMsg) {
60
68
  console.error(c.dim(` Details: ${troubleshootingLink(anchor)}`));
61
69
  }
62
70
  }
71
+ // Feature 03 FR-02: an interactive terminal (tests set FABER_MEMORY_ASSUME_TTY=1 to drive the prompt).
72
+ function isInteractive() {
73
+ return Boolean(process.stdin.isTTY) || process.env.FABER_MEMORY_ASSUME_TTY === '1';
74
+ }
75
+ // After an approve committed to the personal root: push per pushMode, or say what is left.
76
+ async function afterPersonalCommit(config, homeDir, ask) {
77
+ const root = config.roots.personal;
78
+ if (!root || isReadOnlyRoot(root))
79
+ return;
80
+ const info = getAheadInfo(root.path);
81
+ if (!info.hasRemote || info.ahead === 0)
82
+ return;
83
+ const mode = getPushMode(root);
84
+ if (mode === 'never')
85
+ return;
86
+ let push = mode === 'auto';
87
+ if (mode === 'ask' && ask) {
88
+ const answer = await ask(`Push ${info.ahead} commit(s) to origin now? [Y/n] `);
89
+ push = answer !== null && ['', 'y', 'yes'].includes(answer.trim().toLowerCase());
90
+ }
91
+ if (push) {
92
+ const res = await pushPersonalRoot(root, homeDir);
93
+ console.log(res.ok ? c.green(res.message) : c.red(res.message));
94
+ if (res.ok)
95
+ return;
96
+ }
97
+ const reminder = getUnpushedReminder(config, homeDir);
98
+ if (reminder)
99
+ console.log(c.yellow(reminder));
100
+ }
101
+ function createPersonalRoot(config, personalPath, homeDir) {
102
+ const existed = isGitRepo(personalPath);
103
+ gitInitSoloRepo(personalPath, 'main');
104
+ config.roots.personal = {
105
+ uuid: config.roots.personal?.uuid || generateUuid(),
106
+ path: personalPath,
107
+ scope: 'personal',
108
+ defaultBranch: existed ? getDefaultBranch(personalPath) : 'main',
109
+ };
110
+ saveConfig(config, homeDir);
111
+ }
112
+ // Notes already in a chosen folder are not active until they are in Git HEAD.
113
+ function printUncommittedNotesHint(dir) {
114
+ let count = 0;
115
+ try {
116
+ const res = gitSync(['--no-optional-locks', '-C', dir, 'status', '--porcelain', '-uall']);
117
+ if (!res.ok)
118
+ return;
119
+ count = res.stdout.split('\n').filter((l) => /\.md"?$/i.test(l.trim())).length;
120
+ }
121
+ catch {
122
+ return;
123
+ }
124
+ if (count > 0) {
125
+ 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}`));
126
+ }
127
+ }
63
128
  async function main() {
64
129
  const argv = process.argv.slice(2);
65
130
  const cmd = argv[0];
66
131
  const { positional, flags } = parseFlags(argv.slice(1));
67
132
  const homeDir = getHomeDir();
133
+ if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
134
+ console.log(getPackageVersion());
135
+ return 0;
136
+ }
68
137
  if (!cmd || cmd === '--help' || cmd === '-h') {
69
138
  printHelp();
70
139
  return 0;
@@ -76,6 +145,28 @@ async function main() {
76
145
  }
77
146
  if (cmd === 'setup') {
78
147
  const config = loadConfig(homeDir);
148
+ if (flags['read-only']) {
149
+ const url = String(flags['read-only']);
150
+ if (url === 'true') {
151
+ console.error('Usage: faber-memory setup --read-only <git-url> [path]');
152
+ return 1;
153
+ }
154
+ const dest = typeof flags.path === 'string' ? path.resolve(flags.path) : positional[0] ? path.resolve(positional[0]) : DEFAULT_READ_ONLY_PATH;
155
+ const branch = isGitRepo(dest) ? getDefaultBranch(dest) : gitCloneTeamRepo(url, dest);
156
+ config.roots.personal = {
157
+ uuid: config.roots.personal?.uuid || generateUuid(),
158
+ path: dest,
159
+ scope: 'personal',
160
+ defaultBranch: branch,
161
+ readOnly: true,
162
+ };
163
+ saveConfig(config, homeDir);
164
+ const res = await syncAllRoots(config, { homeDir, recompile: true });
165
+ for (const e of res.errors)
166
+ printErrorWithHelp(e);
167
+ console.log(c.green(`Configured a read-only personal root at ${dest} (branch: ${branch}). This host only pulls; propose changes on a writing machine.`));
168
+ return res.ok ? 0 : 1;
169
+ }
79
170
  if (flags.team) {
80
171
  const rawUrl = String(flags.team);
81
172
  const { url, normalized } = normalizeTeamUrl(rawUrl);
@@ -106,17 +197,59 @@ async function main() {
106
197
  : positional[0]
107
198
  ? path.resolve(positional[0])
108
199
  : getDefaultPersonalPath();
109
- gitInitSoloRepo(personalPath, 'main');
110
- config.roots.personal = {
111
- uuid: config.roots.personal?.uuid || generateUuid(),
112
- path: personalPath,
113
- scope: 'personal',
114
- defaultBranch: 'main',
115
- };
116
- saveConfig(config, homeDir);
200
+ createPersonalRoot(config, personalPath, homeDir);
117
201
  console.log(c.green(`Initialized personal memory root at ${personalPath} (uuid: ${config.roots.personal.uuid})`));
202
+ printUncommittedNotesHint(personalPath);
203
+ if (typeof flags.remote === 'string') {
204
+ const res = await addPersonalRemote(config, flags.remote, { allowPublic: Boolean(flags['allow-public']), homeDir });
205
+ for (const m of res.messages)
206
+ console.log(m);
207
+ for (const e of res.errors)
208
+ printErrorWithHelp(e);
209
+ saveConfig(config, homeDir);
210
+ return res.ok ? 0 : 1;
211
+ }
118
212
  return 0;
119
213
  }
214
+ if (cmd === 'remote') {
215
+ const config = loadConfig(homeDir);
216
+ const sub = positional[0];
217
+ if (sub === 'add' && positional[1]) {
218
+ const res = await addPersonalRemote(config, positional[1], { allowPublic: Boolean(flags['allow-public']), homeDir });
219
+ for (const m of res.messages)
220
+ console.log(m);
221
+ for (const e of res.errors)
222
+ printErrorWithHelp(e);
223
+ if (res.ok)
224
+ saveConfig(config, homeDir);
225
+ return res.ok ? 0 : 1;
226
+ }
227
+ if (sub === 'remove') {
228
+ const res = removePersonalRemote(config, homeDir);
229
+ for (const m of res.messages)
230
+ console.log(m);
231
+ for (const e of res.errors)
232
+ printErrorWithHelp(e);
233
+ return res.ok ? 0 : 1;
234
+ }
235
+ console.error('Usage: faber-memory remote add <git-url> [--allow-public] | faber-memory remote remove');
236
+ return 1;
237
+ }
238
+ if (cmd === 'push') {
239
+ const config = loadConfig(homeDir);
240
+ const root = config.roots.personal;
241
+ if (!root) {
242
+ printErrorWithHelp('Personal memory root is not configured.');
243
+ return 1;
244
+ }
245
+ const res = await pushPersonalRoot(root, homeDir);
246
+ if (res.ok) {
247
+ console.log(c.green(res.message));
248
+ return 0;
249
+ }
250
+ printErrorWithHelp(res.message);
251
+ return 1;
252
+ }
120
253
  if (cmd === 'config') {
121
254
  const sub = positional[0];
122
255
  const config = loadConfig(homeDir);
@@ -148,6 +281,17 @@ async function main() {
148
281
  console.log(c.green(`Updated team submit mode to ${mode}`));
149
282
  return 0;
150
283
  }
284
+ if (sub === 'set-push-mode') {
285
+ const mode = positional[1];
286
+ if (!['ask', 'auto', 'never'].includes(mode) || !config.roots.personal) {
287
+ console.error('Usage: faber-memory config set-push-mode <ask|auto|never> (needs a personal root)');
288
+ return 1;
289
+ }
290
+ config.roots.personal.pushMode = mode;
291
+ saveConfig(config, homeDir);
292
+ console.log(c.green(`Updated personal push mode to ${mode}`));
293
+ return 0;
294
+ }
151
295
  if (sub === 'unset') {
152
296
  const scope = positional[1];
153
297
  if (!scope || !['personal', 'team'].includes(scope)) {
@@ -211,6 +355,10 @@ async function main() {
211
355
  }
212
356
  if (cmd === 'approve') {
213
357
  const config = loadConfig(homeDir);
358
+ if (isReadOnlyRoot(config.roots.personal)) {
359
+ printErrorWithHelp(READ_ONLY_MESSAGE);
360
+ return 1;
361
+ }
214
362
  const ids = positional;
215
363
  if (ids.length === 0) {
216
364
  console.error('Usage: faber-memory approve <proposal-id> [...]');
@@ -237,6 +385,10 @@ async function main() {
237
385
  printErrorWithHelp(e);
238
386
  return 1;
239
387
  }
388
+ if (outcome.personalCommitted) {
389
+ const ask = isInteractive() && !flags.yes ? (q) => promptLine(q) : undefined;
390
+ await afterPersonalCommit(config, homeDir, ask);
391
+ }
240
392
  return 0;
241
393
  }
242
394
  if (cmd === 'reject') {
@@ -312,32 +464,44 @@ async function main() {
312
464
  }
313
465
  if (cmd === 'review') {
314
466
  const config = loadConfig(homeDir);
467
+ if (isReadOnlyRoot(config.roots.personal)) {
468
+ printErrorWithHelp(READ_ONLY_MESSAGE);
469
+ return 1;
470
+ }
315
471
  const proposals = reconcileAwaitingCommitProposals(homeDir).filter((p) => p.status !== 'awaiting_commit');
316
472
  if (proposals.length === 0) {
317
473
  console.log('No pending proposals to review.');
318
474
  return 0;
319
475
  }
320
476
  const decisions = new Map();
477
+ // One readline for the whole review, so the push question (feature 03 FR-02) reads the same input.
478
+ let rl;
479
+ let askPush;
321
480
  if (flags['approve-all']) {
322
481
  for (const p of proposals)
323
482
  decisions.set(p.id, 'approve');
324
483
  }
325
484
  else {
326
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
485
+ const reviewRl = readline.createInterface({ input: process.stdin, output: process.stdout });
486
+ rl = reviewRl;
327
487
  let interrupted = false;
328
- rl.on('SIGINT', () => {
488
+ reviewRl.on('SIGINT', () => {
329
489
  interrupted = true;
330
490
  console.log(c.yellow('\nInterrupted — saving decisions made so far...'));
331
- rl.close();
491
+ reviewRl.close();
332
492
  });
333
- const lineIter = rl[Symbol.asyncIterator]();
493
+ const lineIter = reviewRl[Symbol.asyncIterator]();
334
494
  const ask = async (q) => {
495
+ if (interrupted)
496
+ return null;
335
497
  process.stdout.write(q);
336
498
  const next = await lineIter.next();
337
499
  if (next.done)
338
500
  return null;
339
501
  return String(next.value);
340
502
  };
503
+ if (isInteractive() && !flags.yes)
504
+ askPush = ask;
341
505
  const MAX_PREVIEW_LINES = 12;
342
506
  try {
343
507
  let idx = 0;
@@ -440,8 +604,9 @@ async function main() {
440
604
  }
441
605
  }
442
606
  }
443
- finally {
444
- rl.close();
607
+ catch (err) {
608
+ reviewRl.close();
609
+ throw err;
445
610
  }
446
611
  }
447
612
  const toApprove = [];
@@ -466,7 +631,11 @@ async function main() {
466
631
  printErrorWithHelp(e);
467
632
  exitCode = 1;
468
633
  }
634
+ else if (outcome.personalCommitted) {
635
+ await afterPersonalCommit(config, homeDir, askPush);
636
+ }
469
637
  }
638
+ rl?.close();
470
639
  const remainingCount = proposals.length - toApprove.length - toReject.length;
471
640
  console.log(`\n${c.bold('Review summary:')} ` +
472
641
  `${c.green(`${toApprove.length} approved`)} | ` +
@@ -487,7 +656,12 @@ async function main() {
487
656
  console.log(` Team root: ${config.roots.team.path} (HEAD: ${getHeadSha(config.roots.team.path)?.slice(0, 8) || 'none'}, mode: ${config.roots.team.submitMode || 'auto'})`);
488
657
  }
489
658
  if (config.roots.personal) {
490
- console.log(` Personal root: ${config.roots.personal.path} (HEAD: ${getHeadSha(config.roots.personal.path)?.slice(0, 8) || 'none'})`);
659
+ const pr = config.roots.personal;
660
+ const mode = pr.readOnly ? 'read-only host' : `push: ${getPushMode(pr)}`;
661
+ console.log(` Personal root: ${pr.path} (HEAD: ${getHeadSha(pr.path)?.slice(0, 8) || 'none'}, ${mode})`);
662
+ const reminder = getUnpushedReminder(config, homeDir);
663
+ if (reminder)
664
+ console.log(c.yellow(` ${reminder}`));
491
665
  }
492
666
  console.log(` Project root: ${projectRes.projectRoot || 'none'} (source: ${projectRes.source})`);
493
667
  if (loaded.uncommittedWarnings.length > 0) {
@@ -572,6 +746,9 @@ async function main() {
572
746
  console.log(c.dim(` details: ${troubleshootingLink(s.anchor)}`));
573
747
  }
574
748
  }
749
+ if (res.skippedHygiene.length > 0) {
750
+ 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.`));
751
+ }
575
752
  for (const n of res.notes)
576
753
  console.log(n);
577
754
  return 0;
@@ -583,9 +760,42 @@ async function main() {
583
760
  }
584
761
  if (cmd === 'init') {
585
762
  const config = loadConfig(homeDir);
586
- const apply = Boolean(flags.apply);
587
763
  const undo = Boolean(flags.undo);
764
+ // init applies by default; --preview (alias --dry-run) only shows the diff.
765
+ // --apply is kept as a no-op alias for older docs and scripts.
766
+ const preview = Boolean(flags.preview || flags['dry-run']);
767
+ if (preview && flags.apply) {
768
+ printErrorWithHelp('Use either --preview or --apply, not both.');
769
+ return 1;
770
+ }
771
+ const apply = !undo && !preview;
588
772
  const projectHint = Boolean(flags['project-hint']);
773
+ // init also creates the personal memory folder, so `setup` is optional:
774
+ // `init <folder>` picks the folder; plain `init` uses ~/.faber/memory when
775
+ // no personal or team root is configured yet.
776
+ if (!undo) {
777
+ const requested = positional[0] ? path.resolve(positional[0]) : undefined;
778
+ const current = config.roots.personal?.path;
779
+ if (requested && current && path.resolve(current) !== requested) {
780
+ printErrorWithHelp(`Personal memory is already at ${current}. To move it, run: faber-memory config set-path personal ${requested}`);
781
+ return 1;
782
+ }
783
+ const target = requested && !current
784
+ ? requested
785
+ : !current && !config.roots.team
786
+ ? getDefaultPersonalPath()
787
+ : undefined;
788
+ if (target) {
789
+ if (preview) {
790
+ console.log(c.cyan(`Would create your personal memory folder at ${target}.`));
791
+ }
792
+ else {
793
+ createPersonalRoot(config, target, homeDir);
794
+ console.log(c.green(`Created your personal memory folder at ${target}.`));
795
+ printUncommittedNotesHint(target);
796
+ }
797
+ }
798
+ }
589
799
  const engines = typeof flags.engine === 'string'
590
800
  ? flags.engine.split(',').map((e) => e.trim())
591
801
  : undefined;
@@ -611,8 +821,12 @@ async function main() {
611
821
  if (res.projectHint) {
612
822
  console.log(`Project hint: ${res.projectHint}`);
613
823
  }
614
- if (!apply && !undo) {
615
- console.log(c.yellow('\nDry-run only. Re-run with --apply to write changes.'));
824
+ if (preview) {
825
+ console.log(c.yellow('\nPreview only. Run "faber-memory init" to write these changes.'));
826
+ }
827
+ else if (apply) {
828
+ const wired = [...new Set(res.plans.map((p) => p.engine))];
829
+ 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.`));
616
830
  }
617
831
  return 0;
618
832
  }
@@ -674,20 +888,26 @@ function printHelp() {
674
888
  console.log(`@fabersep/memory (faber-memory)
675
889
 
676
890
  Commands:
677
- setup [path] [--team <git-url|org/repo> --path <dir> --submit-mode auto|pr]
678
- config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | unset <personal|team>]
679
- init [--apply | --undo] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
891
+ setup [path] [--remote <git-url>] [--team <git-url|org/repo> --path <dir> --submit-mode auto|pr]
892
+ setup --read-only <git-url> [path] (a host that only reads, e.g. a server)
893
+ remote add <git-url> [--allow-public] | remote remove
894
+ push
895
+ config [set-path <personal|team> <new-path> | set-submit-mode <auto|pr> | set-push-mode <ask|auto|never> | unset <personal|team>]
896
+ init [folder] [--remote <git-url>] [--preview | --undo] [--engine claude-code,antigravity,claude-desktop,cursor,codex] [--project-hint]
680
897
  compile [--check] [--repo <dir>]
681
898
  sync [--timeout <ms>]
682
899
  status
683
900
  stats [--days 1..90] [--json] [--cache] [--engine claude-code|antigravity|all] [--log-dir <path>] [--share]
684
901
  doctor [--json] [--strict]
685
- review [--approve-all]
686
- approve <proposal-id> [...] [--mode auto|pr]
902
+ review [--approve-all] [--yes]
903
+ approve <proposal-id> [...] [--mode auto|pr] [--yes]
687
904
  reject <proposal-id> | reject --all [--yes]
688
905
  reset [--include-personal-repo] [--yes]
689
906
  import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--scope personal|team|project] [--split-headings] [--normalize-paths] [--approve]
690
907
  serve
908
+ --version
909
+
910
+ Docs: https://github.com/fabersep/memory#readme
691
911
  `);
692
912
  }
693
913
  main()
@@ -66,6 +66,7 @@ export function loadConfig(homeDir = getHomeDir()) {
66
66
  similarityThreshold: typeof raw.similarityThreshold === 'number'
67
67
  ? raw.similarityThreshold
68
68
  : DEFAULT_SIMILARITY_THRESHOLD,
69
+ ...(typeof raw.similarityHintFloor === 'number' ? { similarityHintFloor: raw.similarityHintFloor } : {}),
69
70
  roots: raw.roots || {},
70
71
  };
71
72
  }
@@ -2,10 +2,11 @@ import * as crypto from 'node:crypto';
2
2
  import * as fs from 'node:fs';
3
3
  import { estimateTokens, renderGlobalL0 } from './compiler.js';
4
4
  import { getCompiledL0Path, getConfigPath, getHomeDir, loadConfig } from './config.js';
5
- import { getHeadSha, getUncommittedFiles, isGitRepo, readHeadFile } from './git.js';
5
+ import { getDefaultBranch, getHeadSha, getUncommittedFiles, gitSync, hasRemote, isGitRepo, readHeadFile } from './git.js';
6
6
  import { scanHygiene } from './hygiene.js';
7
7
  import { BLOCK_END, BLOCK_START, getEngineSpecs, getUserHome } from './init.js';
8
8
  import { readMetrics } from './metrics.js';
9
+ import { getAheadInfo, getUnpushedReminder, readPersonalRemoteState } from './personal-remote.js';
9
10
  import { listAllProposals } from './proposals.js';
10
11
  import { L0_CHURN_WARN_THRESHOLD } from './stats.js';
11
12
  import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
@@ -37,6 +38,31 @@ function hasFaberMemoryMcpEntry(filePath) {
37
38
  return false;
38
39
  }
39
40
  }
41
+ // 02 FR-06 amendment: memory indexes an engine file loads outside the managed block.
42
+ function extraMemoryIndexes(filePath, engine) {
43
+ if (!fs.existsSync(filePath))
44
+ return [];
45
+ let content;
46
+ try {
47
+ content = fs.readFileSync(filePath, 'utf8');
48
+ }
49
+ catch {
50
+ return [];
51
+ }
52
+ const start = content.indexOf(BLOCK_START);
53
+ const end = start === -1 ? -1 : content.indexOf(BLOCK_END, start + BLOCK_START.length);
54
+ const outside = start !== -1 && end !== -1 ? content.slice(0, start) + content.slice(end + BLOCK_END.length) : content;
55
+ const found = new Set();
56
+ if (engine === 'claude-code') {
57
+ for (const m of outside.matchAll(/^\s*@(\S*MEMORY\.md)\s*$/gim))
58
+ found.add(m[1]);
59
+ }
60
+ else {
61
+ for (const m of outside.matchAll(/(?:^|[\s`'"(])([~$\w./\\-]*[\/\\]MEMORY\.md)\b/gim))
62
+ found.add(m[1]);
63
+ }
64
+ return [...found];
65
+ }
40
66
  export function runDoctor(options = {}) {
41
67
  const homeDir = options.homeDir || getHomeDir();
42
68
  const userHome = options.userHome || getUserHome();
@@ -265,6 +291,7 @@ export function runDoctor(options = {}) {
265
291
  const specs = getEngineSpecs();
266
292
  const wiredEngines = [];
267
293
  const mismatchedEngines = [];
294
+ const extraIndexEngines = [];
268
295
  for (const engineName of ['claude-code', 'claude-desktop', 'antigravity', 'cursor']) {
269
296
  const spec = specs[engineName];
270
297
  const mcpWired = spec.mcpConfigFile ? hasFaberMemoryMcpEntry(spec.mcpConfigFile(userHome)) : false;
@@ -296,6 +323,13 @@ export function runDoctor(options = {}) {
296
323
  }
297
324
  }
298
325
  }
326
+ if (spec.instructionFile && (engineName === 'claude-code' || engineName === 'antigravity')) {
327
+ const extras = extraMemoryIndexes(spec.instructionFile(userHome), engineName);
328
+ if (extras.length > 0) {
329
+ extraIndexEngines.push(engineName);
330
+ wiringDetails.push(`${engineName}: loads another memory index outside the managed block: ${extras.join(', ')}.`);
331
+ }
332
+ }
299
333
  if (instrMismatch) {
300
334
  mismatchedEngines.push(engineName);
301
335
  wiringDetails.push(`${engineName}: managed L0 block path does not match ${l0Path}.`);
@@ -309,14 +343,24 @@ export function runDoctor(options = {}) {
309
343
  wiredEngines.push(`${engineName} (${parts.join('+')})`);
310
344
  }
311
345
  }
346
+ if (extraIndexEngines.length > 0) {
347
+ wiringStatus = 'WARN';
348
+ wiringHint =
349
+ 'Remove the other memory index lines so only the faber-memory managed block loads memory.';
350
+ }
312
351
  if (mismatchedEngines.length > 0) {
313
352
  wiringStatus = 'WARN';
314
- wiringHint = 'Run "faber-memory init --apply" to update engine pointers to the current compiled MEMORY.md path.';
353
+ wiringHint = [wiringHint, 'Run "faber-memory init" to update engine pointers to the current compiled MEMORY.md path.']
354
+ .filter(Boolean)
355
+ .join(' ');
356
+ }
357
+ else if (extraIndexEngines.length > 0) {
358
+ // already WARN with its hint
315
359
  }
316
360
  else if (wiredEngines.length === 0) {
317
361
  wiringStatus = 'WARN';
318
362
  wiringDetails.push('No AI coding engine appears wired for faber-memory.');
319
- wiringHint = 'Run "faber-memory init --apply" to wire Claude Code, Antigravity, Claude Desktop, or Cursor.';
363
+ wiringHint = 'Run "faber-memory init" to wire Claude Code, Antigravity, Claude Desktop, or Cursor.';
320
364
  }
321
365
  else {
322
366
  wiringDetails.push(`Wired engines: ${wiredEngines.join(', ')}.`);
@@ -408,6 +452,58 @@ export function runDoctor(options = {}) {
408
452
  details: stabilityDetails,
409
453
  ...(stabilityHint ? { hint: stabilityHint } : {}),
410
454
  });
455
+ // 7. Personal remote (feature 03 FR-03, FR-05); only when a personal root is configured.
456
+ const personal = config?.roots.personal;
457
+ if (personal && isGitRepo(personal.path)) {
458
+ const details = [];
459
+ let status = 'PASS';
460
+ let hint;
461
+ const warn = (detail, fix) => {
462
+ status = 'WARN';
463
+ details.push(detail);
464
+ hint = hint ? `${hint} ${fix}` : fix;
465
+ };
466
+ if (personal.readOnly) {
467
+ details.push('Read-only host: this machine only pulls the personal memory.');
468
+ if (!hasRemote(personal.path))
469
+ warn('The read-only clone has no origin.', 'Re-run faber-memory setup --read-only <url>.');
470
+ if (getUncommittedFiles(personal.path).length > 0) {
471
+ warn('The read-only clone has local edits; sync will not pull it.', `Discard the edits in ${personal.path}.`);
472
+ }
473
+ const branch = gitSync(['--no-optional-locks', '-C', personal.path, 'rev-parse', '--abbrev-ref', 'HEAD']).stdout.trim();
474
+ const expected = personal.defaultBranch || getDefaultBranch(personal.path);
475
+ if (branch && branch !== expected) {
476
+ warn(`The read-only clone is on ${branch}, not ${expected}.`, `Run git -C ${personal.path} checkout ${expected}.`);
477
+ }
478
+ if (getAheadInfo(personal.path).ahead > 0) {
479
+ warn('The read-only clone has local commits.', 'Reset it to origin; a read-only host never commits.');
480
+ }
481
+ const lastPull = readPersonalRemoteState(homeDir).lastPullAt;
482
+ const ageDays = lastPull ? Math.floor((nowMs - Date.parse(lastPull)) / 86400000) : null;
483
+ if (ageDays === null) {
484
+ warn('No successful pull recorded yet.', 'Run faber-memory sync.');
485
+ }
486
+ else if (ageDays > 7) {
487
+ warn(`Last successful pull was ${ageDays} days ago.`, 'Run faber-memory sync and check the host can reach origin.');
488
+ }
489
+ else {
490
+ details.push(`Last successful pull ${ageDays} day(s) ago.`);
491
+ }
492
+ }
493
+ else if (!hasRemote(personal.path)) {
494
+ warn('The personal root has no remote; approved memory stays on this machine.', 'Run faber-memory remote add <url> with a private repository.');
495
+ }
496
+ else {
497
+ const reminder = config ? getUnpushedReminder(config, homeDir) : null;
498
+ if (reminder) {
499
+ warn(reminder, 'Run faber-memory push.');
500
+ }
501
+ else {
502
+ details.push('The personal root is in step with origin.');
503
+ }
504
+ }
505
+ checks.push({ id: 'personal-remote', name: 'Personal remote', status, details, ...(hint ? { hint } : {}) });
506
+ }
411
507
  const hasFail = checks.some((ch) => ch.status === 'FAIL');
412
508
  const hasWarn = checks.some((ch) => ch.status === 'WARN');
413
509
  const overall = hasFail ? 'FAIL' : hasWarn ? 'WARN' : 'PASS';
@@ -1,51 +1,60 @@
1
+ const SECRET_FIX = 'remove the value; store a pointer to where it lives instead';
1
2
  const RULES = [
2
3
  {
3
4
  category: 'secret',
4
5
  pattern: 'private-key',
5
6
  regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
6
7
  label: 'Private key header detected',
8
+ fix: SECRET_FIX,
7
9
  },
8
10
  {
9
11
  category: 'secret',
10
12
  pattern: 'jwt',
11
13
  regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
12
14
  label: 'JWT token detected',
15
+ fix: SECRET_FIX,
13
16
  },
14
17
  {
15
18
  category: 'secret',
16
19
  pattern: 'bearer-token',
17
20
  regex: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}/i,
18
21
  label: 'Bearer token detected',
22
+ fix: SECRET_FIX,
19
23
  },
20
24
  {
21
25
  category: 'secret',
22
26
  pattern: 'api-key-prefix',
23
27
  regex: /\b(?:sk-[A-Za-z0-9_-]{16,}|sk_live_[A-Za-z0-9]{12,}|ghp_[A-Za-z0-9]{20,}|gho_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
24
28
  label: 'Known API key prefix detected',
29
+ fix: SECRET_FIX,
25
30
  },
26
31
  {
27
32
  category: 'secret',
28
33
  pattern: 'credential-assignment',
29
34
  regex: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/i,
30
35
  label: 'Credential assignment detected',
36
+ fix: SECRET_FIX,
31
37
  },
32
38
  {
33
39
  category: 'machine-path',
34
40
  pattern: 'macos-user-path',
35
41
  regex: /\/Users\/[A-Za-z0-9._-]+\//,
36
42
  label: 'Machine-specific macOS home path detected',
43
+ fix: 'write ~/ or $HOME instead of /Users/<name>/',
37
44
  },
38
45
  {
39
46
  category: 'machine-path',
40
47
  pattern: 'linux-user-path',
41
48
  regex: /\/home\/[A-Za-z0-9._-]+\//,
42
49
  label: 'Machine-specific Linux home path detected',
50
+ fix: 'write ~/ or $HOME instead of /home/<name>/',
43
51
  },
44
52
  {
45
53
  category: 'machine-path',
46
54
  pattern: 'windows-user-path',
47
55
  regex: /\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
48
56
  label: 'Machine-specific Windows home path detected',
57
+ fix: 'write ~\\ or %USERPROFILE% instead of C:\\Users\\<name>\\',
49
58
  },
50
59
  ];
51
60
  export function scanHygiene(content) {
@@ -64,7 +73,7 @@ export function scanHygiene(content) {
64
73
  line: i + 1,
65
74
  category: rule.category,
66
75
  pattern: rule.pattern,
67
- message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}`,
76
+ message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}; fix: ${rule.fix}`,
68
77
  redactedSnippet,
69
78
  });
70
79
  break;