@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.
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Extension surface: availability gating and the two tool handlers.
3
+ *
4
+ * The load-bearing behaviour is that an unconfigured repo contributes NOTHING —
5
+ * no tools, no prompt — mirroring `@pal-code/jev`.
6
+ */
7
+
8
+ import {afterEach, beforeEach, describe, expect, test} from 'bun:test';
9
+ import {existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
10
+ import {tmpdir} from 'node:os';
11
+ import {join} from 'node:path';
12
+
13
+ import extension from './index.js';
14
+
15
+ let repo: string;
16
+ let previousCwd: string;
17
+
18
+ beforeEach(() => {
19
+ repo = mkdtempSync(join(tmpdir(), 'pal-memory-ext-'));
20
+ previousCwd = process.cwd();
21
+ process.chdir(repo);
22
+ });
23
+
24
+ afterEach(() => {
25
+ process.chdir(previousCwd);
26
+ rmSync(repo, {recursive: true, force: true});
27
+ });
28
+
29
+ function enableWrite() {
30
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: true}));
31
+ }
32
+
33
+ function seedMemory(body = '# index\n\nnotes') {
34
+ mkdirSync(join(repo, '.memory'), {recursive: true});
35
+ writeFileSync(join(repo, '.memory', 'index.md'), body);
36
+ }
37
+
38
+ describe('availability', () => {
39
+ test('an extension with no .memory directory and no write offers nothing', () => {
40
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: false}));
41
+ expect(extension.available).toBe(false);
42
+ expect(extension.tools).toEqual([]);
43
+ });
44
+
45
+ test('write enabled creates the directory on setup, making the tools available', async () => {
46
+ // The chicken-and-egg this fixes: `available` used to require the
47
+ // directory, nothing created it, so memory_save could never be reached to
48
+ // create it. setup() now does, before `available` is read.
49
+ enableWrite();
50
+ expect(existsSync(join(repo, '.memory'))).toBe(false);
51
+
52
+ await extension.setup?.();
53
+
54
+ expect(existsSync(join(repo, '.memory'))).toBe(true);
55
+ expect(extension.available).toBe(true);
56
+ expect(extension.tools.map((t) => t.function.name)).toEqual(['memory_lookup', 'memory_save']);
57
+ });
58
+
59
+ test('setup is a no-op when writing is disabled', async () => {
60
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: false}));
61
+
62
+ await extension.setup?.();
63
+
64
+ expect(existsSync(join(repo, '.memory'))).toBe(false);
65
+ expect(extension.available).toBe(false);
66
+ });
67
+
68
+ test('setup does not seed an index.md', async () => {
69
+ // A stub doc would list as a doc that can never be fresh.
70
+ enableWrite();
71
+ await extension.setup?.();
72
+
73
+ expect(existsSync(join(repo, '.memory', 'index.md'))).toBe(false);
74
+ });
75
+
76
+ test('setup respects a custom directory name', async () => {
77
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: true, dir: '.notes'}));
78
+
79
+ await extension.setup?.();
80
+
81
+ expect(existsSync(join(repo, '.notes'))).toBe(true);
82
+ expect(existsSync(join(repo, '.memory'))).toBe(false);
83
+ });
84
+
85
+ test('a .memory directory makes both tools available', () => {
86
+ seedMemory();
87
+ expect(extension.available).toBe(true);
88
+ expect(extension.tools.map((t) => t.function.name)).toEqual(['memory_lookup', 'memory_save']);
89
+ });
90
+
91
+ test('every advertised tool has a handler', () => {
92
+ seedMemory();
93
+ for (const tool of extension.tools) {
94
+ expect(typeof extension.handlers[tool.function.name]).toBe('function');
95
+ }
96
+ });
97
+
98
+ test('carries guidance naming both tools and the memory-first ordering', () => {
99
+ const prompt = extension.prompt ?? '';
100
+ expect(prompt).toContain('memory_lookup');
101
+ expect(prompt).toContain('memory_save');
102
+ expect(prompt).toContain('BEFORE you start exploring the codebase');
103
+ });
104
+
105
+ test('the trigger is situational, not gated on a task type', () => {
106
+ // Regression guard: an earlier version only fired "for schema, migrations,
107
+ // data fixes", which a model doing a normal feature task never matches.
108
+ const prompt = extension.prompt ?? '';
109
+ expect(prompt).toContain('BEFORE');
110
+ expect(prompt).toContain('on every');
111
+ expect(prompt).not.toContain('for a task about schema');
112
+ });
113
+
114
+ test('the lookup tool description tells the model to call it before exploring', () => {
115
+ seedMemory();
116
+ const lookup = extension.tools.find((t) => t.function.name === 'memory_lookup')!;
117
+ expect(lookup.function.description).toContain('BEFORE exploring');
118
+ expect(lookup.function.description).toContain('any task');
119
+ });
120
+
121
+ test('the prompt is withheld when memory is disabled and no directory exists', () => {
122
+ // Guard against a prompt that mentions tools the model cannot call.
123
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: false}));
124
+ expect(extension.available).toBe(false);
125
+ });
126
+ });
127
+
128
+ describe('memory_lookup', () => {
129
+ const lookup = (args: Record<string, unknown>) =>
130
+ extension.handlers.memory_lookup(args, {} as never);
131
+
132
+ test('explains an empty memory dir rather than pretending it has content', async () => {
133
+ mkdirSync(join(repo, '.memory'), {recursive: true});
134
+ const out = await lookup({});
135
+ expect(out).toContain('No knowledge recorded');
136
+ expect(out).toContain('memory_save');
137
+ });
138
+
139
+ test('index mode lists docs with staleness markers', async () => {
140
+ seedMemory();
141
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
142
+ writeFileSync(
143
+ join(repo, '.memory', 'schemas', 'core.md'),
144
+ '---\ncovers: db/**\n---\n# Core schema',
145
+ );
146
+ const out = await lookup({});
147
+ expect(out).toContain('schemas/core.md');
148
+ expect(out).toContain('Core schema');
149
+ // No verified_at → '?' marker, and the legend must explain it.
150
+ expect(out).toContain('?');
151
+ expect(out).toContain('needing verification');
152
+ });
153
+
154
+ test('reads one doc and labels it a hint when stale', async () => {
155
+ seedMemory();
156
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
157
+ writeFileSync(
158
+ join(repo, '.memory', 'schemas', 'core.md'),
159
+ '---\ncovers: db/**\nverified_at: deadbeef\n---\n# Core\n\nsoft delete on users',
160
+ );
161
+ const out = await lookup({id: 'schemas/core.md'});
162
+ expect(out).toContain('soft delete on users');
163
+ expect(out).toContain('HINT ONLY');
164
+ });
165
+
166
+ test('lists known ids when the requested id is missing', async () => {
167
+ seedMemory();
168
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
169
+ writeFileSync(join(repo, '.memory', 'schemas', 'core.md'), '---\n---\n# Core');
170
+ const out = await lookup({id: 'schemas/nope.md'});
171
+ expect(out).toContain('No doc "schemas/nope.md"');
172
+ // Points at the ids that DO exist, not at the excluded index.md.
173
+ expect(out).toContain('schemas/core.md');
174
+ });
175
+
176
+ test('searches across docs and reports doc:line', async () => {
177
+ seedMemory();
178
+ mkdirSync(join(repo, '.memory', 'playbooks'), {recursive: true});
179
+ writeFileSync(
180
+ join(repo, '.memory', 'playbooks', 'fix.md'),
181
+ '---\ncovers: db/**\n---\n# Fix\n\nbackfill the timezone column',
182
+ );
183
+ const out = await lookup({query: 'timezone'});
184
+ expect(out).toContain('playbooks/fix.md:');
185
+ expect(out).toContain('backfill the timezone column');
186
+ });
187
+
188
+ test('reports no matches without erroring', async () => {
189
+ seedMemory();
190
+ expect(await lookup({query: 'zzz-not-here'})).toContain('Nothing in .memory matches');
191
+ });
192
+
193
+ test('kind filter narrows the index', async () => {
194
+ seedMemory();
195
+ mkdirSync(join(repo, '.memory', 'playbooks'), {recursive: true});
196
+ writeFileSync(join(repo, '.memory', 'playbooks', 'fix.md'), '---\n---\n# Fix');
197
+ const out = await lookup({kind: 'playbook'});
198
+ expect(out).toContain('playbooks/fix.md');
199
+ // The doc list itself must exclude index.md (the hint line still names it).
200
+ expect(out.split('\n')[0]).toContain('1 doc(s)');
201
+ expect(out).not.toContain('index.md — ');
202
+ });
203
+
204
+ test('names the drifted file so the next agent knows where to look', async () => {
205
+ seedMemory();
206
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
207
+ writeFileSync(
208
+ join(repo, '.memory', 'schemas', 'core.md'),
209
+ '---\ncovers: db/**\nverified_at: deadbeef\n---\n# Core\n\nnotes',
210
+ );
211
+ const out = await lookup({id: 'schemas/core.md'});
212
+ expect(out).toContain('HINT ONLY');
213
+ expect(out).toContain('memory_save');
214
+ });
215
+
216
+ test('an invented kind is filterable, not rejected', async () => {
217
+ seedMemory();
218
+ mkdirSync(join(repo, '.memory', 'discoveries'), {recursive: true});
219
+ writeFileSync(
220
+ join(repo, '.memory', 'discoveries', 'retry.md'),
221
+ '---\ncovers: src/**\n---\n# Retry cap',
222
+ );
223
+ const out = await lookup({kind: 'discoveries'});
224
+ // Inferred from the directory; the filter must not silently drop it.
225
+ expect(out).toContain('discoveries/retry.md');
226
+ });
227
+ });
228
+
229
+ describe('memory_save', () => {
230
+ const save = (args: Record<string, unknown>) => extension.handlers.memory_save(args, {} as never);
231
+
232
+ test('refuses to write when writing is disabled, and says how to enable it', async () => {
233
+ seedMemory();
234
+ writeFileSync(join(repo, 'memory.json'), JSON.stringify({write: false}));
235
+ const out = await save({
236
+ id: 'schemas/core.md',
237
+ kind: 'schema',
238
+ title: 'T',
239
+ body: 'b',
240
+ covers: ['db/**'],
241
+ });
242
+ expect(out).toContain('disabled');
243
+ expect(out).toContain('memory.json');
244
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(false);
245
+ });
246
+
247
+ test('writes a doc once enabled', async () => {
248
+ seedMemory();
249
+ enableWrite();
250
+ const out = await save({
251
+ id: 'schemas/core.md',
252
+ kind: 'schema',
253
+ title: 'Core',
254
+ body: 'users.deleted_at is soft delete',
255
+ covers: ['db/migrations/**'],
256
+ });
257
+ expect(out).toContain('Saved schemas/core.md');
258
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(true);
259
+ });
260
+
261
+ test('renders the title as an H1 when the body has none', async () => {
262
+ seedMemory();
263
+ enableWrite();
264
+ await save({
265
+ id: 'schemas/core.md',
266
+ kind: 'schema',
267
+ title: 'Core Schema',
268
+ body: 'notes',
269
+ covers: ['db/**'],
270
+ });
271
+ const text = readFileSync(join(repo, '.memory', 'schemas', 'core.md'), 'utf-8');
272
+ expect(text).toContain('# Core Schema');
273
+ });
274
+
275
+ test('requires covers for schemas and playbooks', async () => {
276
+ seedMemory();
277
+ enableWrite();
278
+ const out = await save({id: 'schemas/core.md', kind: 'schema', title: 'T', body: 'b'});
279
+ expect(out).toContain('`covers` is required');
280
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(false);
281
+ });
282
+
283
+ test('allows a run without covers, since a run is dated and scoped', async () => {
284
+ seedMemory();
285
+ enableWrite();
286
+ const out = await save({id: 'runs/2026-01-01-x/intent.md', kind: 'run', title: 'X', body: 'b'});
287
+ expect(out).toContain('Saved');
288
+ });
289
+
290
+ test('writes a doc into a directory that did not exist yet', async () => {
291
+ // The point: an agent mid-task can record what it learned without first
292
+ // knowing (or being told) which folder it "should" belong in.
293
+ seedMemory();
294
+ enableWrite();
295
+ const out = await save({
296
+ id: 'discoveries/payments-retry.md',
297
+ kind: 'gotcha',
298
+ title: 'Payments retry has a 3-attempt cap',
299
+ body: 'Hardcoded in the worker; not in config.',
300
+ covers: ['src/payments/**'],
301
+ });
302
+ expect(out).toContain('Saved discoveries/payments-retry.md');
303
+ expect(existsSync(join(repo, '.memory', 'discoveries', 'payments-retry.md'))).toBe(true);
304
+ });
305
+
306
+ test('accepts an open kind vocabulary and it round-trips through lookup', async () => {
307
+ seedMemory();
308
+ enableWrite();
309
+ await save({
310
+ id: 'discoveries/x.md',
311
+ kind: 'gotcha',
312
+ title: 'A gotcha',
313
+ body: 'b',
314
+ covers: ['src/**'],
315
+ });
316
+ expect(existsSync(join(repo, '.memory', 'discoveries', 'x.md'))).toBe(true);
317
+ });
318
+
319
+ test('validates kind', async () => {
320
+ seedMemory();
321
+ enableWrite();
322
+ expect(await save({id: 'a.md', kind: '', title: 'T', body: 'b', covers: ['x']})).toContain(
323
+ '`kind` is required',
324
+ );
325
+ });
326
+
327
+ test('validates required fields', async () => {
328
+ seedMemory();
329
+ enableWrite();
330
+ expect(await save({id: '', kind: 'schema', title: 'T', body: 'b', covers: ['x']})).toContain(
331
+ '`id` is required',
332
+ );
333
+ expect(await save({id: 'a.md', kind: 'schema', title: '', body: 'b', covers: ['x']})).toContain(
334
+ '`title` is required',
335
+ );
336
+ expect(await save({id: 'a.md', kind: 'schema', title: 'T', body: '', covers: ['x']})).toContain(
337
+ '`body` is required',
338
+ );
339
+ });
340
+
341
+ test('refuses a silent overwrite and reports it as an error', async () => {
342
+ seedMemory();
343
+ enableWrite();
344
+ const args = {id: 'schemas/core.md', kind: 'schema', title: 'T', body: 'b', covers: ['db/**']};
345
+ await save(args);
346
+ const second = await save(args);
347
+ expect(second).toContain('already exists');
348
+ });
349
+ });
package/src/index.ts ADDED
@@ -0,0 +1,313 @@
1
+ /**
2
+ * @pal-code/memory — repo knowledge memory for pal.
3
+ *
4
+ * The problem this solves: an agent re-explores the same codebase every session,
5
+ * and a human re-derives the same schema/script for a recurring task because the
6
+ * artifact lived in a working tree and got deleted.
7
+ *
8
+ * The mechanism is the same one skills use — cheap index in context, bodies on
9
+ * demand — plus one rule that makes it safe: a doc is only *trusted* when its
10
+ * `covers` paths are unchanged since `verified_at`. Staleness is computed from
11
+ * git, never asserted by the doc.
12
+ *
13
+ * Availability mirrors `@pal-code/jev`: no `.memory` directory means no tools and
14
+ * no prompt fragment, so a repo that doesn't use this pays zero tokens.
15
+ */
16
+
17
+ import {existsSync, mkdirSync} from 'node:fs';
18
+
19
+ import type {ToolDef, ToolExtension, ToolHandler} from '@pal-code/core';
20
+
21
+ import {resolveMemorySettings, memoryRoot} from './config.js';
22
+ import type {MemorySettings} from './config.js';
23
+ import {checkFreshness, listDocs, saveDoc, searchDocs} from './store.js';
24
+ import type {MemoryDoc} from './store.js';
25
+
26
+ function settingsFor(cwd?: string): MemorySettings {
27
+ return resolveMemorySettings(cwd);
28
+ }
29
+
30
+ /**
31
+ * Is this repo using repo memory?
32
+ *
33
+ * Mirrors `@pal-code/workflow`: true when the memory directory exists, or when
34
+ * writing is enabled — because then `setup` can create it. Gating on the
35
+ * directory alone would make the extension permanently unavailable in exactly
36
+ * the repo where someone wants to start recording for the first time.
37
+ */
38
+ function isAvailable(): boolean {
39
+ const settings = settingsFor();
40
+ return existsSync(memoryRoot(settings)) || settings.write;
41
+ }
42
+
43
+ /**
44
+ * Create the memory directory on first load when writing is enabled.
45
+ *
46
+ * Without this, `write: true` alone still left the extension inert on a fresh
47
+ * repo: `available` was false because the directory did not exist, and nothing
48
+ * ever created it, so `memory_save` could not be reached to create it either.
49
+ * The same chicken-and-egg that `work_start` solves for `.work`.
50
+ *
51
+ * Deliberately does not seed an `index.md`: an empty directory already reads as
52
+ * "no knowledge recorded yet", and a stub would show up in the index as a doc
53
+ * that can never be fresh.
54
+ *
55
+ * Runs before `available` is read (see core's loader), so creating the
56
+ * directory here is what makes the getter above return true. Never throws — a
57
+ * read-only checkout must degrade to "unavailable", not to a failed extension.
58
+ */
59
+ function ensureMemoryRoot(): void {
60
+ const settings = settingsFor();
61
+ if (!settings.write) return;
62
+ try {
63
+ mkdirSync(memoryRoot(settings), {recursive: true});
64
+ } catch {
65
+ // Read-only filesystem, or a path that is not a directory. Leave it to
66
+ // isAvailable to report the extension as unavailable.
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Explain how a doc went stale, so the diff doubles as a pointer.
72
+ *
73
+ * A stale doc is not just "not fresh" — the fact that a specific file changed is
74
+ * information the next agent can act on immediately, without re-reading anything.
75
+ */
76
+ function driftHint(changed: string[]): string {
77
+ if (changed.length === 0) return '';
78
+ const shown = changed.slice(0, 5);
79
+ const more = changed.length > shown.length ? ` (+${changed.length - shown.length} more)` : '';
80
+ return `Start here: ${shown.join(', ')}${more}`;
81
+ }
82
+
83
+ /** Compact one-line staleness marker used in listings. */
84
+ function mark(doc: MemoryDoc, settings: MemorySettings): string {
85
+ const fresh = checkFreshness(doc, settings);
86
+ const icon = fresh.status === 'fresh' ? '✓' : fresh.status === 'stale' ? '!' : '?';
87
+ return `${icon} ${doc.id} — ${doc.title} (${fresh.reason})`;
88
+ }
89
+
90
+ const lookupDef: ToolDef = {
91
+ type: 'function',
92
+ function: {
93
+ name: 'memory_lookup',
94
+ description:
95
+ "Read this repo's remembered knowledge (.memory) BEFORE exploring the codebase. Call it with no arguments first on any task: it is one cheap call that returns the doc index plus a git-computed staleness verdict per doc, and a previous session may already have recorded the clue you are about to rediscover. Use `id` to read one doc, `query` to search across docs. `fresh` means the doc's covered paths are unchanged since it was verified — trust it and skip re-exploring those paths. `stale`/`unknown` means treat it as a hint, verify against the code, and note which files drifted. Explore only what memory did not answer.",
96
+ parameters: {
97
+ type: 'object',
98
+ properties: {
99
+ id: {
100
+ type: 'string',
101
+ description:
102
+ 'Doc path relative to .memory, e.g. "schemas/core.md" or "playbooks/backfill.md"',
103
+ },
104
+ query: {type: 'string', description: 'Search titles and bodies for this text'},
105
+ kind: {
106
+ type: 'string',
107
+ description: 'Filter the index to one kind',
108
+ enum: ['schema', 'playbook', 'run'],
109
+ },
110
+ limit: {type: 'number', description: 'Max docs to list (default 40)'},
111
+ },
112
+ },
113
+ },
114
+ };
115
+
116
+ const saveDef: ToolDef = {
117
+ type: 'function',
118
+ function: {
119
+ name: 'memory_save',
120
+ description:
121
+ 'Record knowledge you had to derive by exploring or verifying, so the next session does not repeat it. Call this after you verified something against the real code or schema — especially when a memory doc was stale and you worked out the current truth. Requires `memory.write` in config; if writing is disabled the call says so. Never invent a `verified_at`: it defaults to the current HEAD, which is exactly what makes the doc trustworthy later. Prefer updating an existing doc over adding a near-duplicate.',
122
+ parameters: {
123
+ type: 'object',
124
+ properties: {
125
+ id: {
126
+ type: 'string',
127
+ description: 'Path under .memory ending in .md, e.g. "schemas/core.md"',
128
+ },
129
+ kind: {
130
+ type: 'string',
131
+ description:
132
+ 'What this is, in your own words — "schema", "playbook", "run", "gotcha", "data-fix", anything. An open vocabulary on purpose: knowledge found during real work rarely fits a fixed taxonomy. Used to filter in memory_lookup.',
133
+ },
134
+ title: {type: 'string', description: 'Human title (becomes the H1)'},
135
+ covers: {
136
+ type: 'array',
137
+ description:
138
+ 'Globs of the code/paths this doc describes. Required — without it staleness cannot be detected.',
139
+ items: {type: 'string'},
140
+ },
141
+ body: {type: 'string', description: 'Markdown body. Be specific and include the gotchas.'},
142
+ overwrite: {
143
+ type: 'boolean',
144
+ description:
145
+ 'Replace an existing doc. Defaults to false so nothing is clobbered silently.',
146
+ },
147
+ extra: {
148
+ type: 'object',
149
+ description: 'Extra frontmatter fields, e.g. {"database": "core", "use_when": "..."}',
150
+ additionalProperties: {type: 'string'},
151
+ },
152
+ },
153
+ required: ['id', 'kind', 'title', 'body'],
154
+ },
155
+ },
156
+ };
157
+
158
+ const handlers: Record<string, ToolHandler> = {
159
+ memory_lookup: async (args) => {
160
+ const settings = settingsFor();
161
+
162
+ const id = typeof args.id === 'string' ? args.id.trim() : '';
163
+ if (id !== '') {
164
+ const docs = listDocs(settings);
165
+ const doc = docs.find((d) => d.id === id);
166
+ if (!doc) {
167
+ const known = docs.map((d) => d.id).join('\n ');
168
+ return `No doc "${id}" in ${settings.dir}. Known docs:\n ${known || '(none)'}`;
169
+ }
170
+ const fresh = checkFreshness(doc, settings);
171
+ const header = [
172
+ `# ${doc.title}`,
173
+ `id: ${doc.id} (${doc.kind})`,
174
+ `staleness: ${fresh.status} — ${fresh.reason}`,
175
+ fresh.changed.length > 0 ? `changed since verification: ${fresh.changed.join(', ')}` : '',
176
+ fresh.uncommitted.length > 0
177
+ ? `note (not staleness): uncommitted changes in covered paths — ${fresh.uncommitted.join(', ')}`
178
+ : '',
179
+ fresh.status === 'fresh'
180
+ ? 'TRUSTED: covered paths are unchanged. You may skip re-exploring them.'
181
+ : 'HINT ONLY: verify against the code before relying on this. The drift itself tells you where to look:',
182
+ driftHint(fresh.changed),
183
+ fresh.status === 'fresh'
184
+ ? ''
185
+ : 'After verifying, update this doc and refresh `verified_at` with memory_save.',
186
+ '',
187
+ ]
188
+ .filter((line) => line !== '')
189
+ .join('\n');
190
+ return `${header}\n---\n${doc.body}`;
191
+ }
192
+
193
+ const query = typeof args.query === 'string' ? args.query.trim() : '';
194
+ if (query !== '') {
195
+ const hits = searchDocs(settings, query);
196
+ if (hits.length === 0) return `Nothing in ${settings.dir} matches "${query}".`;
197
+ return hits.map((hit) => `${hit.doc.id}:${hit.line} — ${hit.snippet}`).join('\n');
198
+ }
199
+
200
+ // Index mode: call out docs that are actually trustworthy.
201
+ const kindFilter = typeof args.kind === 'string' ? args.kind : '';
202
+ const limit = args.limit ? Math.max(1, Number(args.limit)) : 40;
203
+ const docs = listDocs(settings).filter((d) => kindFilter === '' || d.kind === kindFilter);
204
+
205
+ if (docs.length === 0) {
206
+ return `No knowledge recorded in ${settings.dir} yet. Explore the code normally; you can write findings back with memory_save once it is enabled.`;
207
+ }
208
+
209
+ const lines = docs.slice(0, limit).map((doc) => mark(doc, settings));
210
+ const freshCount = docs.filter((d) => checkFreshness(d, settings).status === 'fresh').length;
211
+ return [
212
+ `${docs.length} doc(s) in ${settings.dir} (${freshCount} fresh, ${docs.length - freshCount} needing verification):`,
213
+ ...lines,
214
+ '',
215
+ 'Read one with memory_lookup({id}).',
216
+ '✓ = trust and skip exploration · ! = covered paths changed, re-verify · ? = no verified_at',
217
+ ].join('\n');
218
+ },
219
+
220
+ memory_save: async (args) => {
221
+ const settings = settingsFor();
222
+ if (!settings.write) {
223
+ return `Writing to ${settings.dir} is disabled. Set {"write": true} in memory.json (project root) or ~/.pal/memory.json to enable it. Reading still works.`;
224
+ }
225
+
226
+ const id = typeof args.id === 'string' ? args.id : '';
227
+ const kind = typeof args.kind === 'string' ? args.kind : '';
228
+ const title = typeof args.title === 'string' ? args.title.trim() : '';
229
+ const body = typeof args.body === 'string' ? args.body : '';
230
+
231
+ if (id === '') return 'Error: `id` is required (e.g. "schemas/core.md").';
232
+ if (kind.trim() === '') {
233
+ return 'Error: `kind` is required — name what this is in your own words (e.g. "schema", "playbook", "run", "gotcha", "data-fix").';
234
+ }
235
+ if (title === '') return 'Error: `title` is required.';
236
+ if (body.trim() === '') return 'Error: `body` is required.';
237
+
238
+ const covers = Array.isArray(args.covers)
239
+ ? args.covers.filter((c): c is string => typeof c === 'string' && c.trim() !== '')
240
+ : [];
241
+ if (covers.length === 0 && kind !== 'run') {
242
+ return 'Error: `covers` is required for schema and playbook docs — without it staleness cannot be detected and the doc can never be trusted.';
243
+ }
244
+
245
+ const extra = (args.extra && typeof args.extra === 'object' ? args.extra : {}) as Record<
246
+ string,
247
+ unknown
248
+ >;
249
+ const fields: Record<string, string | number | boolean | null> = {kind};
250
+ for (const [key, value] of Object.entries(extra)) {
251
+ if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) {
252
+ fields[key] = value as string | number | boolean | null;
253
+ }
254
+ }
255
+
256
+ const result = saveDoc(
257
+ settings,
258
+ {
259
+ id,
260
+ fields,
261
+ lists: {covers},
262
+ // Title is rendered as the H1 so the file reads naturally by hand too.
263
+ body: body.trim().startsWith('#') ? body : `# ${title}\n\n${body}`,
264
+ },
265
+ process.cwd(),
266
+ args.overwrite === true,
267
+ );
268
+
269
+ if (!result.ok) return `Error: ${result.error}`;
270
+ return `Saved ${result.id} in ${settings.dir} (${covers.length} cover pattern(s), verified at HEAD).\nNext session will see it in memory_lookup and can skip re-exploring those paths.`;
271
+ },
272
+ };
273
+
274
+ /**
275
+ * Guidance the tool schemas cannot carry.
276
+ *
277
+ * Placed last in the system prompt by core, only while this extension is loaded
278
+ * and available. The load-bearing part is the ORDERING: memory before exploring.
279
+ * Models default to exploring immediately, so without this the directory is dead
280
+ * weight — and the trigger has to be situational ("before you explore") rather
281
+ * than task-shaped ("for schema work"), because a situational trigger is
282
+ * something the model can actually observe in its own plan.
283
+ */
284
+ const PROMPT = [
285
+ 'REPO MEMORY: This repo keeps notes from previous sessions in `.memory`.',
286
+ 'BEFORE you start exploring the codebase — before a broad search, before reading',
287
+ 'many files — call `memory_lookup` with no arguments. It is one cheap call and',
288
+ 'returns an index plus a git-computed staleness verdict per doc. Do this on every',
289
+ 'task, not just schema or data work: a previous session may already have recorded',
290
+ 'the exact clue you are about to spend turns rediscovering. A `fresh` doc means',
291
+ 'its covered paths are unchanged since it was verified — trust it and skip',
292
+ 're-exploring those paths. A `stale` or `unknown` doc is a hint only: verify',
293
+ 'against the real code, and it will point you at the files that drifted.',
294
+ 'Then explore whatever memory did not answer. When a doc was stale, or when you',
295
+ 'had to derive something the hard way, write it back with `memory_save` and',
296
+ 'refresh `verified_at` — that is what makes the next session faster. Never write',
297
+ 'a doc without `covers` globs, and prefer updating an existing doc over adding a',
298
+ 'near-duplicate. If memory has nothing relevant, say nothing about it and carry',
299
+ 'on normally.',
300
+ ].join(' ');
301
+
302
+ export default {
303
+ name: 'memory',
304
+ get available() {
305
+ return isAvailable();
306
+ },
307
+ get tools() {
308
+ return isAvailable() ? [lookupDef, saveDef] : [];
309
+ },
310
+ prompt: PROMPT,
311
+ setup: ensureMemoryRoot,
312
+ handlers,
313
+ } satisfies ToolExtension;