@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.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,434 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import * as readline from 'node:readline';
5
+ import { compileGlobalL0 } from './compiler.js';
6
+ import { generateUuid, getCompiledL0Path, getDefaultPersonalPath, getHomeDir, loadConfig, saveConfig, } from './config.js';
7
+ import { getDefaultBranch, getHeadSha, gitCloneTeamRepo, gitInitSoloRepo, isGitRepo, } from './git.js';
8
+ import { runImport } from './importer.js';
9
+ import { formatUnifiedDiff, planOrApplyInit } from './init.js';
10
+ import { FaberMemoryMcpServer } from './mcp.js';
11
+ import { approveProposalsBatch, findProposalById, reconcileAwaitingCommitProposals, rejectProposal, saveProposal, } from './proposals.js';
12
+ import { loadAllScopes, resolveProjectRoot } from './store.js';
13
+ import { syncAllRoots } from './sync.js';
14
+ function parseFlags(args) {
15
+ const positional = [];
16
+ const flags = {};
17
+ for (let i = 0; i < args.length; i++) {
18
+ const arg = args[i];
19
+ if (arg.startsWith('--')) {
20
+ const eqIdx = arg.indexOf('=');
21
+ if (eqIdx !== -1) {
22
+ flags[arg.slice(2, eqIdx)] = arg.slice(eqIdx + 1);
23
+ }
24
+ else {
25
+ const key = arg.slice(2);
26
+ const next = args[i + 1];
27
+ if (next && !next.startsWith('--')) {
28
+ flags[key] = next;
29
+ i++;
30
+ }
31
+ else {
32
+ flags[key] = true;
33
+ }
34
+ }
35
+ }
36
+ else {
37
+ positional.push(arg);
38
+ }
39
+ }
40
+ return { positional, flags };
41
+ }
42
+ async function main() {
43
+ const argv = process.argv.slice(2);
44
+ const cmd = argv[0];
45
+ const { positional, flags } = parseFlags(argv.slice(1));
46
+ const homeDir = getHomeDir();
47
+ if (!cmd || cmd === '--help' || cmd === '-h') {
48
+ printHelp();
49
+ return 0;
50
+ }
51
+ if (cmd === 'serve') {
52
+ const server = new FaberMemoryMcpServer({ homeDir, cwd: process.cwd() });
53
+ server.serveStdio();
54
+ return 0;
55
+ }
56
+ if (cmd === 'setup') {
57
+ const config = loadConfig(homeDir);
58
+ if (flags.team) {
59
+ const url = String(flags.team);
60
+ const dest = typeof flags.path === 'string'
61
+ ? path.resolve(flags.path)
62
+ : path.join(homeDir, 'clones', 'team');
63
+ const submitMode = flags['submit-mode'] === 'pr' ? 'pr' : 'auto';
64
+ const defaultBranch = isGitRepo(dest)
65
+ ? getDefaultBranch(dest)
66
+ : gitCloneTeamRepo(url, dest);
67
+ config.roots.team = {
68
+ uuid: config.roots.team?.uuid || generateUuid(),
69
+ path: dest,
70
+ scope: 'team',
71
+ remote: url,
72
+ defaultBranch,
73
+ submitMode,
74
+ };
75
+ saveConfig(config, homeDir);
76
+ console.log(`Configured team root at ${dest} (branch: ${defaultBranch}, uuid: ${config.roots.team.uuid})`);
77
+ return 0;
78
+ }
79
+ const personalPath = typeof flags.path === 'string'
80
+ ? path.resolve(flags.path)
81
+ : positional[0]
82
+ ? path.resolve(positional[0])
83
+ : 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})`);
93
+ return 0;
94
+ }
95
+ if (cmd === 'config') {
96
+ const sub = positional[0];
97
+ const config = loadConfig(homeDir);
98
+ if (sub === 'set-path') {
99
+ const scope = positional[1];
100
+ const newPath = positional[2];
101
+ if (!scope || !newPath || !['personal', 'team'].includes(scope)) {
102
+ console.error('Usage: faber-memory config set-path <personal|team> <new-path>');
103
+ return 1;
104
+ }
105
+ const root = config.roots[scope];
106
+ if (!root) {
107
+ console.error(`Root "${scope}" is not configured yet.`);
108
+ return 1;
109
+ }
110
+ root.path = path.resolve(newPath);
111
+ saveConfig(config, homeDir);
112
+ console.log(`Updated ${scope} root path to ${root.path} (uuid preserved: ${root.uuid})`);
113
+ return 0;
114
+ }
115
+ if (sub === 'set-submit-mode') {
116
+ const mode = positional[1];
117
+ if (!['auto', 'pr'].includes(mode) || !config.roots.team) {
118
+ console.error('Usage: faber-memory config set-submit-mode <auto|pr>');
119
+ return 1;
120
+ }
121
+ config.roots.team.submitMode = mode;
122
+ saveConfig(config, homeDir);
123
+ console.log(`Updated team submit mode to ${mode}`);
124
+ return 0;
125
+ }
126
+ console.log(JSON.stringify(config, null, 2));
127
+ return 0;
128
+ }
129
+ if (cmd === 'compile') {
130
+ const config = loadConfig(homeDir);
131
+ const checkOnly = Boolean(flags.check);
132
+ const standaloneRepoDir = typeof flags.repo === 'string' ? path.resolve(flags.repo) : undefined;
133
+ const res = compileGlobalL0(config, {
134
+ homeDir,
135
+ checkOnly,
136
+ includeProjectCheck: checkOnly,
137
+ cwd: process.cwd(),
138
+ standaloneRepoDir,
139
+ });
140
+ for (const w of res.warnings)
141
+ console.warn(`Warning: ${w}`);
142
+ if (!res.ok) {
143
+ for (const e of res.errors)
144
+ console.error(`Error: ${e}`);
145
+ return 1;
146
+ }
147
+ if (checkOnly) {
148
+ console.log(`OK: compile --check passed (${res.estimatedTokens}/${res.budget} estimated tokens).`);
149
+ }
150
+ else {
151
+ console.log(`Compiled L0 to ${res.outputPath} (${res.estimatedTokens}/${res.budget} estimated tokens).`);
152
+ }
153
+ return 0;
154
+ }
155
+ if (cmd === 'sync') {
156
+ const config = loadConfig(homeDir);
157
+ const timeoutMs = typeof flags.timeout === 'string' ? Number(flags.timeout) : 5000;
158
+ const res = await syncAllRoots(config, { homeDir, timeoutMs, recompile: true });
159
+ for (const w of res.warnings)
160
+ console.warn(`Warning: ${w}`);
161
+ if (!res.ok) {
162
+ for (const e of res.errors)
163
+ console.error(`Error: ${e}`);
164
+ return 1;
165
+ }
166
+ console.log(res.advanced
167
+ ? 'Synced remote updates and recompiled L0.'
168
+ : 'Already up to date; L0 compiled.');
169
+ return 0;
170
+ }
171
+ if (cmd === 'approve') {
172
+ const config = loadConfig(homeDir);
173
+ const ids = positional;
174
+ if (ids.length === 0) {
175
+ console.error('Usage: faber-memory approve <proposal-id> [...]');
176
+ return 1;
177
+ }
178
+ const proposals = [];
179
+ for (const id of ids) {
180
+ const p = findProposalById(id, homeDir);
181
+ if (!p) {
182
+ console.error(`Error: Proposal "${id}" not found.`);
183
+ return 1;
184
+ }
185
+ proposals.push(p);
186
+ }
187
+ const modeOverride = flags.mode === 'pr' || flags.mode === 'auto' ? flags.mode : undefined;
188
+ const outcome = await approveProposalsBatch(config, proposals, {
189
+ homeDir,
190
+ teamSubmitModeOverride: modeOverride,
191
+ });
192
+ for (const m of outcome.messages)
193
+ console.log(m);
194
+ if (!outcome.ok) {
195
+ for (const e of outcome.errors)
196
+ console.error(`Error: ${e}`);
197
+ return 1;
198
+ }
199
+ return 0;
200
+ }
201
+ if (cmd === 'reject') {
202
+ const id = positional[0];
203
+ if (!id) {
204
+ console.error('Usage: faber-memory reject <proposal-id>');
205
+ return 1;
206
+ }
207
+ try {
208
+ const removed = rejectProposal(id, homeDir);
209
+ console.log(`Rejected and removed proposal ${removed.id}.`);
210
+ return 0;
211
+ }
212
+ catch (err) {
213
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
214
+ return 1;
215
+ }
216
+ }
217
+ if (cmd === 'review') {
218
+ const config = loadConfig(homeDir);
219
+ const proposals = reconcileAwaitingCommitProposals(homeDir).filter((p) => p.status !== 'awaiting_commit');
220
+ if (proposals.length === 0) {
221
+ console.log('No pending proposals to review.');
222
+ return 0;
223
+ }
224
+ const toApprove = [];
225
+ if (flags['approve-all']) {
226
+ toApprove.push(...proposals);
227
+ }
228
+ else {
229
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
230
+ const lineIter = rl[Symbol.asyncIterator]();
231
+ const ask = async (q) => {
232
+ process.stdout.write(q);
233
+ const next = await lineIter.next();
234
+ return next.done ? '' : String(next.value);
235
+ };
236
+ 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}`);
241
+ if (p.forceNew && p.reason) {
242
+ console.log(`force_new reason: ${p.reason}`);
243
+ }
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();
248
+ if (answer === 'a' || answer === 'approve') {
249
+ toApprove.push(p);
250
+ }
251
+ else if (answer === 'e' || answer === 'edit') {
252
+ const newBody = (await ask('New body (single line or leave empty to keep): ')).trim();
253
+ if (newBody) {
254
+ p.body = newBody;
255
+ saveProposal(p, homeDir);
256
+ }
257
+ const confirm = (await ask('Approve edited proposal? [y/N]: ')).trim().toLowerCase();
258
+ if (confirm === 'y' || confirm === 'yes') {
259
+ toApprove.push(p);
260
+ }
261
+ }
262
+ else if (answer === 'r' || answer === 'reject') {
263
+ rejectProposal(p.id, homeDir);
264
+ console.log(`Rejected ${p.id}.`);
265
+ }
266
+ else {
267
+ console.log(`Skipped ${p.id}.`);
268
+ }
269
+ }
270
+ }
271
+ finally {
272
+ rl.close();
273
+ }
274
+ }
275
+ if (toApprove.length > 0) {
276
+ const outcome = await approveProposalsBatch(config, toApprove, { homeDir });
277
+ for (const m of outcome.messages)
278
+ console.log(m);
279
+ if (!outcome.ok) {
280
+ for (const e of outcome.errors)
281
+ console.error(`Error: ${e}`);
282
+ return 1;
283
+ }
284
+ }
285
+ return 0;
286
+ }
287
+ if (cmd === 'status') {
288
+ const config = loadConfig(homeDir);
289
+ const projectRes = resolveProjectRoot(undefined, process.cwd());
290
+ const loaded = loadAllScopes(config, projectRes);
291
+ const proposals = reconcileAwaitingCommitProposals(homeDir);
292
+ console.log('FaberSEP Memory Status');
293
+ console.log(` Compiled L0: ${getCompiledL0Path(homeDir)} (${fs.existsSync(getCompiledL0Path(homeDir)) ? 'present' : 'missing'})`);
294
+ if (config.roots.team) {
295
+ 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
+ }
297
+ if (config.roots.personal) {
298
+ console.log(` Personal root: ${config.roots.personal.path} (HEAD: ${getHeadSha(config.roots.personal.path)?.slice(0, 8) || 'none'})`);
299
+ }
300
+ console.log(` Project root: ${projectRes.projectRoot || 'none'} (source: ${projectRes.source})`);
301
+ if (loaded.uncommittedWarnings.length > 0) {
302
+ console.log('Warnings:');
303
+ for (const w of loaded.uncommittedWarnings)
304
+ console.log(` - ${w}`);
305
+ }
306
+ const nowMs = Date.now();
307
+ const staleMs = config.staleDays * 24 * 60 * 60 * 1000;
308
+ console.log(`Pending proposals: ${proposals.length}`);
309
+ for (const p of proposals) {
310
+ const ageDays = Math.floor((nowMs - Date.parse(p.createdAt)) / (24 * 60 * 60 * 1000));
311
+ const isStale = nowMs - Date.parse(p.createdAt) > staleMs;
312
+ const flagsList = [p.status];
313
+ if (isStale)
314
+ flagsList.push(`STALE (${ageDays}d > ${config.staleDays}d)`);
315
+ console.log(` - ${p.id} [${p.scope}/${p.action}] (${flagsList.join(', ')}): ${p.summary}`);
316
+ if (p.status === 'awaiting_commit' && p.targetFilePath) {
317
+ console.log(` file: ${p.targetFilePath} — run "git add ${p.targetFilePath} && git commit" to activate`);
318
+ }
319
+ if (p.status === 'push_failed' && p.error) {
320
+ console.log(` push error: ${p.error}`);
321
+ }
322
+ }
323
+ return 0;
324
+ }
325
+ if (cmd === 'import') {
326
+ const config = loadConfig(homeDir);
327
+ const from = flags.from;
328
+ const sourcePath = positional[0];
329
+ if (!from || !sourcePath) {
330
+ console.error('Usage: faber-memory import --from <markdown-dir|claude-memory|agents-md|cursor-rules> <path> [--split-headings] [--approve]');
331
+ return 1;
332
+ }
333
+ try {
334
+ const res = await runImport(config, {
335
+ from,
336
+ sourcePath: path.resolve(sourcePath),
337
+ scope: typeof flags.scope === 'string' ? flags.scope : 'personal',
338
+ splitHeadings: Boolean(flags['split-headings']),
339
+ approve: Boolean(flags.approve),
340
+ homeDir,
341
+ cwd: process.cwd(),
342
+ });
343
+ console.log(`Staged ${res.staged.length} proposal(s) in pre-memory.`);
344
+ if (res.approvedIds.length > 0) {
345
+ console.log(`Approved ${res.approvedIds.length} proposal(s) in solo mode.`);
346
+ }
347
+ if (res.duplicates.length > 0) {
348
+ console.log(`Duplicates skipped (${res.duplicates.length}):`);
349
+ for (const d of res.duplicates) {
350
+ console.log(` - ${d.source} matches "${d.matchedId}" (${d.summary})`);
351
+ }
352
+ }
353
+ if (res.skippedHygiene.length > 0) {
354
+ console.log(`Hygiene skipped (${res.skippedHygiene.length}):`);
355
+ for (const s of res.skippedHygiene) {
356
+ console.log(` - ${s.source}: ${s.reason}`);
357
+ }
358
+ }
359
+ for (const n of res.notes)
360
+ console.log(n);
361
+ return 0;
362
+ }
363
+ catch (err) {
364
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
365
+ return 1;
366
+ }
367
+ }
368
+ if (cmd === 'init') {
369
+ const config = loadConfig(homeDir);
370
+ const apply = Boolean(flags.apply);
371
+ const undo = Boolean(flags.undo);
372
+ const projectHint = Boolean(flags['project-hint']);
373
+ const engines = typeof flags.engine === 'string'
374
+ ? flags.engine.split(',').map((e) => e.trim())
375
+ : undefined;
376
+ try {
377
+ const res = planOrApplyInit(config, {
378
+ apply,
379
+ undo,
380
+ engines,
381
+ projectHint,
382
+ homeDir,
383
+ });
384
+ for (const n of res.notes)
385
+ console.log(n);
386
+ for (const p of res.plans) {
387
+ console.log(formatUnifiedDiff(p));
388
+ }
389
+ if (undo && res.backups.length > 0) {
390
+ console.log(`Backup files preserved (not auto-restored): ${res.backups.join(', ')}`);
391
+ }
392
+ if (res.projectHint) {
393
+ console.log(`Project hint: ${res.projectHint}`);
394
+ }
395
+ if (!apply && !undo) {
396
+ console.log('\nDry-run only. Re-run with --apply to write changes.');
397
+ }
398
+ return 0;
399
+ }
400
+ catch (err) {
401
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
402
+ return 1;
403
+ }
404
+ }
405
+ console.error(`Unknown command: ${cmd}`);
406
+ printHelp();
407
+ return 1;
408
+ }
409
+ function printHelp() {
410
+ console.log(`@fabersep/memory (faber-memory)
411
+
412
+ 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]
416
+ compile [--check] [--repo <dir>]
417
+ sync [--timeout <ms>]
418
+ status
419
+ review [--approve-all]
420
+ 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]
423
+ serve
424
+ `);
425
+ }
426
+ main()
427
+ .then((code) => {
428
+ if (code !== 0)
429
+ process.exit(code);
430
+ })
431
+ .catch((err) => {
432
+ console.error(err instanceof Error ? err.message : String(err));
433
+ process.exit(1);
434
+ });
@@ -0,0 +1,19 @@
1
+ import { MemoryEntry, UserConfig } from './types.js';
2
+ export declare function estimateTokens(text: string): number;
3
+ export interface CompileResult {
4
+ ok: boolean;
5
+ output?: string;
6
+ estimatedTokens: number;
7
+ budget: number;
8
+ outputPath?: string;
9
+ errors: string[];
10
+ warnings: string[];
11
+ }
12
+ export declare function renderGlobalL0(teamEntries: MemoryEntry[], personalEntries: MemoryEntry[]): string;
13
+ export declare function compileGlobalL0(config: UserConfig, options?: {
14
+ homeDir?: string;
15
+ checkOnly?: boolean;
16
+ includeProjectCheck?: boolean;
17
+ cwd?: string;
18
+ standaloneRepoDir?: string;
19
+ }): CompileResult;
@@ -0,0 +1,171 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { getCompiledL0Path, getHomeDir, getStateDir, withStateLock } from './config.js';
5
+ import { formatHygieneErrors, scanHygiene } from './hygiene.js';
6
+ import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot, } from './store.js';
7
+ import { COMPILER_VERSION, } from './types.js';
8
+ export function estimateTokens(text) {
9
+ return Math.ceil(Buffer.byteLength(text, 'utf8') / 4);
10
+ }
11
+ function renderEntryL0(entry) {
12
+ if (entry.l0 === 'body') {
13
+ return `### ${entry.id} (${entry.type})\n\n${entry.body}`;
14
+ }
15
+ return `- \`${entry.id}\` (${entry.type}): ${entry.summary}`;
16
+ }
17
+ export function renderGlobalL0(teamEntries, personalEntries) {
18
+ const teamActive = teamEntries
19
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
20
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
21
+ const personalActive = personalEntries
22
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
23
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
24
+ const sections = [
25
+ `<!-- generated by @fabersep/memory v${COMPILER_VERSION} — do not edit manually -->`,
26
+ '# Memory (L0)',
27
+ ];
28
+ if (teamActive.length > 0) {
29
+ sections.push('## Team\n\n' + teamActive.map(renderEntryL0).join('\n'));
30
+ }
31
+ if (personalActive.length > 0) {
32
+ sections.push('## Personal\n\n' + personalActive.map(renderEntryL0).join('\n'));
33
+ }
34
+ if (teamActive.length === 0 && personalActive.length === 0) {
35
+ sections.push('_No active L0 memory entries._');
36
+ }
37
+ return sections.join('\n\n') + '\n';
38
+ }
39
+ export function compileGlobalL0(config, options = {}) {
40
+ const homeDir = options.homeDir || getHomeDir();
41
+ const errors = [];
42
+ const warnings = [];
43
+ const teamScope = config.roots.team
44
+ ? loadScopeFromHead(config.roots.team.path, 'team')
45
+ : undefined;
46
+ const personalScope = config.roots.personal
47
+ ? loadScopeFromHead(config.roots.personal.path, 'personal')
48
+ : undefined;
49
+ // Standalone repo CI mode: if neither team nor personal is configured, or standaloneRepoDir is given
50
+ const standaloneScope = options.standaloneRepoDir
51
+ ? loadScopeFromHead(options.standaloneRepoDir, 'team')
52
+ : !teamScope && !personalScope && options.checkOnly && options.cwd
53
+ ? loadScopeFromHead(options.cwd, 'team')
54
+ : undefined;
55
+ const effectiveTeam = teamScope || standaloneScope;
56
+ for (const sc of [effectiveTeam, personalScope]) {
57
+ if (!sc)
58
+ continue;
59
+ for (const err of sc.errors) {
60
+ errors.push(`[${err.scope}] ${err.filePath}: ${err.message}`);
61
+ }
62
+ if (sc.uncommittedFiles.length > 0) {
63
+ warnings.push(`Uncommitted edits in ${sc.scope} root (${sc.uncommittedFiles.join(', ')}); compiled from committed HEAD only.`);
64
+ }
65
+ for (const entry of sc.entries) {
66
+ const contentToScan = `${entry.summary}\n${entry.body}`;
67
+ const hygiene = scanHygiene(contentToScan);
68
+ if (hygiene.length > 0) {
69
+ errors.push(formatHygieneErrors(hygiene, `[${entry.scope}] ${entry.filePath}`));
70
+ }
71
+ }
72
+ }
73
+ // Check duplicate active IDs across team and personal
74
+ const teamActiveMap = new Map();
75
+ for (const e of effectiveTeam?.entries || []) {
76
+ if (e.status !== 'active')
77
+ continue;
78
+ if (teamActiveMap.has(e.id)) {
79
+ errors.push(`Duplicate active entry ID "${e.id}" within team scope.`);
80
+ }
81
+ teamActiveMap.set(e.id, e);
82
+ }
83
+ const personalActiveMap = new Map();
84
+ for (const e of personalScope?.entries || []) {
85
+ if (e.status !== 'active')
86
+ continue;
87
+ if (personalActiveMap.has(e.id)) {
88
+ errors.push(`Duplicate active entry ID "${e.id}" within personal scope.`);
89
+ }
90
+ if (teamActiveMap.has(e.id)) {
91
+ errors.push(`Duplicate active entry ID "${e.id}" across scopes "team" and "personal". Resolve the collision before compiling.`);
92
+ }
93
+ personalActiveMap.set(e.id, e);
94
+ }
95
+ // Optional project-level check (only in compile --check when inside a project repo)
96
+ if (options.includeProjectCheck) {
97
+ const projRes = resolveProjectRoot(undefined, options.cwd || process.cwd());
98
+ if (projRes.source !== 'none' && projRes.projectRoot) {
99
+ const projScope = loadScopeFromHead(projRes.projectRoot, 'project', PROJECT_MEMORY_REL_DIR);
100
+ for (const err of projScope.errors) {
101
+ errors.push(`[project] ${err.filePath}: ${err.message}`);
102
+ }
103
+ for (const entry of projScope.entries) {
104
+ const hygiene = scanHygiene(`${entry.summary}\n${entry.body}`);
105
+ if (hygiene.length > 0) {
106
+ errors.push(formatHygieneErrors(hygiene, `[project] ${entry.filePath}`));
107
+ }
108
+ if (entry.status === 'active') {
109
+ if (teamActiveMap.has(entry.id)) {
110
+ errors.push(`Duplicate active entry ID "${entry.id}" across scopes "project" and "team".`);
111
+ }
112
+ if (personalActiveMap.has(entry.id)) {
113
+ errors.push(`Duplicate active entry ID "${entry.id}" across scopes "project" and "personal".`);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+ const output = renderGlobalL0(effectiveTeam?.entries || [], personalScope?.entries || []);
120
+ const outHygiene = scanHygiene(output);
121
+ if (outHygiene.length > 0) {
122
+ errors.push(formatHygieneErrors(outHygiene, 'compiled MEMORY.md'));
123
+ }
124
+ const tokens = estimateTokens(output);
125
+ if (tokens > config.tokenBudget) {
126
+ const contributors = [
127
+ ...(effectiveTeam?.entries || []),
128
+ ...(personalScope?.entries || []),
129
+ ]
130
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
131
+ .map((e) => ({
132
+ id: e.id,
133
+ scope: e.scope,
134
+ tokens: estimateTokens(renderEntryL0(e)),
135
+ }))
136
+ .sort((a, b) => b.tokens - a.tokens)
137
+ .slice(0, 10);
138
+ const list = contributors
139
+ .map((c) => ` - ${c.id} (${c.scope}): ~${c.tokens} tokens`)
140
+ .join('\n');
141
+ errors.push(`Compiled L0 exceeds token budget (${tokens} > ${config.tokenBudget} estimated tokens). Largest entries:\n${list}`);
142
+ }
143
+ if (errors.length > 0) {
144
+ return {
145
+ ok: false,
146
+ estimatedTokens: tokens,
147
+ budget: config.tokenBudget,
148
+ errors,
149
+ warnings,
150
+ };
151
+ }
152
+ const outputPath = getCompiledL0Path(homeDir);
153
+ if (!options.checkOnly) {
154
+ withStateLock(() => {
155
+ const stateDir = getStateDir(homeDir);
156
+ fs.mkdirSync(stateDir, { recursive: true });
157
+ const tmpPath = path.join(stateDir, `MEMORY.md.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`);
158
+ fs.writeFileSync(tmpPath, output, 'utf8');
159
+ fs.renameSync(tmpPath, outputPath);
160
+ }, homeDir);
161
+ }
162
+ return {
163
+ ok: true,
164
+ output,
165
+ estimatedTokens: tokens,
166
+ budget: config.tokenBudget,
167
+ outputPath,
168
+ errors: [],
169
+ warnings,
170
+ };
171
+ }
@@ -0,0 +1,20 @@
1
+ import { UserConfig } from './types.js';
2
+ export declare function getHomeDir(): string;
3
+ export declare function getConfigPath(homeDir?: string): string;
4
+ export declare function getStateDir(homeDir?: string): string;
5
+ export declare function getCompiledL0Path(homeDir?: string): string;
6
+ export declare function getPreMemoryRootDir(rootUuid: string, homeDir?: string): string;
7
+ export declare function getAllPreMemoryBaseDir(homeDir?: string): string;
8
+ export declare function getDefaultPersonalPath(): string;
9
+ export declare function getProjectRootUuid(projectRootPath: string): string;
10
+ export declare function sanitizeUserTag(raw?: string): string;
11
+ export declare function defaultConfig(): UserConfig;
12
+ export declare function loadConfig(homeDir?: string): UserConfig;
13
+ export declare function saveConfig(config: UserConfig, homeDir?: string): void;
14
+ export declare function generateUuid(): string;
15
+ export declare function generateProposalId(userTag: string): string;
16
+ /**
17
+ * Per-state-directory advisory lock using atomic mkdir with bounded retry.
18
+ * Ensures concurrent compile/approve calls never interleave writes.
19
+ */
20
+ export declare function withStateLock<T>(fn: () => T, homeDir?: string, timeoutMs?: number): T;