@fabersep/memory 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +271 -2
- package/dist/src/bm25.d.ts +26 -0
- package/dist/src/bm25.js +183 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +434 -0
- package/dist/src/compiler.d.ts +19 -0
- package/dist/src/compiler.js +171 -0
- package/dist/src/config.d.ts +20 -0
- package/dist/src/config.js +134 -0
- package/dist/src/frontmatter.d.ts +22 -0
- package/dist/src/frontmatter.js +199 -0
- package/dist/src/git.d.ts +33 -0
- package/dist/src/git.js +251 -0
- package/dist/src/hygiene.d.ts +3 -0
- package/dist/src/hygiene.js +81 -0
- package/dist/src/importer.d.ts +26 -0
- package/dist/src/importer.js +211 -0
- package/dist/src/index.d.ts +13 -0
- package/dist/src/index.js +13 -0
- package/dist/src/init.d.ts +42 -0
- package/dist/src/init.js +242 -0
- package/dist/src/mcp.d.ts +128 -0
- package/dist/src/mcp.js +381 -0
- package/dist/src/proposals.d.ts +34 -0
- package/dist/src/proposals.js +383 -0
- package/dist/src/store.d.ts +23 -0
- package/dist/src/store.js +161 -0
- package/dist/src/sync.d.ts +13 -0
- package/dist/src/sync.js +47 -0
- package/dist/src/types.d.ts +100 -0
- package/dist/src/types.js +17 -0
- package/package.json +50 -4
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const RULES = [
|
|
2
|
+
{
|
|
3
|
+
category: 'secret',
|
|
4
|
+
pattern: 'private-key',
|
|
5
|
+
regex: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
6
|
+
label: 'Private key header detected',
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
category: 'secret',
|
|
10
|
+
pattern: 'jwt',
|
|
11
|
+
regex: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
|
|
12
|
+
label: 'JWT token detected',
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
category: 'secret',
|
|
16
|
+
pattern: 'bearer-token',
|
|
17
|
+
regex: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}/i,
|
|
18
|
+
label: 'Bearer token detected',
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
category: 'secret',
|
|
22
|
+
pattern: 'api-key-prefix',
|
|
23
|
+
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
|
+
label: 'Known API key prefix detected',
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
category: 'secret',
|
|
28
|
+
pattern: 'credential-assignment',
|
|
29
|
+
regex: /\b(?:api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd)\s*[:=]\s*["']?[A-Za-z0-9._~+/=-]{12,}["']?/i,
|
|
30
|
+
label: 'Credential assignment detected',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
category: 'machine-path',
|
|
34
|
+
pattern: 'macos-user-path',
|
|
35
|
+
regex: /\/Users\/[A-Za-z0-9._-]+\//,
|
|
36
|
+
label: 'Machine-specific macOS home path detected',
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
category: 'machine-path',
|
|
40
|
+
pattern: 'linux-user-path',
|
|
41
|
+
regex: /\/home\/[A-Za-z0-9._-]+\//,
|
|
42
|
+
label: 'Machine-specific Linux home path detected',
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
category: 'machine-path',
|
|
46
|
+
pattern: 'windows-user-path',
|
|
47
|
+
regex: /\b[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
|
|
48
|
+
label: 'Machine-specific Windows home path detected',
|
|
49
|
+
},
|
|
50
|
+
];
|
|
51
|
+
export function scanHygiene(content) {
|
|
52
|
+
const findings = [];
|
|
53
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
54
|
+
for (let i = 0; i < lines.length; i++) {
|
|
55
|
+
const lineText = lines[i];
|
|
56
|
+
for (const rule of RULES) {
|
|
57
|
+
const match = rule.regex.exec(lineText);
|
|
58
|
+
if (match) {
|
|
59
|
+
const redactedSnippet = lineText
|
|
60
|
+
.replace(rule.regex, rule.category === 'secret' ? '[REDACTED]' : '[MACHINE_PATH]')
|
|
61
|
+
.trim()
|
|
62
|
+
.slice(0, 120);
|
|
63
|
+
findings.push({
|
|
64
|
+
line: i + 1,
|
|
65
|
+
category: rule.category,
|
|
66
|
+
pattern: rule.pattern,
|
|
67
|
+
message: `${rule.label} (${rule.category}/${rule.pattern}) at line ${i + 1}`,
|
|
68
|
+
redactedSnippet,
|
|
69
|
+
});
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return findings;
|
|
75
|
+
}
|
|
76
|
+
export function formatHygieneErrors(findings, sourceName) {
|
|
77
|
+
const prefix = sourceName ? `${sourceName}: ` : '';
|
|
78
|
+
return findings
|
|
79
|
+
.map((f) => `${prefix}line ${f.line} [${f.category}/${f.pattern}]: ${f.message} (${f.redactedSnippet})`)
|
|
80
|
+
.join('\n');
|
|
81
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Proposal, Scope, UserConfig } from './types.js';
|
|
2
|
+
export type ImportSourceType = 'markdown-dir' | 'claude-memory' | 'agents-md' | 'cursor-rules';
|
|
3
|
+
export declare const CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE = "To disable Claude Code auto-memory so future writes do not bypass pre-memory, set \"autoMemoryEnabled\": false in ~/.claude/settings.json (or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1).";
|
|
4
|
+
export interface ImportResult {
|
|
5
|
+
staged: Proposal[];
|
|
6
|
+
approvedIds: string[];
|
|
7
|
+
duplicates: {
|
|
8
|
+
source: string;
|
|
9
|
+
matchedId: string;
|
|
10
|
+
summary: string;
|
|
11
|
+
}[];
|
|
12
|
+
skippedHygiene: {
|
|
13
|
+
source: string;
|
|
14
|
+
reason: string;
|
|
15
|
+
}[];
|
|
16
|
+
notes: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function runImport(config: UserConfig, options: {
|
|
19
|
+
from: ImportSourceType;
|
|
20
|
+
sourcePath: string;
|
|
21
|
+
scope?: Scope;
|
|
22
|
+
splitHeadings?: boolean;
|
|
23
|
+
approve?: boolean;
|
|
24
|
+
homeDir?: string;
|
|
25
|
+
cwd?: string;
|
|
26
|
+
}): Promise<ImportResult>;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { findNearDuplicates } from './bm25.js';
|
|
4
|
+
import { getHomeDir } from './config.js';
|
|
5
|
+
import { parseMarkdownWithFrontmatter, slugify } from './frontmatter.js';
|
|
6
|
+
import { scanHygiene } from './hygiene.js';
|
|
7
|
+
import { approveProposalsBatch, createProposal, reconcileAwaitingCommitProposals, } from './proposals.js';
|
|
8
|
+
import { loadAllScopes, resolveProjectRoot } from './store.js';
|
|
9
|
+
import { VALID_TYPES } from './types.js';
|
|
10
|
+
export const CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE = 'To disable Claude Code auto-memory so future writes do not bypass pre-memory, set "autoMemoryEnabled": false in ~/.claude/settings.json (or CLAUDE_CODE_DISABLE_AUTO_MEMORY=1).';
|
|
11
|
+
function inferType(raw, filename) {
|
|
12
|
+
if (typeof raw.type === 'string' && VALID_TYPES.includes(raw.type)) {
|
|
13
|
+
return raw.type;
|
|
14
|
+
}
|
|
15
|
+
const lower = filename.toLowerCase();
|
|
16
|
+
if (lower.includes('decision'))
|
|
17
|
+
return 'decision';
|
|
18
|
+
if (lower.includes('lesson') || lower.includes('mistake'))
|
|
19
|
+
return 'lesson';
|
|
20
|
+
if (lower.includes('pref') || lower.includes('style'))
|
|
21
|
+
return 'preference';
|
|
22
|
+
if (lower.includes('ref') || lower.includes('catalog'))
|
|
23
|
+
return 'reference';
|
|
24
|
+
return 'rule';
|
|
25
|
+
}
|
|
26
|
+
function inferSummary(raw, body, fallbackName) {
|
|
27
|
+
for (const key of ['summary', 'description', 'name', 'title']) {
|
|
28
|
+
const val = raw[key];
|
|
29
|
+
if (typeof val === 'string' && val.trim()) {
|
|
30
|
+
return val.replace(/\s+/g, ' ').trim();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const firstHeading = body
|
|
34
|
+
.split('\n')
|
|
35
|
+
.map((l) => l.trim())
|
|
36
|
+
.find((l) => l.startsWith('#'));
|
|
37
|
+
if (firstHeading) {
|
|
38
|
+
return firstHeading.replace(/^#+\s*/, '').trim();
|
|
39
|
+
}
|
|
40
|
+
const firstLine = body
|
|
41
|
+
.split('\n')
|
|
42
|
+
.map((l) => l.trim())
|
|
43
|
+
.find((l) => l.length > 0);
|
|
44
|
+
return (firstLine || fallbackName).slice(0, 140);
|
|
45
|
+
}
|
|
46
|
+
function splitTopLevelHeadings(content) {
|
|
47
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
48
|
+
const sections = [];
|
|
49
|
+
let current = null;
|
|
50
|
+
for (const line of lines) {
|
|
51
|
+
const m = line.match(/^#{1,2}\s+(.+)$/);
|
|
52
|
+
if (m) {
|
|
53
|
+
if (current && current.lines.join('\n').trim()) {
|
|
54
|
+
sections.push(current);
|
|
55
|
+
}
|
|
56
|
+
current = { title: m[1].trim(), lines: [line] };
|
|
57
|
+
}
|
|
58
|
+
else if (current) {
|
|
59
|
+
current.lines.push(line);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (current && current.lines.join('\n').trim()) {
|
|
63
|
+
sections.push(current);
|
|
64
|
+
}
|
|
65
|
+
return sections.map((s) => ({ title: s.title, body: s.lines.join('\n').trim() }));
|
|
66
|
+
}
|
|
67
|
+
function collectMarkdownFiles(targetPath) {
|
|
68
|
+
const stat = fs.statSync(targetPath);
|
|
69
|
+
if (stat.isFile())
|
|
70
|
+
return [targetPath];
|
|
71
|
+
const results = [];
|
|
72
|
+
for (const entry of fs.readdirSync(targetPath, { withFileTypes: true })) {
|
|
73
|
+
const full = path.join(targetPath, entry.name);
|
|
74
|
+
if (entry.isDirectory()) {
|
|
75
|
+
if (entry.name.startsWith('.'))
|
|
76
|
+
continue;
|
|
77
|
+
results.push(...collectMarkdownFiles(full));
|
|
78
|
+
}
|
|
79
|
+
else if (entry.isFile() && /\.(md|mdc)$/i.test(entry.name)) {
|
|
80
|
+
results.push(full);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return results.sort();
|
|
84
|
+
}
|
|
85
|
+
export async function runImport(config, options) {
|
|
86
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
87
|
+
const targetScope = options.scope || 'personal';
|
|
88
|
+
const cwd = options.cwd || process.cwd();
|
|
89
|
+
if (options.approve && targetScope !== 'personal') {
|
|
90
|
+
throw new Error('--approve during import is allowed in solo (personal) mode only.');
|
|
91
|
+
}
|
|
92
|
+
const projectRes = resolveProjectRoot(undefined, cwd);
|
|
93
|
+
const loaded = loadAllScopes(config, projectRes);
|
|
94
|
+
const pending = reconcileAwaitingCommitProposals(homeDir);
|
|
95
|
+
const staged = [];
|
|
96
|
+
const duplicates = [];
|
|
97
|
+
const skippedHygiene = [];
|
|
98
|
+
const notes = [];
|
|
99
|
+
if (options.from === 'claude-memory') {
|
|
100
|
+
notes.push(CLAUDE_DISABLE_AUTOMEMORY_GUIDANCE);
|
|
101
|
+
}
|
|
102
|
+
const candidates = [];
|
|
103
|
+
if (options.from === 'markdown-dir' || options.from === 'claude-memory') {
|
|
104
|
+
const files = collectMarkdownFiles(options.sourcePath);
|
|
105
|
+
for (const filePath of files) {
|
|
106
|
+
const base = path.basename(filePath);
|
|
107
|
+
if (base.toLowerCase() === 'memory.md' || base.toLowerCase() === 'catalog.md' || base.toLowerCase() === 'readme.md') {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
111
|
+
const parsed = parseMarkdownWithFrontmatter(raw);
|
|
112
|
+
const summary = inferSummary(parsed.rawFrontmatter, parsed.body, base);
|
|
113
|
+
const type = inferType(parsed.rawFrontmatter, base);
|
|
114
|
+
const tags = [];
|
|
115
|
+
if (Array.isArray(parsed.rawFrontmatter.tags)) {
|
|
116
|
+
tags.push(...parsed.rawFrontmatter.tags.map(String));
|
|
117
|
+
}
|
|
118
|
+
const meta = parsed.rawFrontmatter.metadata;
|
|
119
|
+
if (meta && typeof meta.scope === 'string' && meta.scope.trim()) {
|
|
120
|
+
tags.push(`legacy-scope:${meta.scope.trim()}`);
|
|
121
|
+
}
|
|
122
|
+
candidates.push({
|
|
123
|
+
source: filePath,
|
|
124
|
+
entryId: slugify(base),
|
|
125
|
+
summary,
|
|
126
|
+
type,
|
|
127
|
+
tags,
|
|
128
|
+
body: parsed.body.trim() || summary,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
// agents-md or cursor-rules
|
|
134
|
+
const files = collectMarkdownFiles(options.sourcePath);
|
|
135
|
+
for (const filePath of files) {
|
|
136
|
+
const base = path.basename(filePath);
|
|
137
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
138
|
+
const parsed = parseMarkdownWithFrontmatter(raw);
|
|
139
|
+
if (options.splitHeadings) {
|
|
140
|
+
const sections = splitTopLevelHeadings(parsed.body);
|
|
141
|
+
if (sections.length > 0) {
|
|
142
|
+
for (const sec of sections) {
|
|
143
|
+
candidates.push({
|
|
144
|
+
source: `${filePath}#${sec.title}`,
|
|
145
|
+
entryId: slugify(sec.title),
|
|
146
|
+
summary: sec.title,
|
|
147
|
+
type: 'rule',
|
|
148
|
+
tags: [options.from],
|
|
149
|
+
body: sec.body,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const summary = inferSummary(parsed.rawFrontmatter, parsed.body, base);
|
|
156
|
+
candidates.push({
|
|
157
|
+
source: filePath,
|
|
158
|
+
entryId: slugify(base),
|
|
159
|
+
summary,
|
|
160
|
+
type: 'rule',
|
|
161
|
+
tags: [options.from],
|
|
162
|
+
body: parsed.body.trim() || summary,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const c of candidates) {
|
|
167
|
+
const hygiene = scanHygiene(`${c.summary}\n${c.body}`);
|
|
168
|
+
if (hygiene.length > 0) {
|
|
169
|
+
skippedHygiene.push({
|
|
170
|
+
source: c.source,
|
|
171
|
+
reason: hygiene.map((h) => h.message).join('; '),
|
|
172
|
+
});
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const dupes = findNearDuplicates(c.summary, c.body, loaded.activeEntries, [...pending, ...staged], config.similarityThreshold);
|
|
176
|
+
if (dupes.length > 0) {
|
|
177
|
+
duplicates.push({
|
|
178
|
+
source: c.source,
|
|
179
|
+
matchedId: dupes[0].id,
|
|
180
|
+
summary: dupes[0].summary,
|
|
181
|
+
});
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
const proposal = createProposal(config, {
|
|
185
|
+
scope: targetScope,
|
|
186
|
+
action: 'create',
|
|
187
|
+
entryId: c.entryId,
|
|
188
|
+
summary: c.summary,
|
|
189
|
+
type: c.type,
|
|
190
|
+
tags: c.tags,
|
|
191
|
+
body: c.body,
|
|
192
|
+
projectRootPath: targetScope === 'project' ? projectRes.projectRoot : undefined,
|
|
193
|
+
}, homeDir);
|
|
194
|
+
staged.push(proposal);
|
|
195
|
+
}
|
|
196
|
+
const approvedIds = [];
|
|
197
|
+
if (options.approve && staged.length > 0) {
|
|
198
|
+
const outcome = await approveProposalsBatch(config, staged, { homeDir });
|
|
199
|
+
if (!outcome.ok) {
|
|
200
|
+
throw new Error(`Import --approve failed: ${outcome.errors.join('; ')}`);
|
|
201
|
+
}
|
|
202
|
+
approvedIds.push(...outcome.approvedIds);
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
staged,
|
|
206
|
+
approvedIds,
|
|
207
|
+
duplicates,
|
|
208
|
+
skippedHygiene,
|
|
209
|
+
notes,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export * from './config.js';
|
|
3
|
+
export * from './git.js';
|
|
4
|
+
export * from './frontmatter.js';
|
|
5
|
+
export * from './hygiene.js';
|
|
6
|
+
export * from './store.js';
|
|
7
|
+
export * from './compiler.js';
|
|
8
|
+
export * from './bm25.js';
|
|
9
|
+
export * from './proposals.js';
|
|
10
|
+
export * from './sync.js';
|
|
11
|
+
export * from './importer.js';
|
|
12
|
+
export * from './init.js';
|
|
13
|
+
export * from './mcp.js';
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * from './types.js';
|
|
2
|
+
export * from './config.js';
|
|
3
|
+
export * from './git.js';
|
|
4
|
+
export * from './frontmatter.js';
|
|
5
|
+
export * from './hygiene.js';
|
|
6
|
+
export * from './store.js';
|
|
7
|
+
export * from './compiler.js';
|
|
8
|
+
export * from './bm25.js';
|
|
9
|
+
export * from './proposals.js';
|
|
10
|
+
export * from './sync.js';
|
|
11
|
+
export * from './importer.js';
|
|
12
|
+
export * from './init.js';
|
|
13
|
+
export * from './mcp.js';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { UserConfig } from './types.js';
|
|
2
|
+
export declare const BLOCK_START = "<!-- faber-memory:start -->";
|
|
3
|
+
export declare const BLOCK_END = "<!-- faber-memory:end -->";
|
|
4
|
+
export declare const PROJECT_HINT_LINE = "Project memory: run npx @fabersep/memory init";
|
|
5
|
+
export type EngineName = 'claude-code' | 'claude-desktop' | 'antigravity' | 'cursor' | 'codex';
|
|
6
|
+
export interface EngineSpec {
|
|
7
|
+
name: EngineName;
|
|
8
|
+
verifiedImport: boolean;
|
|
9
|
+
gap: boolean;
|
|
10
|
+
instructionFile?: (userHome: string) => string;
|
|
11
|
+
mcpConfigFile?: (userHome: string) => string;
|
|
12
|
+
renderBlock?: (compiledL0Path: string) => string;
|
|
13
|
+
}
|
|
14
|
+
export declare function getEngineSpecs(): Record<EngineName, EngineSpec>;
|
|
15
|
+
export interface FilePlan {
|
|
16
|
+
filePath: string;
|
|
17
|
+
kind: 'instruction' | 'mcp-config';
|
|
18
|
+
engine: EngineName;
|
|
19
|
+
before: string | null;
|
|
20
|
+
after: string;
|
|
21
|
+
changed: boolean;
|
|
22
|
+
backupPath?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface InitPlanResult {
|
|
25
|
+
plans: FilePlan[];
|
|
26
|
+
backups: string[];
|
|
27
|
+
notes: string[];
|
|
28
|
+
projectHint?: string;
|
|
29
|
+
}
|
|
30
|
+
export declare function getUserHome(): string;
|
|
31
|
+
export declare function upsertManagedBlock(existing: string, block: string): string;
|
|
32
|
+
export declare function removeManagedBlock(existing: string): string;
|
|
33
|
+
export declare function detectTargetEngines(userHome: string, requested?: EngineName[]): EngineName[];
|
|
34
|
+
export declare function planOrApplyInit(config: UserConfig, options?: {
|
|
35
|
+
apply?: boolean;
|
|
36
|
+
undo?: boolean;
|
|
37
|
+
engines?: EngineName[];
|
|
38
|
+
projectHint?: boolean;
|
|
39
|
+
homeDir?: string;
|
|
40
|
+
userHome?: string;
|
|
41
|
+
}): InitPlanResult;
|
|
42
|
+
export declare function formatUnifiedDiff(plan: FilePlan): string;
|
package/dist/src/init.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as os from 'node:os';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { getCompiledL0Path, getHomeDir } from './config.js';
|
|
5
|
+
import { compileGlobalL0 } from './compiler.js';
|
|
6
|
+
export const BLOCK_START = '<!-- faber-memory:start -->';
|
|
7
|
+
export const BLOCK_END = '<!-- faber-memory:end -->';
|
|
8
|
+
export const PROJECT_HINT_LINE = 'Project memory: run npx @fabersep/memory init';
|
|
9
|
+
export function getEngineSpecs() {
|
|
10
|
+
return {
|
|
11
|
+
'claude-code': {
|
|
12
|
+
name: 'claude-code',
|
|
13
|
+
verifiedImport: true,
|
|
14
|
+
gap: false,
|
|
15
|
+
instructionFile: (home) => path.join(home, '.claude', 'CLAUDE.md'),
|
|
16
|
+
mcpConfigFile: (home) => path.join(home, '.claude.json'),
|
|
17
|
+
renderBlock: (l0Path) => `${BLOCK_START}\n@${l0Path}\n${BLOCK_END}`,
|
|
18
|
+
},
|
|
19
|
+
'claude-desktop': {
|
|
20
|
+
name: 'claude-desktop',
|
|
21
|
+
verifiedImport: false,
|
|
22
|
+
gap: false,
|
|
23
|
+
mcpConfigFile: (home) => process.platform === 'darwin'
|
|
24
|
+
? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
|
|
25
|
+
: path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
|
|
26
|
+
},
|
|
27
|
+
antigravity: {
|
|
28
|
+
name: 'antigravity',
|
|
29
|
+
verifiedImport: true,
|
|
30
|
+
gap: false,
|
|
31
|
+
instructionFile: (home) => path.join(home, '.gemini', 'GEMINI.md'),
|
|
32
|
+
mcpConfigFile: (home) => path.join(home, '.gemini', 'config', 'mcp_config.json'),
|
|
33
|
+
renderBlock: (l0Path) => `${BLOCK_START}\nAt session start, read ${l0Path} for global L0 memory and use the faber-memory MCP tools (memory_search, memory_get, memory_propose) for deeper recall.\n${BLOCK_END}`,
|
|
34
|
+
},
|
|
35
|
+
cursor: {
|
|
36
|
+
name: 'cursor',
|
|
37
|
+
verifiedImport: false,
|
|
38
|
+
gap: true,
|
|
39
|
+
mcpConfigFile: (home) => path.join(home, '.cursor', 'mcp.json'),
|
|
40
|
+
},
|
|
41
|
+
codex: {
|
|
42
|
+
name: 'codex',
|
|
43
|
+
verifiedImport: false,
|
|
44
|
+
gap: true,
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function getUserHome() {
|
|
49
|
+
return process.env.FABER_USER_HOME || os.homedir();
|
|
50
|
+
}
|
|
51
|
+
export function upsertManagedBlock(existing, block) {
|
|
52
|
+
const escapedStart = escapeRegex(BLOCK_START);
|
|
53
|
+
const escapedEnd = escapeRegex(BLOCK_END);
|
|
54
|
+
const regex = new RegExp(`${escapedStart}[\\s\\S]*?${escapedEnd}`, 'g');
|
|
55
|
+
if (regex.test(existing)) {
|
|
56
|
+
let first = true;
|
|
57
|
+
const replaced = existing.replace(regex, () => {
|
|
58
|
+
if (first) {
|
|
59
|
+
first = false;
|
|
60
|
+
return block;
|
|
61
|
+
}
|
|
62
|
+
return '';
|
|
63
|
+
});
|
|
64
|
+
return replaced.replace(/\n{3,}/g, '\n\n').trimEnd() + '\n';
|
|
65
|
+
}
|
|
66
|
+
const trimmed = existing.trimEnd();
|
|
67
|
+
return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
|
|
68
|
+
}
|
|
69
|
+
export function removeManagedBlock(existing) {
|
|
70
|
+
const escapedStart = escapeRegex(BLOCK_START);
|
|
71
|
+
const escapedEnd = escapeRegex(BLOCK_END);
|
|
72
|
+
const regex = new RegExp(`\\n?${escapedStart}[\\s\\S]*?${escapedEnd}\\n?`, 'g');
|
|
73
|
+
const next = existing.replace(regex, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
74
|
+
return next ? `${next}\n` : '';
|
|
75
|
+
}
|
|
76
|
+
function escapeRegex(s) {
|
|
77
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
78
|
+
}
|
|
79
|
+
function upsertMcpJson(existingRaw) {
|
|
80
|
+
let obj = {};
|
|
81
|
+
if (existingRaw && existingRaw.trim()) {
|
|
82
|
+
try {
|
|
83
|
+
obj = JSON.parse(existingRaw);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
obj = {};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const servers = obj.mcpServers && typeof obj.mcpServers === 'object'
|
|
90
|
+
? { ...obj.mcpServers }
|
|
91
|
+
: {};
|
|
92
|
+
servers['faber-memory'] = {
|
|
93
|
+
command: 'npx',
|
|
94
|
+
args: ['-y', '@fabersep/memory', 'serve'],
|
|
95
|
+
};
|
|
96
|
+
obj.mcpServers = servers;
|
|
97
|
+
return JSON.stringify(obj, null, 2) + '\n';
|
|
98
|
+
}
|
|
99
|
+
function removeMcpJson(existingRaw) {
|
|
100
|
+
let obj = {};
|
|
101
|
+
try {
|
|
102
|
+
obj = JSON.parse(existingRaw);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return existingRaw;
|
|
106
|
+
}
|
|
107
|
+
if (obj.mcpServers && typeof obj.mcpServers === 'object') {
|
|
108
|
+
const servers = { ...obj.mcpServers };
|
|
109
|
+
delete servers['faber-memory'];
|
|
110
|
+
obj.mcpServers = servers;
|
|
111
|
+
}
|
|
112
|
+
return JSON.stringify(obj, null, 2) + '\n';
|
|
113
|
+
}
|
|
114
|
+
export function detectTargetEngines(userHome, requested) {
|
|
115
|
+
if (requested && requested.length > 0)
|
|
116
|
+
return requested;
|
|
117
|
+
const detected = [];
|
|
118
|
+
if (fs.existsSync(path.join(userHome, '.claude')))
|
|
119
|
+
detected.push('claude-code');
|
|
120
|
+
if (fs.existsSync(path.join(userHome, '.gemini')))
|
|
121
|
+
detected.push('antigravity');
|
|
122
|
+
if (fs.existsSync(path.join(userHome, '.cursor')))
|
|
123
|
+
detected.push('cursor');
|
|
124
|
+
if (detected.length === 0)
|
|
125
|
+
detected.push('claude-code');
|
|
126
|
+
return detected;
|
|
127
|
+
}
|
|
128
|
+
export function planOrApplyInit(config, options = {}) {
|
|
129
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
130
|
+
const userHome = options.userHome || getUserHome();
|
|
131
|
+
const specs = getEngineSpecs();
|
|
132
|
+
const engines = detectTargetEngines(userHome, options.engines);
|
|
133
|
+
const compiledL0Path = getCompiledL0Path(homeDir);
|
|
134
|
+
const notes = [];
|
|
135
|
+
const plans = [];
|
|
136
|
+
const backups = [];
|
|
137
|
+
if (options.apply && !options.undo) {
|
|
138
|
+
// Always compile L0 BEFORE writing any user-level pointer (AC-19b1)
|
|
139
|
+
const comp = compileGlobalL0(config, { homeDir });
|
|
140
|
+
if (!comp.ok) {
|
|
141
|
+
throw new Error(`L0 compilation failed before init --apply:\n${comp.errors.join('\n')}`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const engineName of engines) {
|
|
145
|
+
const spec = specs[engineName];
|
|
146
|
+
if (!spec)
|
|
147
|
+
continue;
|
|
148
|
+
if (spec.gap) {
|
|
149
|
+
notes.push(`Engine "${engineName}" is marked GAP for user-level instruction import; wiring MCP-only delivery.`);
|
|
150
|
+
}
|
|
151
|
+
if (spec.instructionFile && spec.renderBlock && !spec.gap) {
|
|
152
|
+
const filePath = spec.instructionFile(userHome);
|
|
153
|
+
const exists = fs.existsSync(filePath);
|
|
154
|
+
const before = exists ? fs.readFileSync(filePath, 'utf8') : null;
|
|
155
|
+
const after = options.undo
|
|
156
|
+
? before !== null
|
|
157
|
+
? removeManagedBlock(before)
|
|
158
|
+
: ''
|
|
159
|
+
: upsertManagedBlock(before || '', spec.renderBlock(compiledL0Path));
|
|
160
|
+
const changed = (before ?? '') !== after;
|
|
161
|
+
const plan = {
|
|
162
|
+
filePath,
|
|
163
|
+
kind: 'instruction',
|
|
164
|
+
engine: engineName,
|
|
165
|
+
before,
|
|
166
|
+
after,
|
|
167
|
+
changed,
|
|
168
|
+
};
|
|
169
|
+
if (options.undo && fs.existsSync(`${filePath}.bak`)) {
|
|
170
|
+
plan.backupPath = `${filePath}.bak`;
|
|
171
|
+
backups.push(`${filePath}.bak`);
|
|
172
|
+
}
|
|
173
|
+
plans.push(plan);
|
|
174
|
+
}
|
|
175
|
+
if (spec.mcpConfigFile) {
|
|
176
|
+
const filePath = spec.mcpConfigFile(userHome);
|
|
177
|
+
const exists = fs.existsSync(filePath);
|
|
178
|
+
const before = exists ? fs.readFileSync(filePath, 'utf8') : null;
|
|
179
|
+
const after = options.undo
|
|
180
|
+
? before !== null
|
|
181
|
+
? removeMcpJson(before)
|
|
182
|
+
: ''
|
|
183
|
+
: upsertMcpJson(before);
|
|
184
|
+
const changed = (before ?? '') !== after;
|
|
185
|
+
const plan = {
|
|
186
|
+
filePath,
|
|
187
|
+
kind: 'mcp-config',
|
|
188
|
+
engine: engineName,
|
|
189
|
+
before,
|
|
190
|
+
after,
|
|
191
|
+
changed,
|
|
192
|
+
};
|
|
193
|
+
if (options.undo && fs.existsSync(`${filePath}.bak`)) {
|
|
194
|
+
plan.backupPath = `${filePath}.bak`;
|
|
195
|
+
backups.push(`${filePath}.bak`);
|
|
196
|
+
}
|
|
197
|
+
plans.push(plan);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (options.apply || options.undo) {
|
|
201
|
+
for (const p of plans) {
|
|
202
|
+
if (!p.changed)
|
|
203
|
+
continue;
|
|
204
|
+
if (options.undo && p.before === null)
|
|
205
|
+
continue;
|
|
206
|
+
fs.mkdirSync(path.dirname(p.filePath), { recursive: true });
|
|
207
|
+
if (!options.undo && p.before !== null) {
|
|
208
|
+
const bakPath = `${p.filePath}.bak`;
|
|
209
|
+
if (!fs.existsSync(bakPath)) {
|
|
210
|
+
fs.writeFileSync(bakPath, p.before, 'utf8');
|
|
211
|
+
p.backupPath = bakPath;
|
|
212
|
+
backups.push(bakPath);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
fs.writeFileSync(p.filePath, p.after, 'utf8');
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
plans,
|
|
220
|
+
backups,
|
|
221
|
+
notes,
|
|
222
|
+
projectHint: options.projectHint ? PROJECT_HINT_LINE : undefined,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
export function formatUnifiedDiff(plan) {
|
|
226
|
+
const beforeLines = (plan.before ?? '').split('\n');
|
|
227
|
+
const afterLines = plan.after.split('\n');
|
|
228
|
+
const header = `--- ${plan.filePath} (before)\n+++ ${plan.filePath} (after)`;
|
|
229
|
+
if (!plan.changed) {
|
|
230
|
+
return `${header}\n (no changes)`;
|
|
231
|
+
}
|
|
232
|
+
const out = [header];
|
|
233
|
+
for (const line of beforeLines) {
|
|
234
|
+
if (line && !afterLines.includes(line))
|
|
235
|
+
out.push(`- ${line}`);
|
|
236
|
+
}
|
|
237
|
+
for (const line of afterLines) {
|
|
238
|
+
if (line && !beforeLines.includes(line))
|
|
239
|
+
out.push(`+ ${line}`);
|
|
240
|
+
}
|
|
241
|
+
return out.join('\n');
|
|
242
|
+
}
|