@fabersep/memory 0.0.0-stage → 0.2.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.
Files changed (43) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +399 -2
  3. package/dist/src/bm25.d.ts +26 -0
  4. package/dist/src/bm25.js +183 -0
  5. package/dist/src/cache-logs.d.ts +47 -0
  6. package/dist/src/cache-logs.js +433 -0
  7. package/dist/src/cli.d.ts +2 -0
  8. package/dist/src/cli.js +701 -0
  9. package/dist/src/compiler.d.ts +23 -0
  10. package/dist/src/compiler.js +211 -0
  11. package/dist/src/config.d.ts +20 -0
  12. package/dist/src/config.js +134 -0
  13. package/dist/src/doctor.d.ts +23 -0
  14. package/dist/src/doctor.js +447 -0
  15. package/dist/src/frontmatter.d.ts +22 -0
  16. package/dist/src/frontmatter.js +199 -0
  17. package/dist/src/git.d.ts +33 -0
  18. package/dist/src/git.js +251 -0
  19. package/dist/src/hygiene.d.ts +7 -0
  20. package/dist/src/hygiene.js +89 -0
  21. package/dist/src/importer.d.ts +34 -0
  22. package/dist/src/importer.js +261 -0
  23. package/dist/src/index.d.ts +18 -0
  24. package/dist/src/index.js +18 -0
  25. package/dist/src/init.d.ts +43 -0
  26. package/dist/src/init.js +280 -0
  27. package/dist/src/mcp.d.ts +218 -0
  28. package/dist/src/mcp.js +437 -0
  29. package/dist/src/metrics.d.ts +72 -0
  30. package/dist/src/metrics.js +179 -0
  31. package/dist/src/proposals.d.ts +34 -0
  32. package/dist/src/proposals.js +420 -0
  33. package/dist/src/stats.d.ts +165 -0
  34. package/dist/src/stats.js +579 -0
  35. package/dist/src/store.d.ts +23 -0
  36. package/dist/src/store.js +161 -0
  37. package/dist/src/sync.d.ts +15 -0
  38. package/dist/src/sync.js +47 -0
  39. package/dist/src/types.d.ts +100 -0
  40. package/dist/src/types.js +17 -0
  41. package/dist/src/ui.d.ts +19 -0
  42. package/dist/src/ui.js +74 -0
  43. package/package.json +50 -4
@@ -0,0 +1,447 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import { estimateTokens, renderGlobalL0 } from './compiler.js';
4
+ import { getCompiledL0Path, getConfigPath, getHomeDir, loadConfig } from './config.js';
5
+ import { getHeadSha, getUncommittedFiles, isGitRepo, readHeadFile } from './git.js';
6
+ import { scanHygiene } from './hygiene.js';
7
+ import { BLOCK_END, BLOCK_START, getEngineSpecs, getUserHome } from './init.js';
8
+ import { readMetrics } from './metrics.js';
9
+ import { listAllProposals } from './proposals.js';
10
+ import { L0_CHURN_WARN_THRESHOLD } from './stats.js';
11
+ import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot } from './store.js';
12
+ import { c, hr } from './ui.js';
13
+ function sha256(content) {
14
+ return crypto.createHash('sha256').update(content).digest('hex');
15
+ }
16
+ function extractManagedBlock(content) {
17
+ const startIdx = content.indexOf(BLOCK_START);
18
+ if (startIdx === -1)
19
+ return null;
20
+ const endIdx = content.indexOf(BLOCK_END, startIdx + BLOCK_START.length);
21
+ if (endIdx === -1)
22
+ return null;
23
+ return content.slice(startIdx + BLOCK_START.length, endIdx);
24
+ }
25
+ function hasFaberMemoryMcpEntry(filePath) {
26
+ if (!fs.existsSync(filePath))
27
+ return false;
28
+ try {
29
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
30
+ return Boolean(raw &&
31
+ typeof raw === 'object' &&
32
+ raw.mcpServers &&
33
+ typeof raw.mcpServers === 'object' &&
34
+ 'faber-memory' in raw.mcpServers);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ export function runDoctor(options = {}) {
41
+ const homeDir = options.homeDir || getHomeDir();
42
+ const userHome = options.userHome || getUserHome();
43
+ const cwd = options.cwd || process.cwd();
44
+ const nowMs = options.nowMs ?? Date.now();
45
+ const strict = Boolean(options.strict);
46
+ const checks = [];
47
+ // 1. Config & Git roots health
48
+ let config = null;
49
+ const cfgPath = getConfigPath(homeDir);
50
+ const configDetails = [];
51
+ let configStatus = 'PASS';
52
+ let configHint;
53
+ if (!fs.existsSync(cfgPath)) {
54
+ configStatus = 'FAIL';
55
+ configDetails.push(`Config file not found at ${cfgPath}.`);
56
+ configHint = 'Run "faber-memory setup" to initialize your memory configuration.';
57
+ }
58
+ else {
59
+ try {
60
+ config = loadConfig(homeDir);
61
+ }
62
+ catch {
63
+ configStatus = 'FAIL';
64
+ configDetails.push(`Config file at ${cfgPath} is corrupt or unparseable JSON.`);
65
+ configHint = 'Fix or recreate config.json (or run "faber-memory setup" after backing it up).';
66
+ }
67
+ }
68
+ const projRes = resolveProjectRoot(undefined, cwd);
69
+ if (config) {
70
+ const hasPersonal = Boolean(config.roots.personal);
71
+ const hasTeam = Boolean(config.roots.team);
72
+ if (!hasPersonal && !hasTeam) {
73
+ configStatus = 'FAIL';
74
+ configDetails.push('Neither personal nor team memory root is configured.');
75
+ configHint = 'Run "faber-memory setup" to configure a personal or team memory root.';
76
+ }
77
+ else {
78
+ const configuredRoots = [config.roots.personal, config.roots.team].filter(Boolean);
79
+ for (const root of configuredRoots) {
80
+ if (!root)
81
+ continue;
82
+ if (!fs.existsSync(root.path)) {
83
+ configStatus = 'FAIL';
84
+ configDetails.push(`${root.scope} root path does not exist: ${root.path}`);
85
+ configHint = `Restore the ${root.scope} repo or update its path with "faber-memory config set-path ${root.scope} <path>".`;
86
+ continue;
87
+ }
88
+ if (!isGitRepo(root.path)) {
89
+ configStatus = 'FAIL';
90
+ configDetails.push(`${root.scope} root is not a valid Git repository: ${root.path}`);
91
+ configHint = `Re-initialize the ${root.scope} root with "faber-memory setup".`;
92
+ continue;
93
+ }
94
+ const sha = getHeadSha(root.path);
95
+ if (!sha) {
96
+ configStatus = 'FAIL';
97
+ configDetails.push(`${root.scope} root has no valid HEAD commit: ${root.path}`);
98
+ configHint = `Create an initial commit in ${root.path}.`;
99
+ continue;
100
+ }
101
+ configDetails.push(`${root.scope} root OK (HEAD ${sha.slice(0, 8)}).`);
102
+ const uncommitted = getUncommittedFiles(root.path);
103
+ if (uncommitted.length > 0) {
104
+ if (configStatus !== 'FAIL')
105
+ configStatus = 'WARN';
106
+ configDetails.push(`${root.scope} root has ${uncommitted.length} uncommitted file(s): ${uncommitted.slice(0, 5).join(', ')}`);
107
+ if (!configHint) {
108
+ configHint = `Commit or discard uncommitted edits in the ${root.scope} memory root.`;
109
+ }
110
+ }
111
+ }
112
+ if (!hasPersonal && hasTeam) {
113
+ if (configStatus !== 'FAIL')
114
+ configStatus = 'WARN';
115
+ configDetails.push('Team root is configured, but no personal memory root is configured.');
116
+ if (!configHint) {
117
+ configHint = 'Run "faber-memory setup" if you also want a personal memory root.';
118
+ }
119
+ }
120
+ if (projRes.source !== 'none' && projRes.projectRoot) {
121
+ const projUncommitted = getUncommittedFiles(projRes.projectRoot, PROJECT_MEMORY_REL_DIR);
122
+ if (projUncommitted.length > 0) {
123
+ if (configStatus !== 'FAIL')
124
+ configStatus = 'WARN';
125
+ configDetails.push(`project memory has ${projUncommitted.length} uncommitted file(s): ${projUncommitted.slice(0, 5).join(', ')}`);
126
+ if (!configHint) {
127
+ configHint = 'Commit pending project memory files in .faber/memory/ to activate them.';
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ checks.push({
134
+ id: 'config-and-roots',
135
+ name: 'Config & Git roots',
136
+ status: configStatus,
137
+ details: configDetails,
138
+ ...(configHint ? { hint: configHint } : {}),
139
+ });
140
+ // Load scopes once (read-only from HEAD; never standalone cwd fallback)
141
+ const teamScope = config?.roots.team && isGitRepo(config.roots.team.path)
142
+ ? loadScopeFromHead(config.roots.team.path, 'team')
143
+ : undefined;
144
+ const personalScope = config?.roots.personal && isGitRepo(config.roots.personal.path)
145
+ ? loadScopeFromHead(config.roots.personal.path, 'personal')
146
+ : undefined;
147
+ const projectScope = projRes.source !== 'none' && projRes.projectRoot && isGitRepo(projRes.projectRoot)
148
+ ? loadScopeFromHead(projRes.projectRoot, 'project', PROJECT_MEMORY_REL_DIR)
149
+ : undefined;
150
+ // 2. Compiled L0 health
151
+ const l0Path = getCompiledL0Path(homeDir);
152
+ const l0Details = [];
153
+ let l0Status = 'PASS';
154
+ let l0Hint;
155
+ if (!config) {
156
+ l0Status = 'FAIL';
157
+ l0Details.push('Skipped because config.json could not be loaded.');
158
+ l0Hint = 'Fix config.json first, then run "faber-memory compile".';
159
+ }
160
+ else if (!fs.existsSync(l0Path)) {
161
+ l0Status = 'FAIL';
162
+ l0Details.push(`Compiled L0 MEMORY.md is missing at ${l0Path}.`);
163
+ l0Hint = 'Run "faber-memory compile" to generate compiled L0 MEMORY.md.';
164
+ }
165
+ else {
166
+ const onDiskText = fs.readFileSync(l0Path, 'utf8');
167
+ const onDiskTokens = estimateTokens(onDiskText);
168
+ const expectedText = renderGlobalL0(teamScope?.entries || [], personalScope?.entries || []);
169
+ const expectedTokens = estimateTokens(expectedText);
170
+ if (onDiskTokens > config.tokenBudget || expectedTokens > config.tokenBudget) {
171
+ l0Status = 'FAIL';
172
+ l0Details.push(`Compiled L0 exceeds token budget (${Math.max(onDiskTokens, expectedTokens)} > ${config.tokenBudget} estimated tokens).`);
173
+ l0Hint = 'Move lower-priority entries to l0: none or shorten summaries, then run "faber-memory compile".';
174
+ }
175
+ else if (sha256(onDiskText) !== sha256(expectedText)) {
176
+ l0Status = 'WARN';
177
+ l0Details.push(`Compiled L0 MEMORY.md is stale (differs from current committed HEAD team + personal entries).`);
178
+ l0Hint = 'Run "faber-memory compile" to refresh compiled L0 MEMORY.md.';
179
+ }
180
+ else {
181
+ l0Details.push(`Compiled L0 is up to date (${onDiskTokens}/${config.tokenBudget} estimated tokens).`);
182
+ }
183
+ }
184
+ checks.push({
185
+ id: 'compiled-l0',
186
+ name: 'Compiled L0',
187
+ status: l0Status,
188
+ details: l0Details,
189
+ ...(l0Hint ? { hint: l0Hint } : {}),
190
+ });
191
+ // 3. Schema, ID & hygiene integrity (does NOT repeat Check 2's over-budget check)
192
+ const integrityDetails = [];
193
+ let integrityStatus = 'PASS';
194
+ let integrityHint;
195
+ if (!config) {
196
+ integrityStatus = 'FAIL';
197
+ integrityDetails.push('Skipped because config.json could not be loaded.');
198
+ integrityHint = 'Fix config.json first.';
199
+ }
200
+ else {
201
+ const scopesToCheck = [teamScope, personalScope, projectScope].filter(Boolean);
202
+ const activeIdsByScope = new Map();
203
+ for (const sc of scopesToCheck) {
204
+ if (!sc)
205
+ continue;
206
+ for (const err of sc.errors) {
207
+ integrityStatus = 'FAIL';
208
+ integrityDetails.push(`[${err.scope}] ${err.filePath}: ${err.message}`);
209
+ }
210
+ const seenInScope = new Set();
211
+ for (const entry of sc.entries) {
212
+ const hygiene = scanHygiene(`${entry.summary}\n${entry.body}`);
213
+ if (hygiene.length > 0) {
214
+ integrityStatus = 'FAIL';
215
+ integrityDetails.push(`[${entry.scope}] ${entry.filePath}: ${hygiene.map((h) => h.category).join(', ')} hygiene violation (${hygiene.length} finding(s)).`);
216
+ }
217
+ if (entry.status === 'active') {
218
+ if (seenInScope.has(entry.id)) {
219
+ integrityStatus = 'FAIL';
220
+ integrityDetails.push(`Duplicate active ID "${entry.id}" within ${sc.scope} scope.`);
221
+ }
222
+ seenInScope.add(entry.id);
223
+ }
224
+ }
225
+ activeIdsByScope.set(sc.scope, seenInScope);
226
+ }
227
+ // Cross-scope duplicate active IDs
228
+ const scopePairs = [
229
+ ['team', 'personal'],
230
+ ['project', 'team'],
231
+ ['project', 'personal'],
232
+ ];
233
+ for (const [a, b] of scopePairs) {
234
+ const setA = activeIdsByScope.get(a);
235
+ const setB = activeIdsByScope.get(b);
236
+ if (!setA || !setB)
237
+ continue;
238
+ for (const id of setA) {
239
+ if (setB.has(id)) {
240
+ integrityStatus = 'FAIL';
241
+ integrityDetails.push(`Duplicate active ID "${id}" across scopes "${a}" and "${b}".`);
242
+ }
243
+ }
244
+ }
245
+ if (integrityStatus === 'FAIL') {
246
+ integrityHint =
247
+ 'Fix the reported frontmatter, duplicate ID, or hygiene violations, commit, and re-run "faber-memory compile --check".';
248
+ }
249
+ else {
250
+ const totalChecked = scopesToCheck.reduce((sum, sc) => sum + (sc?.entries?.length || 0), 0);
251
+ integrityDetails.push(`Checked ${totalChecked} committed entry/entries: schema, IDs, and hygiene OK.`);
252
+ }
253
+ }
254
+ checks.push({
255
+ id: 'hygiene-and-schema',
256
+ name: 'Schema, ID & hygiene',
257
+ status: integrityStatus,
258
+ details: integrityDetails,
259
+ ...(integrityHint ? { hint: integrityHint } : {}),
260
+ });
261
+ // 4. Engine wiring check (read-only, respects FABER_USER_HOME, never executes npx)
262
+ const wiringDetails = [];
263
+ let wiringStatus = 'PASS';
264
+ let wiringHint;
265
+ const specs = getEngineSpecs();
266
+ const wiredEngines = [];
267
+ const mismatchedEngines = [];
268
+ for (const engineName of ['claude-code', 'claude-desktop', 'antigravity', 'cursor']) {
269
+ const spec = specs[engineName];
270
+ const mcpWired = spec.mcpConfigFile ? hasFaberMemoryMcpEntry(spec.mcpConfigFile(userHome)) : false;
271
+ let instrWired = false;
272
+ let instrMismatch = false;
273
+ if (spec.instructionFile && (engineName === 'claude-code' || engineName === 'antigravity')) {
274
+ const instrPath = spec.instructionFile(userHome);
275
+ if (fs.existsSync(instrPath)) {
276
+ try {
277
+ const content = fs.readFileSync(instrPath, 'utf8');
278
+ const block = extractManagedBlock(content);
279
+ if (block !== null) {
280
+ instrWired = true;
281
+ if (engineName === 'claude-code') {
282
+ const expectedLine = `@${l0Path}`;
283
+ if (!block.includes(expectedLine)) {
284
+ instrMismatch = true;
285
+ }
286
+ }
287
+ else if (engineName === 'antigravity') {
288
+ if (!block.includes(l0Path)) {
289
+ instrMismatch = true;
290
+ }
291
+ }
292
+ }
293
+ }
294
+ catch {
295
+ // Ignore read errors
296
+ }
297
+ }
298
+ }
299
+ if (instrMismatch) {
300
+ mismatchedEngines.push(engineName);
301
+ wiringDetails.push(`${engineName}: managed L0 block path does not match ${l0Path}.`);
302
+ }
303
+ if (mcpWired || instrWired) {
304
+ const parts = [];
305
+ if (instrWired)
306
+ parts.push('L0');
307
+ if (mcpWired)
308
+ parts.push('MCP');
309
+ wiredEngines.push(`${engineName} (${parts.join('+')})`);
310
+ }
311
+ }
312
+ if (mismatchedEngines.length > 0) {
313
+ wiringStatus = 'WARN';
314
+ wiringHint = 'Run "faber-memory init --apply" to update engine pointers to the current compiled MEMORY.md path.';
315
+ }
316
+ else if (wiredEngines.length === 0) {
317
+ wiringStatus = 'WARN';
318
+ 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.';
320
+ }
321
+ else {
322
+ wiringDetails.push(`Wired engines: ${wiredEngines.join(', ')}.`);
323
+ }
324
+ checks.push({
325
+ id: 'engine-wiring',
326
+ name: 'Engine wiring',
327
+ status: wiringStatus,
328
+ details: wiringDetails,
329
+ ...(wiringHint ? { hint: wiringHint } : {}),
330
+ });
331
+ // 5. Pre-memory queue health (strictly read-only: uses listAllProposals, never deletes files)
332
+ const queueDetails = [];
333
+ let queueStatus = 'PASS';
334
+ let queueHint;
335
+ const rawProposals = listAllProposals(homeDir);
336
+ const activeProposals = rawProposals.filter((p) => {
337
+ if (p.status === 'awaiting_commit' && p.projectRootPath && p.targetFilePath) {
338
+ const committed = readHeadFile(p.projectRootPath, p.targetFilePath);
339
+ if (committed !== null)
340
+ return false;
341
+ }
342
+ return true;
343
+ });
344
+ const staleDays = config?.staleDays ?? 14;
345
+ const staleMs = staleDays * 24 * 60 * 60 * 1000;
346
+ let staleCount = 0;
347
+ let pushFailedCount = 0;
348
+ let awaitingCommitCount = 0;
349
+ for (const p of activeProposals) {
350
+ const createdMs = Date.parse(p.createdAt);
351
+ if (Number.isFinite(createdMs) && nowMs - createdMs > staleMs) {
352
+ staleCount++;
353
+ }
354
+ if (p.status === 'push_failed')
355
+ pushFailedCount++;
356
+ if (p.status === 'awaiting_commit')
357
+ awaitingCommitCount++;
358
+ }
359
+ if (staleCount > 0) {
360
+ queueStatus = 'WARN';
361
+ queueDetails.push(`${staleCount} stale proposal(s) older than ${staleDays} days.`);
362
+ }
363
+ if (pushFailedCount > 0) {
364
+ queueStatus = 'WARN';
365
+ queueDetails.push(`${pushFailedCount} team proposal(s) in push_failed state.`);
366
+ }
367
+ if (awaitingCommitCount > 0) {
368
+ queueStatus = 'WARN';
369
+ queueDetails.push(`${awaitingCommitCount} project proposal(s) awaiting git commit.`);
370
+ }
371
+ if (queueStatus === 'WARN') {
372
+ queueHint = 'Run "faber-memory status" and "faber-memory review" to resolve queued proposals.';
373
+ }
374
+ else {
375
+ queueDetails.push(`Pre-memory queue healthy (${activeProposals.length} pending proposal(s)).`);
376
+ }
377
+ checks.push({
378
+ id: 'pre-memory-queue',
379
+ name: 'Pre-memory queue',
380
+ status: queueStatus,
381
+ details: queueDetails,
382
+ ...(queueHint ? { hint: queueHint } : {}),
383
+ });
384
+ // 6. Cache stability check
385
+ const stabilityDetails = [];
386
+ let stabilityStatus = 'PASS';
387
+ let stabilityHint;
388
+ const metrics = readMetrics(homeDir);
389
+ if (!metrics.exists) {
390
+ stabilityDetails.push('No metrics.jsonl ledger yet; skipping L0 churn check.');
391
+ }
392
+ else {
393
+ const sevenDayCutoffMs = nowMs - 7 * 24 * 60 * 60 * 1000;
394
+ const recentChanges = metrics.events.filter((e) => e.type === 'compile' && e.changed && Date.parse(e.ts) >= sevenDayCutoffMs).length;
395
+ if (recentChanges > L0_CHURN_WARN_THRESHOLD) {
396
+ stabilityStatus = 'WARN';
397
+ stabilityDetails.push(`Frequent L0 hash changes detected: ${recentChanges} changes in the last 7 days (threshold: ${L0_CHURN_WARN_THRESHOLD}).`);
398
+ stabilityHint = 'Batch memory approvals at session end to preserve LLM prompt-cache reuse.';
399
+ }
400
+ else {
401
+ stabilityDetails.push(`L0 stability OK (${recentChanges} hash change(s) in the last 7 days).`);
402
+ }
403
+ }
404
+ checks.push({
405
+ id: 'cache-stability',
406
+ name: 'Cache stability',
407
+ status: stabilityStatus,
408
+ details: stabilityDetails,
409
+ ...(stabilityHint ? { hint: stabilityHint } : {}),
410
+ });
411
+ const hasFail = checks.some((ch) => ch.status === 'FAIL');
412
+ const hasWarn = checks.some((ch) => ch.status === 'WARN');
413
+ const overall = hasFail ? 'FAIL' : hasWarn ? 'WARN' : 'PASS';
414
+ const exitCode = hasFail || (strict && hasWarn) ? 1 : 0;
415
+ return {
416
+ schemaVersion: 1,
417
+ strict,
418
+ overall,
419
+ exitCode,
420
+ checks,
421
+ };
422
+ }
423
+ export function formatDoctorReport(report) {
424
+ const lines = [];
425
+ lines.push(c.bold('FaberSEP Memory Doctor (read-only)'));
426
+ lines.push(c.dim(hr('─', 64)));
427
+ for (const ch of report.checks) {
428
+ const badge = ch.status === 'PASS'
429
+ ? c.green('[PASS]')
430
+ : ch.status === 'WARN'
431
+ ? c.yellow('[WARN]')
432
+ : c.red('[FAIL]');
433
+ lines.push(`${badge} ${c.bold(ch.name)}`);
434
+ for (const d of ch.details) {
435
+ lines.push(` ${d}`);
436
+ }
437
+ if (ch.hint) {
438
+ lines.push(c.cyan(` Hint: ${ch.hint}`));
439
+ }
440
+ }
441
+ lines.push(c.dim(hr('─', 64)));
442
+ const passCount = report.checks.filter((ch) => ch.status === 'PASS').length;
443
+ const warnCount = report.checks.filter((ch) => ch.status === 'WARN').length;
444
+ const failCount = report.checks.filter((ch) => ch.status === 'FAIL').length;
445
+ lines.push(`Summary: ${c.green(`${passCount} PASS`)} | ${c.yellow(`${warnCount} WARN`)} | ${c.red(`${failCount} FAIL`)}${report.strict ? ' (strict mode)' : ''}`);
446
+ return lines.join('\n');
447
+ }
@@ -0,0 +1,22 @@
1
+ import { EntryFrontmatter, EntryStatus, EntryType, L0Mode, Scope } from './types.js';
2
+ export interface ParsedMarkdown {
3
+ rawFrontmatter: Record<string, unknown>;
4
+ hasFrontmatter: boolean;
5
+ body: string;
6
+ }
7
+ export declare function parseMarkdownWithFrontmatter(content: string): ParsedMarkdown;
8
+ export declare function validateFrontmatter(raw: Record<string, unknown>, scope: Scope): {
9
+ frontmatter?: EntryFrontmatter;
10
+ errors: string[];
11
+ };
12
+ export declare function serializeEntryMarkdown(fm: {
13
+ summary: string;
14
+ type: EntryType;
15
+ tags?: string[];
16
+ status?: EntryStatus;
17
+ superseded_by?: string;
18
+ l0?: L0Mode;
19
+ last_verified?: string;
20
+ }, body: string): string;
21
+ export declare function extractLinks(body: string): string[];
22
+ export declare function slugify(input: string): string;
@@ -0,0 +1,199 @@
1
+ import { VALID_L0_MODES, VALID_STATUSES, VALID_TYPES, } from './types.js';
2
+ export function parseMarkdownWithFrontmatter(content) {
3
+ const normalized = content.replace(/\r\n/g, '\n');
4
+ if (!normalized.startsWith('---\n')) {
5
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
6
+ }
7
+ const endIdx = normalized.indexOf('\n---', 3);
8
+ if (endIdx === -1) {
9
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
10
+ }
11
+ const afterClose = endIdx + 4;
12
+ if (afterClose < normalized.length &&
13
+ normalized[afterClose] !== '\n' &&
14
+ normalized[afterClose] !== ' ') {
15
+ return { rawFrontmatter: {}, hasFrontmatter: false, body: normalized };
16
+ }
17
+ const yamlBlock = normalized.slice(4, endIdx);
18
+ const rest = normalized.slice(afterClose).replace(/^\n/, '');
19
+ return {
20
+ rawFrontmatter: parseSimpleYaml(yamlBlock),
21
+ hasFrontmatter: true,
22
+ body: rest,
23
+ };
24
+ }
25
+ function parseSimpleYaml(yamlText) {
26
+ const result = {};
27
+ const lines = yamlText.split('\n');
28
+ let i = 0;
29
+ while (i < lines.length) {
30
+ const line = lines[i];
31
+ if (!line.trim() || line.trim().startsWith('#')) {
32
+ i++;
33
+ continue;
34
+ }
35
+ const keyMatch = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
36
+ if (!keyMatch) {
37
+ i++;
38
+ continue;
39
+ }
40
+ const key = keyMatch[1];
41
+ const valStr = keyMatch[2].trim();
42
+ if (valStr === '' || valStr === '|' || valStr === '>') {
43
+ // Check indented block: array, nested map, or multiline scalar
44
+ const blockLines = [];
45
+ let j = i + 1;
46
+ while (j < lines.length && (/^\s+/.test(lines[j]) || lines[j].trim() === '')) {
47
+ if (lines[j].trim() === '' && valStr === '') {
48
+ j++;
49
+ continue;
50
+ }
51
+ blockLines.push(lines[j]);
52
+ j++;
53
+ }
54
+ if (valStr === '|' || valStr === '>') {
55
+ const cleaned = blockLines.map((l) => l.replace(/^\s{2}/, ''));
56
+ result[key] = (valStr === '>' ? cleaned.join(' ') : cleaned.join('\n')).trim();
57
+ }
58
+ else if (blockLines.length > 0 && blockLines.every((l) => /^\s*-\s+/.test(l))) {
59
+ result[key] = blockLines.map((l) => unquote(l.replace(/^\s*-\s+/, '').trim()));
60
+ }
61
+ else if (blockLines.length > 0 && blockLines.some((l) => /^\s+[A-Za-z0-9_-]+:/.test(l))) {
62
+ const nested = {};
63
+ for (const bl of blockLines) {
64
+ const nm = bl.match(/^\s+([A-Za-z0-9_-]+):\s*(.*)$/);
65
+ if (nm)
66
+ nested[nm[1]] = unquote(nm[2].trim());
67
+ }
68
+ result[key] = nested;
69
+ }
70
+ else {
71
+ result[key] = '';
72
+ }
73
+ i = j;
74
+ continue;
75
+ }
76
+ if (valStr.startsWith('[') && valStr.endsWith(']')) {
77
+ const inner = valStr.slice(1, -1).trim();
78
+ result[key] = inner
79
+ ? inner.split(',').map((item) => unquote(item.trim())).filter(Boolean)
80
+ : [];
81
+ }
82
+ else {
83
+ result[key] = unquote(valStr);
84
+ }
85
+ i++;
86
+ }
87
+ return result;
88
+ }
89
+ function unquote(val) {
90
+ if ((val.startsWith('"') && val.endsWith('"') && val.length >= 2) ||
91
+ (val.startsWith("'") && val.endsWith("'") && val.length >= 2)) {
92
+ return val.slice(1, -1).replace(/\\"/g, '"').replace(/\\n/g, '\n');
93
+ }
94
+ return val;
95
+ }
96
+ export function validateFrontmatter(raw, scope) {
97
+ const errors = [];
98
+ const summary = typeof raw.summary === 'string' ? raw.summary.trim() : '';
99
+ if (!summary) {
100
+ errors.push('missing required frontmatter field "summary"');
101
+ }
102
+ else if (summary.includes('\n')) {
103
+ errors.push('"summary" must be a single line');
104
+ }
105
+ const rawType = typeof raw.type === 'string' ? raw.type.trim() : '';
106
+ if (!rawType) {
107
+ errors.push('missing required frontmatter field "type"');
108
+ }
109
+ else if (!VALID_TYPES.includes(rawType)) {
110
+ errors.push(`invalid "type" "${rawType}" (expected one of: ${VALID_TYPES.join(', ')})`);
111
+ }
112
+ const rawStatus = typeof raw.status === 'string' && raw.status.trim() ? raw.status.trim() : 'active';
113
+ if (!VALID_STATUSES.includes(rawStatus)) {
114
+ errors.push(`invalid "status" "${rawStatus}" (expected one of: ${VALID_STATUSES.join(', ')})`);
115
+ }
116
+ const defaultL0 = scope === 'project' ? 'none' : 'line';
117
+ const rawL0 = typeof raw.l0 === 'string' && raw.l0.trim() ? raw.l0.trim() : defaultL0;
118
+ if (!VALID_L0_MODES.includes(rawL0)) {
119
+ errors.push(`invalid "l0" "${rawL0}" (expected one of: ${VALID_L0_MODES.join(', ')})`);
120
+ }
121
+ let tags = [];
122
+ if (Array.isArray(raw.tags)) {
123
+ tags = raw.tags.map((t) => String(t).trim()).filter(Boolean);
124
+ }
125
+ else if (typeof raw.tags === 'string' && raw.tags.trim()) {
126
+ tags = raw.tags.split(',').map((t) => t.trim()).filter(Boolean);
127
+ }
128
+ const superseded_by = typeof raw.superseded_by === 'string' && raw.superseded_by.trim()
129
+ ? raw.superseded_by.trim()
130
+ : undefined;
131
+ const last_verified = typeof raw.last_verified === 'string' && raw.last_verified.trim()
132
+ ? raw.last_verified.trim()
133
+ : undefined;
134
+ if (errors.length > 0) {
135
+ return { errors };
136
+ }
137
+ return {
138
+ frontmatter: {
139
+ summary,
140
+ type: rawType,
141
+ tags,
142
+ status: rawStatus,
143
+ superseded_by,
144
+ l0: rawL0,
145
+ last_verified,
146
+ },
147
+ errors: [],
148
+ };
149
+ }
150
+ function quoteIfNeeded(value) {
151
+ if (/[:#[\]{}&*!|>'"%@`,?]/.test(value) || value.trim() !== value) {
152
+ return JSON.stringify(value);
153
+ }
154
+ return value;
155
+ }
156
+ export function serializeEntryMarkdown(fm, body) {
157
+ const lines = ['---'];
158
+ lines.push(`summary: ${quoteIfNeeded(fm.summary.replace(/\s+/g, ' ').trim())}`);
159
+ lines.push(`type: ${fm.type}`);
160
+ if (fm.tags && fm.tags.length > 0) {
161
+ lines.push(`tags: [${fm.tags.map((t) => quoteIfNeeded(t)).join(', ')}]`);
162
+ }
163
+ if (fm.status && fm.status !== 'active') {
164
+ lines.push(`status: ${fm.status}`);
165
+ }
166
+ if (fm.superseded_by) {
167
+ lines.push(`superseded_by: ${fm.superseded_by}`);
168
+ }
169
+ if (fm.l0) {
170
+ lines.push(`l0: ${fm.l0}`);
171
+ }
172
+ if (fm.last_verified) {
173
+ lines.push(`last_verified: ${fm.last_verified}`);
174
+ }
175
+ lines.push('---');
176
+ const trimmedBody = body.replace(/\r\n/g, '\n').trim();
177
+ return `${lines.join('\n')}\n\n${trimmedBody}\n`;
178
+ }
179
+ export function extractLinks(body) {
180
+ const links = new Set();
181
+ const mdLinkRegex = /\[[^\]]+\]\(([^)\s]+)\)/g;
182
+ let m;
183
+ while ((m = mdLinkRegex.exec(body)) !== null) {
184
+ links.add(m[1]);
185
+ }
186
+ const urlRegex = /https?:\/\/[^\s)>\]]+/g;
187
+ while ((m = urlRegex.exec(body)) !== null) {
188
+ links.add(m[0].replace(/[.,;:!?]+$/, ''));
189
+ }
190
+ return Array.from(links);
191
+ }
192
+ export function slugify(input) {
193
+ return (input
194
+ .toLowerCase()
195
+ .replace(/\.md$/i, '')
196
+ .replace(/[^a-z0-9]+/g, '-')
197
+ .replace(/^-+|-+$/g, '')
198
+ .slice(0, 64) || 'memory-entry');
199
+ }