Skip to content

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

fix: re-inject the session context after a Gemini compression (#398)

Brenno Ferrari6beaf3e4979b
diff --git a/.claude/rules/hooks-per-agent.md b/.claude/rules/hooks-per-agent.md
index 8342eb5..67762da 100644
--- a/.claude/rules/hooks-per-agent.md
+++ b/.claude/rules/hooks-per-agent.md
@@ -13,9 +13,9 @@ 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 |
-| `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) | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `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 | PreCompact | — | PreCompress |
+| `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 |
| `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 a2c89ba..443b7fa 100644
--- a/.claude/scripts/classify-message.ts
+++ b/.claude/scripts/classify-message.ts
@@ -17,6 +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";
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
// CLASSIFY_HINT_STATE routes the state file into a tmp path for tests
@@ -68,6 +69,11 @@ if (toEmit.length > 0) {
);
}
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;
+if (reinjected !== null) parts.push(reinjected);
if (parts.length > 0) {
const eventName =
diff --git a/.claude/scripts/lib/reinject.ts b/.claude/scripts/lib/reinject.ts
new file mode 100644
index 0000000..f88843e
--- /dev/null
+++ b/.claude/scripts/lib/reinject.ts
@@ -0,0 +1,113 @@
+/**
+ * Re-injecting the session context after a Gemini compression (#357).
+ *
+ * Gemini CLI fires no SessionStart when it compresses a conversation: its
+ * SessionStart sources are startup, resume and clear. And the compression
+ * summarises the early turn that carried the session context. Interactive
+ * Gemini adds SessionStart's additionalContext as an ordinary first user turn,
+ * and compression sends history up to its split point to a summariser,
+ * rebuilding only the environment context (gemini-cli ui/AppContainer.tsx and
+ * 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.
+ *
+ * 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.
+ */
+
+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";
+
+/** The session's marker file. */
+const markerPath = (dir: string, sessionId: string): string => sessionFile(dir, sessionId, "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 !== "";
+}
+
+/**
+ * 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.
+ */
+export function markReinject(dir: string, sessionId: string): void {
+ mkdirSync(dir, { recursive: true });
+ pruneHandoffs(dir, Date.now());
+ writeFileSync(markerPath(dir, sessionId), "");
+}
+
+/**
+ * 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;
+}
+
+/** 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;
+ }
+}
diff --git a/.claude/scripts/lib/stop-handoff.ts b/.claude/scripts/lib/stop-handoff.ts
index 937a470..cd92598 100644
--- a/.claude/scripts/lib/stop-handoff.ts
+++ b/.claude/scripts/lib/stop-handoff.ts
@@ -41,9 +41,14 @@ export const HANDOFF_DIR = envPath(process.env, "STOP_HANDOFF_DIR", join(dirname
/** Reports nobody picked up are removed after this long. */
export const HANDOFF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
-/** The session's handoff file. Session ids are reduced to a safe filename. */
+/** A per-session file in `dir`, the session id reduced to a safe filename. */
+export function sessionFile(dir: string, sessionId: string, extension: string): string {
+ return join(dir, `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.${extension}`);
+}
+
+/** The session's handoff file. */
export function handoffPath(dir: string, sessionId: string): string {
- return join(dir, `${sessionId.replace(/[^A-Za-z0-9_-]/g, "_")}.txt`);
+ return sessionFile(dir, sessionId, "txt");
}
/** Save `text` for the session's next prompt, replacing any unread report. Throws if it cannot. */
diff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.ts
index f7d2fd4..63245ef 100644
--- a/.claude/scripts/pre-compact.ts
+++ b/.claude/scripts/pre-compact.ts
@@ -22,10 +22,14 @@ 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 { HANDOFF_DIR } from "./lib/stop-handoff.ts";
type HookInput = {
readonly transcript_path?: unknown;
readonly trigger?: unknown;
+ readonly hook_event_name?: unknown;
+ readonly session_id?: unknown;
};
const BACKUP_RETAIN = 30;
@@ -80,6 +84,17 @@ 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)) {
+ try {
+ markReinject(HANDOFF_DIR, input.session_id as string);
+ } catch (err) {
+ debug(`pre-compact: could not mark the re-injection: ${(err as Error).message}`);
+ }
+ }
+
const transcriptPath =
typeof input.transcript_path === "string" ? input.transcript_path : "";
const trigger =
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index c0fc0a8..d70351a 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -86,11 +86,13 @@ import {
scanActiveHygiene,
} from "./lib/active-hygiene.ts";
+import { takeReinject } from "./lib/reinject.ts";
+import { HANDOFF_DIR } from "./lib/stop-handoff.ts";
import { debug, envelopedLimit, fitWithMeter, type OutputLimit, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
import { readOmMod } from "./lib/om-mod.ts";
import { resolveProjectDir } from "./lib/project-dir.ts";
-type HookInput = { readonly source?: unknown };
+type HookInput = { readonly source?: unknown; readonly session_id?: unknown };
// The SessionStart payload carries `source` (startup/clear/resume/compact).
// Missing or unparseable stdin fails open to full mode. stdin is OPTIONAL
@@ -117,6 +119,11 @@ 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 {
diff --git a/.claude/scripts/tests/classify-message.test.ts b/.claude/scripts/tests/classify-message.test.ts
index c242fcc..09e5083 100644
--- a/.claude/scripts/tests/classify-message.test.ts
+++ b/.claude/scripts/tests/classify-message.test.ts
@@ -7,7 +7,7 @@ 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 { mkdtempSync } from "node:fs";
+import { mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { takeHandoff, writeHandoff } from "../lib/stop-handoff.ts";
import { SIGNALS } from "../lib/signals.ts";
@@ -444,3 +444,60 @@ describe("classify — the Stop report handoff", () => {
assert.equal(takeHandoff(join(dir, "handoff"), "s-other"), "NOT-YOURS", "left for its own session");
});
});
+
+/**
+ * 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.
+ */
+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");
+
+ /** 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 => {
+ const root = mkdtempSync(join(tmpdir(), "reinject-hook-"));
+ try {
+ const vault = join(root, "vault");
+ mkdirSync(vault);
+ run({ STOP_HANDOFF_DIR: join(root, "handoff"), CLAUDE_PROJECT_DIR: vault });
+ } finally {
+ rmTemp(root);
+ }
+ };
+ const compress = (env: Record<string, string>, sessionId: string) =>
+ spawnHook(PRE_COMPACT, { hook_event_name: "PreCompress", session_id: sessionId, trigger: "auto" }, env);
+
+ test("PreCompress marks the session; the next prompt gets the context, the one after does not", () => {
+ withVault((env) => {
+ assert.equal(compress(env, "gem-1").code, 0);
+
+ const prompt = { hook_event_name: "BeforeAgent", session_id: "gem-1", prompt: "hello world" };
+ const first = spawnHook(SCRIPT, prompt, env, { timeoutMs: 60_000 });
+ 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");
+
+ 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", () => {
+ 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 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");
+ });
+ });
+
+ test("Claude Code's PreCompact marks 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);
+ assert.equal(after.stdout, "");
+ });
+ });
+});
diff --git a/.claude/scripts/tests/reinject.test.ts b/.claude/scripts/tests/reinject.test.ts
new file mode 100644
index 0000000..83cdb30
--- /dev/null
+++ b/.claude/scripts/tests/reinject.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Re-injecting the session context after a Gemini compression (#357).
+ *
+ * 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
+ * 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 { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { markReinject, reinjectContext, schedulesReinject, takeReinject } from "../lib/reinject.ts";
+import { rmTemp } from "./_helpers.ts";
+
+const withDir = (run: (dir: string) => void): void => {
+ const dir = mkdtempSync(join(tmpdir(), "reinject-"));
+ try {
+ run(dir);
+ } finally {
+ rmTemp(dir);
+ }
+};
+
+describe("schedulesReinject", () => {
+ test("Gemini's PreCompress with a session schedules it", () => {
+ assert.equal(schedulesReinject({ hook_event_name: "PreCompress", session_id: "s1" }), true);
+ });
+
+ 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("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);
+ });
+});
+
+describe("the marker", () => {
+ test("is taken once, per session", () => {
+ 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");
+ });
+ });
+
+ test("a session id is reduced to a safe file name", () => {
+ 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");
+ assert.equal(existsSync(join(root, "escape.reinject")), false);
+ assert.equal(takeReinject(dir, "../escape"), true);
+ });
+ });
+});
+
+describe("reinjectContext", () => {
+ 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("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);
+ });
+ });
+});