@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.
package/README.md CHANGED
@@ -1,3 +1,117 @@
1
- # Temporary Holding Version
1
+ # @pal-code/memory
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Repo memory for pal — so an agent **reads what previous sessions learned before
4
+ re-exploring the codebase**, and a recurring task stops being re-derived from
5
+ scratch every time.
6
+
7
+ Ships two tools and one prompt fragment:
8
+
9
+ | Tool | What it does |
10
+ |---|---|
11
+ | `memory_lookup` | Index of known docs (with a per-doc staleness verdict), one doc by `id`, or a text search |
12
+ | `memory_save` | Write a doc back, stamped with the current HEAD so the next session can trust it |
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ pal add @pal-code/memory
18
+ ```
19
+
20
+ Then create a `.memory/` directory in the repo you want it for. **No directory means
21
+ no tools and no prompt** — the extension reports itself unavailable, so repos that
22
+ don't use it pay zero tokens. This mirrors `@pal-code/jev`.
23
+
24
+ ## Why the staleness verdict is the whole design
25
+
26
+ The failure mode of every "agent memory folder" is silent drift: a note that was
27
+ true three refactors ago reads exactly like a fresh one. So a doc is never trusted
28
+ on its own word. Each doc declares:
29
+
30
+ ```yaml
31
+ covers: db/migrations/**, src/db/** # what it describes
32
+ verified_at: <git sha> # when it was checked
33
+ ```
34
+
35
+ `memory_lookup` runs `git diff --name-only <verified_at>..HEAD -- <covers>` and
36
+ reports one of:
37
+
38
+ | Verdict | Meaning | What the agent should do |
39
+ |---|---|---|
40
+ | `fresh` | covered paths unchanged since `verified_at` | **trust it, skip exploring those paths** |
41
+ | `stale` | covered paths changed (it lists which) | hint only — verify against the code |
42
+ | `unknown` | no `verified_at` | hint only |
43
+ | `uncheckable` | bad sha, no `covers`, or not a repo | hint only |
44
+
45
+ `memory_save` defaults `verified_at` to HEAD, so a doc written right after verifying
46
+ against real code is immediately `fresh` — and starts decaying the moment that code
47
+ changes.
48
+
49
+ ## Layout
50
+
51
+ ```
52
+ .memory/
53
+ index.md # one screen, the session entry point
54
+ schemas/<schema>.md # tables, FKs, gotchas
55
+ playbooks/<workflow>.md # reusable STEPS for a recurring task
56
+ runs/<date>-<slug>/ # one past execution: intent.md + script.sql
57
+ ```
58
+
59
+ `playbook` and `run` are deliberately separate: a playbook is the workflow, a run is
60
+ one instance of it. Knowledge kept only in a run dies with that run.
61
+
62
+ Directories starting with `_` are skipped, so `_TEMPLATE.md` files can live alongside
63
+ real docs.
64
+
65
+ ## Config
66
+
67
+ Extension-owned (per `EXTENSIONS.md`) — nothing goes in `.pal.json`:
68
+
69
+ | Level | Path |
70
+ |---|---|
71
+ | Project | `./memory.json` |
72
+ | User | `~/.pal/memory.json` |
73
+
74
+ ```json
75
+ {
76
+ "dir": ".memory",
77
+ "write": false,
78
+ "staleAfterDays": 90
79
+ }
80
+ ```
81
+
82
+ | Key | Default | Meaning |
83
+ |---|---|---|
84
+ | `dir` | `.memory` | Directory name, relative to the repo root |
85
+ | `write` | `false` | Allow `memory_save`. Reads always work |
86
+ | `staleAfterDays` | `90` | Reserved for time-based decay |
87
+
88
+ Resolution: defaults → project → user. A malformed config is ignored, never fatal.
89
+
90
+ **Writing is off by default on purpose.** Auto-writing knowledge produces junk that
91
+ later agents trust; enabling it is a deliberate act.
92
+
93
+ ## Keeping it out of git
94
+
95
+ Hide the directory machine-wide rather than in any project `.gitignore`:
96
+
97
+ ```sh
98
+ mkdir -p ~/.config/git
99
+ printf '.memory/\n' >> ~/.config/git/ignore
100
+ git config --global core.excludesFile ~/.config/git/ignore
101
+ ```
102
+
103
+ `ripgrep` and `biome` inherit this through git, so nothing lints or greps it either.
104
+
105
+ One consequence worth knowing: `pal`'s `grep_search` passes `--hidden` but not
106
+ `--no-ignore`, so it will **not** find `.memory` content. Address it by path
107
+ (`memory_lookup`, or `read .memory/index.md`) rather than by searching for it.
108
+
109
+ ## Safety notes
110
+
111
+ - `saveDoc` refuses ids containing `..`, absolute paths, non-`.md` names, and
112
+ `_`-prefixed template names; writes are contained to the memory root.
113
+ - An existing doc is never clobbered without `overwrite: true`.
114
+ - `schema` and `playbook` docs require `covers` — a doc whose staleness cannot be
115
+ detected is worse than no doc, because it will be trusted forever.
116
+ - Treat committed `.memory` content as **untrusted input** in any repo you did not
117
+ write. It reaches the model's context; review before trusting.
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@pal-code/memory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.18",
4
+ "description": "Repo knowledge memory for pal — schemas, playbooks and past runs the agent reads before re-exploring",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "exports": {
11
+ ".": "./src/index.ts"
12
+ },
13
+ "files": [
14
+ "src/**/*.ts"
15
+ ],
16
+ "dependencies": {
17
+ "@pal-code/core": "0.0.18"
18
+ },
19
+ "engines": {
20
+ "bun": ">=1.1.0"
21
+ }
22
+ }
@@ -0,0 +1,97 @@
1
+ import {describe, expect, test} from 'bun:test';
2
+
3
+ import {resolveMemorySettings} from './config.js';
4
+
5
+ import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs';
6
+ import {tmpdir} from 'node:os';
7
+ import {join} from 'node:path';
8
+
9
+ /** Point HOME at a temp dir so the user layer can be controlled. */
10
+ function withHome<T>(fn: (home: string) => T): T {
11
+ const home = mkdtempSync(join(tmpdir(), 'pal-memory-home-'));
12
+ const previous = process.env.HOME;
13
+ const previousProfile = process.env.USERPROFILE;
14
+ process.env.HOME = home;
15
+ process.env.USERPROFILE = home;
16
+ try {
17
+ return fn(home);
18
+ } finally {
19
+ if (previous === undefined) delete process.env.HOME;
20
+ else process.env.HOME = previous;
21
+ if (previousProfile === undefined) delete process.env.USERPROFILE;
22
+ else process.env.USERPROFILE = previousProfile;
23
+ rmSync(home, {recursive: true, force: true});
24
+ }
25
+ }
26
+
27
+ function project(files: Record<string, unknown>): string {
28
+ const dir = mkdtempSync(join(tmpdir(), 'pal-memory-proj-'));
29
+ for (const [name, content] of Object.entries(files)) {
30
+ writeFileSync(join(dir, name), JSON.stringify(content));
31
+ }
32
+ return dir;
33
+ }
34
+
35
+ describe('resolveMemorySettings', () => {
36
+ test('defaults when nothing is configured', () => {
37
+ const dir = project({});
38
+ withHome(() => {
39
+ const settings = resolveMemorySettings(dir);
40
+ expect(settings.dir).toBe('.memory');
41
+ expect(settings.write).toBe(false);
42
+ expect(settings.staleAfterDays).toBe(90);
43
+ });
44
+ rmSync(dir, {recursive: true, force: true});
45
+ });
46
+
47
+ test('project memory.json overrides defaults', () => {
48
+ const dir = project({'memory.json': {dir: '.notes', write: true, staleAfterDays: 30}});
49
+ withHome(() => {
50
+ const settings = resolveMemorySettings(dir);
51
+ expect(settings.dir).toBe('.notes');
52
+ expect(settings.write).toBe(true);
53
+ expect(settings.staleAfterDays).toBe(30);
54
+ });
55
+ rmSync(dir, {recursive: true, force: true});
56
+ });
57
+
58
+ test('user config wins over project config', () => {
59
+ const dir = project({'memory.json': {dir: '.project', write: false}});
60
+ withHome((home) => {
61
+ mkdirSync(join(home, '.pal'), {recursive: true});
62
+ writeFileSync(
63
+ join(home, '.pal', 'memory.json'),
64
+ JSON.stringify({dir: '.personal', write: true}),
65
+ );
66
+ const settings = resolveMemorySettings(dir);
67
+ expect(settings.dir).toBe('.personal');
68
+ expect(settings.write).toBe(true);
69
+ });
70
+ rmSync(dir, {recursive: true, force: true});
71
+ });
72
+
73
+ test('a malformed config is ignored rather than throwing', () => {
74
+ const dir = mkdtempSync(join(tmpdir(), 'pal-memory-bad-'));
75
+ writeFileSync(join(dir, 'memory.json'), '{not json');
76
+ withHome(() => {
77
+ expect(resolveMemorySettings(dir).dir).toBe('.memory');
78
+ });
79
+ rmSync(dir, {recursive: true, force: true});
80
+ });
81
+
82
+ test('an invalid staleAfterDays falls back instead of poisoning the value', () => {
83
+ const dir = project({'memory.json': {staleAfterDays: -5}});
84
+ withHome(() => {
85
+ expect(resolveMemorySettings(dir).staleAfterDays).toBe(90);
86
+ });
87
+ rmSync(dir, {recursive: true, force: true});
88
+ });
89
+
90
+ test('a non-boolean write flag is ignored', () => {
91
+ const dir = project({'memory.json': {write: 'yes'}});
92
+ withHome(() => {
93
+ expect(resolveMemorySettings(dir).write).toBe(false);
94
+ });
95
+ rmSync(dir, {recursive: true, force: true});
96
+ });
97
+ });
package/src/config.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `.memory` config — extension-owned, per EXTENSIONS.md.
3
+ *
4
+ * ./memory.json project (committed)
5
+ * ~/.pal/memory.json user
6
+ *
7
+ * Nothing here goes in `.pal.json`. Every field degrades to a default rather
8
+ * than throwing, because a bad config must never stop pal from starting.
9
+ */
10
+
11
+ import {existsSync, readFileSync} from 'node:fs';
12
+ import {homedir} from 'node:os';
13
+ import {join} from 'node:path';
14
+
15
+ export interface MemorySettings {
16
+ /** Directory name, relative to the repo root. */
17
+ dir: string;
18
+ /** Allow the write/record tools at all. Reads are always allowed. */
19
+ write: boolean;
20
+ /** How many days before a playbook is flagged stale even if `covers` is clean. */
21
+ staleAfterDays: number;
22
+ }
23
+
24
+ const DEFAULTS: MemorySettings = {
25
+ dir: '.memory',
26
+ write: false,
27
+ staleAfterDays: 90,
28
+ };
29
+
30
+ function readJson(path: string): Record<string, unknown> | null {
31
+ try {
32
+ if (!existsSync(path)) return null;
33
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));
34
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
35
+ return parsed as Record<string, unknown>;
36
+ } catch {
37
+ return null; // malformed config is ignored, never fatal
38
+ }
39
+ }
40
+
41
+ function coerce(raw: Record<string, unknown>): Partial<MemorySettings> {
42
+ const out: Partial<MemorySettings> = {};
43
+ if (typeof raw.dir === 'string' && raw.dir.trim() !== '') out.dir = raw.dir.trim();
44
+ if (typeof raw.write === 'boolean') out.write = raw.write;
45
+ if (typeof raw.staleAfterDays === 'number' && Number.isFinite(raw.staleAfterDays)) {
46
+ if (raw.staleAfterDays >= 0) out.staleAfterDays = Math.floor(raw.staleAfterDays);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /** Resolve settings: defaults → project `memory.json` → user `~/.pal/memory.json`. */
52
+ export function resolveMemorySettings(cwd: string = process.cwd()): MemorySettings {
53
+ const project = readJson(join(cwd, 'memory.json'));
54
+ const user = readJson(join(homedir(), '.pal', 'memory.json'));
55
+ return {
56
+ ...DEFAULTS,
57
+ ...(project ? coerce(project) : {}),
58
+ ...(user ? coerce(user) : {}),
59
+ };
60
+ }
61
+
62
+ /** Absolute path to the memory directory for a repo. */
63
+ export function memoryRoot(settings: MemorySettings, cwd: string = process.cwd()): string {
64
+ return join(cwd, settings.dir);
65
+ }
@@ -0,0 +1,87 @@
1
+ import {describe, expect, test} from 'bun:test';
2
+
3
+ import {parseMemoryFrontmatter, renderFrontmatter, splitList} from './frontmatter.js';
4
+
5
+ describe('parseMemoryFrontmatter', () => {
6
+ test('parses flat key: value pairs', () => {
7
+ const fm = parseMemoryFrontmatter('---\nkind: schema\nverified_at: abc123\n---\nbody text');
8
+ expect(fm?.fields.kind).toBe('schema');
9
+ expect(fm?.fields.verified_at).toBe('abc123');
10
+ expect(fm?.body).toBe('body text');
11
+ });
12
+
13
+ test('accepts a YAML list, which core-style flat parsing would reject', () => {
14
+ const fm = parseMemoryFrontmatter(
15
+ '---\ncovers:\n - db/migrations/**\n - src/db/**\nverified_at: abc\n---\nx',
16
+ );
17
+ expect(fm?.lists.covers).toEqual(['db/migrations/**', 'src/db/**']);
18
+ expect(fm?.fields.verified_at).toBe('abc');
19
+ });
20
+
21
+ test('accepts a comma-separated covers value', () => {
22
+ const fm = parseMemoryFrontmatter('---\ncovers: a/**, b/**\n---\nx');
23
+ expect(fm?.lists.covers).toEqual(['a/**', 'b/**']);
24
+ });
25
+
26
+ test('unquotes values and strips trailing comments', () => {
27
+ const fm = parseMemoryFrontmatter('---\nkind: "schema"\nidempotent: false # default\n---\nx');
28
+ expect(fm?.fields.kind).toBe('schema');
29
+ expect(fm?.fields.idempotent).toBe('false');
30
+ });
31
+
32
+ test('keeps a placeholder verified_at distinguishable from a real one', () => {
33
+ const fm = parseMemoryFrontmatter('---\nverified_at: <git sha>\n---\nx');
34
+ expect(fm?.fields.verified_at).toBe('<git sha>');
35
+ });
36
+
37
+ test('returns null without frontmatter', () => {
38
+ expect(parseMemoryFrontmatter('# just a doc')).toBeNull();
39
+ });
40
+
41
+ test('returns null on an unterminated block', () => {
42
+ expect(parseMemoryFrontmatter('---\nkind: schema\nno closing')).toBeNull();
43
+ });
44
+
45
+ test('returns null on a malformed line', () => {
46
+ expect(parseMemoryFrontmatter('---\nnot a pair\n---\nx')).toBeNull();
47
+ });
48
+
49
+ test('tolerates a BOM', () => {
50
+ const fm = parseMemoryFrontmatter('\uFEFF---\nkind: schema\n---\nx');
51
+ expect(fm?.fields.kind).toBe('schema');
52
+ });
53
+ });
54
+
55
+ describe('renderFrontmatter', () => {
56
+ test('round-trips through the parser', () => {
57
+ const rendered = renderFrontmatter(
58
+ {kind: 'schema', verified_at: 'abc'},
59
+ {covers: ['a/**', 'b/**']},
60
+ );
61
+ const parsed = parseMemoryFrontmatter(`${rendered}\nbody`);
62
+ expect(parsed?.fields.kind).toBe('schema');
63
+ expect(parsed?.lists.covers).toEqual(['a/**', 'b/**']);
64
+ expect(parsed?.body).toBe('body');
65
+ });
66
+
67
+ test('writes a round-trippable comma form, not a YAML list', () => {
68
+ const rendered = renderFrontmatter({kind: 'schema'}, {covers: ['a/**', 'b/**']});
69
+ expect(rendered).toContain('covers: a/**, b/**');
70
+ });
71
+
72
+ test('omits null and empty values', () => {
73
+ const rendered = renderFrontmatter({kind: 'schema', applied_at: null}, {covers: []});
74
+ expect(rendered).not.toContain('applied_at');
75
+ expect(rendered).not.toContain('covers');
76
+ });
77
+ });
78
+
79
+ describe('splitList', () => {
80
+ test('splits and trims', () => {
81
+ expect(splitList('a, b ,c')).toEqual(['a', 'b', 'c']);
82
+ });
83
+
84
+ test('drops empty entries', () => {
85
+ expect(splitList('a,,b,')).toEqual(['a', 'b']);
86
+ });
87
+ });
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Frontmatter reader for `.memory` docs.
3
+ *
4
+ * Deliberately does NOT reuse core's `parseFrontmatter`: that one is flat
5
+ * `key: value` only and returns `null` on a YAML list, which is the natural way
6
+ * to write `covers:`. A knowledge doc that core would reject as "malformed"
7
+ * must still parse here, so this reader accepts both styles:
8
+ *
9
+ * covers: a/**, b/** (comma-separated, preferred — writes stay simple)
10
+ * covers:
11
+ * - a/**
12
+ * - b/**
13
+ *
14
+ * Malformed input still yields `null` so callers can warn and skip.
15
+ */
16
+
17
+ export interface MemoryFrontmatter {
18
+ /** Scalar fields. List-valued fields are joined with `, ` for uniformity. */
19
+ fields: Record<string, string>;
20
+ /** Multi-value fields, keyed by name (e.g. `covers`). */
21
+ lists: Record<string, string[]>;
22
+ /** Everything after the closing `---`. */
23
+ body: string;
24
+ }
25
+
26
+ const LIST_KEY = /^([A-Za-z_][\w-]*)\s*:\s*$/;
27
+ const SCALAR_KEY = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/;
28
+ const LIST_ITEM = /^-\s+(.*)$/;
29
+
30
+ function unquote(value: string): string {
31
+ const trimmed = value.trim();
32
+ if (trimmed.length >= 2) {
33
+ const first = trimmed[0];
34
+ const last = trimmed[trimmed.length - 1];
35
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
36
+ return trimmed.slice(1, -1);
37
+ }
38
+ }
39
+ // Drop a trailing ` # comment` that follows an unquoted value.
40
+ const comment = trimmed.indexOf(' #');
41
+ return comment === -1 ? trimmed : trimmed.slice(0, comment).trim();
42
+ }
43
+
44
+ /** Split a comma/space separated scalar into list items. */
45
+ export function splitList(value: string): string[] {
46
+ return value
47
+ .split(',')
48
+ .map((item) => unquote(item))
49
+ .filter((item) => item !== '');
50
+ }
51
+
52
+ export function parseMemoryFrontmatter(text: string): MemoryFrontmatter | null {
53
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
54
+ const lines = source.split(/\r?\n/);
55
+ if (lines[0]?.trim() !== '---') return null;
56
+
57
+ const fields: Record<string, string> = {};
58
+ const lists: Record<string, string[]> = {};
59
+ let closing = -1;
60
+
61
+ for (let i = 1; i < lines.length; i++) {
62
+ const raw = lines[i];
63
+ const line = raw.trim();
64
+
65
+ if (line === '---') {
66
+ closing = i;
67
+ break;
68
+ }
69
+ if (line === '' || line.startsWith('#')) continue;
70
+
71
+ const listKey = LIST_KEY.exec(line);
72
+ if (listKey) {
73
+ // Consume the following `- item` lines (indented or not).
74
+ const items: string[] = [];
75
+ while (i + 1 < lines.length) {
76
+ const next = lines[i + 1].trim();
77
+ if (next === '' || next.startsWith('#')) {
78
+ i++;
79
+ continue;
80
+ }
81
+ const item = LIST_ITEM.exec(next);
82
+ if (!item) break;
83
+ const value = unquote(item[1]);
84
+ if (value !== '') items.push(value);
85
+ i++;
86
+ }
87
+ lists[listKey[1]] = items;
88
+ continue;
89
+ }
90
+
91
+ const scalar = SCALAR_KEY.exec(line);
92
+ if (!scalar) return null; // not `key: value` and not a list → malformed
93
+ const key = scalar[1];
94
+ const value = unquote(scalar[2]);
95
+ fields[key] = value;
96
+
97
+ // A comma-separated value for a known list field is normalised into `lists`
98
+ // as well, so callers never have to care which style the author used.
99
+ if (key === 'covers' || key === 'schema_docs' || key === 'tags') {
100
+ lists[key] = splitList(value);
101
+ }
102
+ }
103
+
104
+ if (closing === -1) return null; // unterminated block
105
+ return {fields, lists, body: lines.slice(closing + 1).join('\n')};
106
+ }
107
+
108
+ /** Serialise fields + lists back into a `---` block. */
109
+ export function renderFrontmatter(
110
+ fields: Record<string, string | number | boolean | null>,
111
+ lists: Record<string, string[]>,
112
+ ): string {
113
+ const lines = ['---'];
114
+ for (const [key, value] of Object.entries(fields)) {
115
+ if (value === null || value === undefined) continue;
116
+ lines.push(`${key}: ${value}`);
117
+ }
118
+ for (const [key, values] of Object.entries(lists)) {
119
+ if (values.length === 0) continue;
120
+ lines.push(`${key}: ${values.join(', ')}`);
121
+ }
122
+ lines.push('---');
123
+ return lines.join('\n');
124
+ }