@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,383 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { generateProposalId, getAllPreMemoryBaseDir, getHomeDir, getPreMemoryRootDir, getProjectRootUuid, withStateLock, } from './config.js';
|
|
4
|
+
import { compileGlobalL0 } from './compiler.js';
|
|
5
|
+
import { parseMarkdownWithFrontmatter, serializeEntryMarkdown, slugify, } from './frontmatter.js';
|
|
6
|
+
import { buildCompareUrl, createThrowawayWorktree, getDefaultBranch, getRemoteUrl, gitCommitFiles, gitPullFfOnly, gitSync, isBranchProtectionRejection, readHeadFile, removeThrowawayWorktree, } from './git.js';
|
|
7
|
+
import { formatHygieneErrors, scanHygiene } from './hygiene.js';
|
|
8
|
+
import { PROJECT_MEMORY_REL_DIR } from './store.js';
|
|
9
|
+
export const CACHE_GUIDANCE_NOTE = 'Note: Updated L0 applies to new sessions; batching reviews at session end maximizes prompt-cache reuse.';
|
|
10
|
+
export function saveProposal(proposal, homeDir = getHomeDir()) {
|
|
11
|
+
const dir = getPreMemoryRootDir(proposal.rootUuid, homeDir);
|
|
12
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
13
|
+
const filePath = path.join(dir, `${proposal.id}.json`);
|
|
14
|
+
fs.writeFileSync(filePath, JSON.stringify(proposal, null, 2) + '\n', 'utf8');
|
|
15
|
+
return filePath;
|
|
16
|
+
}
|
|
17
|
+
export function deleteProposal(proposal, homeDir = getHomeDir()) {
|
|
18
|
+
const filePath = path.join(getPreMemoryRootDir(proposal.rootUuid, homeDir), `${proposal.id}.json`);
|
|
19
|
+
if (fs.existsSync(filePath)) {
|
|
20
|
+
fs.unlinkSync(filePath);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function listAllProposals(homeDir = getHomeDir()) {
|
|
24
|
+
const baseDir = getAllPreMemoryBaseDir(homeDir);
|
|
25
|
+
if (!fs.existsSync(baseDir))
|
|
26
|
+
return [];
|
|
27
|
+
const proposals = [];
|
|
28
|
+
for (const rootUuid of fs.readdirSync(baseDir)) {
|
|
29
|
+
const rootDir = path.join(baseDir, rootUuid);
|
|
30
|
+
if (!fs.statSync(rootDir).isDirectory())
|
|
31
|
+
continue;
|
|
32
|
+
for (const file of fs.readdirSync(rootDir)) {
|
|
33
|
+
if (!file.endsWith('.json'))
|
|
34
|
+
continue;
|
|
35
|
+
try {
|
|
36
|
+
const raw = JSON.parse(fs.readFileSync(path.join(rootDir, file), 'utf8'));
|
|
37
|
+
proposals.push(raw);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Skip malformed file
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
proposals.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));
|
|
45
|
+
return proposals;
|
|
46
|
+
}
|
|
47
|
+
export function reconcileAwaitingCommitProposals(homeDir = getHomeDir()) {
|
|
48
|
+
const all = listAllProposals(homeDir);
|
|
49
|
+
const remaining = [];
|
|
50
|
+
for (const p of all) {
|
|
51
|
+
if (p.status === 'awaiting_commit' && p.projectRootPath && p.targetFilePath) {
|
|
52
|
+
const committed = readHeadFile(p.projectRootPath, p.targetFilePath);
|
|
53
|
+
if (committed !== null) {
|
|
54
|
+
deleteProposal(p, homeDir);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
remaining.push(p);
|
|
59
|
+
}
|
|
60
|
+
return remaining;
|
|
61
|
+
}
|
|
62
|
+
export function findProposalById(id, homeDir = getHomeDir()) {
|
|
63
|
+
const all = reconcileAwaitingCommitProposals(homeDir);
|
|
64
|
+
return all.find((p) => p.id === id) || null;
|
|
65
|
+
}
|
|
66
|
+
export function createProposal(config, input, homeDir = getHomeDir()) {
|
|
67
|
+
let rootUuid;
|
|
68
|
+
if (input.scope === 'personal') {
|
|
69
|
+
if (!config.roots.personal) {
|
|
70
|
+
throw new Error('Personal memory root is not configured.');
|
|
71
|
+
}
|
|
72
|
+
rootUuid = config.roots.personal.uuid;
|
|
73
|
+
}
|
|
74
|
+
else if (input.scope === 'team') {
|
|
75
|
+
if (!config.roots.team) {
|
|
76
|
+
throw new Error('Team memory root is not configured.');
|
|
77
|
+
}
|
|
78
|
+
rootUuid = config.roots.team.uuid;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
if (!input.projectRootPath) {
|
|
82
|
+
throw new Error('Project scope requires an active project root.');
|
|
83
|
+
}
|
|
84
|
+
rootUuid = getProjectRootUuid(input.projectRootPath);
|
|
85
|
+
}
|
|
86
|
+
const entryId = input.action === 'update' && input.targetId
|
|
87
|
+
? input.targetId
|
|
88
|
+
: input.entryId
|
|
89
|
+
? slugify(input.entryId)
|
|
90
|
+
: slugify(input.summary);
|
|
91
|
+
const proposal = {
|
|
92
|
+
id: generateProposalId(config.userTag),
|
|
93
|
+
rootUuid,
|
|
94
|
+
scope: input.scope,
|
|
95
|
+
action: input.action,
|
|
96
|
+
entryId,
|
|
97
|
+
targetId: input.targetId,
|
|
98
|
+
summary: input.summary.replace(/\s+/g, ' ').trim(),
|
|
99
|
+
type: input.type,
|
|
100
|
+
tags: input.tags || [],
|
|
101
|
+
l0: input.l0,
|
|
102
|
+
body: input.body.trim(),
|
|
103
|
+
forceNew: input.forceNew,
|
|
104
|
+
reason: input.reason,
|
|
105
|
+
status: 'pending',
|
|
106
|
+
createdAt: new Date().toISOString(),
|
|
107
|
+
projectRootPath: input.projectRootPath,
|
|
108
|
+
};
|
|
109
|
+
saveProposal(proposal, homeDir);
|
|
110
|
+
return proposal;
|
|
111
|
+
}
|
|
112
|
+
export function rejectProposal(id, homeDir = getHomeDir()) {
|
|
113
|
+
const proposal = findProposalById(id, homeDir);
|
|
114
|
+
if (!proposal) {
|
|
115
|
+
throw new Error(`Proposal "${id}" not found in pre-memory.`);
|
|
116
|
+
}
|
|
117
|
+
deleteProposal(proposal, homeDir);
|
|
118
|
+
return proposal;
|
|
119
|
+
}
|
|
120
|
+
function applyProposalFilesToDir(repoDir, subDir, proposal) {
|
|
121
|
+
const touched = [];
|
|
122
|
+
const targetDir = subDir ? path.join(repoDir, subDir) : repoDir;
|
|
123
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
124
|
+
const relEntryPath = subDir
|
|
125
|
+
? path.posix.join(subDir, `${proposal.entryId}.md`)
|
|
126
|
+
: `${proposal.entryId}.md`;
|
|
127
|
+
const absEntryPath = path.join(repoDir, relEntryPath);
|
|
128
|
+
const markdown = serializeEntryMarkdown({
|
|
129
|
+
summary: proposal.summary,
|
|
130
|
+
type: proposal.type,
|
|
131
|
+
tags: proposal.tags,
|
|
132
|
+
status: 'active',
|
|
133
|
+
l0: proposal.l0 || (proposal.scope === 'project' ? 'none' : 'line'),
|
|
134
|
+
}, proposal.body);
|
|
135
|
+
fs.writeFileSync(absEntryPath, markdown, 'utf8');
|
|
136
|
+
touched.push(relEntryPath);
|
|
137
|
+
if (proposal.action === 'supersede' && proposal.targetId && proposal.targetId !== proposal.entryId) {
|
|
138
|
+
const targetRel = subDir
|
|
139
|
+
? path.posix.join(subDir, `${proposal.targetId}.md`)
|
|
140
|
+
: `${proposal.targetId}.md`;
|
|
141
|
+
const targetAbs = path.join(repoDir, targetRel);
|
|
142
|
+
if (fs.existsSync(targetAbs)) {
|
|
143
|
+
const existingRaw = fs.readFileSync(targetAbs, 'utf8');
|
|
144
|
+
const parsed = parseMarkdownWithFrontmatter(existingRaw);
|
|
145
|
+
const oldSummary = typeof parsed.rawFrontmatter.summary === 'string'
|
|
146
|
+
? parsed.rawFrontmatter.summary
|
|
147
|
+
: proposal.targetId;
|
|
148
|
+
const oldType = typeof parsed.rawFrontmatter.type === 'string'
|
|
149
|
+
? parsed.rawFrontmatter.type
|
|
150
|
+
: 'rule';
|
|
151
|
+
const oldTags = Array.isArray(parsed.rawFrontmatter.tags)
|
|
152
|
+
? parsed.rawFrontmatter.tags.map(String)
|
|
153
|
+
: [];
|
|
154
|
+
const updatedOld = serializeEntryMarkdown({
|
|
155
|
+
summary: oldSummary,
|
|
156
|
+
type: oldType,
|
|
157
|
+
tags: oldTags,
|
|
158
|
+
status: 'superseded',
|
|
159
|
+
superseded_by: proposal.entryId,
|
|
160
|
+
l0: 'none',
|
|
161
|
+
}, parsed.body);
|
|
162
|
+
fs.writeFileSync(targetAbs, updatedOld, 'utf8');
|
|
163
|
+
touched.push(targetRel);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return touched;
|
|
167
|
+
}
|
|
168
|
+
export async function approveProposalsBatch(config, proposals, options = {}) {
|
|
169
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
170
|
+
const messages = [];
|
|
171
|
+
const errors = [];
|
|
172
|
+
const approvedIds = [];
|
|
173
|
+
let compareUrl;
|
|
174
|
+
let recompiledL0 = false;
|
|
175
|
+
if (proposals.length === 0) {
|
|
176
|
+
return { ok: true, approvedIds: [], messages: ['No proposals to approve.'], errors: [] };
|
|
177
|
+
}
|
|
178
|
+
// Hygiene check every proposal first (AC-20b1)
|
|
179
|
+
for (const p of proposals) {
|
|
180
|
+
const findings = scanHygiene(`${p.summary}\n${p.body}`);
|
|
181
|
+
if (findings.length > 0) {
|
|
182
|
+
errors.push(formatHygieneErrors(findings, `proposal ${p.id}`));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (errors.length > 0) {
|
|
186
|
+
return { ok: false, approvedIds: [], messages: [], errors };
|
|
187
|
+
}
|
|
188
|
+
// Group by scope
|
|
189
|
+
const byScope = new Map();
|
|
190
|
+
for (const p of proposals) {
|
|
191
|
+
const list = byScope.get(p.scope) || [];
|
|
192
|
+
list.push(p);
|
|
193
|
+
byScope.set(p.scope, list);
|
|
194
|
+
}
|
|
195
|
+
// 1. Personal scope: single commit + single L0 recompile
|
|
196
|
+
const personalProps = byScope.get('personal') || [];
|
|
197
|
+
if (personalProps.length > 0) {
|
|
198
|
+
const root = config.roots.personal;
|
|
199
|
+
if (!root) {
|
|
200
|
+
errors.push('Personal memory root is not configured.');
|
|
201
|
+
return { ok: false, approvedIds, messages, errors };
|
|
202
|
+
}
|
|
203
|
+
const touched = [];
|
|
204
|
+
for (const p of personalProps) {
|
|
205
|
+
touched.push(...applyProposalFilesToDir(root.path, '', p));
|
|
206
|
+
}
|
|
207
|
+
const commitMsg = personalProps.length === 1
|
|
208
|
+
? `memory(${personalProps[0].action}): ${personalProps[0].entryId} [${personalProps[0].id}]`
|
|
209
|
+
: `memory(batch): approve ${personalProps.length} proposals (${personalProps.map((p) => p.id).join(', ')})`;
|
|
210
|
+
gitCommitFiles(root.path, touched, commitMsg);
|
|
211
|
+
for (const p of personalProps) {
|
|
212
|
+
deleteProposal(p, homeDir);
|
|
213
|
+
approvedIds.push(p.id);
|
|
214
|
+
}
|
|
215
|
+
const comp = compileGlobalL0(config, { homeDir });
|
|
216
|
+
if (!comp.ok) {
|
|
217
|
+
errors.push(...comp.errors);
|
|
218
|
+
return { ok: false, approvedIds, messages, errors };
|
|
219
|
+
}
|
|
220
|
+
recompiledL0 = true;
|
|
221
|
+
messages.push(`Approved ${personalProps.length} personal proposal(s) in 1 commit and recompiled L0 (${comp.estimatedTokens}/${comp.budget} tokens).`);
|
|
222
|
+
}
|
|
223
|
+
// 2. Project scope: write uncommitted file(s) and mark awaiting_commit
|
|
224
|
+
const projectProps = byScope.get('project') || [];
|
|
225
|
+
if (projectProps.length > 0) {
|
|
226
|
+
for (const p of projectProps) {
|
|
227
|
+
if (!p.projectRootPath) {
|
|
228
|
+
errors.push(`Project proposal ${p.id} is missing projectRootPath.`);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const touched = applyProposalFilesToDir(p.projectRootPath, PROJECT_MEMORY_REL_DIR, p);
|
|
232
|
+
p.status = 'awaiting_commit';
|
|
233
|
+
p.targetFilePath = touched[0];
|
|
234
|
+
saveProposal(p, homeDir);
|
|
235
|
+
approvedIds.push(p.id);
|
|
236
|
+
messages.push(`Staged project memory file ${touched[0]} (uncommitted). Run: git add ${touched.join(' ')} && git commit -m "memory: ${p.entryId}"`);
|
|
237
|
+
}
|
|
238
|
+
if (errors.length > 0) {
|
|
239
|
+
return { ok: false, approvedIds, messages, errors };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// 3. Team scope: throwaway git worktree from origin/<defaultBranch>
|
|
243
|
+
const teamProps = byScope.get('team') || [];
|
|
244
|
+
if (teamProps.length > 0) {
|
|
245
|
+
const root = config.roots.team;
|
|
246
|
+
if (!root) {
|
|
247
|
+
errors.push('Team memory root is not configured.');
|
|
248
|
+
return { ok: false, approvedIds, messages, errors };
|
|
249
|
+
}
|
|
250
|
+
const res = await approveTeamBatch(config, root, teamProps, homeDir, options.teamSubmitModeOverride);
|
|
251
|
+
if (!res.ok) {
|
|
252
|
+
errors.push(...res.errors);
|
|
253
|
+
return { ok: false, approvedIds, messages, errors };
|
|
254
|
+
}
|
|
255
|
+
approvedIds.push(...res.approvedIds);
|
|
256
|
+
messages.push(...res.messages);
|
|
257
|
+
if (res.compareUrl)
|
|
258
|
+
compareUrl = res.compareUrl;
|
|
259
|
+
if (res.recompiledL0)
|
|
260
|
+
recompiledL0 = true;
|
|
261
|
+
}
|
|
262
|
+
if (recompiledL0) {
|
|
263
|
+
messages.push(CACHE_GUIDANCE_NOTE);
|
|
264
|
+
}
|
|
265
|
+
return {
|
|
266
|
+
ok: true,
|
|
267
|
+
approvedIds,
|
|
268
|
+
messages,
|
|
269
|
+
errors: [],
|
|
270
|
+
compareUrl,
|
|
271
|
+
recompiledL0,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
async function approveTeamBatch(config, root, teamProps, homeDir, overrideMode) {
|
|
275
|
+
const defaultBranch = root.defaultBranch || getDefaultBranch(root.path);
|
|
276
|
+
const submitMode = overrideMode || root.submitMode || 'auto';
|
|
277
|
+
const branchName = teamProps.length === 1
|
|
278
|
+
? `memory/proposal-${teamProps[0].id}`
|
|
279
|
+
: `memory/proposal-${teamProps[0].id}-batch`;
|
|
280
|
+
let worktreeDir = null;
|
|
281
|
+
try {
|
|
282
|
+
worktreeDir = createThrowawayWorktree(root.path, defaultBranch);
|
|
283
|
+
const touched = [];
|
|
284
|
+
for (const p of teamProps) {
|
|
285
|
+
touched.push(...applyProposalFilesToDir(worktreeDir, '', p));
|
|
286
|
+
}
|
|
287
|
+
const commitMsg = teamProps.length === 1
|
|
288
|
+
? `memory(${teamProps[0].action}): ${teamProps[0].entryId} [${teamProps[0].id}]`
|
|
289
|
+
: `memory(batch): approve ${teamProps.length} proposals (${teamProps.map((p) => p.id).join(', ')})`;
|
|
290
|
+
gitCommitFiles(worktreeDir, touched, commitMsg);
|
|
291
|
+
const remoteUrl = root.remote || getRemoteUrl(root.path);
|
|
292
|
+
if (submitMode === 'auto') {
|
|
293
|
+
const directPush = gitSync(['-C', worktreeDir, 'push', 'origin', `HEAD:${defaultBranch}`]);
|
|
294
|
+
if (directPush.ok) {
|
|
295
|
+
for (const p of teamProps) {
|
|
296
|
+
deleteProposal(p, homeDir);
|
|
297
|
+
}
|
|
298
|
+
// Sync serving clone & recompile L0
|
|
299
|
+
const pull = await gitPullFfOnly(root.path, 5000);
|
|
300
|
+
let recompiledL0 = false;
|
|
301
|
+
if (pull.ok) {
|
|
302
|
+
const comp = compileGlobalL0(config, { homeDir });
|
|
303
|
+
if (comp.ok)
|
|
304
|
+
recompiledL0 = true;
|
|
305
|
+
}
|
|
306
|
+
return {
|
|
307
|
+
ok: true,
|
|
308
|
+
approvedIds: teamProps.map((p) => p.id),
|
|
309
|
+
messages: [
|
|
310
|
+
`Pushed ${teamProps.length} team proposal(s) directly to origin/${defaultBranch} and synced local L0.`,
|
|
311
|
+
],
|
|
312
|
+
errors: [],
|
|
313
|
+
recompiledL0,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
if (!isBranchProtectionRejection(directPush.stderr)) {
|
|
317
|
+
markPushFailed(teamProps, directPush.stderr.trim() || 'git push failed', homeDir);
|
|
318
|
+
return {
|
|
319
|
+
ok: false,
|
|
320
|
+
approvedIds: [],
|
|
321
|
+
messages: [],
|
|
322
|
+
errors: [`Team push failed: ${directPush.stderr.trim() || 'unknown remote error'}`],
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
// Fall through to PR branch push on branch protection rejection
|
|
326
|
+
}
|
|
327
|
+
const prPush = gitSync([
|
|
328
|
+
'-C',
|
|
329
|
+
worktreeDir,
|
|
330
|
+
'push',
|
|
331
|
+
'origin',
|
|
332
|
+
`HEAD:refs/heads/${branchName}`,
|
|
333
|
+
]);
|
|
334
|
+
if (!prPush.ok) {
|
|
335
|
+
markPushFailed(teamProps, prPush.stderr.trim() || 'git push branch failed', homeDir);
|
|
336
|
+
return {
|
|
337
|
+
ok: false,
|
|
338
|
+
approvedIds: [],
|
|
339
|
+
messages: [],
|
|
340
|
+
errors: [`Team PR branch push failed: ${prPush.stderr.trim() || 'unknown remote error'}`],
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
const compareUrl = buildCompareUrl(remoteUrl, defaultBranch, branchName);
|
|
344
|
+
for (const p of teamProps) {
|
|
345
|
+
deleteProposal(p, homeDir);
|
|
346
|
+
}
|
|
347
|
+
return {
|
|
348
|
+
ok: true,
|
|
349
|
+
approvedIds: teamProps.map((p) => p.id),
|
|
350
|
+
messages: [
|
|
351
|
+
`Pushed branch ${branchName} to remote.`,
|
|
352
|
+
`Create PR: ${compareUrl}`,
|
|
353
|
+
],
|
|
354
|
+
errors: [],
|
|
355
|
+
compareUrl,
|
|
356
|
+
recompiledL0: false,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
361
|
+
markPushFailed(teamProps, msg, homeDir);
|
|
362
|
+
return {
|
|
363
|
+
ok: false,
|
|
364
|
+
approvedIds: [],
|
|
365
|
+
messages: [],
|
|
366
|
+
errors: [`Team approval failed: ${msg}`],
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
finally {
|
|
370
|
+
if (worktreeDir) {
|
|
371
|
+
removeThrowawayWorktree(root.path, worktreeDir);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function markPushFailed(proposals, error, homeDir) {
|
|
376
|
+
withStateLock(() => {
|
|
377
|
+
for (const p of proposals) {
|
|
378
|
+
p.status = 'push_failed';
|
|
379
|
+
p.error = error;
|
|
380
|
+
saveProposal(p, homeDir);
|
|
381
|
+
}
|
|
382
|
+
}, homeDir);
|
|
383
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { MemoryEntry, ProjectRootResolution, Scope, UserConfig, ValidationError } from './types.js';
|
|
2
|
+
export declare const PROJECT_MEMORY_REL_DIR = ".faber/memory";
|
|
3
|
+
export interface LoadedScopeResult {
|
|
4
|
+
scope: Scope;
|
|
5
|
+
rootPath: string;
|
|
6
|
+
headSha: string | null;
|
|
7
|
+
entries: MemoryEntry[];
|
|
8
|
+
errors: ValidationError[];
|
|
9
|
+
uncommittedFiles: string[];
|
|
10
|
+
}
|
|
11
|
+
export declare function resolveProjectRoot(mcpRoots?: string[], cwd?: string): ProjectRootResolution;
|
|
12
|
+
export declare function loadScopeFromHead(repoDir: string, scope: Scope, subPath?: string): LoadedScopeResult;
|
|
13
|
+
export interface LoadedAllScopes {
|
|
14
|
+
team?: LoadedScopeResult;
|
|
15
|
+
personal?: LoadedScopeResult;
|
|
16
|
+
project?: LoadedScopeResult;
|
|
17
|
+
projectResolution: ProjectRootResolution;
|
|
18
|
+
allEntries: MemoryEntry[];
|
|
19
|
+
activeEntries: MemoryEntry[];
|
|
20
|
+
shadowWarnings: string[];
|
|
21
|
+
uncommittedWarnings: string[];
|
|
22
|
+
}
|
|
23
|
+
export declare function loadAllScopes(config: UserConfig, projectResolution: ProjectRootResolution): LoadedAllScopes;
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { extractLinks, parseMarkdownWithFrontmatter, validateFrontmatter, } from './frontmatter.js';
|
|
5
|
+
import { findGitRoot, getHeadSha, getUncommittedFiles, isGitRepo, listHeadMarkdownFiles, readHeadFile, } from './git.js';
|
|
6
|
+
export const PROJECT_MEMORY_REL_DIR = '.faber/memory';
|
|
7
|
+
export function resolveProjectRoot(mcpRoots, cwd = process.cwd()) {
|
|
8
|
+
if (mcpRoots && mcpRoots.length > 0) {
|
|
9
|
+
for (const rawRoot of mcpRoots) {
|
|
10
|
+
const fsPath = rawRoot.startsWith('file://') ? safeFileUriToPath(rawRoot) : rawRoot;
|
|
11
|
+
if (!fsPath)
|
|
12
|
+
continue;
|
|
13
|
+
const memDir = path.join(fsPath, PROJECT_MEMORY_REL_DIR);
|
|
14
|
+
if (fs.existsSync(memDir) && fs.statSync(memDir).isDirectory()) {
|
|
15
|
+
return { source: 'mcp-roots', projectRoot: fsPath, memoryDir: memDir };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const gitRoot = findGitRoot(cwd);
|
|
20
|
+
if (gitRoot) {
|
|
21
|
+
const memDir = path.join(gitRoot, PROJECT_MEMORY_REL_DIR);
|
|
22
|
+
if (fs.existsSync(memDir) && fs.statSync(memDir).isDirectory()) {
|
|
23
|
+
return { source: 'cwd', projectRoot: gitRoot, memoryDir: memDir };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return { source: 'none' };
|
|
27
|
+
}
|
|
28
|
+
function safeFileUriToPath(uri) {
|
|
29
|
+
try {
|
|
30
|
+
return fileURLToPath(uri);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function loadScopeFromHead(repoDir, scope, subPath = '') {
|
|
37
|
+
if (!fs.existsSync(repoDir) || !isGitRepo(repoDir)) {
|
|
38
|
+
return {
|
|
39
|
+
scope,
|
|
40
|
+
rootPath: repoDir,
|
|
41
|
+
headSha: null,
|
|
42
|
+
entries: [],
|
|
43
|
+
errors: [],
|
|
44
|
+
uncommittedFiles: [],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const headSha = getHeadSha(repoDir);
|
|
48
|
+
const uncommittedFiles = getUncommittedFiles(repoDir, subPath);
|
|
49
|
+
if (!headSha) {
|
|
50
|
+
return {
|
|
51
|
+
scope,
|
|
52
|
+
rootPath: repoDir,
|
|
53
|
+
headSha: null,
|
|
54
|
+
entries: [],
|
|
55
|
+
errors: [],
|
|
56
|
+
uncommittedFiles,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const mdFiles = listHeadMarkdownFiles(repoDir, subPath);
|
|
60
|
+
const entries = [];
|
|
61
|
+
const errors = [];
|
|
62
|
+
for (const relPath of mdFiles) {
|
|
63
|
+
const base = path.basename(relPath);
|
|
64
|
+
if (base.toLowerCase() === 'readme.md') {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const rawContent = readHeadFile(repoDir, relPath);
|
|
68
|
+
if (rawContent === null)
|
|
69
|
+
continue;
|
|
70
|
+
const parsed = parseMarkdownWithFrontmatter(rawContent);
|
|
71
|
+
if (!parsed.hasFrontmatter) {
|
|
72
|
+
errors.push({
|
|
73
|
+
scope,
|
|
74
|
+
filePath: relPath,
|
|
75
|
+
message: 'missing YAML frontmatter (required fields: summary, type)',
|
|
76
|
+
});
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const validated = validateFrontmatter(parsed.rawFrontmatter, scope);
|
|
80
|
+
if (validated.errors.length > 0 || !validated.frontmatter) {
|
|
81
|
+
for (const msg of validated.errors) {
|
|
82
|
+
errors.push({ scope, filePath: relPath, message: msg });
|
|
83
|
+
}
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const id = base.replace(/\.md$/i, '');
|
|
87
|
+
entries.push({
|
|
88
|
+
id,
|
|
89
|
+
scope,
|
|
90
|
+
filePath: relPath,
|
|
91
|
+
...validated.frontmatter,
|
|
92
|
+
body: parsed.body.trim(),
|
|
93
|
+
links: extractLinks(parsed.body),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
scope,
|
|
98
|
+
rootPath: repoDir,
|
|
99
|
+
headSha,
|
|
100
|
+
entries,
|
|
101
|
+
errors,
|
|
102
|
+
uncommittedFiles,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export function loadAllScopes(config, projectResolution) {
|
|
106
|
+
const team = config.roots.team
|
|
107
|
+
? loadScopeFromHead(config.roots.team.path, 'team')
|
|
108
|
+
: undefined;
|
|
109
|
+
const personal = config.roots.personal
|
|
110
|
+
? loadScopeFromHead(config.roots.personal.path, 'personal')
|
|
111
|
+
: undefined;
|
|
112
|
+
const project = projectResolution.source !== 'none' && projectResolution.projectRoot
|
|
113
|
+
? loadScopeFromHead(projectResolution.projectRoot, 'project', PROJECT_MEMORY_REL_DIR)
|
|
114
|
+
: undefined;
|
|
115
|
+
const globalIds = new Map();
|
|
116
|
+
for (const e of team?.entries || []) {
|
|
117
|
+
if (e.status === 'active')
|
|
118
|
+
globalIds.set(e.id, 'team');
|
|
119
|
+
}
|
|
120
|
+
for (const e of personal?.entries || []) {
|
|
121
|
+
if (e.status === 'active')
|
|
122
|
+
globalIds.set(e.id, 'personal');
|
|
123
|
+
}
|
|
124
|
+
const shadowWarnings = [];
|
|
125
|
+
if (project) {
|
|
126
|
+
for (const e of project.entries) {
|
|
127
|
+
if (e.status === 'active' && globalIds.has(e.id)) {
|
|
128
|
+
const globalScope = globalIds.get(e.id);
|
|
129
|
+
e.shadowed = true;
|
|
130
|
+
e.shadowWarning = `Project entry "${e.id}" collides with active ${globalScope} entry "${e.id}" and is marked shadowed.`;
|
|
131
|
+
shadowWarnings.push(e.shadowWarning);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const allEntries = [
|
|
136
|
+
...(team?.entries || []),
|
|
137
|
+
...(personal?.entries || []),
|
|
138
|
+
...(project?.entries || []),
|
|
139
|
+
];
|
|
140
|
+
const activeEntries = allEntries.filter((e) => e.status === 'active');
|
|
141
|
+
const uncommittedWarnings = [];
|
|
142
|
+
if (team && team.uncommittedFiles.length > 0) {
|
|
143
|
+
uncommittedWarnings.push(`Uncommitted edits in team memory root (${team.uncommittedFiles.join(', ')}); serving committed HEAD only.`);
|
|
144
|
+
}
|
|
145
|
+
if (personal && personal.uncommittedFiles.length > 0) {
|
|
146
|
+
uncommittedWarnings.push(`Uncommitted edits in personal memory root (${personal.uncommittedFiles.join(', ')}); serving committed HEAD only.`);
|
|
147
|
+
}
|
|
148
|
+
if (project && project.uncommittedFiles.length > 0) {
|
|
149
|
+
uncommittedWarnings.push(`Uncommitted edits in project memory (${project.uncommittedFiles.join(', ')}); run "git add ${project.uncommittedFiles.join(' ')} && git commit" to activate.`);
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
team,
|
|
153
|
+
personal,
|
|
154
|
+
project,
|
|
155
|
+
projectResolution,
|
|
156
|
+
allEntries,
|
|
157
|
+
activeEntries,
|
|
158
|
+
shadowWarnings,
|
|
159
|
+
uncommittedWarnings,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { UserConfig } from './types.js';
|
|
2
|
+
export interface SyncResult {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
advanced: boolean;
|
|
5
|
+
warnings: string[];
|
|
6
|
+
errors: string[];
|
|
7
|
+
recompiled: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function syncAllRoots(config: UserConfig, options?: {
|
|
10
|
+
homeDir?: string;
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
recompile?: boolean;
|
|
13
|
+
}): Promise<SyncResult>;
|
package/dist/src/sync.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { getHomeDir } from './config.js';
|
|
2
|
+
import { compileGlobalL0 } from './compiler.js';
|
|
3
|
+
import { getHeadSha, gitPullFfOnly, hasRemote } from './git.js';
|
|
4
|
+
export async function syncAllRoots(config, options = {}) {
|
|
5
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
6
|
+
const timeoutMs = options.timeoutMs ?? 5000;
|
|
7
|
+
const shouldRecompile = options.recompile !== false;
|
|
8
|
+
const warnings = [];
|
|
9
|
+
const errors = [];
|
|
10
|
+
let advanced = false;
|
|
11
|
+
const roots = [config.roots.team, config.roots.personal].filter(Boolean);
|
|
12
|
+
for (const root of roots) {
|
|
13
|
+
if (!root)
|
|
14
|
+
continue;
|
|
15
|
+
if (!hasRemote(root.path))
|
|
16
|
+
continue;
|
|
17
|
+
const beforeSha = getHeadSha(root.path);
|
|
18
|
+
const pull = await gitPullFfOnly(root.path, timeoutMs);
|
|
19
|
+
if (!pull.ok) {
|
|
20
|
+
const msg = `[${root.scope}] ${pull.error || 'pull failed'}`;
|
|
21
|
+
errors.push(msg);
|
|
22
|
+
warnings.push(msg);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const afterSha = getHeadSha(root.path);
|
|
26
|
+
if (beforeSha !== afterSha) {
|
|
27
|
+
advanced = true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
let recompiled = false;
|
|
31
|
+
if (shouldRecompile && errors.length === 0) {
|
|
32
|
+
const comp = compileGlobalL0(config, { homeDir });
|
|
33
|
+
if (comp.ok) {
|
|
34
|
+
recompiled = true;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
errors.push(...comp.errors);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
ok: errors.length === 0,
|
|
42
|
+
advanced,
|
|
43
|
+
warnings,
|
|
44
|
+
errors,
|
|
45
|
+
recompiled,
|
|
46
|
+
};
|
|
47
|
+
}
|