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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
112 changes: 112 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<!-- <ts> [<sid>] -->` 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 = /<!--\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s*\[([0-9A-Za-z_-]{1,64})\]\s*-->/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<boolean> {
if (qmdAvailable) return true;
if (getQmdUpdateMode() !== "background") return false;
Expand Down Expand Up @@ -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
Expand Down
148 changes: 148 additions & 0 deletions test/unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ import {
dailyPath,
ensureDirs,
ensureQmdEmbed,
findLastExitSummaryTimestamp,
forgetBlocks,
formatLocalTimestamp,
getEmbedProbeTimeoutMs,
getExitSummaryReasoningEffort,
getExitSummaryTimeoutMs,
getQmdSearchTimeoutMs,
hasNewMessagesSince,
isExitSummaryEmpty,
isExitSummaryEnabled,
nowTimestamp,
parseLocalTimestamp,
parseScratchpad,
probeEmbeddings,
qmdCollectionInstructions,
Expand Down Expand Up @@ -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()),
`<!-- ${formatLocalTimestamp(new Date())} [aaaaaaaa] -->\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()), `<!-- ${ts} [exit-tes] -->\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()),
`<!-- ${formatLocalTimestamp(summaryAt)} [abcdef12] -->\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()),
`<!-- ${formatLocalTimestamp(summaryAt)} [abcdef12] -->\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 = [
Expand Down