Skip to content
Closed
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
20 changes: 15 additions & 5 deletions src/commands/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
initSyncConfig,
tryAutoPull,
tryAutoPush,
isAutoPushConfigured,
maybeSyncNudge,
type SyncTransport,
} from "../memory/remote-sync.js";
Expand All @@ -48,6 +49,7 @@ import {
userPromptSubmitReminder,
maybeStartMidSessionIndex,
runSessionEndIndex,
startDetachedSessionEndIndex,
sessionStartRecovery,
} from "../memory/hook.js";
import { decisionsForPaths, changedPaths } from "../memory/clusters.js";
Expand Down Expand Up @@ -683,11 +685,19 @@ async function memHook(): Promise<boolean> {
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") {
Expand Down
43 changes: 35 additions & 8 deletions src/memory/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
37 changes: 37 additions & 0 deletions src/memory/remote-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
initSyncConfig,
tryAutoPull,
tryAutoPush,
isAutoPushConfigured,
maybeSyncNudge,
type SyncConfig,
} from "./remote-sync.js";
Expand Down Expand Up @@ -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-"));
Expand Down
14 changes: 14 additions & 0 deletions src/memory/remote-sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down