@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,23 @@
1
+ import { CompileTrigger } from './metrics.js';
2
+ import { MemoryEntry, UserConfig } from './types.js';
3
+ export declare function estimateTokens(text: string): number;
4
+ export interface CompileResult {
5
+ ok: boolean;
6
+ output?: string;
7
+ estimatedTokens: number;
8
+ budget: number;
9
+ outputPath?: string;
10
+ errors: string[];
11
+ warnings: string[];
12
+ }
13
+ export declare function renderEntryFullBody(entry: MemoryEntry): string;
14
+ export declare function estimateCorpusTokens(entries: MemoryEntry[]): number;
15
+ export declare function renderGlobalL0(teamEntries: MemoryEntry[], personalEntries: MemoryEntry[]): string;
16
+ export declare function compileGlobalL0(config: UserConfig, options?: {
17
+ homeDir?: string;
18
+ checkOnly?: boolean;
19
+ includeProjectCheck?: boolean;
20
+ cwd?: string;
21
+ standaloneRepoDir?: string;
22
+ trigger?: CompileTrigger;
23
+ }): CompileResult;
@@ -0,0 +1,211 @@
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 { appendMetric } from './metrics.js';
7
+ import { loadScopeFromHead, PROJECT_MEMORY_REL_DIR, resolveProjectRoot, } from './store.js';
8
+ import { COMPILER_VERSION, } from './types.js';
9
+ export function estimateTokens(text) {
10
+ return Math.ceil(Buffer.byteLength(text, 'utf8') / 4);
11
+ }
12
+ export function renderEntryFullBody(entry) {
13
+ return `### ${entry.id} (${entry.type})\n\n${entry.body}`;
14
+ }
15
+ export function estimateCorpusTokens(entries) {
16
+ const active = entries
17
+ .filter((e) => e.status === 'active')
18
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
19
+ if (active.length === 0)
20
+ return 0;
21
+ return estimateTokens(active.map(renderEntryFullBody).join('\n'));
22
+ }
23
+ function renderEntryL0(entry) {
24
+ if (entry.l0 === 'body') {
25
+ return renderEntryFullBody(entry);
26
+ }
27
+ return `- \`${entry.id}\` (${entry.type}): ${entry.summary}`;
28
+ }
29
+ export function renderGlobalL0(teamEntries, personalEntries) {
30
+ const teamActive = teamEntries
31
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
32
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
33
+ const personalActive = personalEntries
34
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
35
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
36
+ const sections = [
37
+ `<!-- generated by @fabersep/memory v${COMPILER_VERSION} — do not edit manually -->`,
38
+ '# Memory (L0)',
39
+ ];
40
+ if (teamActive.length > 0) {
41
+ sections.push('## Team\n\n' + teamActive.map(renderEntryL0).join('\n'));
42
+ }
43
+ if (personalActive.length > 0) {
44
+ sections.push('## Personal\n\n' + personalActive.map(renderEntryL0).join('\n'));
45
+ }
46
+ if (teamActive.length === 0 && personalActive.length === 0) {
47
+ sections.push('_No active L0 memory entries._');
48
+ }
49
+ return sections.join('\n\n') + '\n';
50
+ }
51
+ export function compileGlobalL0(config, options = {}) {
52
+ const homeDir = options.homeDir || getHomeDir();
53
+ const errors = [];
54
+ const warnings = [];
55
+ const teamScope = config.roots.team
56
+ ? loadScopeFromHead(config.roots.team.path, 'team')
57
+ : undefined;
58
+ const personalScope = config.roots.personal
59
+ ? loadScopeFromHead(config.roots.personal.path, 'personal')
60
+ : undefined;
61
+ // Standalone repo CI mode: if neither team nor personal is configured, or standaloneRepoDir is given
62
+ const standaloneScope = options.standaloneRepoDir
63
+ ? loadScopeFromHead(options.standaloneRepoDir, 'team')
64
+ : !teamScope && !personalScope && options.checkOnly && options.cwd
65
+ ? loadScopeFromHead(options.cwd, 'team')
66
+ : undefined;
67
+ const effectiveTeam = teamScope || standaloneScope;
68
+ for (const sc of [effectiveTeam, personalScope]) {
69
+ if (!sc)
70
+ continue;
71
+ for (const err of sc.errors) {
72
+ errors.push(`[${err.scope}] ${err.filePath}: ${err.message}`);
73
+ }
74
+ if (sc.uncommittedFiles.length > 0) {
75
+ warnings.push(`Uncommitted edits in ${sc.scope} root (${sc.uncommittedFiles.join(', ')}); compiled from committed HEAD only.`);
76
+ }
77
+ for (const entry of sc.entries) {
78
+ const contentToScan = `${entry.summary}\n${entry.body}`;
79
+ const hygiene = scanHygiene(contentToScan);
80
+ if (hygiene.length > 0) {
81
+ errors.push(formatHygieneErrors(hygiene, `[${entry.scope}] ${entry.filePath}`));
82
+ }
83
+ }
84
+ }
85
+ // Check duplicate active IDs across team and personal
86
+ const teamActiveMap = new Map();
87
+ for (const e of effectiveTeam?.entries || []) {
88
+ if (e.status !== 'active')
89
+ continue;
90
+ if (teamActiveMap.has(e.id)) {
91
+ errors.push(`Duplicate active entry ID "${e.id}" within team scope.`);
92
+ }
93
+ teamActiveMap.set(e.id, e);
94
+ }
95
+ const personalActiveMap = new Map();
96
+ for (const e of personalScope?.entries || []) {
97
+ if (e.status !== 'active')
98
+ continue;
99
+ if (personalActiveMap.has(e.id)) {
100
+ errors.push(`Duplicate active entry ID "${e.id}" within personal scope.`);
101
+ }
102
+ if (teamActiveMap.has(e.id)) {
103
+ errors.push(`Duplicate active entry ID "${e.id}" across scopes "team" and "personal". Resolve the collision before compiling.`);
104
+ }
105
+ personalActiveMap.set(e.id, e);
106
+ }
107
+ // Optional project-level check (only in compile --check when inside a project repo)
108
+ if (options.includeProjectCheck) {
109
+ const projRes = resolveProjectRoot(undefined, options.cwd || process.cwd());
110
+ if (projRes.source !== 'none' && projRes.projectRoot) {
111
+ const projScope = loadScopeFromHead(projRes.projectRoot, 'project', PROJECT_MEMORY_REL_DIR);
112
+ for (const err of projScope.errors) {
113
+ errors.push(`[project] ${err.filePath}: ${err.message}`);
114
+ }
115
+ for (const entry of projScope.entries) {
116
+ const hygiene = scanHygiene(`${entry.summary}\n${entry.body}`);
117
+ if (hygiene.length > 0) {
118
+ errors.push(formatHygieneErrors(hygiene, `[project] ${entry.filePath}`));
119
+ }
120
+ if (entry.status === 'active') {
121
+ if (teamActiveMap.has(entry.id)) {
122
+ errors.push(`Duplicate active entry ID "${entry.id}" across scopes "project" and "team".`);
123
+ }
124
+ if (personalActiveMap.has(entry.id)) {
125
+ errors.push(`Duplicate active entry ID "${entry.id}" across scopes "project" and "personal".`);
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ const output = renderGlobalL0(effectiveTeam?.entries || [], personalScope?.entries || []);
132
+ const outHygiene = scanHygiene(output);
133
+ if (outHygiene.length > 0) {
134
+ errors.push(formatHygieneErrors(outHygiene, 'compiled MEMORY.md'));
135
+ }
136
+ const tokens = estimateTokens(output);
137
+ if (tokens > config.tokenBudget) {
138
+ const contributors = [
139
+ ...(effectiveTeam?.entries || []),
140
+ ...(personalScope?.entries || []),
141
+ ]
142
+ .filter((e) => e.status === 'active' && (e.l0 === 'line' || e.l0 === 'body'))
143
+ .map((e) => ({
144
+ id: e.id,
145
+ scope: e.scope,
146
+ tokens: estimateTokens(renderEntryL0(e)),
147
+ }))
148
+ .sort((a, b) => b.tokens - a.tokens)
149
+ .slice(0, 10);
150
+ const list = contributors
151
+ .map((c) => ` - ${c.id} (${c.scope}): ~${c.tokens} tokens`)
152
+ .join('\n');
153
+ errors.push(`Compiled L0 exceeds token budget (${tokens} > ${config.tokenBudget} estimated tokens). Largest entries:\n${list}`);
154
+ }
155
+ if (errors.length > 0) {
156
+ return {
157
+ ok: false,
158
+ estimatedTokens: tokens,
159
+ budget: config.tokenBudget,
160
+ errors,
161
+ warnings,
162
+ };
163
+ }
164
+ const outputPath = getCompiledL0Path(homeDir);
165
+ if (!options.checkOnly) {
166
+ let initial = false;
167
+ let changed = false;
168
+ const newHash = crypto.createHash('sha256').update(output, 'utf8').digest('hex');
169
+ withStateLock(() => {
170
+ const stateDir = getStateDir(homeDir);
171
+ fs.mkdirSync(stateDir, { recursive: true });
172
+ if (fs.existsSync(outputPath)) {
173
+ const priorBytes = fs.readFileSync(outputPath);
174
+ const priorHash = crypto.createHash('sha256').update(priorBytes).digest('hex');
175
+ initial = false;
176
+ changed = priorHash !== newHash;
177
+ }
178
+ else {
179
+ initial = true;
180
+ changed = false;
181
+ }
182
+ const tmpPath = path.join(stateDir, `MEMORY.md.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`);
183
+ fs.writeFileSync(tmpPath, output, 'utf8');
184
+ fs.renameSync(tmpPath, outputPath);
185
+ }, homeDir);
186
+ const activeGlobalEntries = [
187
+ ...(effectiveTeam?.entries || []),
188
+ ...(personalScope?.entries || []),
189
+ ].filter((e) => e.status === 'active');
190
+ appendMetric({
191
+ type: 'compile',
192
+ ts: new Date().toISOString(),
193
+ trigger: options.trigger || 'cli',
194
+ initial,
195
+ changed,
196
+ l0_sha256: newHash,
197
+ l0_tokens: tokens,
198
+ corpus_tokens: estimateCorpusTokens(activeGlobalEntries),
199
+ active_entries: activeGlobalEntries.length,
200
+ }, homeDir);
201
+ }
202
+ return {
203
+ ok: true,
204
+ output,
205
+ estimatedTokens: tokens,
206
+ budget: config.tokenBudget,
207
+ outputPath,
208
+ errors: [],
209
+ warnings,
210
+ };
211
+ }
@@ -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;
@@ -0,0 +1,134 @@
1
+ import * as crypto from 'node:crypto';
2
+ import * as fs from 'node:fs';
3
+ import * as os from 'node:os';
4
+ import * as path from 'node:path';
5
+ import { DEFAULT_SIMILARITY_THRESHOLD, DEFAULT_STALE_DAYS, DEFAULT_TOKEN_BUDGET, } from './types.js';
6
+ export function getHomeDir() {
7
+ return process.env.FABER_MEMORY_HOME || path.join(os.homedir(), '.config', 'faber-memory');
8
+ }
9
+ export function getConfigPath(homeDir = getHomeDir()) {
10
+ return path.join(homeDir, 'config.json');
11
+ }
12
+ export function getStateDir(homeDir = getHomeDir()) {
13
+ return path.join(homeDir, 'state');
14
+ }
15
+ export function getCompiledL0Path(homeDir = getHomeDir()) {
16
+ return path.join(getStateDir(homeDir), 'MEMORY.md');
17
+ }
18
+ export function getPreMemoryRootDir(rootUuid, homeDir = getHomeDir()) {
19
+ return path.join(getStateDir(homeDir), 'pre-memory', rootUuid);
20
+ }
21
+ export function getAllPreMemoryBaseDir(homeDir = getHomeDir()) {
22
+ return path.join(getStateDir(homeDir), 'pre-memory');
23
+ }
24
+ export function getDefaultPersonalPath() {
25
+ return path.join(os.homedir(), '.faber', 'memory');
26
+ }
27
+ export function getProjectRootUuid(projectRootPath) {
28
+ const normalized = path.resolve(projectRootPath);
29
+ const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
30
+ return `proj-${hash}`;
31
+ }
32
+ export function sanitizeUserTag(raw) {
33
+ const source = raw || safeUsername();
34
+ const cleaned = source.toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 8);
35
+ return cleaned || 'dev';
36
+ }
37
+ function safeUsername() {
38
+ try {
39
+ return os.userInfo().username || 'dev';
40
+ }
41
+ catch {
42
+ return process.env.USER || process.env.USERNAME || 'dev';
43
+ }
44
+ }
45
+ export function defaultConfig() {
46
+ return {
47
+ version: 1,
48
+ userTag: sanitizeUserTag(),
49
+ tokenBudget: DEFAULT_TOKEN_BUDGET,
50
+ staleDays: DEFAULT_STALE_DAYS,
51
+ similarityThreshold: DEFAULT_SIMILARITY_THRESHOLD,
52
+ roots: {},
53
+ };
54
+ }
55
+ export function loadConfig(homeDir = getHomeDir()) {
56
+ const cfgPath = getConfigPath(homeDir);
57
+ if (!fs.existsSync(cfgPath)) {
58
+ return defaultConfig();
59
+ }
60
+ const raw = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
61
+ return {
62
+ version: 1,
63
+ userTag: raw.userTag || sanitizeUserTag(),
64
+ tokenBudget: typeof raw.tokenBudget === 'number' ? raw.tokenBudget : DEFAULT_TOKEN_BUDGET,
65
+ staleDays: typeof raw.staleDays === 'number' ? raw.staleDays : DEFAULT_STALE_DAYS,
66
+ similarityThreshold: typeof raw.similarityThreshold === 'number'
67
+ ? raw.similarityThreshold
68
+ : DEFAULT_SIMILARITY_THRESHOLD,
69
+ roots: raw.roots || {},
70
+ };
71
+ }
72
+ export function saveConfig(config, homeDir = getHomeDir()) {
73
+ fs.mkdirSync(homeDir, { recursive: true });
74
+ const cfgPath = getConfigPath(homeDir);
75
+ const tmpPath = `${cfgPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
76
+ fs.writeFileSync(tmpPath, JSON.stringify(config, null, 2) + '\n', 'utf8');
77
+ fs.renameSync(tmpPath, cfgPath);
78
+ }
79
+ export function generateUuid() {
80
+ return crypto.randomUUID();
81
+ }
82
+ export function generateProposalId(userTag) {
83
+ const tag = sanitizeUserTag(userTag);
84
+ const suffix = crypto.randomBytes(2).toString('hex');
85
+ return `p-${tag}-${suffix}`;
86
+ }
87
+ /**
88
+ * Per-state-directory advisory lock using atomic mkdir with bounded retry.
89
+ * Ensures concurrent compile/approve calls never interleave writes.
90
+ */
91
+ export function withStateLock(fn, homeDir = getHomeDir(), timeoutMs = 10000) {
92
+ const stateDir = getStateDir(homeDir);
93
+ fs.mkdirSync(stateDir, { recursive: true });
94
+ const lockDir = path.join(stateDir, '.state.lock');
95
+ const deadline = Date.now() + timeoutMs;
96
+ while (true) {
97
+ try {
98
+ fs.mkdirSync(lockDir);
99
+ fs.writeFileSync(path.join(lockDir, 'pid'), String(process.pid), 'utf8');
100
+ break;
101
+ }
102
+ catch (err) {
103
+ const code = err.code;
104
+ if (code !== 'EEXIST')
105
+ throw err;
106
+ // Clear stale locks older than 30s
107
+ try {
108
+ const stat = fs.statSync(lockDir);
109
+ if (Date.now() - stat.mtimeMs > 30000) {
110
+ fs.rmSync(lockDir, { recursive: true, force: true });
111
+ continue;
112
+ }
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ if (Date.now() >= deadline) {
118
+ throw new Error(`Timed out waiting for state lock at ${lockDir}`);
119
+ }
120
+ sleepSync(15 + Math.floor(Math.random() * 25));
121
+ }
122
+ }
123
+ try {
124
+ return fn();
125
+ }
126
+ finally {
127
+ fs.rmSync(lockDir, { recursive: true, force: true });
128
+ }
129
+ }
130
+ function sleepSync(ms) {
131
+ const buf = new SharedArrayBuffer(4);
132
+ const arr = new Int32Array(buf);
133
+ Atomics.wait(arr, 0, 0, ms);
134
+ }
@@ -0,0 +1,23 @@
1
+ export type DoctorStatus = 'PASS' | 'WARN' | 'FAIL';
2
+ export interface DoctorCheckResult {
3
+ id: string;
4
+ name: string;
5
+ status: DoctorStatus;
6
+ details: string[];
7
+ hint?: string;
8
+ }
9
+ export interface DoctorReport {
10
+ schemaVersion: number;
11
+ strict: boolean;
12
+ overall: DoctorStatus;
13
+ exitCode: number;
14
+ checks: DoctorCheckResult[];
15
+ }
16
+ export declare function runDoctor(options?: {
17
+ strict?: boolean;
18
+ homeDir?: string;
19
+ userHome?: string;
20
+ cwd?: string;
21
+ nowMs?: number;
22
+ }): DoctorReport;
23
+ export declare function formatDoctorReport(report: DoctorReport): string;