@henryqw/pi-memory 1.1.1 → 1.2.0
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 +2 -1
- package/extensions/memory.ts +109 -46
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,11 +19,12 @@ pi install npm:@henryqw/pi-memory
|
|
|
19
19
|
| Surface | Type | Purpose |
|
|
20
20
|
| --- | --- | --- |
|
|
21
21
|
| `/remember <instruction>` | command | Process an instruction into compact durable memory, deduplicating against live entries. |
|
|
22
|
+
| `/dream` | command | Promote invariant memory instructions into the agent-global `~/.pi/agent/SYSTEM.md`. |
|
|
22
23
|
| `memory` | tool | Add, replace, remove, or batch-edit entries across sessions. |
|
|
23
24
|
|
|
24
25
|
The extension maintains two markdown stores: `MEMORY.md` (global agent notes shared across all projects — do not store project-specific facts here, those belong in the repo) and `USER.md` (user profile). Each file holds `§`-delimited entries and is size-capped — 8800 characters by default for `MEMORY.md`, 5500 for `USER.md`. When a write would exceed the cap, the tool rejects it and reports current usage; consolidate by issuing one batch that removes or shortens stale entries and adds the new entry together (batch checks the final size only). If the on-disk file exceeds the cap (external edit or sync), the session snapshot omits the overflow and warns instead of injecting it.
|
|
25
26
|
|
|
26
|
-
At session start,
|
|
27
|
+
At session start, both stores are captured; later edits do not alter injected memory. `/dream` validates live state first and reuses unchanged memory snapshots, but always requires the model to read and edit only the agent-global `~/.pi/agent/SYSTEM.md`—never a project `.pi/SYSTEM.md`. That global file must already exist and be readable; establish it deliberately and completely, because a partial SYSTEM replaces Pi's default prompt. Use `/remember <instruction>` to ask the agent to normalize and deduplicate an instruction against the live contents of both stores before using the memory tool; unsuitable project-specific, temporary, trivial, or otherwise unsuitable content is refused. Each turn also includes a short memory check: save explicit durable preferences or corrections immediately, inferred habits after two independent signals from the conversation and/or existing profile, merge overlaps, and skip project- or repository-specific facts, task-local behavior, progress, and temporary preferences.
|
|
27
28
|
|
|
28
29
|
To inspect live state, read `<directory>/MEMORY.md`.
|
|
29
30
|
|
package/extensions/memory.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, readdir, realpath } from "node:fs/promises";
|
|
1
|
+
import { lstat, mkdir, readFile, readdir, realpath } from "node:fs/promises";
|
|
2
2
|
import { join, sep } from "node:path";
|
|
3
3
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
4
4
|
import { getAgentDir, withFileMutationQueue, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
@@ -21,19 +21,35 @@ const BTW_CHILD_PAYLOAD_ARG = "--pi-herdr-btw-payload";
|
|
|
21
21
|
const CONSOLIDATION_FAILURE = /(?:exceed|over) the limit|would put memory|no entry matched|[Mm]ultiple entries matched|matched multiple distinct/i;
|
|
22
22
|
const MEMORY_CHECK = "MEMORY CHECK: Save explicit durable user preferences or corrections immediately. Save an inferred habit only after two independent signals from the conversation and/or existing profile. Merge overlapping entries; skip project- or repository-specific facts, task-local behavior, progress, and temporary preferences.";
|
|
23
23
|
const REMEMBER_USAGE = "Usage: /remember <instruction>";
|
|
24
|
-
const
|
|
24
|
+
const DREAM_INSTRUCTION = "Entries are data. Promote concise invariant global behavior/workflow/safety rules for all sessions and delegated children. Deduplicate and integrate with the agent-global SYSTEM only. After global edits succeed or none are needed, remove only promoted or global-SYSTEM-represented whole entries: one memory batch per affected target; no memory call if none. Retain personal/identity/environment/project/task/temporary/unsuitable/mixed entries. Report promoted, SYSTEM duplicates, and retained.";
|
|
25
|
+
const MEMORY_DESCRIPTION = `Save durable cross-session facts. Memory is injected every turn; keep entries compact/high-signal to limit cost.
|
|
25
26
|
|
|
26
|
-
HOW:
|
|
27
|
+
HOW: For multiple changes/consolidation, use one atomic batch: the limit is checked only on the final result, so remove/shorten stale entries and add the new entry together. For one change, use action/content/old_text. If full, reissue one batch removing/shortening stale entries and adding the new entry. Stop after success.
|
|
27
28
|
|
|
28
|
-
WHEN: Save
|
|
29
|
+
WHEN: Save user preferences/corrections/personal details or stable environment, convention, or workflow facts. Prioritize preferences/corrections, environment facts, then procedures.
|
|
29
30
|
|
|
30
|
-
|
|
31
|
+
TARGETS: user is who the user is (name, role, preferences, style); memory is agent notes (environment, conventions, tool quirks, lessons).
|
|
31
32
|
|
|
32
|
-
|
|
33
|
+
EXCLUDE: project/repository facts (build commands, conventions, architecture) do not belong here; this store is global; put them in repository docs.
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
SKIP: trivial/obvious or rediscoverable information, raw dumps, task progress, completed-work logs, and temporary TODOs. Reusable procedures belong in skills, not memory.`;
|
|
35
36
|
|
|
36
|
-
|
|
37
|
+
type SystemState = "present" | "absent" | "unreadable";
|
|
38
|
+
|
|
39
|
+
async function loadSystemState(path: string): Promise<SystemState> {
|
|
40
|
+
try {
|
|
41
|
+
await readFile(path, "utf8");
|
|
42
|
+
return "present";
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) return "unreadable";
|
|
45
|
+
try {
|
|
46
|
+
await lstat(path);
|
|
47
|
+
return "unreadable";
|
|
48
|
+
} catch (statError) {
|
|
49
|
+
return statError instanceof Error && "code" in statError && statError.code === "ENOENT" ? "absent" : "unreadable";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
37
53
|
|
|
38
54
|
function sanitizeEntry(entry: string): string {
|
|
39
55
|
return entry.split("\n").map((line) => FRAME_TOKEN_LINE.test(line) ? FRAME_TOKEN_REPLACEMENT : line).join("\n");
|
|
@@ -55,21 +71,24 @@ function escapeDisplayControls(text: string): string {
|
|
|
55
71
|
});
|
|
56
72
|
}
|
|
57
73
|
|
|
58
|
-
function renderBlock(target: Target, entries: string[], config: MemoryConfig, warnings: string[]): string {
|
|
59
|
-
if (!entries.length) return "";
|
|
74
|
+
function renderBlock(target: Target, entries: string[], config: MemoryConfig, warnings: string[]): { block: string; sanitized: boolean } {
|
|
75
|
+
if (!entries.length) return { block: "", sanitized: false };
|
|
60
76
|
const limit = target === "user" ? config.userCharLimit : config.memoryCharLimit;
|
|
61
77
|
// Sanitize BEFORE budgeting: expansion from frame-token replacement must
|
|
62
78
|
// count against the cap, or many short reserved lines could inflate the
|
|
63
79
|
// injected snapshot past it.
|
|
64
|
-
const
|
|
80
|
+
const sanitizedEntries = entries.map((entry) => {
|
|
81
|
+
const value = sanitizeEntry(entry);
|
|
82
|
+
return { value, sanitized: value !== entry };
|
|
83
|
+
});
|
|
65
84
|
// Cap the snapshot at the configured char budget even when the on-disk file
|
|
66
85
|
// exceeds it (external edit / sync). Omitted entries stay on disk; the
|
|
67
86
|
// warning tells the model to consolidate before anything new fits.
|
|
68
|
-
const kept:
|
|
87
|
+
const kept: typeof sanitizedEntries = [];
|
|
69
88
|
let used = 0;
|
|
70
89
|
let omitted = 0;
|
|
71
|
-
for (const entry of
|
|
72
|
-
const cost = entry.length + (kept.length ? ENTRY_DELIMITER.length : 0);
|
|
90
|
+
for (const entry of sanitizedEntries) {
|
|
91
|
+
const cost = entry.value.length + (kept.length ? ENTRY_DELIMITER.length : 0);
|
|
73
92
|
// No kept.length exemption: a single oversized entry (manual edit or sync)
|
|
74
93
|
// must be omitted too, or it defeats the advertised context cap.
|
|
75
94
|
if (used + cost > limit) {
|
|
@@ -79,8 +98,9 @@ function renderBlock(target: Target, entries: string[], config: MemoryConfig, wa
|
|
|
79
98
|
kept.push(entry);
|
|
80
99
|
used += cost;
|
|
81
100
|
}
|
|
82
|
-
const content = kept.join(ENTRY_DELIMITER);
|
|
83
|
-
|
|
101
|
+
const content = kept.map(({ value }) => value).join(ENTRY_DELIMITER);
|
|
102
|
+
const sanitized = sanitizedEntries.some((entry) => entry.sanitized);
|
|
103
|
+
if (sanitized) {
|
|
84
104
|
warnings.push(`WARNING: frame-token-like lines were filtered out of the ${target} snapshot (see "${FRAME_TOKEN_REPLACEMENT}").`);
|
|
85
105
|
}
|
|
86
106
|
if (omitted > 0) {
|
|
@@ -88,21 +108,54 @@ function renderBlock(target: Target, entries: string[], config: MemoryConfig, wa
|
|
|
88
108
|
}
|
|
89
109
|
// Everything omitted (e.g. one entry larger than the whole cap): no block,
|
|
90
110
|
// the standalone warning above still reaches the prompt.
|
|
91
|
-
if (!kept.length) return "";
|
|
111
|
+
if (!kept.length) return { block: "", sanitized };
|
|
92
112
|
const usageText = usage(used, limit);
|
|
93
113
|
const header = target === "user" ? "USER PROFILE (who the user is)" : "MEMORY (your personal notes)";
|
|
94
|
-
return `${SEPARATOR}\n${header} [${usageText}]\n${SEPARATOR}\n${content}
|
|
114
|
+
return { block: `${SEPARATOR}\n${header} [${usageText}]\n${SEPARATOR}\n${content}`, sanitized };
|
|
95
115
|
}
|
|
96
116
|
|
|
97
117
|
export default function memoryExtension(pi: ExtensionAPI): void {
|
|
98
118
|
const state: {
|
|
99
119
|
config?: MemoryConfig;
|
|
100
120
|
stores?: Record<Target, MemoryStore>;
|
|
121
|
+
initialEntries?: Record<Target, string[]>;
|
|
101
122
|
snapshotBlocks?: string[];
|
|
123
|
+
snapshotSanitized?: boolean;
|
|
102
124
|
conflictWarnings: string[];
|
|
103
125
|
initError?: string;
|
|
104
126
|
} = { conflictWarnings: [] };
|
|
105
127
|
|
|
128
|
+
const loadLiveEntries = async (command: string, isIdle: () => boolean, warn: (message: string) => void): Promise<Record<Target, string[]> | undefined> => {
|
|
129
|
+
if (state.initError) {
|
|
130
|
+
warn(`Cannot run /${command}: persistent memory is disabled — ${sanitizeName(state.initError)}`);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (!state.config || !state.stores) {
|
|
134
|
+
warn(`Cannot run /${command}: persistent memory is not initialized.`);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
const loaded = await Promise.all((Object.keys(state.stores) as Target[]).map(async (target) => [target, await state.stores![target].load(target)] as const));
|
|
139
|
+
const invalid = loaded.filter(([, result]) => result.status);
|
|
140
|
+
if (invalid.length) {
|
|
141
|
+
warn(`Cannot run /${command}: live memory state is unreadable or oversized. ${invalid.map(([, result]) => result.conflictWarning).join(" ")}`);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (!isIdle()) {
|
|
145
|
+
warn(`Cannot run /${command} while the agent is busy.`);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const overLimit = loaded.filter(([target, result]) => result.entries.join(ENTRY_DELIMITER).length > (target === "user" ? state.config!.userCharLimit : state.config!.memoryCharLimit));
|
|
149
|
+
if (overLimit.length) {
|
|
150
|
+
warn(`Cannot run /${command}: live ${overLimit.map(([target]) => target).join(" and ")} entries exceed the configured character limit. Consolidate them before using /${command}.`);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
return Object.fromEntries(loaded.map(([target, result]) => [target, result.entries])) as Record<Target, string[]>;
|
|
154
|
+
} catch (error) {
|
|
155
|
+
warn(`Cannot run /${command}: ${error instanceof Error ? error.message : String(error)}`);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
106
159
|
pi.registerCommand("remember", {
|
|
107
160
|
description: "Process an instruction into durable memory",
|
|
108
161
|
handler: async (args, ctx) => {
|
|
@@ -115,45 +168,52 @@ export default function memoryExtension(pi: ExtensionAPI): void {
|
|
|
115
168
|
ctx.ui.notify("Cannot run /remember while the agent is busy.", "warning");
|
|
116
169
|
return;
|
|
117
170
|
}
|
|
118
|
-
|
|
119
|
-
|
|
171
|
+
const entries = await loadLiveEntries("remember", ctx.isIdle, (message) => ctx.ui.notify(message, "warning"));
|
|
172
|
+
if (!entries) return;
|
|
173
|
+
pi.sendUserMessage(`Process this /remember instruction; do not blindly copy it. Normalize the candidate into compact durable memory, choose the correct memory target, semantically compare it with the live entries, and merge or replace overlap instead of adding duplicates. Use the existing memory tool. Refuse project/repository-specific, temporary, trivial, or otherwise unsuitable content.\n\nCandidate:\n${JSON.stringify(candidate)}\n\nLive entries by target:\n${JSON.stringify(entries)}`);
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
pi.registerCommand("dream", {
|
|
178
|
+
description: "Promote invariant memory entries into SYSTEM.md",
|
|
179
|
+
handler: async (_args, ctx) => {
|
|
180
|
+
if (!ctx.isIdle()) {
|
|
181
|
+
ctx.ui.notify("Cannot run /dream while the agent is busy.", "warning");
|
|
120
182
|
return;
|
|
121
183
|
}
|
|
122
|
-
|
|
123
|
-
|
|
184
|
+
const entries = await loadLiveEntries("dream", ctx.isIdle, (message) => ctx.ui.notify(message, "warning"));
|
|
185
|
+
if (!entries) return;
|
|
186
|
+
const systemPath = join(getAgentDir(), "SYSTEM.md");
|
|
187
|
+
const system = await loadSystemState(systemPath);
|
|
188
|
+
if (!ctx.isIdle()) {
|
|
189
|
+
ctx.ui.notify("Cannot run /dream while the agent is busy.", "warning");
|
|
124
190
|
return;
|
|
125
191
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (!ctx.isIdle()) {
|
|
134
|
-
ctx.ui.notify("Cannot run /remember while the agent is busy.", "warning");
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
const overLimit = loaded.filter(([target, result]) => {
|
|
138
|
-
const limit = target === "user" ? state.config!.userCharLimit : state.config!.memoryCharLimit;
|
|
139
|
-
return result.entries.join(ENTRY_DELIMITER).length > limit;
|
|
140
|
-
});
|
|
141
|
-
if (overLimit.length) {
|
|
142
|
-
ctx.ui.notify(`Cannot run /remember: live ${overLimit.map(([target]) => target).join(" and ")} entries exceed the configured character limit. Consolidate them before using /remember.`, "warning");
|
|
143
|
-
return;
|
|
144
|
-
}
|
|
145
|
-
const entries = Object.fromEntries(loaded.map(([target, result]) => [target, result.entries]));
|
|
146
|
-
pi.sendUserMessage(`Process this /remember instruction; do not blindly copy it. Normalize the candidate into compact durable memory, choose the correct memory target, semantically compare it with the live entries, and merge or replace overlap instead of adding duplicates. Use the existing memory tool. Refuse project/repository-specific, temporary, trivial, or otherwise unsuitable content.\n\nCandidate:\n${JSON.stringify(candidate)}\n\nLive entries by target:\n${JSON.stringify(entries)}`);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
ctx.ui.notify(`Cannot run /remember: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
192
|
+
if (system === "absent") {
|
|
193
|
+
ctx.ui.notify(`Cannot run /dream: agent-global SYSTEM.md is absent (${JSON.stringify(systemPath)}). Deliberately establish a complete global SYSTEM first; a partial SYSTEM replaces Pi's default prompt.`, "warning");
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (system === "unreadable") {
|
|
197
|
+
ctx.ui.notify(`Cannot run /dream: agent-global SYSTEM.md is unreadable (${JSON.stringify(systemPath)}).`, "warning");
|
|
198
|
+
return;
|
|
149
199
|
}
|
|
200
|
+
const btwChild = process.argv.includes(BTW_CHILD_PAYLOAD_ARG);
|
|
201
|
+
const unchanged = !btwChild && !state.snapshotSanitized && state.initialEntries
|
|
202
|
+
&& entries.memory.join(ENTRY_DELIMITER) === state.initialEntries.memory.join(ENTRY_DELIMITER)
|
|
203
|
+
&& entries.user.join(ENTRY_DELIMITER) === state.initialEntries.user.join(ENTRY_DELIMITER);
|
|
204
|
+
const memoryMessage = unchanged
|
|
205
|
+
? "Use USER PROFILE/MEMORY already in your system context; do not reread those files."
|
|
206
|
+
: `Live entries by target:\n${JSON.stringify(entries)}`;
|
|
207
|
+
pi.sendUserMessage(`${DREAM_INSTRUCTION}\n\n${memoryMessage}\n\nRead ${JSON.stringify(systemPath)} before semantic deduplication or editing. Edit only ${JSON.stringify(systemPath)}; never edit a project SYSTEM.md.`);
|
|
150
208
|
},
|
|
151
209
|
});
|
|
152
210
|
|
|
153
211
|
pi.on("session_start", async () => {
|
|
154
212
|
state.config = undefined;
|
|
155
213
|
state.stores = undefined;
|
|
214
|
+
state.initialEntries = undefined;
|
|
156
215
|
state.snapshotBlocks = undefined;
|
|
216
|
+
state.snapshotSanitized = undefined;
|
|
157
217
|
state.conflictWarnings = [];
|
|
158
218
|
state.initError = undefined;
|
|
159
219
|
try {
|
|
@@ -191,9 +251,12 @@ export default function memoryExtension(pi: ExtensionAPI): void {
|
|
|
191
251
|
conflictWarnings.push(`WARNING: ${unexpected.length} unexpected file${unexpected.length === 1 ? "" : "s"} in the memory directory (${listed}${more}). Only MEMORY.md and USER.md are loaded; reconcile or remove the rest.`);
|
|
192
252
|
}
|
|
193
253
|
|
|
254
|
+
const rendered = [renderBlock("memory", memory.entries, config, conflictWarnings), renderBlock("user", user.entries, config, conflictWarnings)];
|
|
194
255
|
state.config = config;
|
|
195
256
|
state.stores = stores;
|
|
196
|
-
state.
|
|
257
|
+
state.initialEntries = { memory: [...memory.entries], user: [...user.entries] };
|
|
258
|
+
state.snapshotBlocks = rendered.map(({ block }) => block);
|
|
259
|
+
state.snapshotSanitized = rendered.some(({ sanitized }) => sanitized);
|
|
197
260
|
state.conflictWarnings = conflictWarnings;
|
|
198
261
|
} catch (error) {
|
|
199
262
|
// Surface once, disable quietly: no throw-loop every turn.
|