Skip to content

Commit 910d843

Browse files
zlareb1claude
andcommitted
SessionEnd closes a re-asked run with its recalled keys and returns with stdin left open
loom-run read the recalled-key stash after the run.begin it asks again at SessionEnd. loom-session-memory runs beside it and removes the stash, so that run closed without recalled_keys. The stash is now read before any request is awaited. The SessionEnd launcher left stdin open after reading the payload. A host that never closes it held the process through the exit grace, three to eight seconds after the records were sent. The launcher now closes its end once the payload is read. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: Lareb Zafar <lareb.zafar@clickhouse.com>
1 parent f5a535b commit 910d843

6 files changed

Lines changed: 73 additions & 16 deletions

File tree

‎integrations/claude-code-plugin/hooks/loom-record.mjs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs";
3636

3737
/** The scripts each event records with, in the order they start. At
3838
* SessionEnd loom-run reads the recalled-key stash before
39-
* loom-session-memory removes it when its run is begun; a run whose begin
40-
* it has to ask again waits for that answer first and can close without
41-
* the keys. */
39+
* loom-session-memory removes it. */
4240
export const RECORDERS = {
4341
PostToolUse: ["loom-capture"],
4442
PostToolUseFailure: ["loom-capture"],
@@ -55,7 +53,12 @@ function run(event, raw) {
5553

5654
async function hook(script, event, client) {
5755
const raw = await readStdinText();
58-
if (event === "SessionEnd") return run(event, raw);
56+
if (event === "SessionEnd") {
57+
// Left open, a stdin its host never closes would hold this process
58+
// through the exit grace after the records are sent.
59+
process.stdin.destroy();
60+
return run(event, raw);
61+
}
5962
// An agent's token is left to the copy: renewing one is a request.
6063
if (agentMode() || resolveToken()) {
6164
spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` });

‎integrations/claude-code-plugin/hooks/loom-run.mjs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ async function main() {
9292
}
9393

9494
if (event === "SessionEnd") {
95+
// Read before a request is awaited: loom-session-memory, which runs
96+
// beside this script, removes the stash.
97+
const recalled = readRecalledStash(sessionId);
9598
let state = readRunState(sessionId);
9699
let completeOpts = opts;
97100
let deadline;
@@ -118,7 +121,6 @@ async function main() {
118121
// past its own request is reported as cancelled even after the row
119122
// landed. loom-record runs this script beside others in one process,
120123
// where scheduleExit leaves the exit to it.
121-
const recalled = readRecalledStash(sessionId);
122124
const body = completeBody(scope, payload, finalText, process.env, recalled);
123125
// No longer begun, so a resumed session's next prompt opens a new run. The
124126
// id stays for the other SessionEnd hooks, which run beside this one; the

‎integrations/claude-code-plugin/tests/record-hook.test.mjs‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -141,16 +141,19 @@ function payload(event, box) {
141141
});
142142
}
143143

144-
/** Run the launcher with `args`; resolves {code, stdout, stderr} when it exits. */
145-
function runLauncher(args, hookEnv, stdin = "") {
144+
/** Run the launcher with `args`; resolves {code, stdout, stderr} when it
145+
* exits. `leaveOpen` is a host that writes the payload and never closes
146+
* the hook's stdin. */
147+
function runLauncher(args, hookEnv, stdin = "", { leaveOpen = false } = {}) {
146148
return new Promise((resolve) => {
147149
const child = spawn(process.execPath, [HOOK, ...args], { env: hookEnv, cwd: os.tmpdir() });
148150
let stdout = "";
149151
let stderr = "";
150152
child.stdout.on("data", (c) => (stdout += c));
151153
child.stderr.on("data", (c) => (stderr += c));
152154
child.on("close", (code) => resolve({ code, stdout, stderr }));
153-
child.stdin.end(stdin);
155+
if (leaveOpen) child.stdin.write(stdin);
156+
else child.stdin.end(stdin);
154157
});
155158
}
156159

@@ -271,6 +274,27 @@ test("the SessionEnd hook returns with its records sent, and the run's close doe
271274
}
272275
});
273276

277+
test("the SessionEnd hook does not wait on a stdin its host leaves open", async () => {
278+
const box = sandbox();
279+
const loom = await heldLoom();
280+
loom.release();
281+
try {
282+
withTmpdir(box.tmp, () => writeRunBegun(SESSION, `cc-${SESSION}`));
283+
// An exit grace no test waits out: the hook returns when its records are sent.
284+
const hookEnv = env(box, loom.url, { LOOM_HOOK_EXIT_MS: "60000" });
285+
const started = Date.now();
286+
const r = await runLauncher(["SessionEnd"], hookEnv, payload("SessionEnd", box), { leaveOpen: true });
287+
const waited = Date.now() - started;
288+
assert.deepEqual(r, { code: 0, stdout: "", stderr: "" });
289+
assert.ok(loom.ops.includes("run.complete"), `run.complete not sent; seen: ${loom.ops.join(", ")}`);
290+
// The launcher's own bound ends a process that stdin holds open at 16 s.
291+
assert.ok(waited < 10000, `the hook returned after ${waited} ms`);
292+
} finally {
293+
await loom.close();
294+
await removeSandbox(box);
295+
}
296+
});
297+
274298
test("scripts that share the launcher's process look the checkout up once", {
275299
skip: process.platform === "win32",
276300
}, async () => {

‎integrations/claude-code-plugin/tests/run-id-stash.test.mjs‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,14 @@ import os from "node:os";
1010
import path from "node:path";
1111
import { fileURLToPath, pathToFileURL } from "node:url";
1212

13-
import { completeBody, readRunState, sessionRunId, writeRunBegun } from "../lib/run-hook.mjs";
13+
import {
14+
appendRecalledStash,
15+
completeBody,
16+
readRunState,
17+
recalledStashPath,
18+
sessionRunId,
19+
writeRunBegun,
20+
} from "../lib/run-hook.mjs";
1421
import { STALE_STATE_MS, sessionStatePath, sweepStaleStateFiles, writeJsonFile } from "../lib/tmp-state.mjs";
1522
import { recallBody } from "../lib/prompt-recall.mjs";
1623
import { sessionMemoryBody } from "../lib/session-memory.mjs";
@@ -34,9 +41,10 @@ function runHook(event, payload, { tmp, url }) {
3441
});
3542
}
3643

37-
// A fake server: run.begin answers `beginRunId` after `delayMs`; every request is recorded.
44+
// A fake server: run.begin answers `beginRunId` after `delayMs`, calling
45+
// `onBegin` when it arrives; every request is recorded.
3846
async function withServer(
39-
{ beginRunId, delayMs = 0, beginStatus = 200, firstBeginDelayMs = 0, completeDelayMs = 0 },
47+
{ beginRunId, delayMs = 0, beginStatus = 200, firstBeginDelayMs = 0, completeDelayMs = 0, onBegin },
4048
fn,
4149
) {
4250
let begins = 0;
@@ -52,6 +60,7 @@ async function withServer(
5260
res.on("close", () => {
5361
entry.closedAt = Date.now();
5462
});
63+
if (onBegin && req.url.endsWith("/run.begin")) onBegin();
5564
const answer = req.url.endsWith("/run.begin") ? { run_id: beginRunId } : {};
5665
const first = req.url.endsWith("/run.begin") && begins++ === 0;
5766
setTimeout(
@@ -218,6 +227,20 @@ test("a re-sent begin and the close fit Codex's one-second SessionEnd budget", a
218227
});
219228
});
220229

230+
test("a run whose begin is asked again at SessionEnd closes with the keys the session was served", async () => {
231+
const tmp = freshTmp();
232+
withTmpdir(tmp, () => writeJsonFile(sessionStatePath("run", "s12"), { attempted: true, at: Date.now() }));
233+
appendRecalledStash("s12", ["team/rule/lock-order"], tmp);
234+
// loom-session-memory runs beside this hook and removes the stash while the begin is awaited.
235+
const onBegin = () => fs.rmSync(recalledStashPath("s12", tmp));
236+
await withServer({ beginRunId: "r5ess1on", onBegin }, async (url, seen) => {
237+
await runHook("SessionEnd", { session_id: "s12", cwd: tmp, reason: "exit" }, { tmp, url });
238+
const close = seen.find((r) => r.url.endsWith("/run.complete"));
239+
assert.ok(close, "the close was sent");
240+
assert.deepEqual(close.body.recalled_keys, ["team/rule/lock-order"]);
241+
});
242+
});
243+
221244
test("close admission deducts preparation from the shared deadline", async (t) => {
222245
for (const preparationMs of [0, 650, 750]) {
223246
await t.test(`preparation ${preparationMs} ms`, async () => {

‎integrations/codex-plugin/hooks/loom-record.mjs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,7 @@ import { readPrivateFile, removeFile } from "../lib/tmp-state.mjs";
3636

3737
/** The scripts each event records with, in the order they start. At
3838
* SessionEnd loom-run reads the recalled-key stash before
39-
* loom-session-memory removes it when its run is begun; a run whose begin
40-
* it has to ask again waits for that answer first and can close without
41-
* the keys. */
39+
* loom-session-memory removes it. */
4240
export const RECORDERS = {
4341
PostToolUse: ["loom-capture"],
4442
PostToolUseFailure: ["loom-capture"],
@@ -55,7 +53,12 @@ function run(event, raw) {
5553

5654
async function hook(script, event, client) {
5755
const raw = await readStdinText();
58-
if (event === "SessionEnd") return run(event, raw);
56+
if (event === "SessionEnd") {
57+
// Left open, a stdin its host never closes would hold this process
58+
// through the exit grace after the records are sent.
59+
process.stdin.destroy();
60+
return run(event, raw);
61+
}
5962
// An agent's token is left to the copy: renewing one is a request.
6063
if (agentMode() || resolveToken()) {
6164
spawnDetached([script, event, client || "-"], raw, { kind: `record-${event}` });

‎integrations/codex-plugin/hooks/loom-run.mjs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ async function main() {
9292
}
9393

9494
if (event === "SessionEnd") {
95+
// Read before a request is awaited: loom-session-memory, which runs
96+
// beside this script, removes the stash.
97+
const recalled = readRecalledStash(sessionId);
9598
let state = readRunState(sessionId);
9699
let completeOpts = opts;
97100
let deadline;
@@ -118,7 +121,6 @@ async function main() {
118121
// past its own request is reported as cancelled even after the row
119122
// landed. loom-record runs this script beside others in one process,
120123
// where scheduleExit leaves the exit to it.
121-
const recalled = readRecalledStash(sessionId);
122124
const body = completeBody(scope, payload, finalText, process.env, recalled);
123125
// No longer begun, so a resumed session's next prompt opens a new run. The
124126
// id stays for the other SessionEnd hooks, which run beside this one; the

0 commit comments

Comments
 (0)