|
1 | | -import { lstat, mkdir, readFile, readdir, realpath } from "node:fs/promises"; |
| 1 | +import { lstat, mkdir, open, readFile, readdir, realpath, rename, unlink } 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"; |
5 | 5 | import { Text } from "@earendil-works/pi-tui"; |
6 | 6 | import { lock } from "proper-lockfile"; |
7 | 7 | import { Type } from "typebox"; |
8 | 8 | import { configPath, loadMemoryConfig, type MemoryConfig } from "../src/config.ts"; |
9 | | -import { ENTRY_DELIMITER, MemoryStore, usage, type Target } from "../src/store.ts"; |
| 9 | +import { ENTRY_DELIMITER, isReservedFrameLine, MemoryStore, usage, type Target } from "../src/store.ts"; |
10 | 10 |
|
11 | 11 | const SEPARATOR = "═".repeat(46); |
12 | 12 | // Backups and the lock file live OUTSIDE config.directory (which may be |
13 | 13 | // iCloud-synced) so the memory dir holds exactly MEMORY.md and USER.md (ADR 005). |
14 | 14 | const BACKUP_DIR = () => join(getAgentDir(), "config", "pi-memory", "backups"); |
| 15 | +const DREAM_STATE_PATH = () => join(getAgentDir(), "config", "pi-memory", "dream.json"); |
| 16 | +const DREAM_AFTER_MS = 30 * 24 * 60 * 60 * 1000; |
| 17 | +const DREAM_FULL_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000; |
| 18 | +const DREAM_USAGE_PERCENT = 70; |
| 19 | +const DREAM_STATE_MAX_BYTES = 4 * 1024; |
15 | 20 | // Defense-in-depth against snapshot frame spoofing by poisoned on-disk entries. |
16 | | -const FRAME_TOKEN_LINE = /^\s*(?:═{3,}|MEMORY \(your personal notes|USER PROFILE \(who the user is)/; |
17 | 21 | const FRAME_TOKEN_REPLACEMENT = "[filtered frame token]"; |
18 | 22 | const DISPLAY_CONTROL_CHARACTER = /[\p{Cc}\p{Cf}]/gu; |
19 | 23 | // @henryqw/pi-herdr-btw does not export internal/core.ts from its package root. |
@@ -51,8 +55,58 @@ async function loadSystemState(path: string): Promise<SystemState> { |
51 | 55 | } |
52 | 56 | } |
53 | 57 |
|
| 58 | +async function loadLastDreamAt(): Promise<number | undefined> { |
| 59 | + let handle: Awaited<ReturnType<typeof open>> | undefined; |
| 60 | + try { |
| 61 | + handle = await open(DREAM_STATE_PATH(), "r"); |
| 62 | + const buffer = Buffer.alloc(DREAM_STATE_MAX_BYTES + 1); |
| 63 | + let total = 0; |
| 64 | + while (total < buffer.length) { |
| 65 | + const { bytesRead } = await handle.read(buffer, total, buffer.length - total, null); |
| 66 | + if (bytesRead === 0) break; |
| 67 | + total += bytesRead; |
| 68 | + } |
| 69 | + if (total > DREAM_STATE_MAX_BYTES) throw new Error(`Dream state file is too large: ${DREAM_STATE_PATH()}`); |
| 70 | + const parsed: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, total))); |
| 71 | + const lastDreamAt = parsed && typeof parsed === "object" && !Array.isArray(parsed) |
| 72 | + ? (parsed as Record<string, unknown>).lastDreamAt |
| 73 | + : undefined; |
| 74 | + const value = typeof lastDreamAt === "string" ? Date.parse(lastDreamAt) : Number.NaN; |
| 75 | + if (!Number.isFinite(value) || value > Date.now()) throw new Error(`Invalid lastDreamAt in ${DREAM_STATE_PATH()}`); |
| 76 | + return value; |
| 77 | + } catch (error) { |
| 78 | + if (error instanceof Error && "code" in error && error.code === "ENOENT") return; |
| 79 | + throw error; |
| 80 | + } finally { |
| 81 | + await handle?.close(); |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +async function saveLastDreamAt(): Promise<void> { |
| 86 | + const path = DREAM_STATE_PATH(); |
| 87 | + const tempPath = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`; |
| 88 | + let created = false; |
| 89 | + try { |
| 90 | + const handle = await open(tempPath, "wx", 0o600); |
| 91 | + created = true; |
| 92 | + try { |
| 93 | + await handle.writeFile(`${JSON.stringify({ lastDreamAt: new Date().toISOString() }, null, 2)}\n`); |
| 94 | + } finally { |
| 95 | + await handle.close(); |
| 96 | + } |
| 97 | + // rename replaces a destination symlink rather than following it. |
| 98 | + await rename(tempPath, path); |
| 99 | + } finally { |
| 100 | + if (created) { |
| 101 | + await unlink(tempPath).catch((error: NodeJS.ErrnoException) => { |
| 102 | + if (error.code !== "ENOENT") throw error; |
| 103 | + }); |
| 104 | + } |
| 105 | + } |
| 106 | +} |
| 107 | + |
54 | 108 | function sanitizeEntry(entry: string): string { |
55 | | - return entry.split("\n").map((line) => FRAME_TOKEN_LINE.test(line) ? FRAME_TOKEN_REPLACEMENT : line).join("\n"); |
| 109 | + return entry.split("\n").map((line) => isReservedFrameLine(line) ? FRAME_TOKEN_REPLACEMENT : line).join("\n"); |
56 | 110 | } |
57 | 111 |
|
58 | 112 | // Strip control characters so externally-influenced names can't smuggle |
@@ -123,6 +177,8 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
123 | 177 | snapshotSanitized?: boolean; |
124 | 178 | conflictWarnings: string[]; |
125 | 179 | initError?: string; |
| 180 | + dreamPending?: boolean; |
| 181 | + dreamSucceeded?: boolean; |
126 | 182 | } = { conflictWarnings: [] }; |
127 | 183 |
|
128 | 184 | const loadLiveEntries = async (command: string, isIdle: () => boolean, warn: (message: string) => void): Promise<Record<Target, string[]> | undefined> => { |
@@ -204,18 +260,53 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
204 | 260 | const memoryMessage = unchanged |
205 | 261 | ? "Use USER PROFILE/MEMORY already in your system context; do not reread those files." |
206 | 262 | : `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.`); |
| 263 | + state.dreamPending = true; |
| 264 | + state.dreamSucceeded = false; |
| 265 | + try { |
| 266 | + 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.`); |
| 267 | + } catch (error) { |
| 268 | + state.dreamPending = false; |
| 269 | + throw error; |
| 270 | + } |
208 | 271 | }, |
209 | 272 | }); |
210 | 273 |
|
211 | | - pi.on("session_start", async () => { |
| 274 | + pi.on("agent_end", (event) => { |
| 275 | + if (!state.dreamPending) return; |
| 276 | + for (let index = event.messages.length - 1; index >= 0; index--) { |
| 277 | + const message = event.messages[index]; |
| 278 | + if (message?.role !== "assistant") continue; |
| 279 | + state.dreamSucceeded = message.stopReason === "stop"; |
| 280 | + break; |
| 281 | + } |
| 282 | + }); |
| 283 | + |
| 284 | + pi.on("agent_settled", async (_event, ctx) => { |
| 285 | + if (!state.dreamPending) return; |
| 286 | + const succeeded = state.dreamSucceeded; |
| 287 | + state.dreamPending = false; |
| 288 | + state.dreamSucceeded = false; |
| 289 | + if (!succeeded) { |
| 290 | + ctx.ui.notify("Dream did not complete; its timestamp was not updated.", "warning"); |
| 291 | + return; |
| 292 | + } |
| 293 | + try { |
| 294 | + await saveLastDreamAt(); |
| 295 | + } catch (error) { |
| 296 | + ctx.ui.notify(`Dream completed, but its timestamp could not be recorded: ${error instanceof Error ? error.message : String(error)}`, "warning"); |
| 297 | + } |
| 298 | + }); |
| 299 | + |
| 300 | + pi.on("session_start", async (_event, ctx) => { |
212 | 301 | state.config = undefined; |
213 | 302 | state.stores = undefined; |
214 | 303 | state.initialEntries = undefined; |
215 | 304 | state.snapshotBlocks = undefined; |
216 | 305 | state.snapshotSanitized = undefined; |
217 | 306 | state.conflictWarnings = []; |
218 | 307 | state.initError = undefined; |
| 308 | + state.dreamPending = false; |
| 309 | + state.dreamSucceeded = false; |
219 | 310 | try { |
220 | 311 | await mkdir(BACKUP_DIR(), { recursive: true }); |
221 | 312 | const config = loadMemoryConfig(); |
@@ -258,6 +349,24 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
258 | 349 | state.snapshotBlocks = rendered.map(({ block }) => block); |
259 | 350 | state.snapshotSanitized = rendered.some(({ sanitized }) => sanitized); |
260 | 351 | state.conflictWarnings = conflictWarnings; |
| 352 | + |
| 353 | + const memoryChars = memory.entries.join(ENTRY_DELIMITER).length; |
| 354 | + const userChars = user.entries.join(ENTRY_DELIMITER).length; |
| 355 | + const validWithinCap = !memory.status && !user.status |
| 356 | + && memoryChars <= config.memoryCharLimit && userChars <= config.userCharLimit; |
| 357 | + if (!process.argv.includes(BTW_CHILD_PAYLOAD_ARG) && validWithinCap && (memory.entries.length || user.entries.length)) { |
| 358 | + try { |
| 359 | + const lastDreamAt = await loadLastDreamAt(); |
| 360 | + const age = lastDreamAt === undefined ? undefined : Date.now() - lastDreamAt; |
| 361 | + const full = memoryChars * 100 >= config.memoryCharLimit * DREAM_USAGE_PERCENT |
| 362 | + || userChars * 100 >= config.userCharLimit * DREAM_USAGE_PERCENT; |
| 363 | + if (age === undefined || age >= DREAM_AFTER_MS || (full && age >= DREAM_FULL_COOLDOWN_MS)) { |
| 364 | + ctx.ui.notify("Memory dream recommended; run /dream.", "info"); |
| 365 | + } |
| 366 | + } catch (error) { |
| 367 | + ctx.ui.notify(`Cannot check dream reminder: ${error instanceof Error ? error.message : String(error)}`, "warning"); |
| 368 | + } |
| 369 | + } |
261 | 370 | } catch (error) { |
262 | 371 | // Surface once, disable quietly: no throw-loop every turn. |
263 | 372 | state.initError = error instanceof Error ? error.message : String(error); |
|
0 commit comments