@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
package/README.md
CHANGED
|
@@ -1,3 +1,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pal-code/memory
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
The `.memory/` directory is created on load when writing is enabled, which it is by
|
|
21
|
+
default — so the tools work immediately after install. **With `write: false` and no
|
|
22
|
+
existing directory, there are no tools and no prompt**: the extension reports itself
|
|
23
|
+
unavailable, so repos that don't use it pay zero tokens. That gating mirrors
|
|
24
|
+
`@pal-code/jev`.
|
|
25
|
+
|
|
26
|
+
## Why the staleness verdict is the whole design
|
|
27
|
+
|
|
28
|
+
The failure mode of every "agent memory folder" is silent drift: a note that was
|
|
29
|
+
true three refactors ago reads exactly like a fresh one. So a doc is never trusted
|
|
30
|
+
on its own word. Each doc declares:
|
|
31
|
+
|
|
32
|
+
```yaml
|
|
33
|
+
covers: db/migrations/**, src/db/** # what it describes
|
|
34
|
+
verified_at: <git sha> # when it was checked
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`memory_lookup` runs `git diff --name-only <verified_at>..HEAD -- <covers>` and
|
|
38
|
+
reports one of:
|
|
39
|
+
|
|
40
|
+
| Verdict | Meaning | What the agent should do |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `fresh` | covered paths unchanged since `verified_at` | **trust it, skip exploring those paths** |
|
|
43
|
+
| `stale` | covered paths changed (it lists which) | hint only — verify against the code |
|
|
44
|
+
| `unknown` | no `verified_at` | hint only |
|
|
45
|
+
| `uncheckable` | bad sha, no `covers`, or not a repo | hint only |
|
|
46
|
+
|
|
47
|
+
`memory_save` defaults `verified_at` to HEAD, so a doc written right after verifying
|
|
48
|
+
against real code is immediately `fresh` — and starts decaying the moment that code
|
|
49
|
+
changes.
|
|
50
|
+
|
|
51
|
+
## Layout
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
.memory/
|
|
55
|
+
index.md # one screen, the session entry point
|
|
56
|
+
schemas/<schema>.md # tables, FKs, gotchas
|
|
57
|
+
playbooks/<workflow>.md # reusable STEPS for a recurring task
|
|
58
|
+
runs/<date>-<slug>/ # one past execution: intent.md + script.sql
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`playbook` and `run` are deliberately separate: a playbook is the workflow, a run is
|
|
62
|
+
one instance of it. Knowledge kept only in a run dies with that run.
|
|
63
|
+
|
|
64
|
+
Directories starting with `_` are skipped, so `_TEMPLATE.md` files can live alongside
|
|
65
|
+
real docs.
|
|
66
|
+
|
|
67
|
+
## Config
|
|
68
|
+
|
|
69
|
+
Extension-owned (per `EXTENSIONS.md`) — nothing goes in `.pal.json`:
|
|
70
|
+
|
|
71
|
+
| Level | Path |
|
|
72
|
+
|---|---|
|
|
73
|
+
| Project | `./memory.json` |
|
|
74
|
+
| User | `~/.pal/memory.json` |
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{
|
|
78
|
+
"dir": ".memory",
|
|
79
|
+
"write": true,
|
|
80
|
+
"staleAfterDays": 90
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Key | Default | Meaning |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| `dir` | `.memory` | Directory name, relative to the repo root |
|
|
87
|
+
| `write` | `true` | Allow `memory_save`, and create the directory on load. Reads always work |
|
|
88
|
+
| `staleAfterDays` | `90` | Reserved for time-based decay |
|
|
89
|
+
|
|
90
|
+
Resolution: defaults → project → user. A malformed config is ignored, never fatal.
|
|
91
|
+
|
|
92
|
+
**Writing is on by default**, mirroring `@pal-code/workflow`. On load, `setup()`
|
|
93
|
+
creates the memory directory when `write` is on, so a fresh repo gets working tools
|
|
94
|
+
without hand-editing anything — the same chicken-and-egg `work_start` solves for
|
|
95
|
+
`.work`. The directory is not seeded with an `index.md`; an empty directory already
|
|
96
|
+
reads as "no knowledge recorded yet".
|
|
97
|
+
|
|
98
|
+
Opt out with `{"write": false}`. Auto-writing knowledge can produce junk that later
|
|
99
|
+
agents trust, so a repo that does not want memory on disk should turn it off
|
|
100
|
+
explicitly rather than relying on the extension being inert.
|
|
101
|
+
|
|
102
|
+
## Keeping it out of git
|
|
103
|
+
|
|
104
|
+
Hide the directory machine-wide rather than in any project `.gitignore`:
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
mkdir -p ~/.config/git
|
|
108
|
+
printf '.memory/\n' >> ~/.config/git/ignore
|
|
109
|
+
git config --global core.excludesFile ~/.config/git/ignore
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`ripgrep` and `biome` inherit this through git, so nothing lints or greps it either.
|
|
113
|
+
|
|
114
|
+
One consequence worth knowing: `pal`'s `grep_search` passes `--hidden` but not
|
|
115
|
+
`--no-ignore`, so it will **not** find `.memory` content. Address it by path
|
|
116
|
+
(`memory_lookup`, or `read .memory/index.md`) rather than by searching for it.
|
|
117
|
+
|
|
118
|
+
## Safety notes
|
|
119
|
+
|
|
120
|
+
- `saveDoc` refuses ids containing `..`, absolute paths, non-`.md` names, and
|
|
121
|
+
`_`-prefixed template names; writes are contained to the memory root.
|
|
122
|
+
- An existing doc is never clobbered without `overwrite: true`.
|
|
123
|
+
- `schema` and `playbook` docs require `covers` — a doc whose staleness cannot be
|
|
124
|
+
detected is worse than no doc, because it will be trusted forever.
|
|
125
|
+
- Treat committed `.memory` content as **untrusted input** in any repo you did not
|
|
126
|
+
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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.19",
|
|
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.19"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"bun": ">=1.1.0"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
// Writing defaults on so a fresh repo gets working tools; see config.ts.
|
|
42
|
+
expect(settings.write).toBe(true);
|
|
43
|
+
expect(settings.staleAfterDays).toBe(90);
|
|
44
|
+
});
|
|
45
|
+
rmSync(dir, {recursive: true, force: true});
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('project memory.json overrides defaults', () => {
|
|
49
|
+
const dir = project({'memory.json': {dir: '.notes', write: true, staleAfterDays: 30}});
|
|
50
|
+
withHome(() => {
|
|
51
|
+
const settings = resolveMemorySettings(dir);
|
|
52
|
+
expect(settings.dir).toBe('.notes');
|
|
53
|
+
expect(settings.write).toBe(true);
|
|
54
|
+
expect(settings.staleAfterDays).toBe(30);
|
|
55
|
+
});
|
|
56
|
+
rmSync(dir, {recursive: true, force: true});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('user config wins over project config', () => {
|
|
60
|
+
const dir = project({'memory.json': {dir: '.project', write: false}});
|
|
61
|
+
withHome((home) => {
|
|
62
|
+
mkdirSync(join(home, '.pal'), {recursive: true});
|
|
63
|
+
writeFileSync(
|
|
64
|
+
join(home, '.pal', 'memory.json'),
|
|
65
|
+
JSON.stringify({dir: '.personal', write: true}),
|
|
66
|
+
);
|
|
67
|
+
const settings = resolveMemorySettings(dir);
|
|
68
|
+
expect(settings.dir).toBe('.personal');
|
|
69
|
+
expect(settings.write).toBe(true);
|
|
70
|
+
});
|
|
71
|
+
rmSync(dir, {recursive: true, force: true});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('a malformed config is ignored rather than throwing', () => {
|
|
75
|
+
const dir = mkdtempSync(join(tmpdir(), 'pal-memory-bad-'));
|
|
76
|
+
writeFileSync(join(dir, 'memory.json'), '{not json');
|
|
77
|
+
withHome(() => {
|
|
78
|
+
expect(resolveMemorySettings(dir).dir).toBe('.memory');
|
|
79
|
+
});
|
|
80
|
+
rmSync(dir, {recursive: true, force: true});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('an invalid staleAfterDays falls back instead of poisoning the value', () => {
|
|
84
|
+
const dir = project({'memory.json': {staleAfterDays: -5}});
|
|
85
|
+
withHome(() => {
|
|
86
|
+
expect(resolveMemorySettings(dir).staleAfterDays).toBe(90);
|
|
87
|
+
});
|
|
88
|
+
rmSync(dir, {recursive: true, force: true});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test('a non-boolean write flag is ignored', () => {
|
|
92
|
+
const dir = project({'memory.json': {write: 'yes'}});
|
|
93
|
+
withHome(() => {
|
|
94
|
+
// Falls back to the default (true) rather than coercing the string.
|
|
95
|
+
expect(resolveMemorySettings(dir).write).toBe(true);
|
|
96
|
+
});
|
|
97
|
+
rmSync(dir, {recursive: true, force: true});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('an explicit write:false is honoured against the on-by-default', () => {
|
|
101
|
+
const dir = project({'memory.json': {write: false}});
|
|
102
|
+
withHome(() => {
|
|
103
|
+
expect(resolveMemorySettings(dir).write).toBe(false);
|
|
104
|
+
});
|
|
105
|
+
rmSync(dir, {recursive: true, force: true});
|
|
106
|
+
});
|
|
107
|
+
});
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
// Writing is on by default, mirroring `@pal-code/workflow`. Setup creates the
|
|
27
|
+
// directory on load, so a fresh repo gets working memory tools instead of an
|
|
28
|
+
// extension that is inert until the user hand-edits two files. A repo that
|
|
29
|
+
// does not want memory on disk sets `{"write": false}`.
|
|
30
|
+
write: true,
|
|
31
|
+
staleAfterDays: 90,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function readJson(path: string): Record<string, unknown> | null {
|
|
35
|
+
try {
|
|
36
|
+
if (!existsSync(path)) return null;
|
|
37
|
+
const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));
|
|
38
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
39
|
+
return parsed as Record<string, unknown>;
|
|
40
|
+
} catch {
|
|
41
|
+
return null; // malformed config is ignored, never fatal
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function coerce(raw: Record<string, unknown>): Partial<MemorySettings> {
|
|
46
|
+
const out: Partial<MemorySettings> = {};
|
|
47
|
+
if (typeof raw.dir === 'string' && raw.dir.trim() !== '') out.dir = raw.dir.trim();
|
|
48
|
+
if (typeof raw.write === 'boolean') out.write = raw.write;
|
|
49
|
+
if (typeof raw.staleAfterDays === 'number' && Number.isFinite(raw.staleAfterDays)) {
|
|
50
|
+
if (raw.staleAfterDays >= 0) out.staleAfterDays = Math.floor(raw.staleAfterDays);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Resolve settings: defaults → project `memory.json` → user `~/.pal/memory.json`. */
|
|
56
|
+
export function resolveMemorySettings(cwd: string = process.cwd()): MemorySettings {
|
|
57
|
+
const project = readJson(join(cwd, 'memory.json'));
|
|
58
|
+
const user = readJson(join(homedir(), '.pal', 'memory.json'));
|
|
59
|
+
return {
|
|
60
|
+
...DEFAULTS,
|
|
61
|
+
...(project ? coerce(project) : {}),
|
|
62
|
+
...(user ? coerce(user) : {}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Absolute path to the memory directory for a repo. */
|
|
67
|
+
export function memoryRoot(settings: MemorySettings, cwd: string = process.cwd()): string {
|
|
68
|
+
return join(cwd, settings.dir);
|
|
69
|
+
}
|
|
@@ -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
|
+
}
|