From c13a0b923c26c5ff87d43649aae2aa60886b5ee7 Mon Sep 17 00:00:00 2001 From: Adeildo Date: Wed, 21 Oct 2026 15:06:07 -0300 Subject: [PATCH] fix: write the exit summary in the next session instead of blocking quit Signed-off-by: Adeildo --- CHANGELOG.md | 13 ++ README.md | 5 +- index.ts | 347 +++++++++++++++++++++++++++++++++------------- test/unit.test.ts | 187 +++++++++++++++++++++++-- 4 files changed, 443 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 376bb64..7874309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- Quitting no longer waits on the exit summary. Pi stops its screen before it + runs shutdown handlers, so the summary's model call (up to 10 s, plus + `qmd update`) looked like a hang, and the Ctrl+C people pressed to get out + killed pi, its "To resume this session" hint and the summary. Quitting now + saves the transcript under `pending/`, and the next interactive session + writes the summary in the background, into the daily log of the day the + session ended. Quitting the same session again replaces its pending entry, + sessions claim entries by renaming them, and a summary that fails is tried + by the next session up to three times. `PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS` + now bounds that background call and defaults to 60 s. (#55) + ## [0.4.2] — 2026-08-10 ### Added diff --git a/README.md b/README.md index aa028c5..8e2d2d9 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ This ensures in-progress context survives compaction and is visible in the next ### Other behavior +- **Exit summaries**: When a session with real exchange ends (Ctrl+D, `/quit`, session end), quitting only saves its transcript under `pending/` and returns at once. The next interactive session writes the summary in the background, into the daily log of the day the session ended. A summary that fails is tried again by the next session, up to three times. - **Persistence**: Memory files are plain markdown on disk — readable, editable, and git-friendly. - **Recoverable deletion**: `memory_forget` stores complete deleted entries under `recovery/` before changing memory and returns a recovery ID that `memory_restore` can use. Recovery JSON is outside qmd's `**/*.md` index. - **Tool response previews**: Write/scratchpad tools return size-capped previews instead of full file contents. @@ -193,10 +194,10 @@ This ensures in-progress context survives compaction and is visible in the next | `PI_MEMORY_EMBED_PROBE_TIMEOUT_MS` | positive integer (milliseconds) | `15000` | Sets the timeout for the `memory_status` embeddings readiness probe. Raise it on slower machines if the probe reports `unknown` | | `PI_MEMORY_NO_SEARCH` | `1` | unset | Disable selective injection in `per-turn` mode (no effect in `stable` mode) | | `PI_MEMORY_SUMMARIZE_TRANSITIONS` | `1`, `true`, `yes`, `on` | unset | Also write exit summaries during lifecycle transitions (`/reload`, `/new`, `/resume`, `/fork`). By default these transitions skip summaries for speed. | -| `PI_MEMORY_EXIT_SUMMARY` | `0`, `off`, `false`, `no` to disable | unset (enabled) | Disable the exit summary on real quit (Ctrl+D, `/quit`, session end). Quitting then does no LLM call and no `qmd update`, so it is instant; explicit `memory_write` during sessions is unaffected. | +| `PI_MEMORY_EXIT_SUMMARY` | `0`, `off`, `false`, `no` to disable | unset (enabled) | Disable the exit summary on real quit (Ctrl+D, `/quit`, session end). Quitting then saves no transcript for the next session to summarize; explicit `memory_write` during sessions is unaffected. | | `PI_MEMORY_EXIT_SUMMARY_MODEL` | `provider/model-id` | unset (session model) | Model used to write the exit summary, e.g. a cheaper/faster one. Unresolvable specs fall back to the session model with a warning. | | `PI_MEMORY_EXIT_SUMMARY_REASONING_EFFORT` | `minimal`/`low`/`medium`/`high`/`xhigh`/`max`/`none`/`off` | `low` | Reasoning effort for the exit-summary LLM call. Some providers reject certain values (e.g. Baseten GLM-5.2 only accepts `high`/`max`/`none` and returns HTTP 400 for `low`, silently breaking exit summaries). Set this to a value your `PI_MEMORY_EXIT_SUMMARY_MODEL` accepts. Use `off` to omit the parameter and let the provider apply its own default. | -| `PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS` | positive integer (milliseconds) | `10000` | Self-imposed timeout for exit-summary generation on quit. Pi awaits shutdown handlers with no timeout, so a hanging provider would otherwise block quitting indefinitely. On expiry nothing is persisted. | +| `PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS` | positive integer (milliseconds) | `60000` | How long the next session waits on one exit summary before leaving it for the session after. A hanging provider would otherwise hold the rest of the queue. | ## Troubleshooting diff --git a/index.ts b/index.ts index 2f27901..5072bbe 100644 --- a/index.ts +++ b/index.ts @@ -27,7 +27,7 @@ import { type ExecFileOptions, execFile } from "node:child_process"; import { randomUUID } from "node:crypto"; import * as fs from "node:fs"; import * as path from "node:path"; -import { type Message, StringEnum, Type } from "@earendil-works/pi-ai"; +import { StringEnum, Type } from "@earendil-works/pi-ai"; import { complete } from "@earendil-works/pi-ai/compat"; import { convertToLlm, @@ -297,12 +297,6 @@ function formatContextSection(label: string, content: string, mode: TruncateMode type ExitSummaryReason = "ctrl+d" | "slash-quit" | "session-end"; -interface ExitSummaryResult { - summary: string | null; - error?: string; - hasMessages: boolean; -} - function formatExitSummaryReason(reason: ExitSummaryReason): string { if (reason === "ctrl+d") return "ctrl+d"; if (reason === "slash-quit") return "/quit"; @@ -416,11 +410,67 @@ function resolveExitSummaryModel(ctx: ExtensionContext): ExtensionContext["model return ctx.model; } -async function generateExitSummary(ctx: ExtensionContext): Promise { +// --------------------------------------------------------------------------- +// Exit summaries, written by the next session +// --------------------------------------------------------------------------- + +/** + * A session's exit summary, waiting for the next session to write it. + * + * Pi stops its screen before it runs `session_shutdown` handlers and then waits + * for them with no timeout and nothing on screen. A model call made there looked + * like a hang, and the Ctrl+C people pressed to get out of it killed pi, its + * "To resume this session" hint and the summary. So quitting only saves the + * transcript, and the next interactive session writes the summary in the + * background. + */ +interface PendingExitSummary { + version: 1; + sessionId: string; + reason: ExitSummaryReason; + /** When the session ended, which picks the daily log and stamps the entry. */ + endedAt: string; + date: string; + model?: { provider: string; id: string }; + conversation: string; + truncated: boolean; + totalChars: number; + attempts: number; +} + +const EXIT_SUMMARY_MAX_ATTEMPTS = 3; + +type CompleteFn = typeof complete; +let completeFn: CompleteFn = complete; + +/** Replace the model call (for testing). */ +export function _setCompleteForTest(fn: CompleteFn) { + completeFn = fn; +} + +export function _resetCompleteForTest() { + completeFn = complete; +} + +function pendingDir(): string { + return path.join(MEMORY_DIR, "pending"); +} + +/** One file per session, so quitting the same session again replaces what it left. */ +function pendingFileOf(sessionId: string): string { + return path.join(pendingDir(), `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.json`); +} + +function writeJsonAtomic(filePath: string, value: unknown) { + const temporary = `${filePath}.${process.pid}.tmp`; + fs.writeFileSync(temporary, JSON.stringify(value), "utf-8"); + fs.renameSync(temporary, filePath); +} + +/** What the next session needs to summarize this one, or null when there is nothing worth it. */ +function pendingExitSummaryOf(ctx: ExtensionContext, reason: ExitSummaryReason): PendingExitSummary | null { const branch = getSessionBranch(ctx); - if (!branch) { - return { summary: null, error: "Session branch unavailable", hasMessages: false }; - } + if (!branch) return null; const messages = branch .filter((entry): entry is SessionEntry & { type: "message" } => entry.type === "message") @@ -430,60 +480,189 @@ async function generateExitSummary(ctx: ExtensionContext): Promise boolean, +): Promise { + const modelRegistry = ctx.modelRegistry as ExtensionContext["modelRegistry"] & { + find?: (provider: string, modelId: string) => ExtensionContext["model"]; + }; + const model = (pending.model && modelRegistry?.find?.(pending.model.provider, pending.model.id)) || ctx.model; + if (!model) return "failed"; - const summaryMessages: Message[] = [ + const apiKey = await resolveExitSummaryApiKey(ctx, model); + if (!apiKey) return "failed"; + + const response = await completeFn( + model, { - role: "user", - content: [{ type: "text", text: buildExitSummaryPrompt(truncatedText, truncated, totalChars) }], - timestamp: Date.now(), + systemPrompt: EXIT_SUMMARY_SYSTEM_PROMPT, + messages: [ + { + role: "user", + content: [ + { + type: "text", + text: buildExitSummaryPrompt(pending.conversation, pending.truncated, pending.totalChars), + }, + ], + timestamp: Date.now(), + }, + ], }, - ]; + { apiKey, reasoningEffort: getExitSummaryReasoningEffort() }, + ); + const summary = response.content + .filter((c): c is { type: "text"; text: string } => c.type === "text") + .map((c) => c.text) + .join("\n") + .trim(); + + // Only persist real summaries. A summary whose every section is "None." is + // boilerplate the daily-log injection would resurface forever. + if (!summary || isExitSummaryEmpty(summary)) return "empty"; + // Too late: the entry already went back for the next session, which would write it twice. + if (gaveUp()) return "failed"; - try { - const response = await complete( - model, - { systemPrompt: EXIT_SUMMARY_SYSTEM_PROMPT, messages: summaryMessages }, - { apiKey, reasoningEffort: getExitSummaryReasoningEffort() }, - ); + ensureDirs(); + const entry = formatExitSummaryEntry(summary, pending.reason, shortSessionId(pending.sessionId), pending.endedAt); + const filePath = dailyPath(pending.date); + const existing = readFileSafe(filePath) ?? ""; + fs.appendFileSync(filePath, (existing.trim() ? "\n\n" : "") + entry, "utf-8"); + return "written"; +} - const summaryText = response.content - .filter((c): c is { type: "text"; text: string } => c.type === "text") - .map((c) => c.text) - .join("\n") - .trim(); +function writeExitSummaryInTime(ctx: ExtensionContext, pending: PendingExitSummary): Promise { + let gaveUp = false; + let timer: ReturnType | undefined; + const expired = new Promise((resolve) => { + timer = setTimeout(() => { + gaveUp = true; + resolve("failed"); + }, getExitSummaryTimeoutMs()); + }); + const work = writeExitSummary(ctx, pending, () => gaveUp).catch((): ExitSummaryOutcome => "failed"); + return Promise.race([work, expired]).finally(() => clearTimeout(timer)); +} - if (!summaryText) { - return { summary: null, error: "Summary was empty", hasMessages: true }; +/** + * Writes the exit summaries earlier sessions left, one at a time, and returns + * how many reached the daily log. A summary that fails goes back for the next + * session, up to three tries. + */ +export async function writePendingExitSummaries(ctx: ExtensionContext): Promise { + let written = 0; + for (const claimed of claimPendingExitSummaries()) { + const pending = readPendingExitSummary(claimed); + if (!pending) { + fs.rmSync(claimed, { force: true }); + continue; } - - return { summary: summaryText, hasMessages: true }; - } catch (err) { - return { summary: null, error: err instanceof Error ? err.message : String(err), hasMessages: true }; + const outcome = await writeExitSummaryInTime(ctx, pending); + if (outcome === "failed") { + releasePendingExitSummary(claimed, pending); + continue; + } + fs.rmSync(claimed, { force: true }); + if (outcome === "written") written++; } + if (written > 0 && (await ensureQmdAvailableForUpdate())) await runQmdUpdateNow(); + return written; +} + +let pendingExitSummaryWork: Promise | null = null; + +/** The background write the last session start began, if it is still running (for testing). */ +export function _pendingExitSummaryWork(): Promise | null { + return pendingExitSummaryWork; } function getQmdUpdateMode(): "background" | "manual" | "off" { @@ -524,13 +703,13 @@ export function isExitSummaryEmpty(summary: string): boolean { return contentLines.every((line) => /^none\.?$/i.test(line.replace(/^[-*+]\s*/, ""))); } -const DEFAULT_EXIT_SUMMARY_TIMEOUT_MS = 10_000; +const DEFAULT_EXIT_SUMMARY_TIMEOUT_MS = 60_000; /** - * Self-imposed timeout for the exit-summary work on session_shutdown. Pi core - * awaits shutdown handlers with no timeout, and generateExitSummary() is only - * bounded by the provider's own timeout — a hanging provider would otherwise - * block quitting indefinitely. Override with PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS. + * How long one exit summary may take before it waits for the next session. + * The model call is bounded only by the provider's own timeout, and a hanging + * provider would otherwise hold the queue behind it. Override with + * PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS. */ export function getExitSummaryTimeoutMs(): number { const configured = Number(process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS); @@ -1463,6 +1642,15 @@ export default function (pi: ExtensionAPI) { // --- session_start: detect qmd, auto-setup collection --- pi.on("session_start", async (_event, ctx) => { exitSummaryReason = null; + // A print run is often a script and ends soon; leave the summaries to an + // interactive session, where the background call has time to finish. + if (ctx.hasUI && pendingExitSummaryWork === null) { + pendingExitSummaryWork = writePendingExitSummaries(ctx) + .catch(() => 0) + .finally(() => { + pendingExitSummaryWork = null; + }); + } if (terminalInputUnsubscribe) { terminalInputUnsubscribe(); terminalInputUnsubscribe = null; @@ -1497,7 +1685,7 @@ export default function (pi: ExtensionAPI) { refreshMemorySnapshot("session_start"); }); - // --- session_shutdown: write exit summary + clean up timer --- + // --- session_shutdown: leave the exit summary to the next session + clean up timer --- pi.on("session_shutdown", async (event, ctx) => { const shutdownReason = (event as { reason?: string }).reason; @@ -1523,44 +1711,17 @@ export default function (pi: ExtensionAPI) { const reason = exitSummaryReason ?? "session-end"; exitSummaryReason = null; - let summaryTimer: ReturnType | undefined; + if (updateTimer) { + clearTimeout(updateTimer); + updateTimer = null; + } + // Only save what the next session needs: pi has already stopped its + // screen, so anything awaited here looks like a hang. try { - if (reason) { - ensureDirs(); - // Race the summary against a self-imposed timeout: pi core awaits - // shutdown handlers with no timeout, so a hanging provider would - // otherwise block quitting indefinitely. On expiry nothing is - // persisted (the late result, if any, is simply dropped). - const summaryWork = generateExitSummary(ctx); - const expired = new Promise((resolve) => { - summaryTimer = setTimeout(() => resolve(null), getExitSummaryTimeoutMs()); - }); - const result = await Promise.race([summaryWork, expired]); - // Only persist real summaries. The old fallback appended an - // all-"None." boilerplate block on every failed summarization - // (no API key, empty response, …), polluting the daily log — - // which is then re-injected into context every session start. - // Successful-but-empty summaries (every section "None.") are - // filtered out for the same reason. - if (result?.hasMessages && result.summary && !isExitSummaryEmpty(result.summary)) { - const summary = result.summary; - const sid = shortSessionId(ctx.sessionManager.getSessionId()); - const ts = nowTimestamp(); - const entry = formatExitSummaryEntry(summary, reason, sid, ts); - const filePath = dailyPath(todayStr()); - const existing = readFileSafe(filePath) ?? ""; - const separator = existing.trim() ? "\n\n" : ""; - fs.writeFileSync(filePath, existing + separator + entry, "utf-8"); - await ensureQmdAvailableForUpdate(); - await runQmdUpdateNow(); - } - } - } finally { - if (summaryTimer) clearTimeout(summaryTimer); - if (updateTimer) { - clearTimeout(updateTimer); - updateTimer = null; - } + const pending = pendingExitSummaryOf(ctx, reason); + if (pending) savePendingExitSummary(pending); + } catch { + // A failed save must never keep pi from quitting. } }); diff --git a/test/unit.test.ts b/test/unit.test.ts index 5d7725b..cf7c4ba 100644 --- a/test/unit.test.ts +++ b/test/unit.test.ts @@ -16,11 +16,14 @@ import { _clearUpdateTimer, _getEmbedInFlight, _getUpdateTimer, + _pendingExitSummaryWork, _resetBaseDir, + _resetCompleteForTest, _resetExecFileForTest, _resetMemorySnapshot, _resetQmdJsResolutionForTest, _setBaseDir, + _setCompleteForTest, _setExecFileForTest, _setQmdAvailable, buildMemoryContext, @@ -54,6 +57,7 @@ import { serializeScratchpad, shortSessionId, todayStr, + writePendingExitSummaries, yesterdayStr, } from "../index.js"; @@ -68,6 +72,16 @@ function setupTmpDir() { _setBaseDir(tmpDir); } +/** The exit summaries waiting for the next session, by file name. */ +function pendingFiles(): string[] { + const dir = path.join(tmpDir, "pending"); + return fs.existsSync(dir) ? fs.readdirSync(dir).sort() : []; +} + +function readPending(name: string) { + return JSON.parse(fs.readFileSync(path.join(tmpDir, "pending", name), "utf-8")); +} + function cleanupTmpDir() { _resetBaseDir(); _setQmdAvailable(false); @@ -1521,10 +1535,10 @@ describe("lifecycle hooks", () => { expect(fs.existsSync(dailyPath(todayStr()))).toBe(false); }); - test("session_shutdown with reason=quit still attempts the exit summary", async () => { - // Ensure the reload-skip guard does not suppress real quit summaries. - // Summarization cannot succeed here (no API key), so the attempt is - // observed via the API-key lookup — and no boilerplate is written. + test("session_shutdown with reason=quit leaves the summary to the next session", async () => { + // Ensure the reload-skip guard does not suppress real quit summaries, and + // that quitting itself never waits on the model: pi has already stopped its + // screen, so any wait here looks like a hang. const getApiKey = mock(async () => undefined); const ctx = createShutdownCtx({ branch: [ @@ -1567,8 +1581,13 @@ describe("lifecycle hooks", () => { await hooks.session_shutdown({ reason: "quit" }, ctx); - expect(getApiKey).toHaveBeenCalled(); + expect(getApiKey).not.toHaveBeenCalled(); expect(fs.existsSync(dailyPath(todayStr()))).toBe(false); + expect(pendingFiles()).toEqual(["abcdef1234567890.json"]); + const pending = readPending("abcdef1234567890.json"); + expect(pending.conversation).toContain("Please remember we chose dark mode."); + expect(pending.date).toBe(todayStr()); + expect(pending.model).toEqual({ provider: "openai", id: "gpt-4o-mini" }); }); // -- exit summary configurability (PI_MEMORY_EXIT_SUMMARY / PI_MEMORY_EXIT_SUMMARY_MODEL) -- @@ -1635,6 +1654,7 @@ describe("lifecycle hooks", () => { expect(getApiKey).not.toHaveBeenCalled(); expect(fs.existsSync(dailyPath(todayStr()))).toBe(false); + expect(pendingFiles()).toEqual([]); }); test("PI_MEMORY_EXIT_SUMMARY=off (and other aliases) also disable", async () => { @@ -1658,6 +1678,7 @@ describe("lifecycle hooks", () => { }); await hooks.session_shutdown({ reason: "quit" }, ctx); + await writePendingExitSummaries(ctx as any); expect(find).toHaveBeenCalledWith("anthropic", "claude-haiku-4"); expect(getApiKey).toHaveBeenCalledWith(overrideModel); @@ -1675,6 +1696,7 @@ describe("lifecycle hooks", () => { }); await hooks.session_shutdown({ reason: "quit" }, ctx); + await writePendingExitSummaries(ctx as any); expect(getApiKey).toHaveBeenCalledWith(sessionModel); }); @@ -1717,7 +1739,7 @@ describe("lifecycle hooks", () => { }); }); - describe("exit summary shutdown timeout", () => { + describe("exit summary timeout", () => { const fourMessageBranch = () => [ { type: "message", @@ -1764,20 +1786,18 @@ describe("lifecycle hooks", () => { test("getExitSummaryTimeoutMs parses env with fallback to default", () => { delete process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS; - expect(getExitSummaryTimeoutMs()).toBe(10_000); + expect(getExitSummaryTimeoutMs()).toBe(60_000); process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS = "250"; expect(getExitSummaryTimeoutMs()).toBe(250); process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS = "not-a-number"; - expect(getExitSummaryTimeoutMs()).toBe(10_000); + expect(getExitSummaryTimeoutMs()).toBe(60_000); process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS = "-5"; - expect(getExitSummaryTimeoutMs()).toBe(10_000); + expect(getExitSummaryTimeoutMs()).toBe(60_000); }); - test("session_shutdown stays responsive when summary generation hangs", async () => { - // Pi core awaits session_shutdown handlers with no timeout; a hanging - // provider must not block quitting forever. The API-key lookup never - // resolves here, so without a self-imposed timeout this test only fails - // via bun's per-test timeout. + test("a hanging summary gives up at the timeout and waits for the next session", async () => { + // The API-key lookup never resolves here, so without the timeout this + // test only fails via bun's per-test timeout. process.env.PI_MEMORY_EXIT_SUMMARY_TIMEOUT_MS = "50"; const getApiKey = mock(() => new Promise(() => {})); const ctx = createShutdownCtx({ @@ -1787,9 +1807,148 @@ describe("lifecycle hooks", () => { }); await hooks.session_shutdown({ reason: "quit" }, ctx); + expect(await writePendingExitSummaries(ctx as any)).toBe(0); expect(getApiKey).toHaveBeenCalled(); expect(fs.existsSync(dailyPath(todayStr()))).toBe(false); + expect(pendingFiles()).toEqual(["abcdef1234567890.json"]); + expect(readPending("abcdef1234567890.json").attempts).toBe(1); + }); + }); + + describe("exit summaries written by the next session", () => { + const branch = (text: string) => [ + { type: "message", message: { role: "user", content: [{ type: "text", text }], timestamp: 1 } }, + { type: "message", message: { role: "assistant", content: [{ type: "text", text: "Noted." }], timestamp: 2 } }, + { + type: "message", + message: { role: "user", content: [{ type: "text", text: "And the config?" }], timestamp: 3 }, + }, + { + type: "message", + message: { role: "assistant", content: [{ type: "text", text: "Migrated." }], timestamp: 4 }, + }, + ]; + const model = { provider: "openai", id: "gpt-4o-mini" }; + const SUMMARY = + "### Decisions\n- Chose SQLite.\n### Lessons Learned\n- None.\n### Notes\n- None.\n### Follow-ups\n- None."; + const answering = (text: string) => mock(async () => ({ content: [{ type: "text", text }] }) as any); + + afterEach(() => _resetCompleteForTest()); + + test("writes the summary into the daily log of the day the session ended", async () => { + const complete = answering(SUMMARY); + _setCompleteForTest(complete as any); + const ctx = createShutdownCtx({ + branch: branch("We chose SQLite."), + model, + modelRegistry: { getApiKey: async () => "key" }, + }); + await hooks.session_shutdown({ reason: "quit" }, ctx); + const pending = readPending("abcdef1234567890.json"); + pending.date = "2026-01-02"; + pending.endedAt = "2026-01-02 23:59:00"; + fs.writeFileSync(path.join(tmpDir, "pending", "abcdef1234567890.json"), JSON.stringify(pending)); + + expect(await writePendingExitSummaries(ctx as any)).toBe(1); + + const log = fs.readFileSync(dailyPath("2026-01-02"), "utf-8"); + expect(log).toContain(""); + expect(log).toContain("## Session Summary (auto, exit: session-end)"); + expect(log).toContain("- Chose SQLite."); + expect(String((complete.mock.calls[0] as any[])[1].messages[0].content[0].text)).toContain("We chose SQLite."); + expect(pendingFiles()).toEqual([]); + }); + + test("a later quit of the same session replaces its pending summary", async () => { + const first = createShutdownCtx({ branch: branch("First part."), model }); + const second = createShutdownCtx({ branch: [...branch("First part."), ...branch("Second part.")], model }); + await hooks.session_shutdown({ reason: "quit" }, first); + await hooks.session_shutdown({ reason: "quit" }, second); + + expect(pendingFiles()).toEqual(["abcdef1234567890.json"]); + expect(readPending("abcdef1234567890.json").conversation).toContain("Second part."); + }); + + test("a summary with nothing in it is dropped without a write", async () => { + _setCompleteForTest(answering("### Decisions\n- None.\n### Notes\n- None.") as any); + const ctx = createShutdownCtx({ + branch: branch("hi"), + model, + modelRegistry: { getApiKey: async () => "key" }, + }); + await hooks.session_shutdown({ reason: "quit" }, ctx); + + expect(await writePendingExitSummaries(ctx as any)).toBe(0); + expect(fs.existsSync(dailyPath(todayStr()))).toBe(false); + expect(pendingFiles()).toEqual([]); + }); + + test("a summary that keeps failing is dropped after three tries", async () => { + _setCompleteForTest( + mock(async () => { + throw new Error("HTTP 400"); + }) as any, + ); + const ctx = createShutdownCtx({ + branch: branch("hi"), + model, + modelRegistry: { getApiKey: async () => "key" }, + }); + await hooks.session_shutdown({ reason: "quit" }, ctx); + + await writePendingExitSummaries(ctx as any); + await writePendingExitSummaries(ctx as any); + expect(readPending("abcdef1234567890.json").attempts).toBe(2); + await writePendingExitSummaries(ctx as any); + expect(pendingFiles()).toEqual([]); + }); + + test("leaves a summary another live session is writing, and takes over one whose session died", async () => { + const complete = answering(SUMMARY); + _setCompleteForTest(complete as any); + const ctx = createShutdownCtx({ + branch: branch("hi"), + model, + modelRegistry: { getApiKey: async () => "key" }, + }); + await hooks.session_shutdown({ reason: "quit" }, ctx); + const dir = path.join(tmpDir, "pending"); + const live = path.join(dir, `abcdef1234567890.json.${process.ppid}.claimed`); + fs.renameSync(path.join(dir, "abcdef1234567890.json"), live); + + expect(await writePendingExitSummaries(ctx as any)).toBe(0); + expect(complete).not.toHaveBeenCalled(); + + fs.renameSync(live, path.join(dir, "abcdef1234567890.json.2147483646.claimed")); + expect(await writePendingExitSummaries(ctx as any)).toBe(1); + expect(pendingFiles()).toEqual([]); + }); + + test("an interactive session starts writing them, and a print run does not", async () => { + _setCompleteForTest(answering(SUMMARY) as any); + _setExecFileForTest(((_file: string, _args: string[], _opts: any, cb: any) => { + cb(new Error("not available"), "", ""); + }) as any); + try { + const ctx = createShutdownCtx({ + branch: branch("hi"), + model, + modelRegistry: { getApiKey: async () => "key" }, + }); + await hooks.session_shutdown({ reason: "quit" }, ctx); + + await hooks.session_start({}, { ...ctx, hasUI: false }); + expect(_pendingExitSummaryWork()).toBeNull(); + expect(pendingFiles()).toEqual(["abcdef1234567890.json"]); + + const ui = { notify: () => {}, onTerminalInput: () => () => {} }; + await hooks.session_start({}, { ...ctx, hasUI: true, ui }); + await _pendingExitSummaryWork(); + expect(fs.readFileSync(dailyPath(todayStr()), "utf-8")).toContain("- Chose SQLite."); + } finally { + _resetExecFileForTest(); + } }); });