|
1 | | -import { lstat, mkdir, readFile, readdir, realpath } from "node:fs/promises"; |
| 1 | +import { lstat, mkdir, open, readFile, readdir, realpath, writeFile } 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 LAST_DREAM_PATH = () => join(getAgentDir(), "config", "pi-memory", "last-dream.txt"); |
| 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 LAST_DREAM_MAX_BYTES = 64; |
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,31 @@ 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(LAST_DREAM_PATH(), "r"); |
| 62 | + const buffer = Buffer.alloc(LAST_DREAM_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 > LAST_DREAM_MAX_BYTES) throw new Error(`Timestamp file is too large: ${LAST_DREAM_PATH()}`); |
| 70 | + const value = Date.parse(new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, total)).trim()); |
| 71 | + if (!Number.isFinite(value) || value > Date.now()) throw new Error(`Invalid timestamp in ${LAST_DREAM_PATH()}`); |
| 72 | + return value; |
| 73 | + } catch (error) { |
| 74 | + if (error instanceof Error && "code" in error && error.code === "ENOENT") return; |
| 75 | + throw error; |
| 76 | + } finally { |
| 77 | + await handle?.close(); |
| 78 | + } |
| 79 | +} |
| 80 | + |
54 | 81 | function sanitizeEntry(entry: string): string { |
55 | | - return entry.split("\n").map((line) => FRAME_TOKEN_LINE.test(line) ? FRAME_TOKEN_REPLACEMENT : line).join("\n"); |
| 82 | + return entry.split("\n").map((line) => isReservedFrameLine(line) ? FRAME_TOKEN_REPLACEMENT : line).join("\n"); |
56 | 83 | } |
57 | 84 |
|
58 | 85 | // Strip control characters so externally-influenced names can't smuggle |
@@ -123,6 +150,8 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
123 | 150 | snapshotSanitized?: boolean; |
124 | 151 | conflictWarnings: string[]; |
125 | 152 | initError?: string; |
| 153 | + dreamPending?: boolean; |
| 154 | + dreamSucceeded?: boolean; |
126 | 155 | } = { conflictWarnings: [] }; |
127 | 156 |
|
128 | 157 | const loadLiveEntries = async (command: string, isIdle: () => boolean, warn: (message: string) => void): Promise<Record<Target, string[]> | undefined> => { |
@@ -204,18 +233,53 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
204 | 233 | const memoryMessage = unchanged |
205 | 234 | ? "Use USER PROFILE/MEMORY already in your system context; do not reread those files." |
206 | 235 | : `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.`); |
| 236 | + state.dreamPending = true; |
| 237 | + state.dreamSucceeded = false; |
| 238 | + try { |
| 239 | + 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.`); |
| 240 | + } catch (error) { |
| 241 | + state.dreamPending = false; |
| 242 | + throw error; |
| 243 | + } |
208 | 244 | }, |
209 | 245 | }); |
210 | 246 |
|
211 | | - pi.on("session_start", async () => { |
| 247 | + pi.on("agent_end", (event) => { |
| 248 | + if (!state.dreamPending) return; |
| 249 | + for (let index = event.messages.length - 1; index >= 0; index--) { |
| 250 | + const message = event.messages[index]; |
| 251 | + if (message?.role !== "assistant") continue; |
| 252 | + state.dreamSucceeded = message.stopReason !== "error" && message.stopReason !== "aborted" && message.stopReason !== "length"; |
| 253 | + break; |
| 254 | + } |
| 255 | + }); |
| 256 | + |
| 257 | + pi.on("agent_settled", async (_event, ctx) => { |
| 258 | + if (!state.dreamPending) return; |
| 259 | + const succeeded = state.dreamSucceeded; |
| 260 | + state.dreamPending = false; |
| 261 | + state.dreamSucceeded = false; |
| 262 | + if (!succeeded) { |
| 263 | + ctx.ui.notify("Dream did not complete; its timestamp was not updated.", "warning"); |
| 264 | + return; |
| 265 | + } |
| 266 | + try { |
| 267 | + await writeFile(LAST_DREAM_PATH(), `${new Date().toISOString()}\n`, { mode: 0o600 }); |
| 268 | + } catch (error) { |
| 269 | + ctx.ui.notify(`Dream completed, but its timestamp could not be recorded: ${error instanceof Error ? error.message : String(error)}`, "warning"); |
| 270 | + } |
| 271 | + }); |
| 272 | + |
| 273 | + pi.on("session_start", async (_event, ctx) => { |
212 | 274 | state.config = undefined; |
213 | 275 | state.stores = undefined; |
214 | 276 | state.initialEntries = undefined; |
215 | 277 | state.snapshotBlocks = undefined; |
216 | 278 | state.snapshotSanitized = undefined; |
217 | 279 | state.conflictWarnings = []; |
218 | 280 | state.initError = undefined; |
| 281 | + state.dreamPending = false; |
| 282 | + state.dreamSucceeded = false; |
219 | 283 | try { |
220 | 284 | await mkdir(BACKUP_DIR(), { recursive: true }); |
221 | 285 | const config = loadMemoryConfig(); |
@@ -258,6 +322,22 @@ export default function memoryExtension(pi: ExtensionAPI): void { |
258 | 322 | state.snapshotBlocks = rendered.map(({ block }) => block); |
259 | 323 | state.snapshotSanitized = rendered.some(({ sanitized }) => sanitized); |
260 | 324 | state.conflictWarnings = conflictWarnings; |
| 325 | + |
| 326 | + if (!process.argv.includes(BTW_CHILD_PAYLOAD_ARG) && (memory.entries.length || user.entries.length)) { |
| 327 | + try { |
| 328 | + const lastDreamAt = await loadLastDreamAt(); |
| 329 | + const age = lastDreamAt === undefined ? undefined : Date.now() - lastDreamAt; |
| 330 | + const memoryChars = memory.entries.join(ENTRY_DELIMITER).length; |
| 331 | + const userChars = user.entries.join(ENTRY_DELIMITER).length; |
| 332 | + const full = memoryChars * 100 >= config.memoryCharLimit * DREAM_USAGE_PERCENT |
| 333 | + || userChars * 100 >= config.userCharLimit * DREAM_USAGE_PERCENT; |
| 334 | + if (age === undefined || age >= DREAM_AFTER_MS || (full && age >= DREAM_FULL_COOLDOWN_MS)) { |
| 335 | + ctx.ui.notify("Memory dream recommended; run /dream.", "info"); |
| 336 | + } |
| 337 | + } catch (error) { |
| 338 | + ctx.ui.notify(`Cannot check dream reminder: ${error instanceof Error ? error.message : String(error)}`, "warning"); |
| 339 | + } |
| 340 | + } |
261 | 341 | } catch (error) { |
262 | 342 | // Surface once, disable quietly: no throw-loop every turn. |
263 | 343 | state.initError = error instanceof Error ? error.message : String(error); |
|
0 commit comments