From b15af66242828ade39a12d37207f4c283fff63dc Mon Sep 17 00:00:00 2001 From: MiFaZhan <198522268+MiFaZhan@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:41:35 +0800 Subject: [PATCH] fix: don't append the same exit summary twice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exit summaries snapshot the whole session branch, not "messages since the last summary". Quitting, resuming the same session, and quitting again therefore summarizes the identical transcript twice and appends it to the daily log twice. That is not just noise: today's daily log is re-injected into every new session, so the duplicate is paid for in context on every subsequent turn. Compare the newest message in the branch against the last summary already recorded for the session, and skip the LLM call entirely when nothing was added. The scan reads the `` headers in today's and yesterday's daily logs; pre-compaction handoffs use the same header shape and also snapshot the whole branch, so they count as well. Only `message` entries count. Bookkeeping entries (plan-mode-state, compact-thinking-duration, agent-summary, ...) are appended on every session transition and would otherwise defeat the check — in the observed duplicate, the only entries between the two summaries were three plan-mode-state rows. The guard fails open: an unidentifiable session, missing branch, or unparseable timestamp summarizes as before, because losing a summary is worse than writing a duplicate. Signed-off-by: MiFaZhan <198522268+MiFaZhan@users.noreply.github.com> --- CHANGELOG.md | 14 +++++ index.ts | 112 +++++++++++++++++++++++++++++++++++ test/unit.test.ts | 148 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 274 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 376bb64..75f39a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- Exit summaries are no longer written twice for the same session. The summary + snapshots the whole session branch rather than "messages since the last + summary", so quitting, resuming a session, and quitting again appended the + identical transcript to the daily log a second time — which is then re-injected + into context on every subsequent session start. `session_shutdown` now compares + the newest message against the last summary recorded for that session and skips + the LLM call entirely when nothing was added. Only `message` entries count; + bookkeeping entries (`plan-mode-state`, `compact-thinking-duration`, …) are + appended on every transition and would otherwise defeat the check. The guard + fails open — a missing or unparseable timestamp summarizes rather than silently + dropping the session's notes. + ## [0.4.2] — 2026-08-10 ### Added diff --git a/index.ts b/index.ts index 2f27901..f4d540a 100644 --- a/index.ts +++ b/index.ts @@ -562,6 +562,102 @@ export function shouldSkipExitSummaryForReason(reason: string | undefined): bool return ["reload", "new", "resume", "fork"].includes(reason); } +/** + * Session id, or null when the session manager cannot supply one. + * + * `session_shutdown` is also emitted with a bare context on teardown paths, so + * the duplicate guard must never be the thing that throws while quitting — the + * rest of this handler already treats a missing session manager as "no data, + * carry on". + */ +function getSessionIdSafe(ctx: ExtensionContext): string | null { + try { + const id = ctx.sessionManager?.getSessionId?.(); + return typeof id === "string" && id.length > 0 ? id : null; + } catch { + return null; + } +} + +/** + * Timestamp of the last exit summary already written for a session. + * + * Exit summaries snapshot the WHOLE session branch, not "messages since the last + * summary". Quitting, resuming the same session, and quitting again therefore + * summarizes the identical transcript twice and appends it to the daily log + * twice. That is not just noise: today's daily log is re-injected into every new + * session, so the duplicate is paid for in context on every subsequent turn. + * + * Scans today's and yesterday's daily logs (a session resumed across midnight is + * still covered) for `` headers. Pre-compaction handoffs use + * the same header shape and also snapshot the whole branch, so they count too. + * + * Returns null when nothing is recorded for the session, or when the stored + * timestamp cannot be parsed — callers treat null as "summarize", because losing + * a summary is worse than writing a duplicate. + */ +export function findLastExitSummaryTimestamp(sessionId: string): Date | null { + const sid = shortSessionId(sessionId); + let latest: Date | null = null; + for (const date of [todayStr(), yesterdayStr()]) { + let content: string | null; + try { + content = readFileSafe(dailyPath(date)); + } catch { + continue; + } + if (!content) continue; + // The sid group is deliberately not restricted to hex: real session ids are + // UUIDs, but shortSessionId() only slices the first 8 characters, and a + // stricter class would silently stop matching rather than fail loudly. + const headerRegex = //g; + for (const match of content.matchAll(headerRegex)) { + if (match[2] !== sid) continue; + const parsed = parseLocalTimestamp(match[1]); + if (parsed && (!latest || parsed.getTime() > latest.getTime())) latest = parsed; + } + } + return latest; +} + +/** + * True when the branch has gained content since its last recorded summary. + * + * Only `message` entries count. Bookkeeping entries (`plan-mode-state`, + * `compact-thinking-duration`, `agent-summary`, …) are appended on every session + * transition and would otherwise defeat the check — in the observed duplicate, + * the only entries between the two summaries were three `plan-mode-state` rows. + * + * Fails open: a missing branch or unparseable timestamp returns true, so the + * summary still runs. + */ +export function hasNewMessagesSince(branch: SessionEntry[] | null, lastSummaryAt: Date | null): boolean { + if (!lastSummaryAt) return true; + if (!branch) return true; + const cutoff = lastSummaryAt.getTime(); + for (const entry of branch) { + if (entry.type !== "message") continue; + const ts = entry.timestamp; + const millis = typeof ts === "number" ? ts : Date.parse(String(ts)); + if (!Number.isFinite(millis)) return true; + if (millis > cutoff) return true; + } + return false; +} + +/** Format a Date using the same local stamp convention as nowTimestamp(). */ +export function formatLocalTimestamp(d: Date): string { + return `${localDateStr(d)} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`; +} + +/** Parse a local (non-UTC) "YYYY-MM-DD HH:mm:ss" stamp written by nowTimestamp(). */ +export function parseLocalTimestamp(value: string): Date | null { + const m = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value); + if (!m) return null; + const date = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6])); + return Number.isNaN(date.getTime()) ? null : date; +} + async function ensureQmdAvailableForUpdate(): Promise { if (qmdAvailable) return true; if (getQmdUpdateMode() !== "background") return false; @@ -1527,6 +1623,22 @@ export default function (pi: ExtensionAPI) { try { if (reason) { ensureDirs(); + + // Idempotency guard: an exit summary snapshots the whole branch, so + // quitting, resuming the same session, and quitting again would append + // the identical transcript a second time. Compare the newest message + // against the last recorded summary for this session and skip when + // nothing was added in between. Runs BEFORE the LLM call, so a no-op + // quit costs nothing and returns immediately. Fails open: an + // unidentifiable session is summarized rather than silently dropped. + const guardSessionId = getSessionIdSafe(ctx); + if ( + guardSessionId && + !hasNewMessagesSince(getSessionBranch(ctx), findLastExitSummaryTimestamp(guardSessionId)) + ) { + return; + } + // 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 diff --git a/test/unit.test.ts b/test/unit.test.ts index 5d7725b..9e5bcf5 100644 --- a/test/unit.test.ts +++ b/test/unit.test.ts @@ -30,14 +30,18 @@ import { dailyPath, ensureDirs, ensureQmdEmbed, + findLastExitSummaryTimestamp, forgetBlocks, + formatLocalTimestamp, getEmbedProbeTimeoutMs, getExitSummaryReasoningEffort, getExitSummaryTimeoutMs, getQmdSearchTimeoutMs, + hasNewMessagesSince, isExitSummaryEmpty, isExitSummaryEnabled, nowTimestamp, + parseLocalTimestamp, parseScratchpad, probeEmbeddings, qmdCollectionInstructions, @@ -1680,6 +1684,150 @@ describe("lifecycle hooks", () => { }); }); + describe("exit summary duplicate suppression", () => { + const message = (iso: string) => ({ type: "message", id: iso, parentId: null, timestamp: iso, message: {} }); + const bookkeeping = (iso: string, customType: string) => ({ + type: "custom", + customType, + id: iso, + parentId: null, + timestamp: iso, + }); + // Exit summaries are gated on EXIT_SUMMARY_MIN_MESSAGES, so every + // session_shutdown assertion below needs a substantive branch — otherwise + // the handler exits early and the test passes without exercising the guard. + const substantiveBranch = (endIso: string) => [ + message(new Date(Date.parse(endIso) - 40_000).toISOString()), + message(new Date(Date.parse(endIso) - 30_000).toISOString()), + message(new Date(Date.parse(endIso) - 20_000).toISOString()), + message(endIso), + ]; + + test("parseLocalTimestamp reads local stamps and rejects anything else", () => { + const parsed = parseLocalTimestamp("2026-10-15 13:03:46"); + expect(parsed).toBeInstanceOf(Date); + expect(parsed?.getHours()).toBe(13); + expect(parseLocalTimestamp("nope")).toBeNull(); + expect(parseLocalTimestamp("2026-10-15T13:03:46Z")).toBeNull(); + }); + + test("formatLocalTimestamp round-trips through parseLocalTimestamp", () => { + const now = new Date(); + const parsed = parseLocalTimestamp(formatLocalTimestamp(now)); + expect(parsed).not.toBeNull(); + expect(Math.floor((parsed as Date).getTime() / 1000)).toBe(Math.floor(now.getTime() / 1000)); + }); + + test("findLastExitSummaryTimestamp returns null without a daily log", () => { + expect(findLastExitSummaryTimestamp("deadbeef")).toBeNull(); + }); + + test("findLastExitSummaryTimestamp matches only the given session", () => { + ensureDirs(); + fs.writeFileSync( + dailyPath(todayStr()), + `\n## Session Summary (auto, exit: /quit)\n\n- other\n`, + ); + expect(findLastExitSummaryTimestamp("bbbbbbbb")).toBeNull(); + expect(findLastExitSummaryTimestamp("aaaaaaaa")).not.toBeNull(); + }); + + test("findLastExitSummaryTimestamp matches non-hex session ids", () => { + // shortSessionId() only slices 8 characters, so a hex-only character + // class would silently stop matching and let duplicates through. + ensureDirs(); + const ts = formatLocalTimestamp(new Date()); + fs.writeFileSync(dailyPath(todayStr()), `\n## Session Summary\n\n- x\n`); + expect(findLastExitSummaryTimestamp("exit-test-session")).not.toBeNull(); + }); + + test("hasNewMessagesSince fails open without a prior summary or branch", () => { + expect(hasNewMessagesSince([message(new Date().toISOString())], null)).toBe(true); + expect(hasNewMessagesSince(null, new Date())).toBe(true); + }); + + test("bookkeeping-only tail does not re-trigger a summary", () => { + const summaryAt = new Date(Date.now() - 60_000); + const branch = [ + message(new Date(summaryAt.getTime() - 120_000).toISOString()), + // The exact observed tail: three state entries, no new message. + bookkeeping(new Date(summaryAt.getTime() + 1_000).toISOString(), "plan-mode-state"), + bookkeeping(new Date(summaryAt.getTime() + 5_000).toISOString(), "plan-mode-state"), + bookkeeping(new Date(summaryAt.getTime() + 9_000).toISOString(), "compact-thinking-duration"), + ]; + expect(hasNewMessagesSince(branch, summaryAt)).toBe(false); + }); + + test("a genuinely new message re-enables the summary", () => { + const summaryAt = new Date(Date.now() - 60_000); + const branch = [ + message(new Date(summaryAt.getTime() - 120_000).toISOString()), + bookkeeping(new Date(summaryAt.getTime() + 5_000).toISOString(), "plan-mode-state"), + message(new Date(summaryAt.getTime() + 10_000).toISOString()), + ]; + expect(hasNewMessagesSince(branch, summaryAt)).toBe(true); + }); + + test("numeric timestamps and unparseable values are handled", () => { + const summaryAt = new Date(); + expect(hasNewMessagesSince([message(new Date(summaryAt.getTime() - 1_000).toISOString())], summaryAt)).toBe( + false, + ); + const numeric = [{ type: "message", timestamp: summaryAt.getTime() - 1_000 }]; + expect(hasNewMessagesSince(numeric, summaryAt)).toBe(false); + const numericNewer = [{ type: "message", timestamp: summaryAt.getTime() + 1_000 }]; + expect(hasNewMessagesSince(numericNewer, summaryAt)).toBe(true); + expect(hasNewMessagesSince([{ type: "message", timestamp: "garbage" }], summaryAt)).toBe(true); + }); + + test("session_shutdown skips the LLM call when nothing changed since the last summary", async () => { + ensureDirs(); + const summaryAt = new Date(Date.now() - 60_000); + fs.writeFileSync( + dailyPath(todayStr()), + `\n## Session Summary (auto, exit: /quit)\n\n- already summarized\n`, + ); + const getApiKey = mock(async () => "key"); + const ctx = createShutdownCtx({ + sessionId: "abcdef1234567890", + // All four messages predate the recorded summary, plus a bookkeeping + // entry after it: nothing new to summarize. + branch: [ + ...substantiveBranch(new Date(summaryAt.getTime() - 10_000).toISOString()), + bookkeeping(new Date(summaryAt.getTime() + 5_000).toISOString(), "plan-mode-state"), + ], + model: { provider: "openai", id: "gpt-4o-mini" }, + modelRegistry: { getApiKey }, + }); + + await hooks.session_shutdown({ reason: "quit" }, ctx); + + expect(getApiKey).not.toHaveBeenCalled(); + const body = fs.readFileSync(dailyPath(todayStr()), "utf-8"); + expect((body.match(/## Session Summary/g) || []).length).toBe(1); + }); + + test("session_shutdown still summarizes when the branch moved on", async () => { + ensureDirs(); + const summaryAt = new Date(Date.now() - 60_000); + fs.writeFileSync( + dailyPath(todayStr()), + `\n## Session Summary (auto, exit: /quit)\n\n- already summarized\n`, + ); + const getApiKey = mock(async () => "key"); + const ctx = createShutdownCtx({ + sessionId: "abcdef1234567890", + branch: substantiveBranch(new Date(summaryAt.getTime() + 10_000).toISOString()), + model: { provider: "openai", id: "gpt-4o-mini" }, + modelRegistry: { getApiKey }, + }); + + await hooks.session_shutdown({ reason: "quit" }, ctx); + + expect(getApiKey).toHaveBeenCalled(); + }); + }); + describe("isExitSummaryEmpty", () => { test("treats all-None summaries as empty", () => { const summary = [