@pal-code/memory 0.0.0-stage → 0.0.18

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,306 @@
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 offers nothing', () => {
40
+ expect(extension.available).toBe(false);
41
+ expect(extension.tools).toEqual([]);
42
+ });
43
+
44
+ test('a .memory directory makes both tools available', () => {
45
+ seedMemory();
46
+ expect(extension.available).toBe(true);
47
+ expect(extension.tools.map((t) => t.function.name)).toEqual(['memory_lookup', 'memory_save']);
48
+ });
49
+
50
+ test('every advertised tool has a handler', () => {
51
+ seedMemory();
52
+ for (const tool of extension.tools) {
53
+ expect(typeof extension.handlers[tool.function.name]).toBe('function');
54
+ }
55
+ });
56
+
57
+ test('carries guidance naming both tools and the memory-first ordering', () => {
58
+ const prompt = extension.prompt ?? '';
59
+ expect(prompt).toContain('memory_lookup');
60
+ expect(prompt).toContain('memory_save');
61
+ expect(prompt).toContain('BEFORE you start exploring the codebase');
62
+ });
63
+
64
+ test('the trigger is situational, not gated on a task type', () => {
65
+ // Regression guard: an earlier version only fired "for schema, migrations,
66
+ // data fixes", which a model doing a normal feature task never matches.
67
+ const prompt = extension.prompt ?? '';
68
+ expect(prompt).toContain('BEFORE');
69
+ expect(prompt).toContain('on every');
70
+ expect(prompt).not.toContain('for a task about schema');
71
+ });
72
+
73
+ test('the lookup tool description tells the model to call it before exploring', () => {
74
+ seedMemory();
75
+ const lookup = extension.tools.find((t) => t.function.name === 'memory_lookup')!;
76
+ expect(lookup.function.description).toContain('BEFORE exploring');
77
+ expect(lookup.function.description).toContain('any task');
78
+ });
79
+
80
+ test('the prompt does not claim tools exist in a repo without .memory', () => {
81
+ // Guard against a prompt that mentions tools the model cannot call.
82
+ expect(extension.available).toBe(false);
83
+ });
84
+ });
85
+
86
+ describe('memory_lookup', () => {
87
+ const lookup = (args: Record<string, unknown>) =>
88
+ extension.handlers.memory_lookup(args, {} as never);
89
+
90
+ test('explains an empty memory dir rather than pretending it has content', async () => {
91
+ mkdirSync(join(repo, '.memory'), {recursive: true});
92
+ const out = await lookup({});
93
+ expect(out).toContain('No knowledge recorded');
94
+ expect(out).toContain('memory_save');
95
+ });
96
+
97
+ test('index mode lists docs with staleness markers', async () => {
98
+ seedMemory();
99
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
100
+ writeFileSync(
101
+ join(repo, '.memory', 'schemas', 'core.md'),
102
+ '---\ncovers: db/**\n---\n# Core schema',
103
+ );
104
+ const out = await lookup({});
105
+ expect(out).toContain('schemas/core.md');
106
+ expect(out).toContain('Core schema');
107
+ // No verified_at → '?' marker, and the legend must explain it.
108
+ expect(out).toContain('?');
109
+ expect(out).toContain('needing verification');
110
+ });
111
+
112
+ test('reads one doc and labels it a hint when stale', async () => {
113
+ seedMemory();
114
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
115
+ writeFileSync(
116
+ join(repo, '.memory', 'schemas', 'core.md'),
117
+ '---\ncovers: db/**\nverified_at: deadbeef\n---\n# Core\n\nsoft delete on users',
118
+ );
119
+ const out = await lookup({id: 'schemas/core.md'});
120
+ expect(out).toContain('soft delete on users');
121
+ expect(out).toContain('HINT ONLY');
122
+ });
123
+
124
+ test('lists known ids when the requested id is missing', async () => {
125
+ seedMemory();
126
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
127
+ writeFileSync(join(repo, '.memory', 'schemas', 'core.md'), '---\n---\n# Core');
128
+ const out = await lookup({id: 'schemas/nope.md'});
129
+ expect(out).toContain('No doc "schemas/nope.md"');
130
+ // Points at the ids that DO exist, not at the excluded index.md.
131
+ expect(out).toContain('schemas/core.md');
132
+ });
133
+
134
+ test('searches across docs and reports doc:line', async () => {
135
+ seedMemory();
136
+ mkdirSync(join(repo, '.memory', 'playbooks'), {recursive: true});
137
+ writeFileSync(
138
+ join(repo, '.memory', 'playbooks', 'fix.md'),
139
+ '---\ncovers: db/**\n---\n# Fix\n\nbackfill the timezone column',
140
+ );
141
+ const out = await lookup({query: 'timezone'});
142
+ expect(out).toContain('playbooks/fix.md:');
143
+ expect(out).toContain('backfill the timezone column');
144
+ });
145
+
146
+ test('reports no matches without erroring', async () => {
147
+ seedMemory();
148
+ expect(await lookup({query: 'zzz-not-here'})).toContain('Nothing in .memory matches');
149
+ });
150
+
151
+ test('kind filter narrows the index', async () => {
152
+ seedMemory();
153
+ mkdirSync(join(repo, '.memory', 'playbooks'), {recursive: true});
154
+ writeFileSync(join(repo, '.memory', 'playbooks', 'fix.md'), '---\n---\n# Fix');
155
+ const out = await lookup({kind: 'playbook'});
156
+ expect(out).toContain('playbooks/fix.md');
157
+ // The doc list itself must exclude index.md (the hint line still names it).
158
+ expect(out.split('\n')[0]).toContain('1 doc(s)');
159
+ expect(out).not.toContain('index.md — ');
160
+ });
161
+
162
+ test('names the drifted file so the next agent knows where to look', async () => {
163
+ seedMemory();
164
+ mkdirSync(join(repo, '.memory', 'schemas'), {recursive: true});
165
+ writeFileSync(
166
+ join(repo, '.memory', 'schemas', 'core.md'),
167
+ '---\ncovers: db/**\nverified_at: deadbeef\n---\n# Core\n\nnotes',
168
+ );
169
+ const out = await lookup({id: 'schemas/core.md'});
170
+ expect(out).toContain('HINT ONLY');
171
+ expect(out).toContain('memory_save');
172
+ });
173
+
174
+ test('an invented kind is filterable, not rejected', async () => {
175
+ seedMemory();
176
+ mkdirSync(join(repo, '.memory', 'discoveries'), {recursive: true});
177
+ writeFileSync(
178
+ join(repo, '.memory', 'discoveries', 'retry.md'),
179
+ '---\ncovers: src/**\n---\n# Retry cap',
180
+ );
181
+ const out = await lookup({kind: 'discoveries'});
182
+ // Inferred from the directory; the filter must not silently drop it.
183
+ expect(out).toContain('discoveries/retry.md');
184
+ });
185
+ });
186
+
187
+ describe('memory_save', () => {
188
+ const save = (args: Record<string, unknown>) => extension.handlers.memory_save(args, {} as never);
189
+
190
+ test('refuses to write when writing is disabled, and says how to enable it', async () => {
191
+ seedMemory();
192
+ const out = await save({
193
+ id: 'schemas/core.md',
194
+ kind: 'schema',
195
+ title: 'T',
196
+ body: 'b',
197
+ covers: ['db/**'],
198
+ });
199
+ expect(out).toContain('disabled');
200
+ expect(out).toContain('memory.json');
201
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(false);
202
+ });
203
+
204
+ test('writes a doc once enabled', async () => {
205
+ seedMemory();
206
+ enableWrite();
207
+ const out = await save({
208
+ id: 'schemas/core.md',
209
+ kind: 'schema',
210
+ title: 'Core',
211
+ body: 'users.deleted_at is soft delete',
212
+ covers: ['db/migrations/**'],
213
+ });
214
+ expect(out).toContain('Saved schemas/core.md');
215
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(true);
216
+ });
217
+
218
+ test('renders the title as an H1 when the body has none', async () => {
219
+ seedMemory();
220
+ enableWrite();
221
+ await save({
222
+ id: 'schemas/core.md',
223
+ kind: 'schema',
224
+ title: 'Core Schema',
225
+ body: 'notes',
226
+ covers: ['db/**'],
227
+ });
228
+ const text = readFileSync(join(repo, '.memory', 'schemas', 'core.md'), 'utf-8');
229
+ expect(text).toContain('# Core Schema');
230
+ });
231
+
232
+ test('requires covers for schemas and playbooks', async () => {
233
+ seedMemory();
234
+ enableWrite();
235
+ const out = await save({id: 'schemas/core.md', kind: 'schema', title: 'T', body: 'b'});
236
+ expect(out).toContain('`covers` is required');
237
+ expect(existsSync(join(repo, '.memory', 'schemas', 'core.md'))).toBe(false);
238
+ });
239
+
240
+ test('allows a run without covers, since a run is dated and scoped', async () => {
241
+ seedMemory();
242
+ enableWrite();
243
+ const out = await save({id: 'runs/2026-01-01-x/intent.md', kind: 'run', title: 'X', body: 'b'});
244
+ expect(out).toContain('Saved');
245
+ });
246
+
247
+ test('writes a doc into a directory that did not exist yet', async () => {
248
+ // The point: an agent mid-task can record what it learned without first
249
+ // knowing (or being told) which folder it "should" belong in.
250
+ seedMemory();
251
+ enableWrite();
252
+ const out = await save({
253
+ id: 'discoveries/payments-retry.md',
254
+ kind: 'gotcha',
255
+ title: 'Payments retry has a 3-attempt cap',
256
+ body: 'Hardcoded in the worker; not in config.',
257
+ covers: ['src/payments/**'],
258
+ });
259
+ expect(out).toContain('Saved discoveries/payments-retry.md');
260
+ expect(existsSync(join(repo, '.memory', 'discoveries', 'payments-retry.md'))).toBe(true);
261
+ });
262
+
263
+ test('accepts an open kind vocabulary and it round-trips through lookup', async () => {
264
+ seedMemory();
265
+ enableWrite();
266
+ await save({
267
+ id: 'discoveries/x.md',
268
+ kind: 'gotcha',
269
+ title: 'A gotcha',
270
+ body: 'b',
271
+ covers: ['src/**'],
272
+ });
273
+ expect(existsSync(join(repo, '.memory', 'discoveries', 'x.md'))).toBe(true);
274
+ });
275
+
276
+ test('validates kind', async () => {
277
+ seedMemory();
278
+ enableWrite();
279
+ expect(await save({id: 'a.md', kind: '', title: 'T', body: 'b', covers: ['x']})).toContain(
280
+ '`kind` is required',
281
+ );
282
+ });
283
+
284
+ test('validates required fields', async () => {
285
+ seedMemory();
286
+ enableWrite();
287
+ expect(await save({id: '', kind: 'schema', title: 'T', body: 'b', covers: ['x']})).toContain(
288
+ '`id` is required',
289
+ );
290
+ expect(await save({id: 'a.md', kind: 'schema', title: '', body: 'b', covers: ['x']})).toContain(
291
+ '`title` is required',
292
+ );
293
+ expect(await save({id: 'a.md', kind: 'schema', title: 'T', body: '', covers: ['x']})).toContain(
294
+ '`body` is required',
295
+ );
296
+ });
297
+
298
+ test('refuses a silent overwrite and reports it as an error', async () => {
299
+ seedMemory();
300
+ enableWrite();
301
+ const args = {id: 'schemas/core.md', kind: 'schema', title: 'T', body: 'b', covers: ['db/**']};
302
+ await save(args);
303
+ const second = await save(args);
304
+ expect(second).toContain('already exists');
305
+ });
306
+ });
package/src/index.ts ADDED
@@ -0,0 +1,278 @@
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} from 'node:fs';
18
+
19
+ import type {ToolDef, ToolExtension, ToolHandler} from '@pal-code/core';
20
+
21
+ import {resolveMemorySettings} 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
+ /** Is there a `.memory` directory here at all? */
31
+ function isAvailable(): boolean {
32
+ const settings = settingsFor();
33
+ return existsSync(settings.dir) || existsSync(`${settings.dir}/index.md`);
34
+ }
35
+
36
+ /**
37
+ * Explain how a doc went stale, so the diff doubles as a pointer.
38
+ *
39
+ * A stale doc is not just "not fresh" — the fact that a specific file changed is
40
+ * information the next agent can act on immediately, without re-reading anything.
41
+ */
42
+ function driftHint(changed: string[]): string {
43
+ if (changed.length === 0) return '';
44
+ const shown = changed.slice(0, 5);
45
+ const more = changed.length > shown.length ? ` (+${changed.length - shown.length} more)` : '';
46
+ return `Start here: ${shown.join(', ')}${more}`;
47
+ }
48
+
49
+ /** Compact one-line staleness marker used in listings. */
50
+ function mark(doc: MemoryDoc, settings: MemorySettings): string {
51
+ const fresh = checkFreshness(doc, settings);
52
+ const icon = fresh.status === 'fresh' ? '✓' : fresh.status === 'stale' ? '!' : '?';
53
+ return `${icon} ${doc.id} — ${doc.title} (${fresh.reason})`;
54
+ }
55
+
56
+ const lookupDef: ToolDef = {
57
+ type: 'function',
58
+ function: {
59
+ name: 'memory_lookup',
60
+ description:
61
+ "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.",
62
+ parameters: {
63
+ type: 'object',
64
+ properties: {
65
+ id: {
66
+ type: 'string',
67
+ description:
68
+ 'Doc path relative to .memory, e.g. "schemas/core.md" or "playbooks/backfill.md"',
69
+ },
70
+ query: {type: 'string', description: 'Search titles and bodies for this text'},
71
+ kind: {
72
+ type: 'string',
73
+ description: 'Filter the index to one kind',
74
+ enum: ['schema', 'playbook', 'run'],
75
+ },
76
+ limit: {type: 'number', description: 'Max docs to list (default 40)'},
77
+ },
78
+ },
79
+ },
80
+ };
81
+
82
+ const saveDef: ToolDef = {
83
+ type: 'function',
84
+ function: {
85
+ name: 'memory_save',
86
+ description:
87
+ '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.',
88
+ parameters: {
89
+ type: 'object',
90
+ properties: {
91
+ id: {
92
+ type: 'string',
93
+ description: 'Path under .memory ending in .md, e.g. "schemas/core.md"',
94
+ },
95
+ kind: {
96
+ type: 'string',
97
+ description:
98
+ '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.',
99
+ },
100
+ title: {type: 'string', description: 'Human title (becomes the H1)'},
101
+ covers: {
102
+ type: 'array',
103
+ description:
104
+ 'Globs of the code/paths this doc describes. Required — without it staleness cannot be detected.',
105
+ items: {type: 'string'},
106
+ },
107
+ body: {type: 'string', description: 'Markdown body. Be specific and include the gotchas.'},
108
+ overwrite: {
109
+ type: 'boolean',
110
+ description:
111
+ 'Replace an existing doc. Defaults to false so nothing is clobbered silently.',
112
+ },
113
+ extra: {
114
+ type: 'object',
115
+ description: 'Extra frontmatter fields, e.g. {"database": "core", "use_when": "..."}',
116
+ additionalProperties: {type: 'string'},
117
+ },
118
+ },
119
+ required: ['id', 'kind', 'title', 'body'],
120
+ },
121
+ },
122
+ };
123
+
124
+ const handlers: Record<string, ToolHandler> = {
125
+ memory_lookup: async (args) => {
126
+ const settings = settingsFor();
127
+
128
+ const id = typeof args.id === 'string' ? args.id.trim() : '';
129
+ if (id !== '') {
130
+ const docs = listDocs(settings);
131
+ const doc = docs.find((d) => d.id === id);
132
+ if (!doc) {
133
+ const known = docs.map((d) => d.id).join('\n ');
134
+ return `No doc "${id}" in ${settings.dir}. Known docs:\n ${known || '(none)'}`;
135
+ }
136
+ const fresh = checkFreshness(doc, settings);
137
+ const header = [
138
+ `# ${doc.title}`,
139
+ `id: ${doc.id} (${doc.kind})`,
140
+ `staleness: ${fresh.status} — ${fresh.reason}`,
141
+ fresh.changed.length > 0 ? `changed since verification: ${fresh.changed.join(', ')}` : '',
142
+ fresh.uncommitted.length > 0
143
+ ? `note (not staleness): uncommitted changes in covered paths — ${fresh.uncommitted.join(', ')}`
144
+ : '',
145
+ fresh.status === 'fresh'
146
+ ? 'TRUSTED: covered paths are unchanged. You may skip re-exploring them.'
147
+ : 'HINT ONLY: verify against the code before relying on this. The drift itself tells you where to look:',
148
+ driftHint(fresh.changed),
149
+ fresh.status === 'fresh'
150
+ ? ''
151
+ : 'After verifying, update this doc and refresh `verified_at` with memory_save.',
152
+ '',
153
+ ]
154
+ .filter((line) => line !== '')
155
+ .join('\n');
156
+ return `${header}\n---\n${doc.body}`;
157
+ }
158
+
159
+ const query = typeof args.query === 'string' ? args.query.trim() : '';
160
+ if (query !== '') {
161
+ const hits = searchDocs(settings, query);
162
+ if (hits.length === 0) return `Nothing in ${settings.dir} matches "${query}".`;
163
+ return hits.map((hit) => `${hit.doc.id}:${hit.line} — ${hit.snippet}`).join('\n');
164
+ }
165
+
166
+ // Index mode: call out docs that are actually trustworthy.
167
+ const kindFilter = typeof args.kind === 'string' ? args.kind : '';
168
+ const limit = args.limit ? Math.max(1, Number(args.limit)) : 40;
169
+ const docs = listDocs(settings).filter((d) => kindFilter === '' || d.kind === kindFilter);
170
+
171
+ if (docs.length === 0) {
172
+ return `No knowledge recorded in ${settings.dir} yet. Explore the code normally; you can write findings back with memory_save once it is enabled.`;
173
+ }
174
+
175
+ const lines = docs.slice(0, limit).map((doc) => mark(doc, settings));
176
+ const freshCount = docs.filter((d) => checkFreshness(d, settings).status === 'fresh').length;
177
+ return [
178
+ `${docs.length} doc(s) in ${settings.dir} (${freshCount} fresh, ${docs.length - freshCount} needing verification):`,
179
+ ...lines,
180
+ '',
181
+ 'Read one with memory_lookup({id}).',
182
+ '✓ = trust and skip exploration · ! = covered paths changed, re-verify · ? = no verified_at',
183
+ ].join('\n');
184
+ },
185
+
186
+ memory_save: async (args) => {
187
+ const settings = settingsFor();
188
+ if (!settings.write) {
189
+ 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.`;
190
+ }
191
+
192
+ const id = typeof args.id === 'string' ? args.id : '';
193
+ const kind = typeof args.kind === 'string' ? args.kind : '';
194
+ const title = typeof args.title === 'string' ? args.title.trim() : '';
195
+ const body = typeof args.body === 'string' ? args.body : '';
196
+
197
+ if (id === '') return 'Error: `id` is required (e.g. "schemas/core.md").';
198
+ if (kind.trim() === '') {
199
+ return 'Error: `kind` is required — name what this is in your own words (e.g. "schema", "playbook", "run", "gotcha", "data-fix").';
200
+ }
201
+ if (title === '') return 'Error: `title` is required.';
202
+ if (body.trim() === '') return 'Error: `body` is required.';
203
+
204
+ const covers = Array.isArray(args.covers)
205
+ ? args.covers.filter((c): c is string => typeof c === 'string' && c.trim() !== '')
206
+ : [];
207
+ if (covers.length === 0 && kind !== 'run') {
208
+ return 'Error: `covers` is required for schema and playbook docs — without it staleness cannot be detected and the doc can never be trusted.';
209
+ }
210
+
211
+ const extra = (args.extra && typeof args.extra === 'object' ? args.extra : {}) as Record<
212
+ string,
213
+ unknown
214
+ >;
215
+ const fields: Record<string, string | number | boolean | null> = {kind};
216
+ for (const [key, value] of Object.entries(extra)) {
217
+ if (value === null || ['string', 'number', 'boolean'].includes(typeof value)) {
218
+ fields[key] = value as string | number | boolean | null;
219
+ }
220
+ }
221
+
222
+ const result = saveDoc(
223
+ settings,
224
+ {
225
+ id,
226
+ fields,
227
+ lists: {covers},
228
+ // Title is rendered as the H1 so the file reads naturally by hand too.
229
+ body: body.trim().startsWith('#') ? body : `# ${title}\n\n${body}`,
230
+ },
231
+ process.cwd(),
232
+ args.overwrite === true,
233
+ );
234
+
235
+ if (!result.ok) return `Error: ${result.error}`;
236
+ 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.`;
237
+ },
238
+ };
239
+
240
+ /**
241
+ * Guidance the tool schemas cannot carry.
242
+ *
243
+ * Placed last in the system prompt by core, only while this extension is loaded
244
+ * and available. The load-bearing part is the ORDERING: memory before exploring.
245
+ * Models default to exploring immediately, so without this the directory is dead
246
+ * weight — and the trigger has to be situational ("before you explore") rather
247
+ * than task-shaped ("for schema work"), because a situational trigger is
248
+ * something the model can actually observe in its own plan.
249
+ */
250
+ const PROMPT = [
251
+ 'REPO MEMORY: This repo keeps notes from previous sessions in `.memory`.',
252
+ 'BEFORE you start exploring the codebase — before a broad search, before reading',
253
+ 'many files — call `memory_lookup` with no arguments. It is one cheap call and',
254
+ 'returns an index plus a git-computed staleness verdict per doc. Do this on every',
255
+ 'task, not just schema or data work: a previous session may already have recorded',
256
+ 'the exact clue you are about to spend turns rediscovering. A `fresh` doc means',
257
+ 'its covered paths are unchanged since it was verified — trust it and skip',
258
+ 're-exploring those paths. A `stale` or `unknown` doc is a hint only: verify',
259
+ 'against the real code, and it will point you at the files that drifted.',
260
+ 'Then explore whatever memory did not answer. When a doc was stale, or when you',
261
+ 'had to derive something the hard way, write it back with `memory_save` and',
262
+ 'refresh `verified_at` — that is what makes the next session faster. Never write',
263
+ 'a doc without `covers` globs, and prefer updating an existing doc over adding a',
264
+ 'near-duplicate. If memory has nothing relevant, say nothing about it and carry',
265
+ 'on normally.',
266
+ ].join(' ');
267
+
268
+ export default {
269
+ name: 'memory',
270
+ get available() {
271
+ return isAvailable();
272
+ },
273
+ get tools() {
274
+ return isAvailable() ? [lookupDef, saveDef] : [];
275
+ },
276
+ prompt: PROMPT,
277
+ handlers,
278
+ } satisfies ToolExtension;