Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: build the Gemini re-injection at PreCompress, not on the prompt path (#401)

Brenno Ferrarieeda290e2b6c
diff --git a/.claude/rules/hooks-per-agent.md b/.claude/rules/hooks-per-agent.md
index 67762da..d747c25 100644
--- a/.claude/rules/hooks-per-agent.md
+++ b/.claude/rules/hooks-per-agent.md
@@ -12,10 +12,10 @@ The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell,
| Script | Purpose | Claude event | Codex event | Gemini event |
|--------|---------|--------------|-------------|--------------|
-| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
+| `session-start.ts` | Inject vault context at startup; under Gemini, a session whose compressed context is still waiting gets it here, in full (#357) | SessionStart | SessionStart | SessionStart |
| `classify-message.ts` | Classify messages, inject routing hints, hand over the last Stop report (Claude Code and Codex: Gemini's checklist runs on SessionEnd and saves none); under Gemini, re-inject the session context on the first prompt after a compression | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
-| `pre-compact.ts` | Back up transcript before compaction; under Gemini, which fires no SessionStart after compressing, also mark the session for re-injection (#357) | PreCompact | — | PreCompress |
+| `pre-compact.ts` | Back up transcript before compaction; under Gemini, which fires no SessionStart after compressing (read in gemini-cli's source, not observed), also store the session context for re-injection (#357) | PreCompact | — | PreCompress |
| `stop-checklist.ts` | Wrap-up checklist and vault-hygiene drift findings (Claude Code and Codex: per response, deduped; Gemini: once, at shutdown) | Stop | Stop | SessionEnd |
Codex runs these hooks only once the vault folder is trusted and each hook approved (observed with Codex CLI 0.160.0 as of 2026-10-13, #345; the setup is in README's "Using with Other Agents").
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.ts
index 443b7fa..7ad28f4 100644
--- a/.claude/scripts/classify-message.ts
+++ b/.claude/scripts/classify-message.ts
@@ -17,7 +17,7 @@ import { classify } from "./lib/matcher.ts";
import { claimUnseen } from "./lib/hint-state.ts";
import { envPath } from "./lib/env-path.ts";
import { HANDOFF_DIR, takeHandoff } from "./lib/stop-handoff.ts";
-import { reinjectContext } from "./lib/reinject.ts";
+import { takeReinject } from "./lib/reinject.ts";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
// CLASSIFY_HINT_STATE routes the state file into a tmp path for tests
@@ -39,8 +39,8 @@ if (!input) {
// The previous turn's Stop report, if one is waiting (lib/stop-handoff.ts).
// Taken before anything about the prompt is checked: it rides with this
// prompt whatever the prompt holds.
-const sessionId = input.session_id;
-const stopReport = typeof sessionId === "string" && sessionId ? takeHandoff(HANDOFF_DIR, sessionId) : null;
+const sessionId = typeof input.session_id === "string" && input.session_id ? input.session_id : null;
+const stopReport = sessionId !== null ? takeHandoff(HANDOFF_DIR, sessionId) : null;
const prompt = input.prompt;
const usable = typeof prompt === "string" && prompt !== "";
@@ -52,7 +52,7 @@ debug(`classify: matched ${signals.length} signal(s)`);
// a self-pruning state file (7-day age + 200-session cap). Missing/invalid
// session_id fails OPEN — every hint emits, matching today's behavior.
let toEmit = signals;
-if (typeof sessionId === "string" && sessionId && signals.length > 0) {
+if (sessionId !== null && signals.length > 0) {
toEmit = claimUnseen(STATE_PATH, sessionId, signals);
debug(
`classify: ${signals.length - toEmit.length} signal(s) already fired this session`,
@@ -72,7 +72,7 @@ if (stopReport !== null) parts.push(stopReport);
// After a Gemini compression, the session context once (#357). Last: if the
// output cap cuts anything, it cuts the end of the context, not the hints
// claimUnseen has already marked as fired.
-const reinjected = typeof sessionId === "string" && sessionId ? reinjectContext(HANDOFF_DIR, sessionId) : null;
+const reinjected = sessionId !== null ? takeReinject(HANDOFF_DIR, sessionId) : null;
if (reinjected !== null) parts.push(reinjected);
if (parts.length > 0) {
diff --git a/.claude/scripts/lib/reinject.ts b/.claude/scripts/lib/reinject.ts
index f88843e..e801e23 100644
--- a/.claude/scripts/lib/reinject.ts
+++ b/.claude/scripts/lib/reinject.ts
@@ -10,104 +10,60 @@
* context/chatCompressionService.ts, as of 29315e5). Claude Code and Codex
* re-inject on SessionStart `compact` instead.
*
- * So Gemini's PreCompress marks the session (pre-compact.ts), and the next
- * BeforeAgent (classify-message.ts) hands over session-start's full context
- * once. Full, not compact: Claude Code's compact form points at sections it
- * keeps in the conversation, but Gemini's compression summarised those away.
- * A resume or clear first takes the mark (session-start.ts), since it injects
- * the context itself. The mark lives beside the Stop handoffs, and marking
- * prunes old ones, since Gemini's checklist never does.
+ * So Gemini's PreCompress builds session-start's full context and stores it
+ * for the session (pre-compact.ts, with lib/session-start-run.ts), and the
+ * next BeforeAgent (classify-message.ts) hands it over once: a file read on
+ * the prompt path, not a session-start run. Full, not compact: Claude Code's
+ * compact form points at sections it keeps in the conversation, but Gemini's
+ * compression summarised those away. A resume or clear first takes the stored
+ * context and injects the full form itself (session-start.ts). It lives beside
+ * the Stop handoffs, and storing prunes old ones, since Gemini's checklist
+ * never does.
*
* Not covered (inferred from gemini-cli's flow, not observed): a PreCompress
- * whose compression then does nothing still marks the session, so the next
- * prompt gets the context again; and a compression partway through a long
- * turn gets the context back only on the next prompt.
+ * whose compression then does nothing still stores the context, so the next
+ * prompt gets it again; a compression partway through a long turn gets the
+ * context back only on the next prompt; and a resume after that prompt gets
+ * the compact form, whether or not Gemini's saved history kept the
+ * re-injected context (TBC). And the re-injected context leaves out the qmd
+ * self-heal and version warnings: its build skips the qmd work, so a warning
+ * given at startup is lost with the compressed turn.
*/
-import { spawnSync } from "node:child_process";
-import { mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { parseHookContext } from "./hook-io.ts";
-import { REFRESH_SWITCH } from "./qmd.ts";
-import { pruneHandoffs, sessionFile } from "./stop-handoff.ts";
+import { claimSessionFile, pruneHandoffs, writeSessionFile } from "./stop-handoff.ts";
-/** The session's marker file. */
-const markerPath = (dir: string, sessionId: string): string => sessionFile(dir, sessionId, "reinject");
+const EXTENSION = "reinject";
-/** Whether this pre-compaction hook call should schedule a re-injection: Gemini's PreCompress, with a session. */
-export function schedulesReinject(input: { readonly hook_event_name?: unknown; readonly session_id?: unknown }): boolean {
- return input.hook_event_name === "PreCompress" && typeof input.session_id === "string" && input.session_id !== "";
+/** The session to re-inject for, from a pre-compaction hook call: Gemini's PreCompress with a session, else null. */
+export function reinjectSession(input: { readonly hook_event_name?: unknown; readonly session_id?: unknown }): string | null {
+ return input.hook_event_name === "PreCompress" && typeof input.session_id === "string" && input.session_id !== ""
+ ? input.session_id
+ : null;
}
/**
- * Mark the session for a re-injection on its next prompt. Throws if it cannot.
- * Prunes old handoffs and marks first: Gemini runs its checklist on SessionEnd,
- * which never prunes, so a session that ends right after compressing would
- * otherwise leave its mark behind for good.
+ * Store `context` for the session's next prompt, stamped with when it was
+ * built: the prompt can come hours later, and the dated sections are as of
+ * then. A null or empty context stores nothing. Throws if it cannot write.
+ * Prunes old handoffs whatever the context: Gemini runs its checklist on
+ * SessionEnd, which never prunes, so this is the one prune Gemini's handoffs
+ * get.
*/
-export function markReinject(dir: string, sessionId: string): void {
- mkdirSync(dir, { recursive: true });
- pruneHandoffs(dir, Date.now());
- writeFileSync(markerPath(dir, sessionId), "");
+export function storeReinject(dir: string, sessionId: string, context: string | null, now: Date = new Date()): void {
+ pruneHandoffs(dir, now.getTime());
+ if (context === null || context.trim() === "") return;
+ const stamp = `(Session context rebuilt ${localTime(now)}, when the conversation was about to be compressed.)`;
+ writeSessionFile(dir, sessionId, EXTENSION, `${stamp}\n\n${context}`);
}
-/**
- * Take the session's mark, once: true when one was waiting. Claimed by rename
- * first, as the handoff is, so two hooks racing for one mark can't both run
- * session-start.
- */
-export function takeReinject(dir: string, sessionId: string): boolean {
- const target = markerPath(dir, sessionId);
- const claimed = `${target}.${process.pid}.claimed`;
- try {
- renameSync(target, claimed);
- } catch {
- return false;
- }
- try {
- unlinkSync(claimed);
- } catch {
- /* best effort: pruning removes it later */
- }
- return true;
+/** `YYYY-MM-DD HH:MM` in local time, the clock the context's Date section uses. */
+function localTime(d: Date): string {
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
-/** Runs session-start with `stdin` as its hook input and returns its exit status and stdout. */
-export type SessionStartRun = (stdin: Record<string, unknown>) => { readonly status: number | null; readonly stdout: string };
-
-const SESSION_START = join(dirname(dirname(fileURLToPath(import.meta.url))), "session-start.ts");
-
-/**
- * session-start.ts can't be imported: it is a hook script whose work runs at
- * the top level. So it runs as a child, once per compression, hidden on
- * Windows (#390), and bounded under Gemini's 15 s BeforeAgent budget so the
- * hook still answers if the child is slow. The refresh is off in the child:
- * PreCompress already started one.
- */
-export const runSessionStart: SessionStartRun = (stdin) => {
- const r = spawnSync(process.execPath, ["--experimental-strip-types", SESSION_START], {
- input: JSON.stringify(stdin),
- encoding: "utf8",
- timeout: 10_000,
- windowsHide: true,
- env: { ...process.env, [REFRESH_SWITCH]: "off" },
- });
- return { status: r.status, stdout: r.stdout ?? "" };
-};
-
-/**
- * The session context to re-inject on this prompt, or null. Takes the mark
- * first, so a run that fails is not retried on every prompt after it.
- */
-export function reinjectContext(dir: string, sessionId: string, run: SessionStartRun = runSessionStart): string | null {
- if (!takeReinject(dir, sessionId)) return null;
- const r = run({ hook_event_name: "SessionStart", source: "startup", session_id: sessionId });
- if (r.status !== 0) return null;
- try {
- const context = parseHookContext(r.stdout, "SessionStart");
- return context.trim() === "" ? null : context;
- } catch {
- return null;
- }
+/** Take the session's stored context, once: null when none is waiting, or it is empty. */
+export function takeReinject(dir: string, sessionId: string): string | null {
+ const context = claimSessionFile(dir, sessionId, EXTENSION);
+ return context?.trim() ? context : null;
}
diff --git a/.claude/scripts/lib/session-start-run.ts b/.claude/scripts/lib/session-start-run.ts
new file mode 100644
index 0000000..7edf094
--- /dev/null
+++ b/.claude/scripts/lib/session-start-run.ts
@@ -0,0 +1,58 @@
+/**
+ * session-start's full context, from a child run (#357). session-start.ts
+ * can't be imported: it is a hook script whose work runs at the top level.
+ * Only Gemini's PreCompress needs this (lib/reinject.ts), so it stays out of
+ * the modules every prompt loads.
+ */
+
+import { spawnSync } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { debug, parseHookContext } from "./hook-io.ts";
+import { REFRESH_SWITCH } from "./qmd.ts";
+
+/** Runs session-start with `stdin` as its hook input and returns its exit status and stdout. */
+export type SessionStartRun = (stdin: Record<string, unknown>) => { readonly status: number | null; readonly stdout: string };
+
+const SESSION_START = join(dirname(dirname(fileURLToPath(import.meta.url))), "session-start.ts");
+
+/**
+ * The child, hidden on Windows (#390). Bounded at 20 s: PreCompress gets 30 s
+ * in .gemini/settings.json, and the transcript backup has already run in it
+ * by then. A session-start run took 5-12 s on Windows CI (measured
+ * 2026-10-13, #349). The refresh is off in the child: PreCompress already
+ * started one.
+ */
+export const runSessionStart: SessionStartRun = (stdin) => {
+ const r = spawnSync(process.execPath, ["--experimental-strip-types", SESSION_START], {
+ input: JSON.stringify(stdin),
+ encoding: "utf8",
+ timeout: 20_000,
+ windowsHide: true,
+ env: { ...process.env, [REFRESH_SWITCH]: "off" },
+ });
+ return { status: r.status, stdout: r.stdout ?? "" };
+};
+
+/**
+ * session-start's full context, or null when the run failed or gave nothing.
+ * Asked as a startup, the form that carries every section, flagged so it
+ * skips the qmd work startup already did; no session id, so the run never
+ * takes a stored context itself.
+ */
+export function sessionStartContext(run: SessionStartRun = runSessionStart): string | null {
+ const r = run({ hook_event_name: "SessionStart", source: "startup", om_reinject: true });
+ if (r.status !== 0) {
+ debug(`session-start run: exited ${r.status ?? "on a signal or timeout"}`);
+ return null;
+ }
+ try {
+ const context = parseHookContext(r.stdout, "SessionStart");
+ if (context.trim() !== "") return context;
+ debug("session-start run: empty context");
+ return null;
+ } catch (err) {
+ debug(`session-start run: unreadable output: ${(err as Error).message}`);
+ return null;
+ }
+}
diff --git a/.claude/scripts/lib/stop-handoff.ts b/.claude/scripts/lib/stop-handoff.ts
index cd92598..52eaffc 100644
--- a/.claude/scripts/lib/stop-handoff.ts
+++ b/.claude/scripts/lib/stop-handoff.ts
@@ -23,6 +23,10 @@
* collected: the next prompt arrives under a new session id. Nothing is lost
* with it. The dedupe is per session, so the new session's first Stop reports
* the same findings again, and the prune removes the orphan after a week.
+ *
+ * The same per-session files, claim and prune also carry Gemini's stored
+ * session context after a compression (lib/reinject.ts, #357), under their
+ * own extension.
*/
import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
@@ -34,7 +38,9 @@ import { envPath } from "./env-path.ts";
/**
* Where a Stop report waits for the next prompt: one place for the writer
* (stop-checklist) and the reader (classify-message), so they cannot drift
- * apart. STOP_HANDOFF_DIR routes it to a tmp path for tests.
+ * apart; Gemini's stored context (pre-compact, read by classify-message and
+ * session-start) waits beside it. STOP_HANDOFF_DIR routes it to a tmp path
+ * for tests.
*/
export const HANDOFF_DIR = envPath(process.env, "STOP_HANDOFF_DIR", join(dirname(fileURLToPath(import.meta.url)), "..", ".stop-handoff"));
@@ -51,15 +57,25 @@ export function handoffPath(dir: string, sessionId: string): string {
return sessionFile(dir, sessionId, "txt");
}
+/** Save `text` in the session's `extension` file, replacing any unread one. Throws if it cannot. */
+export function writeSessionFile(dir: string, sessionId: string, extension: string, text: string): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileAtomic(sessionFile(dir, sessionId, extension), text);
+}
+
/** Save `text` for the session's next prompt, replacing any unread report. Throws if it cannot. */
export function writeHandoff(dir: string, sessionId: string, text: string): void {
- mkdirSync(dir, { recursive: true });
- writeFileAtomic(handoffPath(dir, sessionId), text);
+ writeSessionFile(dir, sessionId, "txt", text);
}
/** Take the session's report, once. Null when there is none or it cannot be claimed. */
export function takeHandoff(dir: string, sessionId: string): string | null {
- const target = handoffPath(dir, sessionId);
+ return claimSessionFile(dir, sessionId, "txt");
+}
+
+/** Take the session's `extension` file, once: its text, or null when there is none or it cannot be claimed. */
+export function claimSessionFile(dir: string, sessionId: string, extension: string): string | null {
+ const target = sessionFile(dir, sessionId, extension);
const claimed = `${target}.${process.pid}.claimed`;
try {
renameSync(target, claimed);
diff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.ts
index 63245ef..96a8bb9 100644
--- a/.claude/scripts/pre-compact.ts
+++ b/.claude/scripts/pre-compact.ts
@@ -22,7 +22,8 @@ import { debug, readStdinJson } from "./lib/hook-io.ts";
import { isMainModule } from "./lib/main-guard.ts";
import { sentinelPathFrom, triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
-import { markReinject, schedulesReinject } from "./lib/reinject.ts";
+import { reinjectSession, storeReinject } from "./lib/reinject.ts";
+import { sessionStartContext } from "./lib/session-start-run.ts";
import { HANDOFF_DIR } from "./lib/stop-handoff.ts";
type HookInput = {
@@ -84,17 +85,31 @@ if (isMainModule(import.meta.url)) {
});
}
- // Gemini fires no SessionStart after compressing, so mark the session for
- // the next BeforeAgent to re-inject the context (lib/reinject.ts, #357).
- // Before the backup, which can exit early.
- if (schedulesReinject(input)) {
+ // The backup first: it is this hook's own job, and the re-injection below
+ // can take most of Gemini's PreCompress budget. Best effort, so a backup
+ // that throws never costs the re-injection.
+ try {
+ backupTranscript(input);
+ } catch (err) {
+ debug(`pre-compact: backup failed: ${(err as Error).message}`);
+ }
+
+ // Gemini fires no SessionStart after compressing, so store the context for
+ // the next BeforeAgent to re-inject (lib/reinject.ts, #357).
+ const reinjectFor = reinjectSession(input);
+ if (reinjectFor !== null) {
+ const context = sessionStartContext();
try {
- markReinject(HANDOFF_DIR, input.session_id as string);
+ storeReinject(HANDOFF_DIR, reinjectFor, context);
} catch (err) {
- debug(`pre-compact: could not mark the re-injection: ${(err as Error).message}`);
+ debug(`pre-compact: could not store the re-injection: ${(err as Error).message}`);
}
}
+ process.exit(0);
+}
+/** Copy the transcript into thinking/session-logs and prune old copies. Best effort. */
+function backupTranscript(input: HookInput): void {
const transcriptPath =
typeof input.transcript_path === "string" ? input.transcript_path : "";
const trigger =
@@ -102,7 +117,7 @@ if (isMainModule(import.meta.url)) {
if (!transcriptPath) {
debug("pre-compact: no transcript_path in input");
- process.exit(0);
+ return;
}
const projectDir = resolveProjectDir(process.cwd());
@@ -127,9 +142,8 @@ if (isMainModule(import.meta.url)) {
} else {
debug(`pre-compact: copy failed: ${(err as Error).message}`);
}
- process.exit(0);
+ return;
}
pruneBackups(backupDir, BACKUP_RETAIN);
- process.exit(0);
}
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index d70351a..3aa6b0d 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -92,7 +92,7 @@ import { debug, envelopedLimit, fitWithMeter, type OutputLimit, readStdinJson, w
import { readOmMod } from "./lib/om-mod.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
-type HookInput = { readonly source?: unknown; readonly session_id?: unknown };
+type HookInput = { readonly source?: unknown; readonly session_id?: unknown; readonly om_reinject?: unknown };
// The SessionStart payload carries `source` (startup/clear/resume/compact).
// Missing or unparseable stdin fails open to full mode. stdin is OPTIONAL
@@ -119,11 +119,6 @@ async function readHookInput(): Promise<HookInput | null> {
return result;
}
const hookInput = await readHookInput();
-// A Gemini session marked for re-injection after a compression (#357) that is
-// resumed or cleared before its next prompt gets its context here instead.
-if ((hookInput?.source === "resume" || hookInput?.source === "clear") && typeof hookInput.session_id === "string") {
- takeReinject(HANDOFF_DIR, hookInput.session_id);
-}
function readManifestRaw(): string | null {
try {
@@ -160,7 +155,13 @@ if (envFile) {
const omMod = readOmMod(hookInput);
if (omMod === "standdown") process.exit(0);
const delivering = omMod === "deliver";
-const mode = delivering ? "full" : injectionMode(hookInput?.source);
+// A Gemini session compressed since its context was injected (#357) gets it
+// here instead of on its next prompt, and in full whatever the source: the
+// compression summarised away the sections the compact form points at. Taking
+// the stored context consumes it, so after the stand-down, which injects nothing.
+const compressed =
+ typeof hookInput?.session_id === "string" && hookInput.session_id !== "" && takeReinject(HANDOFF_DIR, hookInput.session_id) !== null;
+const mode = delivering || compressed ? "full" : injectionMode(hookInput?.source);
process.chdir(cwd);
@@ -183,7 +184,12 @@ const infraRootFilenames = parseInfraRootFilenames(manifestJson);
// Route through `buildQmdCommand` so the shim-bypass logic that fixes
// the MCP wrapper applies here too.
const qmdIndex = resolveQmdIndex(manifestJson, cwd);
-const qmdEntry = resolveQmdEntry();
+// Gemini's PreCompress builds the context to re-inject (lib/session-start-run.ts,
+// #357): no qmd work in that run. The probes, self-heal and version check ran
+// at startup, a 20 s rebuild here would spend the run's whole budget, and
+// PreCompress started its own refresh.
+const reinjectBuild = hookInput?.om_reinject === true;
+const qmdEntry = reinjectBuild ? null : resolveQmdEntry();
// qmd is OPTIONAL in this template: every self-heal path below is gated on
// a resolvable install (`qmdEntry !== null`). A machine without qmd gets no
@@ -289,7 +295,7 @@ const qmdCwd = bootstrapNeeded ? cwd : tmpdir();
// update too, the same as the write-time refresh worker (#337): a test's
// session-start would otherwise leave a qmd update or bootstrap running
// against its temp vault after the run.
-spawnDetachedQmd(qmdUpdate, "session-start", qmdCwd);
+if (!reinjectBuild) spawnDetachedQmd(qmdUpdate, "session-start", qmdCwd);
type CmdResult =
| { readonly kind: "ok"; readonly stdout: string }
diff --git a/.claude/scripts/tests/classify-message.test.ts b/.claude/scripts/tests/classify-message.test.ts
index 09e5083..c02e57b 100644
--- a/.claude/scripts/tests/classify-message.test.ts
+++ b/.claude/scripts/tests/classify-message.test.ts
@@ -7,8 +7,9 @@ import { test, describe, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
-import { mkdirSync, mkdtempSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
+import { parseHookContext } from "../lib/hook-io.ts";
import { takeHandoff, writeHandoff } from "../lib/stop-handoff.ts";
import { SIGNALS } from "../lib/signals.ts";
import { classify } from "../lib/matcher.ts";
@@ -446,12 +447,13 @@ describe("classify — the Stop report handoff", () => {
});
/**
- * After a Gemini compression (#357): Gemini's PreCompress marks the session,
- * and the next BeforeAgent hands over the session context once. Spawns
- * session-start through classify-message, so it runs on CI.
+ * After a Gemini compression (#357): Gemini's PreCompress stores the session
+ * context, and the next BeforeAgent hands it over once. Spawns session-start
+ * through pre-compact, so it runs on CI.
*/
describe("classify-message — re-injects the session context after a Gemini compression (#357)", () => {
const PRE_COMPACT = resolve(dirname(fileURLToPath(import.meta.url)), "../pre-compact.ts");
+ const SESSION_START = resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts");
/** An empty vault and a handoff folder, both temporary: session-start never reads the real repo. */
const withVault = (run: (env: Record<string, string>) => void): void => {
@@ -464,36 +466,70 @@ describe("classify-message — re-injects the session context after a Gemini com
rmTemp(root);
}
};
- const compress = (env: Record<string, string>, sessionId: string) =>
- spawnHook(PRE_COMPACT, { hook_event_name: "PreCompress", session_id: sessionId, trigger: "auto" }, env);
+ // PreCompress runs session-start itself, so it gets the longer budget.
+ const compress = (env: Record<string, string>, sessionId: string, extra: Record<string, unknown> = {}) =>
+ spawnHook(PRE_COMPACT, { hook_event_name: "PreCompress", session_id: sessionId, trigger: "auto", ...extra }, env, {
+ timeoutMs: 60_000,
+ });
- test("PreCompress marks the session; the next prompt gets the context, the one after does not", () => {
+ test("PreCompress backs up the transcript and stores the context; the next prompt gets it, the one after does not", () => {
withVault((env) => {
- assert.equal(compress(env, "gem-1").code, 0);
+ const transcript = join(env["CLAUDE_PROJECT_DIR"]!, "..", "transcript.jsonl");
+ writeFileSync(transcript, "{}\n");
+ assert.equal(compress(env, "gem-1", { transcript_path: transcript }).code, 0);
+ const logs = join(env["CLAUDE_PROJECT_DIR"]!, "thinking", "session-logs");
+ assert.equal(existsSync(logs) ? readdirSync(logs).length : 0, 1, "the backup still lands");
const prompt = { hook_event_name: "BeforeAgent", session_id: "gem-1", prompt: "hello world" };
- const first = spawnHook(SCRIPT, prompt, env, { timeoutMs: 60_000 });
+ const first = spawnHook(SCRIPT, prompt, env);
assert.equal(first.code, 0);
- const context = (JSON.parse(first.stdout) as { hookSpecificOutput: { additionalContext: string } }).hookSpecificOutput
- .additionalContext;
- assert.match(context, /### Date/, "session-start's context, re-injected");
+ assert.match(parseHookContext(first.stdout, "BeforeAgent"), /### Date/, "session-start's context, re-injected");
const second = spawnHook(SCRIPT, prompt, env);
assert.equal(second.stdout, "", "once: the next prompt gets nothing");
});
});
- test("a resume after the compression takes the mark: it injects the context itself", () => {
+ test("a resume after the compression injects the full context itself, and the next prompt gets no second copy", () => {
withVault((env) => {
- compress(env, "gem-2");
- const SESSION_START = resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts");
- assert.equal(spawnHook(SESSION_START, { hook_event_name: "SessionStart", source: "resume", session_id: "gem-2" }, env).code, 0);
+ const resume = { hook_event_name: "SessionStart", source: "resume", session_id: "gem-2" };
+ const plain = spawnHook(SESSION_START, resume, env);
+ assert.match(parseHookContext(plain.stdout, "SessionStart"), /### Context Pointer/, "a plain resume is the compact form");
+
+ assert.equal(compress(env, "gem-2").code, 0);
+ const resumed = spawnHook(SESSION_START, resume, env);
+ assert.equal(resumed.code, 0);
+ assert.doesNotMatch(parseHookContext(resumed.stdout, "SessionStart"), /### Context Pointer/, "the full form after a compression");
const after = spawnHook(SCRIPT, { hook_event_name: "BeforeAgent", session_id: "gem-2", prompt: "hello world" }, env);
- assert.equal(after.stdout, "", "no second copy of the context");
+ assert.equal(after.stdout, "");
+ });
+ });
+
+ test("a backup that throws doesn't cost the re-injection", () => {
+ withVault((env) => {
+ // A file where the backup folder goes, so its mkdir throws.
+ writeFileSync(join(env["CLAUDE_PROJECT_DIR"]!, "thinking"), "");
+ const transcript = join(env["CLAUDE_PROJECT_DIR"]!, "..", "transcript.jsonl");
+ writeFileSync(transcript, "{}\n");
+ assert.equal(compress(env, "gem-3", { transcript_path: transcript }).code, 0);
+ const first = spawnHook(SCRIPT, { hook_event_name: "BeforeAgent", session_id: "gem-3", prompt: "hello world" }, env);
+ assert.match(parseHookContext(first.stdout, "BeforeAgent"), /### Date/);
+ });
+ });
+
+ test("the re-injection build starts no detached qmd update; an ordinary startup does", () => {
+ withVault((env) => {
+ const debugEnv = { ...env, HOOK_DEBUG: "1" };
+ const spawnLine = "session-start: qmd refresh off";
+ const startup = spawnHook(SESSION_START, { hook_event_name: "SessionStart", source: "startup" }, debugEnv);
+ assert.ok(startup.stderr.includes(spawnLine), "the line this test watches for is logged by an ordinary startup");
+ const build = spawnHook(SESSION_START, { hook_event_name: "SessionStart", source: "startup", om_reinject: true }, debugEnv);
+ assert.equal(build.code, 0);
+ assert.equal(build.stderr.includes(spawnLine), false, "PreCompress already started a refresh");
});
});
- test("Claude Code's PreCompact marks nothing: it re-injects on SessionStart compact", () => {
+ test("Claude Code's PreCompact stores nothing: it re-injects on SessionStart compact", () => {
withVault((env) => {
spawnHook(PRE_COMPACT, { hook_event_name: "PreCompact", session_id: "cc-1", trigger: "auto" }, env);
const after = spawnHook(SCRIPT, { hook_event_name: "UserPromptSubmit", session_id: "cc-1", prompt: "hello world" }, env);
diff --git a/.claude/scripts/tests/reinject.test.ts b/.claude/scripts/tests/reinject.test.ts
index 83cdb30..89d5cc2 100644
--- a/.claude/scripts/tests/reinject.test.ts
+++ b/.claude/scripts/tests/reinject.test.ts
@@ -4,18 +4,20 @@
* Gemini fires no SessionStart on compression, and its compression summarises
* the early turn that carried the session context (gemini-cli
* context/chatCompressionService.ts and ui/AppContainer.tsx, as of 29315e5).
- * So Gemini's PreCompress marks the session, and the next BeforeAgent hands
- * over session-start's compact context once. Claude Code and Codex re-inject on
+ * So Gemini's PreCompress stores session-start's full context, and the next
+ * BeforeAgent hands it over once. Claude Code and Codex re-inject on
* SessionStart `compact` and are left alone.
*/
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { existsSync, mkdtempSync } from "node:fs";
+import { existsSync, mkdtempSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { markReinject, reinjectContext, schedulesReinject, takeReinject } from "../lib/reinject.ts";
+import { reinjectSession, storeReinject, takeReinject } from "../lib/reinject.ts";
+import { sessionStartContext } from "../lib/session-start-run.ts";
+import { HANDOFF_MAX_AGE_MS, writeSessionFile } from "../lib/stop-handoff.ts";
import { rmTemp } from "./_helpers.ts";
const withDir = (run: (dir: string) => void): void => {
@@ -27,28 +29,51 @@ const withDir = (run: (dir: string) => void): void => {
}
};
-describe("schedulesReinject", () => {
- test("Gemini's PreCompress with a session schedules it", () => {
- assert.equal(schedulesReinject({ hook_event_name: "PreCompress", session_id: "s1" }), true);
+describe("reinjectSession", () => {
+ test("Gemini's PreCompress gives its session", () => {
+ assert.equal(reinjectSession({ hook_event_name: "PreCompress", session_id: "s1" }), "s1");
});
- test("Claude Code's PreCompact doesn't: it re-injects on SessionStart compact", () => {
- assert.equal(schedulesReinject({ hook_event_name: "PreCompact", session_id: "s1" }), false);
+ test("Claude Code's PreCompact gives none: it re-injects on SessionStart compact", () => {
+ assert.equal(reinjectSession({ hook_event_name: "PreCompact", session_id: "s1" }), null);
});
test("no session, nothing to key it by", () => {
- assert.equal(schedulesReinject({ hook_event_name: "PreCompress" }), false);
- assert.equal(schedulesReinject({ hook_event_name: "PreCompress", session_id: "" }), false);
+ assert.equal(reinjectSession({ hook_event_name: "PreCompress" }), null);
+ assert.equal(reinjectSession({ hook_event_name: "PreCompress", session_id: "" }), null);
});
});
-describe("the marker", () => {
- test("is taken once, per session", () => {
+describe("the stored context", () => {
+ test("is taken once, by its own session, stamped with when it was built", () => {
withDir((dir) => {
- markReinject(dir, "s1");
- assert.equal(takeReinject(dir, "s2"), false, "another session's marker is not this one's");
- assert.equal(takeReinject(dir, "s1"), true);
- assert.equal(takeReinject(dir, "s1"), false, "once");
+ storeReinject(dir, "s1", "## Session Context\nvolatile", new Date(2026, 9, 14, 9, 5));
+ assert.equal(takeReinject(dir, "s2"), null, "another session's context is not this one's");
+ assert.equal(
+ takeReinject(dir, "s1"),
+ "(Session context rebuilt 2026-10-14 09:05, when the conversation was about to be compressed.)\n\n## Session Context\nvolatile",
+ "in local time, the clock the Date section uses",
+ );
+ assert.equal(takeReinject(dir, "s1"), null, "once");
+ });
+ });
+
+ test("an empty one, or none, is not stored, and old handoffs are pruned either way", () => {
+ withDir((dir) => {
+ writeSessionFile(dir, "old", "txt", "a week-old report");
+ const old = new Date(Date.now() - HANDOFF_MAX_AGE_MS - 60_000);
+ utimesSync(join(dir, "old.txt"), old, old);
+ storeReinject(dir, "s1", null);
+ assert.equal(existsSync(join(dir, "old.txt")), false, "Gemini's one prune runs even when the build failed");
+ storeReinject(dir, "s1", " \n");
+ assert.equal(takeReinject(dir, "s1"), null);
+ });
+ });
+
+ test("an empty file left behind gives nothing", () => {
+ withDir((dir) => {
+ writeSessionFile(dir, "s1", "reinject", " \n");
+ assert.equal(takeReinject(dir, "s1"), null);
});
});
@@ -56,50 +81,29 @@ describe("the marker", () => {
withDir((root) => {
// One level down, so even an escaping write stays inside the temp folder and is cleaned up.
const dir = join(root, "markers");
- markReinject(dir, "../escape");
+ storeReinject(dir, "../escape", "x");
assert.equal(existsSync(join(root, "escape.reinject")), false);
- assert.equal(takeReinject(dir, "../escape"), true);
+ assert.match(takeReinject(dir, "../escape") ?? "", /\n\nx$/);
});
});
});
-describe("reinjectContext", () => {
+describe("sessionStartContext", () => {
const envelope = (context: string) =>
JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context } });
- test("hands over session-start's compact context once after a mark, then nothing", () => {
- withDir((dir) => {
- const asked: Array<Record<string, unknown>> = [];
- const run = (stdin: Record<string, unknown>) => {
- asked.push(stdin);
- return { status: 0, stdout: envelope("## Session Context\nvolatile") };
- };
- markReinject(dir, "s1");
- assert.equal(reinjectContext(dir, "s1", run), "## Session Context\nvolatile");
- assert.equal(asked[0]?.["source"], "startup", "the full context: the compression summarised it away");
- assert.equal(asked[0]?.["session_id"], "s1");
- assert.equal(reinjectContext(dir, "s1", run), null, "the next prompt gets nothing");
- assert.equal(asked.length, 1, "session-start ran once");
- });
- });
-
- test("without a mark, session-start doesn't run", () => {
- withDir((dir) => {
- let ran = false;
- assert.equal(reinjectContext(dir, "s1", () => ((ran = true), { status: 0, stdout: envelope("x") })), null);
- assert.equal(ran, false);
- });
+ test("asks session-start for its full context, with no session to take a stored one", () => {
+ const asked: Array<Record<string, unknown>> = [];
+ const context = sessionStartContext((stdin) => (asked.push(stdin), { status: 0, stdout: envelope("## Session Context") }));
+ assert.equal(context, "## Session Context");
+ assert.equal(asked[0]?.["source"], "startup", "the full context: the compression summarised it away");
+ assert.equal("session_id" in (asked[0] ?? {}), false);
+ assert.equal(asked[0]?.["om_reinject"], true, "flagged, so it skips the qmd work startup already did");
});
- test("a failed or empty run gives nothing, and the mark is spent rather than retried every prompt", () => {
- withDir((dir) => {
- markReinject(dir, "s1");
- assert.equal(reinjectContext(dir, "s1", () => ({ status: 1, stdout: envelope("a run that failed after printing") })), null);
- markReinject(dir, "s1");
- assert.equal(reinjectContext(dir, "s1", () => ({ status: 0, stdout: "not json" })), null);
- markReinject(dir, "s1");
- assert.equal(reinjectContext(dir, "s1", () => ({ status: 0, stdout: envelope("") })), null);
- assert.equal(takeReinject(dir, "s1"), false);
- });
+ test("a failed or empty run gives nothing", () => {
+ assert.equal(sessionStartContext(() => ({ status: 1, stdout: envelope("a run that failed after printing") })), null);
+ assert.equal(sessionStartContext(() => ({ status: 0, stdout: "not json" })), null);
+ assert.equal(sessionStartContext(() => ({ status: 0, stdout: envelope("") })), null);
});
});