Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ follows [Semantic Versioning](https://semver.org/).

## [Unreleased]

### Fixed

- On pi versions with structured system prompt sections, the memory block goes
in a `memory` section instead of a replacement `systemPrompt`. A changed
block, such as after a `/reload` that follows a daily write, no longer
rewrites the whole prompt: pi appends it and keeps the cached prefix. Other
extensions' section changes also stay small deltas. Older pi versions and
`per-turn` mode keep the replacement. (#50, #37)

## [0.4.2] — 2026-08-10

### Added
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ To keep the prefix byte-stable, the extension snapshots the memory context at de
- **Deletions and restores** intentionally refresh the snapshot. These are rare, authority-changing operations: forgotten content must disappear from the prompt immediately, and pi does not copy deleted content into a persisted correction message merely to preserve the cache.
- Set `PI_MEMORY_SNAPSHOT=refresh` for the old behaviour (refresh on long-term write and day rollover, with a `Snapshot <reason> at <hh:mm:ss>` caveat line).

On pi versions with structured system prompt sections, the block goes in its own `<memory>` section instead of replacing the whole system prompt. When the block changes, as after a `/reload` that follows a daily write, pi keeps the cached prefix and appends the new block as a system message. Older pi versions still get the block appended to the system prompt. `per-turn` mode always replaces the system prompt, since a section rebuilt every turn would append the whole block to the transcript every turn.

`memory_write` with `target: daily` and `scratchpad` writes do **not** mark dirty — they're high-frequency and the write content is already echoed via tool-call args. The model can always call `memory_read` / `memory_search` for the authoritative latest state.

Set `PI_MEMORY_SNAPSHOT=per-turn` to opt out and restore the old per-turn rebuild behavior, including automatic per-prompt qmd search injection.
Expand Down
35 changes: 32 additions & 3 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1446,6 +1446,20 @@ function getSnapshotMode(): "stable" | "refresh" | "per-turn" {
return "stable";
}

/** The prompt section pi renders the memory block in, as `<memory>…</memory>`. */
const MEMORY_SECTION = "memory";

/**
* Pi's structured system prompt sections, which recent pi versions expose on
* `before_agent_start`. Undefined on older hosts, which only take a replacement
* `systemPrompt`.
*/
function promptSections(event: { systemPromptOptions?: unknown }): Record<string, string> | undefined {
const options = event.systemPromptOptions as { sections?: unknown } | undefined;
const sections = options?.sections;
return typeof sections === "object" && sections !== null ? (sections as Record<string, string>) : undefined;
}

/** Reset snapshot state (for testing). */
export function _resetMemorySnapshot() {
memorySnapshot = null;
Expand Down Expand Up @@ -1613,9 +1627,19 @@ export default function (pi: ExtensionAPI) {
"for the authoritative latest state; anything written this session is in tool-call history.";
}

if (!memoryContext) return;
// With a section, a changed block (a /reload after a daily write, a
// deletion) is appended as a system message and the cached prefix stays.
// A replacement systemPrompt rewrites the whole prompt instead, and makes pi
// fold every other extension's section changes into it too (#50).
// per-turn changes the block every turn, so it keeps the replacement rather
// than appending the whole block to the transcript on every turn.
const sections = mode === "per-turn" ? undefined : promptSections(event);
if (!memoryContext) {
if (sections) delete sections[MEMORY_SECTION];
return;
}

const headerLines = ["\n\n## Memory"];
const headerLines = ["## Memory"];
if (snapshotCaveat) headerLines.push(`(${snapshotCaveat})`);
headerLines.push(
"The following memory files have been loaded. Use the memory_write tool to persist important information.",
Expand All @@ -1629,8 +1653,13 @@ export default function (pi: ExtensionAPI) {
memoryContext,
);

const block = headerLines.join("\n");
if (sections) {
sections[MEMORY_SECTION] = block;
return;
}
return {
systemPrompt: event.systemPrompt + headerLines.join("\n"),
systemPrompt: `${event.systemPrompt}\n\n${block}`,
};
});

Expand Down
41 changes: 41 additions & 0 deletions test/unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1401,6 +1401,47 @@ describe("lifecycle hooks", () => {
expect(result.systemPrompt).toContain("scratchpad");
});

test("before_agent_start writes memory to its own prompt section when pi has sections", async () => {
fs.writeFileSync(path.join(tmpDir, "MEMORY.md"), "Remember this", "utf-8");
const sections: Record<string, string> = { other: "another extension" };
const event = { systemPrompt: "base prompt", systemPromptOptions: { sections } };
const result = await hooks.before_agent_start(event, {});
// No replacement prompt: pi keeps its cached prefix and appends a delta when memory changes.
expect(result).toBeUndefined();
expect(sections.memory).toStartWith("## Memory");
expect(sections.memory).toContain("Remember this");
expect(sections.other).toBe("another extension");
});

test("before_agent_start removes its prompt section when memory is empty", async () => {
const sections: Record<string, string> = { memory: "left over" };
const event = { systemPrompt: "base prompt", systemPromptOptions: { sections } };
const result = await hooks.before_agent_start(event, {});
expect(result).toBeUndefined();
expect(sections.memory).toBeUndefined();
});

test("before_agent_start keeps replacing the prompt in per-turn mode", async () => {
const previous = process.env.PI_MEMORY_SNAPSHOT;
const previousNoSearch = process.env.PI_MEMORY_NO_SEARCH;
process.env.PI_MEMORY_SNAPSHOT = "per-turn";
process.env.PI_MEMORY_NO_SEARCH = "1";
try {
fs.writeFileSync(path.join(tmpDir, "MEMORY.md"), "Remember this", "utf-8");
const sections: Record<string, string> = {};
const event = { systemPrompt: "base prompt", systemPromptOptions: { sections } };
const result = await hooks.before_agent_start(event, {});
// A section rebuilt every turn would append the whole block to the transcript every turn.
expect(result.systemPrompt).toContain("Remember this");
expect(sections.memory).toBeUndefined();
} finally {
if (previous === undefined) delete process.env.PI_MEMORY_SNAPSHOT;
else process.env.PI_MEMORY_SNAPSHOT = previous;
if (previousNoSearch === undefined) delete process.env.PI_MEMORY_NO_SEARCH;
else process.env.PI_MEMORY_NO_SEARCH = previousNoSearch;
}
});

// -- session_shutdown --

test("session_shutdown clears update timer", async () => {
Expand Down