Skip to content
Merged
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
10 changes: 10 additions & 0 deletions src/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
import {
userPromptSubmitReminder,
maybeStartMidSessionIndex,
startDetachedSessionEnd,
runSessionEndIndex,
sessionStartRecovery,
} from "../memory/hook.js";
Expand Down Expand Up @@ -683,6 +684,15 @@ async function memHook(): Promise<boolean> {
return true;
}
if (event === "session-end") {
// Return instantly: a SessionEnd hook that blocks on the index (or the
// opt-in network push) gets cancelled by Claude Code on exit ("Hook
// cancelled"). The real work runs in a detached worker below.
startDetachedSessionEnd();
return true;
}
if (event === "session-end-run") {
// Internal: the detached SessionEnd worker. No hook is waiting on it, so the
// (potentially slow / networked) capture can run synchronously here.
runSessionEndIndex();
// Opt-in: push this session's memory to your durable store before an
// (ephemeral) container is reclaimed. Fail-soft; notes go to stderr.
Expand Down
39 changes: 39 additions & 0 deletions src/memory/hook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
recentDecisions,
dueForHarnessSweep,
dueForMidSessionIndex,
startDetachedSessionEnd,
} from "./hook.js";
import { getCurrentProjectRoot } from "./project.js";
import { shareEntry } from "./shared.js";
Expand Down Expand Up @@ -227,3 +228,41 @@ describe("memory hook — mid-session index debounce", () => {
assert.equal(dueForMidSessionIndex(mtime + 11 * 60 * 1000), true, "11 min later → due");
});
});

describe("memory hook — detached SessionEnd", () => {
let tmp: string;
const prevDir = process.env.KIT_MEMORY_DIR;
const prevDb = process.env.KIT_MEMORY_DB;

before(() => {
tmp = mkdtempSync(join(tmpdir(), "kit-sessionend-"));
process.env.KIT_MEMORY_DIR = tmp;
process.env.KIT_MEMORY_DB = join(tmp, "memory.db");
});

after(() => {
if (prevDir === undefined) delete process.env.KIT_MEMORY_DIR;
else process.env.KIT_MEMORY_DIR = prevDir;
if (prevDb === undefined) delete process.env.KIT_MEMORY_DB;
else process.env.KIT_MEMORY_DB = prevDb;
rmSync(tmp, { recursive: true, force: true });
});

// The happy path spawns a detached child, which is environment-dependent and
// would fork the test runner; we assert the fail-safe branch instead: with no
// re-exec entry path, it must index inline rather than throw, and report that
// it did NOT detach. A SessionEnd hook must never throw.
it("falls back to an inline index (no throw) when there is no entry to re-exec", () => {
const prevEntry = process.argv[1];
try {
process.argv[1] = "";
let detached: boolean | undefined;
assert.doesNotThrow(() => {
detached = startDetachedSessionEnd();
});
assert.equal(detached, false, "no entry path → did not detach, ran inline");
} finally {
process.argv[1] = prevEntry;
}
});
});
35 changes: 35 additions & 0 deletions src/memory/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,41 @@ export function maybeStartMidSessionIndex(): boolean {
}
}

/**
* Run the SessionEnd capture in a DETACHED background process so the exit hook
* returns instantly. The foreground SessionEnd hook is on a short leash — Claude
* Code cancels it if it doesn't finish promptly ("Hook cancelled") — but the
* capture can be slow (the periodic all-harness sweep) or do network I/O (the
* opt-in memory push). So, exactly like {@link maybeStartMidSessionIndex}, we
* fire-and-forget a `kit memory hook session-end-run` worker (stdio ignored,
* unref'd) that does the real work where blocking is harmless. Returns true iff
* it launched the worker; on failure it falls back to an inline index so a
* session is never lost. The just-ended transcript is already on disk, so the
* detached worker captures it the same as a synchronous run would.
*/
export function startDetachedSessionEnd(): boolean {
try {
const entry = process.argv[1];
if (!entry) {
runSessionEndIndex(); // no entry path to re-exec → at least index inline
return false;
}
const child = spawn(process.execPath, [resolve(entry), "memory", "hook", "session-end-run"], {
detached: true,
stdio: "ignore",
});
child.unref();
return true;
} catch {
try {
runSessionEndIndex(); // fail-safe: capture inline rather than not at all
} catch {
/* fail-open: a SessionEnd hook must never throw */
}
return false;
}
}

/** Index the just-ended session. Returns count of newly indexed messages (fail-open). */
export function runSessionEndIndex(): { messages: number } {
try {
Expand Down
Loading