@pal-code/memory 0.0.0-stage → 0.0.19
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/README.md +125 -2
- package/package.json +20 -4
- package/src/config.test.ts +107 -0
- package/src/config.ts +69 -0
- package/src/frontmatter.test.ts +87 -0
- package/src/frontmatter.ts +124 -0
- package/src/index.test.ts +349 -0
- package/src/index.ts +313 -0
- package/src/store.test.ts +336 -0
- package/src/store.ts +347 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Store tests run against a real temp git repo, because freshness is defined by
|
|
3
|
+
* git — mocking it would test nothing that matters.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import {afterEach, beforeEach, describe, expect, test} from 'bun:test';
|
|
7
|
+
import {execFileSync} from 'node:child_process';
|
|
8
|
+
import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';
|
|
9
|
+
import {tmpdir} from 'node:os';
|
|
10
|
+
import {join} from 'node:path';
|
|
11
|
+
|
|
12
|
+
import {checkFreshness, headSha, listDocs, saveDoc, searchDocs} from './store.js';
|
|
13
|
+
import type {MemorySettings} from './config.js';
|
|
14
|
+
|
|
15
|
+
const SETTINGS: MemorySettings = {dir: '.memory', write: true, staleAfterDays: 90};
|
|
16
|
+
|
|
17
|
+
let repo: string;
|
|
18
|
+
|
|
19
|
+
function git(args: string[]) {
|
|
20
|
+
return execFileSync('git', args, {
|
|
21
|
+
cwd: repo,
|
|
22
|
+
encoding: 'utf-8',
|
|
23
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function commit(message: string): string {
|
|
28
|
+
git(['add', '-A']);
|
|
29
|
+
git(['-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-m', message, '--no-gpg-sign']);
|
|
30
|
+
return git(['rev-parse', 'HEAD']).trim();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function writeDoc(rel: string, content: string) {
|
|
34
|
+
const path = join(repo, '.memory', rel);
|
|
35
|
+
mkdirSync(join(path, '..'), {recursive: true});
|
|
36
|
+
writeFileSync(path, content);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
beforeEach(() => {
|
|
40
|
+
repo = mkdtempSync(join(tmpdir(), 'pal-memory-'));
|
|
41
|
+
git(['init', '-q']);
|
|
42
|
+
mkdirSync(join(repo, '.memory'), {recursive: true});
|
|
43
|
+
mkdirSync(join(repo, 'db', 'migrations'), {recursive: true});
|
|
44
|
+
writeFileSync(join(repo, 'db', 'migrations', '001.sql'), 'CREATE TABLE a (id int);');
|
|
45
|
+
commit('init');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
afterEach(() => {
|
|
49
|
+
rmSync(repo, {recursive: true, force: true});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('listDocs', () => {
|
|
53
|
+
test('finds markdown docs and skips underscore templates', () => {
|
|
54
|
+
writeDoc('index.md', '# index');
|
|
55
|
+
writeDoc('schemas/_TEMPLATE.md', '# template');
|
|
56
|
+
writeDoc('schemas/core.md', '---\nkind: schema\n---\n# Core schema');
|
|
57
|
+
|
|
58
|
+
const ids = listDocs(SETTINGS, repo).map((d) => d.id);
|
|
59
|
+
// index.md is a root-level meta doc: excluded as index noise, not knowledge.
|
|
60
|
+
expect(ids).toEqual(['schemas/core.md']);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('derives kind from the directory when no kind field exists', () => {
|
|
64
|
+
writeDoc('playbooks/fix.md', '---\ncovers: db/**\n---\n# Fix');
|
|
65
|
+
const doc = listDocs(SETTINGS, repo).find((d) => d.id === 'playbooks/fix.md');
|
|
66
|
+
expect(doc?.kind).toBe('playbook');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('uses the H1 as the title, falling back to the file name', () => {
|
|
70
|
+
writeDoc('schemas/core.md', '---\n---\n# The Core Schema\ntext');
|
|
71
|
+
writeDoc('schemas/other.md', 'no heading here');
|
|
72
|
+
const docs = listDocs(SETTINGS, repo);
|
|
73
|
+
expect(docs.find((d) => d.id === 'schemas/core.md')?.title).toBe('The Core Schema');
|
|
74
|
+
expect(docs.find((d) => d.id === 'schemas/other.md')?.title).toBe('other.md');
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('is empty for a missing directory instead of throwing', () => {
|
|
78
|
+
expect(listDocs({...SETTINGS, dir: 'nope'}, repo)).toEqual([]);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('checkFreshness', () => {
|
|
83
|
+
test('fresh when covered paths are unchanged since verified_at', () => {
|
|
84
|
+
const sha = headSha(repo)!;
|
|
85
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
86
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
87
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('fresh');
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('stale once a covered file changes, and reports which', () => {
|
|
91
|
+
const sha = headSha(repo)!;
|
|
92
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
93
|
+
writeFileSync(join(repo, 'db', 'migrations', '002.sql'), 'ALTER TABLE a ADD b int;');
|
|
94
|
+
commit('add migration');
|
|
95
|
+
|
|
96
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
97
|
+
const fresh = checkFreshness(doc, SETTINGS, repo);
|
|
98
|
+
expect(fresh.status).toBe('stale');
|
|
99
|
+
expect(fresh.changed).toEqual(['db/migrations/002.sql']);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('a brand-new UNTRACKED migration in a covered dir is advisory, not stale', () => {
|
|
103
|
+
// Untracked = the work is not committed yet, so the codebase has not actually
|
|
104
|
+
// moved on. It must not read as STALE or a doc written this session would be
|
|
105
|
+
// invalidated instantly — but it is surfaced as a note.
|
|
106
|
+
const sha = headSha(repo)!;
|
|
107
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
108
|
+
writeFileSync(join(repo, 'db', 'migrations', '003.sql'), 'ALTER TABLE a ADD c int;');
|
|
109
|
+
|
|
110
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
111
|
+
const fresh = checkFreshness(doc, SETTINGS, repo);
|
|
112
|
+
expect(fresh.status).toBe('fresh');
|
|
113
|
+
expect(fresh.uncommitted).toContain('db/migrations/003.sql');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
test('an uncommitted edit to a covered file is advisory, not stale', () => {
|
|
117
|
+
const sha = headSha(repo)!;
|
|
118
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
119
|
+
writeFileSync(join(repo, 'db', 'migrations', '001.sql'), 'CREATE TABLE a (id bigint);');
|
|
120
|
+
|
|
121
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
122
|
+
const fresh = checkFreshness(doc, SETTINGS, repo);
|
|
123
|
+
expect(fresh.status).toBe('fresh');
|
|
124
|
+
expect(fresh.uncommitted).toContain('db/migrations/001.sql');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('a doc written this session is fresh, never stale on its own write', () => {
|
|
128
|
+
// The exact bug found in real use: memory_save stamps HEAD, then the covering
|
|
129
|
+
// paths show as modified because the files ARE the pending work.
|
|
130
|
+
const sha = headSha(repo)!;
|
|
131
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
132
|
+
writeFileSync(join(repo, 'db', 'migrations', '004.sql'), '-- new');
|
|
133
|
+
|
|
134
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
135
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('fresh');
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
test('once the change is COMMITTED, the same doc goes stale', () => {
|
|
139
|
+
const sha = headSha(repo)!;
|
|
140
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
141
|
+
writeFileSync(join(repo, 'db', 'migrations', '005.sql'), '-- committed');
|
|
142
|
+
commit('migration 005');
|
|
143
|
+
|
|
144
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
145
|
+
const fresh = checkFreshness(doc, SETTINGS, repo);
|
|
146
|
+
expect(fresh.status).toBe('stale');
|
|
147
|
+
expect(fresh.changed).toContain('db/migrations/005.sql');
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('uncommitted paths are reported intact, not truncated', () => {
|
|
151
|
+
// Porcelain lines are `XY PATH`; a fixed-width slice ate the first character
|
|
152
|
+
// and reported "ackage.json". Guard the parse.
|
|
153
|
+
const sha = headSha(repo)!;
|
|
154
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
155
|
+
writeFileSync(join(repo, 'db', 'migrations', '001.sql'), '-- edited');
|
|
156
|
+
|
|
157
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
158
|
+
expect(checkFreshness(doc, SETTINGS, repo).uncommitted).toEqual(['db/migrations/001.sql']);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('a new doc inside .memory does not make covered docs stale', () => {
|
|
162
|
+
// Writing to .memory must not look like drift in the code it documents.
|
|
163
|
+
const sha = headSha(repo)!;
|
|
164
|
+
writeDoc(
|
|
165
|
+
'schemas/core.md',
|
|
166
|
+
`---\ncovers: db/migrations/**, .memory/**\nverified_at: ${sha}\n---\n# Core`,
|
|
167
|
+
);
|
|
168
|
+
writeDoc('runs/2026-01-01-x/intent.md', '---\nkind: run\n---\n# Run');
|
|
169
|
+
|
|
170
|
+
const doc = listDocs(SETTINGS, repo).find((d) => d.id === 'schemas/core.md')!;
|
|
171
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('fresh');
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
test('stays fresh when an UNRELATED file changes', () => {
|
|
175
|
+
const sha = headSha(repo)!;
|
|
176
|
+
writeDoc('schemas/core.md', `---\ncovers: db/migrations/**\nverified_at: ${sha}\n---\n# Core`);
|
|
177
|
+
writeFileSync(join(repo, 'unrelated.txt'), 'hi');
|
|
178
|
+
commit('unrelated');
|
|
179
|
+
|
|
180
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
181
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('fresh');
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('unknown when verified_at is absent', () => {
|
|
185
|
+
writeDoc('schemas/core.md', '---\ncovers: db/**\n---\n# Core');
|
|
186
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
187
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('unknown');
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test('unknown when verified_at is still the template placeholder', () => {
|
|
191
|
+
writeDoc('schemas/core.md', '---\ncovers: db/**\nverified_at: <git sha>\n---\n# Core');
|
|
192
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
193
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('unknown');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
test('uncheckable when verified_at is not a real commit', () => {
|
|
197
|
+
writeDoc('schemas/core.md', '---\ncovers: db/**\nverified_at: deadbeefdeadbeef\n---\n# Core');
|
|
198
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
199
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('uncheckable');
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
test('uncheckable without covers, since drift cannot be detected', () => {
|
|
203
|
+
const sha = headSha(repo)!;
|
|
204
|
+
writeDoc('schemas/core.md', `---\nverified_at: ${sha}\n---\n# Core`);
|
|
205
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
206
|
+
const fresh = checkFreshness(doc, SETTINGS, repo);
|
|
207
|
+
expect(fresh.status).toBe('uncheckable');
|
|
208
|
+
expect(fresh.reason).toContain('covers');
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
describe('searchDocs', () => {
|
|
213
|
+
test('matches body text and reports a line number', () => {
|
|
214
|
+
writeDoc('schemas/core.md', '---\n---\n# Core\n\nusers.deleted_at is soft-delete');
|
|
215
|
+
const hits = searchDocs(SETTINGS, 'soft-delete', repo);
|
|
216
|
+
expect(hits).toHaveLength(1);
|
|
217
|
+
expect(hits[0].doc.id).toBe('schemas/core.md');
|
|
218
|
+
// Numbered within the frontmatter-stripped body: '# Core' is line 1.
|
|
219
|
+
expect(hits[0].line).toBe(3);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('matches the title case-insensitively', () => {
|
|
223
|
+
writeDoc('playbooks/Backfill.md', '---\n---\n# Backfill Timezone');
|
|
224
|
+
expect(searchDocs(SETTINGS, 'backfill', repo)).toHaveLength(1);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test('an empty query matches nothing', () => {
|
|
228
|
+
writeDoc('schemas/core.md', '# Core');
|
|
229
|
+
expect(searchDocs(SETTINGS, ' ', repo)).toEqual([]);
|
|
230
|
+
});
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
describe('saveDoc', () => {
|
|
234
|
+
test('writes a doc and stamps HEAD when verified_at is omitted', () => {
|
|
235
|
+
const sha = headSha(repo)!;
|
|
236
|
+
const result = saveDoc(
|
|
237
|
+
SETTINGS,
|
|
238
|
+
{
|
|
239
|
+
id: 'schemas/core.md',
|
|
240
|
+
fields: {kind: 'schema'},
|
|
241
|
+
lists: {covers: ['db/**']},
|
|
242
|
+
body: '# Core\n\nnotes',
|
|
243
|
+
},
|
|
244
|
+
repo,
|
|
245
|
+
);
|
|
246
|
+
expect(result.ok).toBe(true);
|
|
247
|
+
|
|
248
|
+
const doc = listDocs(SETTINGS, repo)[0];
|
|
249
|
+
expect(doc.fields.verified_at).toBe(sha);
|
|
250
|
+
expect(doc.lists.covers).toEqual(['db/**']);
|
|
251
|
+
expect(doc.body).toContain('notes');
|
|
252
|
+
// The stamped doc is immediately trustworthy.
|
|
253
|
+
expect(checkFreshness(doc, SETTINGS, repo).status).toBe('fresh');
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test('refuses to clobber an existing doc without overwrite', () => {
|
|
257
|
+
const args = {
|
|
258
|
+
id: 'schemas/core.md',
|
|
259
|
+
fields: {kind: 'schema'},
|
|
260
|
+
lists: {covers: ['db/**']},
|
|
261
|
+
body: '# A',
|
|
262
|
+
};
|
|
263
|
+
expect(saveDoc(SETTINGS, args, repo).ok).toBe(true);
|
|
264
|
+
const second = saveDoc(SETTINGS, args, repo);
|
|
265
|
+
expect(second.ok).toBe(false);
|
|
266
|
+
if (!second.ok) expect(second.error).toContain('already exists');
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
test('overwrites when asked', () => {
|
|
270
|
+
const first = {
|
|
271
|
+
id: 'schemas/core.md',
|
|
272
|
+
fields: {kind: 'schema'},
|
|
273
|
+
lists: {covers: ['db/**']},
|
|
274
|
+
body: '# A',
|
|
275
|
+
};
|
|
276
|
+
saveDoc(SETTINGS, first, repo);
|
|
277
|
+
const second = saveDoc(SETTINGS, {...first, body: '# B'}, repo, true);
|
|
278
|
+
expect(second.ok).toBe(true);
|
|
279
|
+
expect(listDocs(SETTINGS, repo)[0].body).toContain('# B');
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
test('rejects path traversal out of the memory root', () => {
|
|
283
|
+
for (const id of ['../evil.md', 'schemas/../../evil.md', '/etc/evil.md']) {
|
|
284
|
+
const result = saveDoc(
|
|
285
|
+
SETTINGS,
|
|
286
|
+
{id, fields: {kind: 'schema'}, lists: {covers: ['db/**']}, body: '# x'},
|
|
287
|
+
repo,
|
|
288
|
+
);
|
|
289
|
+
expect(result.ok).toBe(false);
|
|
290
|
+
if (!result.ok) {
|
|
291
|
+
// Rejected by an explicit message, not by crashing on a weird path.
|
|
292
|
+
expect(result.error).toMatch(/refusing|must be relative/);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
test('containment is separator-agnostic, so it holds on macOS and Windows alike', () => {
|
|
298
|
+
// The check must not rely on the host separator: forward-slash traversal has
|
|
299
|
+
// to be rejected identically everywhere.
|
|
300
|
+
for (const id of ['schemas/../../../etc/x.md', 'a/../b/../../x.md']) {
|
|
301
|
+
const result = saveDoc(SETTINGS, {id, fields: {}, lists: {}, body: 'x'}, repo);
|
|
302
|
+
expect(result.ok).toBe(false);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
test('rejects a non-markdown id', () => {
|
|
307
|
+
const result = saveDoc(
|
|
308
|
+
SETTINGS,
|
|
309
|
+
{id: 'schemas/core.txt', fields: {}, lists: {}, body: 'x'},
|
|
310
|
+
repo,
|
|
311
|
+
);
|
|
312
|
+
expect(result.ok).toBe(false);
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
test('rejects reserved underscore ids', () => {
|
|
316
|
+
const result = saveDoc(
|
|
317
|
+
SETTINGS,
|
|
318
|
+
{id: 'schemas/_TEMPLATE.md', fields: {}, lists: {}, body: 'x'},
|
|
319
|
+
repo,
|
|
320
|
+
);
|
|
321
|
+
expect(result.ok).toBe(false);
|
|
322
|
+
if (!result.ok) expect(result.error).toContain('reserved');
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
test('creates nested directories', () => {
|
|
326
|
+
const result = saveDoc(
|
|
327
|
+
SETTINGS,
|
|
328
|
+
{id: 'runs/2026-01-01-backfill/intent.md', fields: {kind: 'run'}, lists: {}, body: '# Run'},
|
|
329
|
+
repo,
|
|
330
|
+
);
|
|
331
|
+
expect(result.ok).toBe(true);
|
|
332
|
+
expect(listDocs(SETTINGS, repo).map((d) => d.id)).toContain(
|
|
333
|
+
'runs/2026-01-01-backfill/intent.md',
|
|
334
|
+
);
|
|
335
|
+
});
|
|
336
|
+
});
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading and writing `.memory` docs.
|
|
3
|
+
*
|
|
4
|
+
* The invariant that makes this useful rather than dangerous: a doc is only
|
|
5
|
+
* trusted when its `covers` paths are provably unchanged since `verified_at`.
|
|
6
|
+
* Everything else is a hint. `lookup` enforces that mechanically — it never
|
|
7
|
+
* reports a doc as `fresh` on the author's word.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync} from 'node:fs';
|
|
11
|
+
import {execFileSync} from 'node:child_process';
|
|
12
|
+
import {basename, dirname, isAbsolute, join, relative} from 'node:path';
|
|
13
|
+
import type {Dirent} from 'node:fs';
|
|
14
|
+
|
|
15
|
+
import {parseMemoryFrontmatter, renderFrontmatter} from './frontmatter.js';
|
|
16
|
+
import type {MemorySettings} from './config.js';
|
|
17
|
+
import {memoryRoot} from './config.js';
|
|
18
|
+
|
|
19
|
+
export type MemoryKind = 'schema' | 'playbook' | 'run' | 'note' | (string & {});
|
|
20
|
+
|
|
21
|
+
export interface MemoryDoc {
|
|
22
|
+
/** Path relative to the memory root, forward-slashed. */
|
|
23
|
+
id: string;
|
|
24
|
+
kind: MemoryKind;
|
|
25
|
+
title: string;
|
|
26
|
+
fields: Record<string, string>;
|
|
27
|
+
lists: Record<string, string[]>;
|
|
28
|
+
body: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Staleness verdict for one doc. */
|
|
32
|
+
export interface Freshness {
|
|
33
|
+
status: 'fresh' | 'stale' | 'unknown' | 'uncheckable';
|
|
34
|
+
/** Why it is not fresh — shown to the model so it can act on it. */
|
|
35
|
+
reason: string;
|
|
36
|
+
/** Committed drift since `verified_at`: the authoritative staleness signal. */
|
|
37
|
+
changed: string[];
|
|
38
|
+
/** Uncommitted/untracked changes in covered paths — advisory, not staleness. */
|
|
39
|
+
uncommitted: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const KIND_DIRS: Array<{prefix: string; kind: MemoryKind}> = [
|
|
43
|
+
{prefix: 'schemas', kind: 'schema'},
|
|
44
|
+
{prefix: 'playbooks', kind: 'playbook'},
|
|
45
|
+
{prefix: 'runs', kind: 'run'},
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
function kindFor(id: string): MemoryKind {
|
|
49
|
+
const head = id.split('/')[0];
|
|
50
|
+
// `head` is the filename for a root-level doc (index.md), not a folder.
|
|
51
|
+
if (!id.includes('/')) return 'other';
|
|
52
|
+
const known = KIND_DIRS.find((k) => k.prefix === head);
|
|
53
|
+
if (known) return known.kind;
|
|
54
|
+
// Any other folder is its own kind. Knowledge discovered mid-task gets
|
|
55
|
+
// recorded under whatever name the author chose; making the kind vocabulary
|
|
56
|
+
// closed here would mean those docs vanish from a kind filter.
|
|
57
|
+
return head;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Every `.md` file under the memory root (skips `_TEMPLATE`-prefixed paths). */
|
|
61
|
+
function walk(dir: string, root: string, out: string[]): void {
|
|
62
|
+
let entries: Dirent[];
|
|
63
|
+
try {
|
|
64
|
+
entries = readdirSync(dir, {withFileTypes: true});
|
|
65
|
+
} catch {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
if (entry.name.startsWith('_')) continue; // templates, not knowledge
|
|
70
|
+
const full = join(dir, entry.name);
|
|
71
|
+
if (entry.isDirectory()) {
|
|
72
|
+
walk(full, root, out);
|
|
73
|
+
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) {
|
|
74
|
+
out.push(relative(root, full).replace(/\\/g, '/'));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** First markdown H1 in the body, falling back to the file name. */
|
|
80
|
+
function titleOf(doc: {body: string; id: string}): string {
|
|
81
|
+
for (const line of doc.body.split(/\r?\n/)) {
|
|
82
|
+
const match = /^#\s+(.+)$/.exec(line.trim());
|
|
83
|
+
if (match) return match[1].trim();
|
|
84
|
+
}
|
|
85
|
+
return basename(doc.id);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function listDocs(settings: MemorySettings, cwd: string = process.cwd()): MemoryDoc[] {
|
|
89
|
+
const root = memoryRoot(settings, cwd);
|
|
90
|
+
const ids: string[] = [];
|
|
91
|
+
walk(root, root, ids);
|
|
92
|
+
|
|
93
|
+
const docs: MemoryDoc[] = [];
|
|
94
|
+
for (const id of ids.sort()) {
|
|
95
|
+
// Root-level meta docs describe the mechanism, not the repo. They are worth
|
|
96
|
+
// reading once by a human, but they are noise in a lookup index and would
|
|
97
|
+
// otherwise always show as "needing verification".
|
|
98
|
+
if (id === 'README.md' || id === 'index.md') continue;
|
|
99
|
+
const parsed = readDoc(root, id);
|
|
100
|
+
if (parsed) docs.push(parsed);
|
|
101
|
+
}
|
|
102
|
+
return docs;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function readDoc(root: string, id: string): MemoryDoc | null {
|
|
106
|
+
let text: string;
|
|
107
|
+
try {
|
|
108
|
+
text = readFileSync(join(root, id), 'utf-8');
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const fm = parseMemoryFrontmatter(text);
|
|
113
|
+
// A doc without frontmatter is still readable — it just can never be fresh.
|
|
114
|
+
const fields = fm?.fields ?? {};
|
|
115
|
+
const lists = fm?.lists ?? {};
|
|
116
|
+
const body = fm?.body ?? text;
|
|
117
|
+
const explicitKind = fields.kind?.trim();
|
|
118
|
+
return {
|
|
119
|
+
id,
|
|
120
|
+
// An explicit `kind` always wins — the author knows what a doc is. Only when
|
|
121
|
+
// it is absent do we infer one from the directory. The vocabulary is open on
|
|
122
|
+
// purpose: knowledge discovered during real work rarely fits a fixed taxonomy,
|
|
123
|
+
// and forcing it into a bucket produces either a lie or no doc at all.
|
|
124
|
+
kind: explicitKind !== undefined && explicitKind !== '' ? explicitKind : kindFor(id),
|
|
125
|
+
title: titleOf({body, id}),
|
|
126
|
+
fields,
|
|
127
|
+
lists,
|
|
128
|
+
body,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function git(cwd: string, args: string[]): string | null {
|
|
133
|
+
try {
|
|
134
|
+
return execFileSync('git', args, {
|
|
135
|
+
cwd,
|
|
136
|
+
encoding: 'utf-8',
|
|
137
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
138
|
+
timeout: 10_000,
|
|
139
|
+
}).trim();
|
|
140
|
+
} catch {
|
|
141
|
+
return null; // not a repo, or the sha is unresolvable
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Decide whether a doc may be trusted.
|
|
147
|
+
*
|
|
148
|
+
* `fresh` — `verified_at` resolves and no covered path changed since.
|
|
149
|
+
* `stale` — covered paths changed; the doc is a hint, re-verify by reading code.
|
|
150
|
+
* `unknown` — no `verified_at`, so freshness cannot be established.
|
|
151
|
+
* `uncheckable` — git can't answer (no repo, bad sha, no `covers`).
|
|
152
|
+
*/
|
|
153
|
+
export function checkFreshness(
|
|
154
|
+
doc: MemoryDoc,
|
|
155
|
+
settings: MemorySettings,
|
|
156
|
+
cwd: string = process.cwd(),
|
|
157
|
+
): Freshness {
|
|
158
|
+
const verifiedAt = doc.fields.verified_at?.trim();
|
|
159
|
+
if (!verifiedAt || verifiedAt.includes('<')) {
|
|
160
|
+
return {
|
|
161
|
+
status: 'unknown',
|
|
162
|
+
reason: 'no verified_at recorded',
|
|
163
|
+
changed: [],
|
|
164
|
+
uncommitted: [],
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (git(cwd, ['rev-parse', '--verify', '--quiet', `${verifiedAt}^{commit}`]) === null) {
|
|
169
|
+
return {
|
|
170
|
+
status: 'uncheckable',
|
|
171
|
+
reason: `verified_at "${verifiedAt}" is not a commit in this repo`,
|
|
172
|
+
changed: [],
|
|
173
|
+
uncommitted: [],
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const covers = (doc.lists.covers ?? []).filter((c) => c !== '');
|
|
178
|
+
if (covers.length === 0) {
|
|
179
|
+
return {
|
|
180
|
+
status: 'uncheckable',
|
|
181
|
+
reason: 'no covers paths, so drift cannot be detected',
|
|
182
|
+
changed: [],
|
|
183
|
+
uncommitted: [],
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Authoritative staleness: commits made since the doc was verified. `sha..HEAD`
|
|
188
|
+
// compares two commits, which is the question that matters — has the codebase
|
|
189
|
+
// actually moved on since someone checked?
|
|
190
|
+
const committed = git(cwd, ['diff', '--name-only', `${verifiedAt}..HEAD`, '--', ...covers]);
|
|
191
|
+
if (committed === null) {
|
|
192
|
+
return {
|
|
193
|
+
status: 'uncheckable',
|
|
194
|
+
reason: 'git diff failed',
|
|
195
|
+
changed: [],
|
|
196
|
+
uncommitted: [],
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
const committedFiles = committed.split(/\r?\n/).filter((f) => f !== '');
|
|
200
|
+
|
|
201
|
+
// Advisory: anything in the working tree that differs, including files that do
|
|
202
|
+
// not exist in HEAD at all. This is NOT staleness — an agent writing a doc
|
|
203
|
+
// mid-session would otherwise invalidate it instantly — but it is worth saying
|
|
204
|
+
// so the reader knows the tree is dirty where the doc applies.
|
|
205
|
+
const dirty = git(cwd, ['status', '--porcelain', '--', ...covers]);
|
|
206
|
+
const uncommitted = (dirty ?? '')
|
|
207
|
+
.split(/\r?\n/)
|
|
208
|
+
.filter((line) => line.trim() !== '')
|
|
209
|
+
// Porcelain is `XY PATH` — two status chars, a space, then the path. Slice by
|
|
210
|
+
// the actual separator rather than a fixed width; git can emit an extra
|
|
211
|
+
// leading space and a blind slice(3) silently truncates the first path.
|
|
212
|
+
.map((line) => line.replace(/^.{1,2}\s+/, '').trim())
|
|
213
|
+
.map((f) => f.replace(/^.* -> /, '')) // renames render as "old -> new"
|
|
214
|
+
.filter((f) => f !== '')
|
|
215
|
+
.filter((f) => !isMemoryPath(f, settings))
|
|
216
|
+
.filter((f) => !committedFiles.includes(f));
|
|
217
|
+
|
|
218
|
+
if (committedFiles.length === 0) {
|
|
219
|
+
const reason =
|
|
220
|
+
uncommitted.length === 0
|
|
221
|
+
? `covered paths unchanged since ${verifiedAt.slice(0, 8)}`
|
|
222
|
+
: `no commits since ${verifiedAt.slice(0, 8)} (working tree has uncommitted changes)`;
|
|
223
|
+
return {status: 'fresh', reason, changed: [], uncommitted};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
status: 'stale',
|
|
228
|
+
reason: `${committedFiles.length} covered file(s) changed since ${verifiedAt.slice(0, 8)}`,
|
|
229
|
+
changed: committedFiles.slice(0, 20),
|
|
230
|
+
uncommitted,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** True when a repo-relative path lives inside the memory directory itself. */
|
|
235
|
+
function isMemoryPath(relPath: string, settings: MemorySettings): boolean {
|
|
236
|
+
const memoryDir = settings.dir.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
237
|
+
return relPath.replace(/\\/g, '/').startsWith(`${memoryDir}/`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Current HEAD sha, or null outside a repo. */
|
|
241
|
+
export function headSha(cwd: string = process.cwd()): string | null {
|
|
242
|
+
return git(cwd, ['rev-parse', 'HEAD']);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface SearchHit {
|
|
246
|
+
doc: MemoryDoc;
|
|
247
|
+
/** 1-based line number of the first matching line. */
|
|
248
|
+
line: number;
|
|
249
|
+
snippet: string;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Case-insensitive substring search across titles and bodies. */
|
|
253
|
+
export function searchDocs(
|
|
254
|
+
settings: MemorySettings,
|
|
255
|
+
query: string,
|
|
256
|
+
cwd: string = process.cwd(),
|
|
257
|
+
limit = 10,
|
|
258
|
+
): SearchHit[] {
|
|
259
|
+
const needle = query.toLowerCase();
|
|
260
|
+
if (needle.trim() === '') return [];
|
|
261
|
+
|
|
262
|
+
const hits: SearchHit[] = [];
|
|
263
|
+
for (const doc of listDocs(settings, cwd)) {
|
|
264
|
+
if (doc.title.toLowerCase().includes(needle) || doc.id.toLowerCase().includes(needle)) {
|
|
265
|
+
hits.push({doc, line: 1, snippet: doc.title});
|
|
266
|
+
if (hits.length >= limit) break;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const lines = doc.body.split(/\r?\n/);
|
|
270
|
+
for (let i = 0; i < lines.length; i++) {
|
|
271
|
+
if (lines[i].toLowerCase().includes(needle)) {
|
|
272
|
+
hits.push({doc, line: i + 1, snippet: lines[i].trim().slice(0, 200)});
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (hits.length >= limit) break;
|
|
277
|
+
}
|
|
278
|
+
return hits;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Write a doc back, refusing to clobber one that exists unless `overwrite`.
|
|
283
|
+
*
|
|
284
|
+
* Returns a *relative* path so the model sees something it can quote later.
|
|
285
|
+
*/
|
|
286
|
+
export function saveDoc(
|
|
287
|
+
settings: MemorySettings,
|
|
288
|
+
input: {
|
|
289
|
+
id: string;
|
|
290
|
+
fields: Record<string, string | number | boolean | null>;
|
|
291
|
+
lists: Record<string, string[]>;
|
|
292
|
+
body: string;
|
|
293
|
+
},
|
|
294
|
+
cwd: string = process.cwd(),
|
|
295
|
+
overwrite = false,
|
|
296
|
+
): {ok: true; id: string} | {ok: false; error: string} {
|
|
297
|
+
const root = memoryRoot(settings, cwd);
|
|
298
|
+
// An absolute path is rejected rather than silently relativised: rewriting
|
|
299
|
+
// "/etc/x.md" into ".memory/etc/x.md" is contained, but it hides a caller
|
|
300
|
+
// mistake instead of surfacing it.
|
|
301
|
+
if (isAbsolute(input.id)) {
|
|
302
|
+
return {ok: false, error: `id must be relative to ${settings.dir}, got "${input.id}"`};
|
|
303
|
+
}
|
|
304
|
+
const id = input.id.replace(/\\/g, '/').replace(/^\/+/, '');
|
|
305
|
+
|
|
306
|
+
// Containment: never escape the memory root, never write outside it.
|
|
307
|
+
if (id === '' || id.split('/').some((seg) => seg === '..' || seg === '')) {
|
|
308
|
+
return {ok: false, error: `refusing suspicious id "${input.id}"`};
|
|
309
|
+
}
|
|
310
|
+
if (!id.toLowerCase().endsWith('.md')) {
|
|
311
|
+
return {ok: false, error: 'id must end with .md'};
|
|
312
|
+
}
|
|
313
|
+
if (basename(id).startsWith('_')) {
|
|
314
|
+
return {ok: false, error: 'ids starting with "_" are reserved for templates'};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const target = join(root, id);
|
|
318
|
+
// Containment check that does not depend on the platform separator: split the
|
|
319
|
+
// relative path and reject any `..` segment. Avoids hand-built '\\' vs '/'
|
|
320
|
+
// comparisons that only hold on one OS.
|
|
321
|
+
const relToRoot = relative(root, target);
|
|
322
|
+
if (relToRoot.startsWith('..') || relToRoot.split(/[\\/]/).includes('..')) {
|
|
323
|
+
return {ok: false, error: `refusing to write outside ${settings.dir}`};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (existsSync(target) && !overwrite) {
|
|
327
|
+
return {ok: false, error: `${id} already exists — pass overwrite:true to update it`};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const fields = {...input.fields};
|
|
331
|
+
// Never let a write invent freshness: stamp whatever the caller verified at,
|
|
332
|
+
// or HEAD when they did not say.
|
|
333
|
+
if (!fields.verified_at) fields.verified_at = headSha(cwd) ?? null;
|
|
334
|
+
|
|
335
|
+
const content = `${renderFrontmatter(fields, input.lists)}\n\n${input.body.trim()}\n`;
|
|
336
|
+
try {
|
|
337
|
+
mkdirSync(dirname(target), {recursive: true});
|
|
338
|
+
writeFileSync(target, content, 'utf-8');
|
|
339
|
+
} catch (err) {
|
|
340
|
+
return {ok: false, error: err instanceof Error ? err.message : String(err)};
|
|
341
|
+
}
|
|
342
|
+
return {ok: true, id};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// probe
|
|
346
|
+
|
|
347
|
+
// probe
|