diff --git a/CHANGELOG.md b/CHANGELOG.md index 3da7a8f6..1307b40b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Fixed +- **SessionEnd memory hook no longer reported as "Hook cancelled".** The + `kit memory hook session-end` ran its indexing inline, so a periodic + all-harness sweep (or a hung opt-in `push_on_end`) could overrun Claude Code's + shutdown window and surface as `SessionEnd hook … failed: Hook cancelled`. On + the common path (no `push_on_end`) the index now runs in a detached, + fire-and-forget child so the hook returns instantly — the index still completes, + and the next SessionStart recovery re-indexes any missed tail. The ephemeral + `push_on_end` path still indexes inline (the push must observe this session's + rows before the container is reclaimed). Fail-open throughout. - **PAL finding sync no longer device-blind — a real security blocker can't be silently cleared across devices.** The adversarial pass on the 3.0 surface found that `palSyncFindings` auto-closed findings purely by source-tag + scope, diff --git a/src/commands/memory.ts b/src/commands/memory.ts index dad31c78..b878dd36 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -29,6 +29,7 @@ import { initSyncConfig, tryAutoPull, tryAutoPush, + isAutoPushConfigured, maybeSyncNudge, type SyncTransport, } from "../memory/remote-sync.js"; @@ -48,6 +49,7 @@ import { userPromptSubmitReminder, maybeStartMidSessionIndex, runSessionEndIndex, + startDetachedSessionEndIndex, sessionStartRecovery, } from "../memory/hook.js"; import { decisionsForPaths, changedPaths } from "../memory/clusters.js"; @@ -683,11 +685,19 @@ async function memHook(): Promise { return true; } if (event === "session-end") { - runSessionEndIndex(); - // Opt-in: push this session's memory to your durable store before an - // (ephemeral) container is reclaimed. Fail-soft; notes go to stderr. - const pushed = tryAutoPush(getCurrentProjectRoot()); - if (pushed.note) console.error(`${c.dim}${pushed.note}${c.reset}`); + if (isAutoPushConfigured()) { + // Ephemeral-container path: the push must include THIS session, so the + // index has to finish before it → run inline, then push to the durable + // store before the container is reclaimed. Fail-soft; notes go to stderr. + runSessionEndIndex(); + const pushed = tryAutoPush(getCurrentProjectRoot()); + if (pushed.note) console.error(`${c.dim}${pushed.note}${c.reset}`); + } else { + // Common path (no push_on_end): detach the index so the hook returns + // instantly. Indexing inline lets a periodic all-harness sweep overrun + // Claude Code's shutdown window → "SessionEnd hook … Hook cancelled". + startDetachedSessionEndIndex(); + } return true; } if (event === "session-start") { diff --git a/src/memory/hook.ts b/src/memory/hook.ts index a8bf3d75..b0759424 100644 --- a/src/memory/hook.ts +++ b/src/memory/hook.ts @@ -244,19 +244,46 @@ export function maybeStartMidSessionIndex(): boolean { try { if (!dueForMidSessionIndex()) return false; markMidSessionIndexed(); // stamp first → debounce holds even if the spawn races - const entry = process.argv[1]; - if (!entry) return false; - const child = spawn(process.execPath, [resolve(entry), "memory", "index"], { - detached: true, - stdio: "ignore", - }); - child.unref(); - return true; + return spawnDetachedIndex(); } catch { return false; // fail-open: never block a prompt } } +/** + * Launch a DETACHED `kit memory index` (fire-and-forget, stdio ignored, unref'd) + * and return immediately — the caller never waits on the index. Shared by the + * mid-session debounce and the SessionEnd hook. Returns true iff it launched. + */ +function spawnDetachedIndex(): boolean { + const entry = process.argv[1]; + if (!entry) return false; + const child = spawn(process.execPath, [resolve(entry), "memory", "index"], { + detached: true, + stdio: "ignore", + }); + child.unref(); + return true; +} + +/** + * SessionEnd indexing for the common path (no `push_on_end`): run the index in a + * DETACHED child so the hook returns instantly. Indexing inline lets a periodic + * all-harness sweep overrun Claude Code's shutdown window, which surfaces as + * "SessionEnd hook … failed: Hook cancelled". The detached index still completes; + * and the next SessionStart recovery re-indexes any tail it missed. Fail-open. + * + * NOTE: callers that push on end (ephemeral containers) must NOT use this — the + * push has to observe this session's freshly-indexed rows, so it indexes inline. + */ +export function startDetachedSessionEndIndex(): boolean { + try { + return spawnDetachedIndex(); + } catch { + return false; // fail-open: a session must never be blocked on exit + } +} + /** Index the just-ended session. Returns count of newly indexed messages (fail-open). */ export function runSessionEndIndex(): { messages: number } { try { diff --git a/src/memory/remote-sync.test.ts b/src/memory/remote-sync.test.ts index 1d67acb6..2455cb6e 100644 --- a/src/memory/remote-sync.test.ts +++ b/src/memory/remote-sync.test.ts @@ -14,6 +14,7 @@ import { initSyncConfig, tryAutoPull, tryAutoPush, + isAutoPushConfigured, maybeSyncNudge, type SyncConfig, } from "./remote-sync.js"; @@ -104,6 +105,42 @@ describe("remote-sync — loadSyncConfig (LOCAL, ~/.kit only)", () => { }); }); +describe("remote-sync — isAutoPushConfigured (SessionEnd inline-vs-detached gate)", () => { + const withCfg = (toml: string | null, fn: () => void) => { + const dir = mkdtempSync(join(tmpdir(), "kit-autopush-")); + const prev = process.env.KIT_MEMORY_DIR; + process.env.KIT_MEMORY_DIR = dir; + try { + if (toml !== null) writeFileSync(getSyncConfigPath(), toml); + fn(); + } finally { + if (prev === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + } + }; + + it("false when unconfigured, or configured without push_on_end", () => { + withCfg(null, () => assert.equal(isAutoPushConfigured(), false)); + withCfg('[memory.sync]\nremote = "git@h:me/mem.git"\n', () => + assert.equal(isAutoPushConfigured(), false), + ); + }); + + it("true only when push_on_end = true", () => { + withCfg('[memory.sync]\nremote = "git@h:me/mem.git"\npush_on_end = true\n', () => + assert.equal(isAutoPushConfigured(), true), + ); + }); + + it("fail-safe false on a malformed config (never forces an inline push)", () => { + // a remote starting with '-' throws in loadSyncConfig → isAutoPushConfigured swallows it + withCfg('[memory.sync]\nremote = "--upload-pack=x"\npush_on_end = true\n', () => + assert.equal(isAutoPushConfigured(), false), + ); + }); +}); + describe("remote-sync — assertRemoteNotProjectOrigin (anti-exfil guard)", () => { it("throws when the sync remote IS the project's origin", () => { const proj = mkdtempSync(join(tmpdir(), "kit-proj-")); diff --git a/src/memory/remote-sync.ts b/src/memory/remote-sync.ts index 876b07fc..92cd0437 100644 --- a/src/memory/remote-sync.ts +++ b/src/memory/remote-sync.ts @@ -399,6 +399,20 @@ export function tryAutoPull(projectRoot: string): AutoSyncResult { } } +/** + * True iff `[memory.sync] push_on_end = true`. Cheap, fail-safe (false on any + * error). The SessionEnd hook uses this to decide whether the index must run + * inline — so the push includes this session — or can be detached for a fast, + * never-cancelled exit on the common (no-push) path. + */ +export function isAutoPushConfigured(): boolean { + try { + return loadSyncConfig()?.pushOnEnd === true; + } catch { + return false; + } +} + /** * Index-and-push at session end when `[memory.sync] push_on_end = true`. The key * piece for EPHEMERAL containers: the session's memory reaches your durable store