diff --git a/scripts/hooks/evaluate-session.js b/scripts/hooks/evaluate-session.js index ce41f0f3a..bbb2f7252 100644 --- a/scripts/hooks/evaluate-session.js +++ b/scripts/hooks/evaluate-session.js @@ -20,8 +20,7 @@ const { readFile, countInFile, getTempDir, - log, - output + log } = require('../lib/utils'); const { resolveHookSessionId } = require('../lib/hook-session'); const { @@ -121,9 +120,12 @@ async function main() { log(`[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns`); log(`[ContinuousLearning] Save learned skills to: ${learnedSkillsPath}`); - deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn }); - - process.exit(0); + // When a nudge was delivered, the process exits from the stdout-write + // callback, only after the Stop JSON has flushed. Exiting here instead + // would race the flush and could truncate the payload. + if (!deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn })) { + process.exit(0); + } } /** @@ -133,35 +135,38 @@ async function main() { * decision "block" + reason, which continues the turn with the reason as * context. Plain stdout text is not a delivery channel on Stop, so nothing * else is ever written to stdout here. Every gate fails closed. + * + * Returns true when the Stop JSON was written (the process then exits from + * the write callback, once the payload has flushed), false otherwise. */ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn }) { if (!stopNudgeOptIn) { log('[ContinuousLearning] Stop nudge opt-in is off, skipping delivery'); - return; + return false; } // A payload that names a different event means this script is running // under the wrong registration; an absent field is tolerated (older // harnesses omit it), a mismatched one is not. if (input && input.hook_event_name && input.hook_event_name !== 'Stop') { log(`[ContinuousLearning] Skipping delivery: hook event is ${input.hook_event_name}, not Stop`); - return; + return false; } // Stop-loop protection: when a previous Stop already continued this stop, // the hook is re-firing and must pass through, never block again. if (input && input.stop_hook_active === true) { log('[ContinuousLearning] Skipping delivery: Stop hook already fired for this stop'); - return; + return false; } // The payload session id identifies the harness conversation; env ids are // only fallbacks, never preferred over it. const sessionId = resolveSessionId(resolveHookSessionId(stdinData)); if (!sessionId) { log('[ContinuousLearning] Skipping delivery: no session id available'); - return; + return false; } if (!hasRegisteredSessionLease(input, sessionId)) { log('[ContinuousLearning] Skipping delivery: no SessionStart lease for this session'); - return; + return false; } // The session id is sanitized upstream by resolveSessionId, so the // marker filename cannot traverse out of the temp dir. @@ -181,12 +186,16 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s } else { log(`[ContinuousLearning] Warning: could not record delivery marker, skipping delivery: ${err.message}`); } - return; + return false; } - output({ + // Write the Stop JSON with a flush callback and exit from it: a plain + // console.log followed by process.exit(0) can truncate the payload when + // stdout is a pipe, because the write is asynchronous. + process.stdout.write(`${JSON.stringify({ decision: 'block', reason: `[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns. Save learned skills to: ${learnedSkillsPath}` - }); + })}\n`, () => process.exit(0)); + return true; } /** diff --git a/tests/hooks/evaluate-session.test.js b/tests/hooks/evaluate-session.test.js index b7cb86ccd..c8d27e13e 100644 --- a/tests/hooks/evaluate-session.test.js +++ b/tests/hooks/evaluate-session.test.js @@ -579,6 +579,65 @@ function runTests() { } })) passed++; else failed++; + if (test('delivers the full Stop JSON even when stdout writes are asynchronous', () => { + // Regression: the Stop JSON was written with console.log and main() + // called process.exit(0) immediately after, so when stdout is a pipe + // the write is asynchronous and the exit can truncate the payload + // (Node documents this process.exit truncation for piped stdout). + // Force every stdout write to be asynchronous with a preload, so the + // race reproduces deterministically instead of relying on pipe timing. + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-flush-1'; + const marker = deliveryMarkerPath(sessionId); + const preloadPath = path.join(testDir, 'async-stdout-preload.js'); + fs.writeFileSync(preloadPath, [ + '// Test-only preload: defer every stdout write to the next macrotask,', + '// so a process.exit(0) before the flush drops the data.', + 'const origWrite = process.stdout.write.bind(process.stdout);', + 'process.stdout.write = function (chunk, encoding, cb) {', + ' if (typeof encoding === \'function\') { cb = encoding; encoding = undefined; }', + ' setImmediate(() => origWrite(chunk, encoding, cb));', + ' return true;', + '};', + '', + ].join('\n')); + try { + fs.rmSync(marker, { force: true }); + registerLeaseFor(testDir, homunculusDir, sessionId); + const result = withOptInConfig(true, () => { + const spawned = spawnSync('node', ['-r', preloadPath, evaluateScript], { + encoding: 'utf8', + input: JSON.stringify(stopPayload(transcript, sessionId, testDir)), + timeout: 10000, + env: isolatedEnv({ CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir }), + }); + return { + code: spawned.error || spawned.signal ? null : spawned.status, + stdout: spawned.stdout || '', + stderr: spawned.stderr || '', + }; + }); + assert.strictEqual(result.code, 0); + let parsed; + try { + parsed = JSON.parse(result.stdout); + } catch { + assert.fail(`Stdout must arrive complete even with async stdout writes. Got: ${result.stdout}`); + } + assert.strictEqual(parsed.decision, 'block', 'Native Stop delivery blocks the stop'); + assert.ok( + typeof parsed.reason === 'string' && parsed.reason.includes('12 messages'), + `Reason must carry the session signal. Got: ${parsed.reason}` + ); + } finally { + fs.rmSync(marker, { force: true }); + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + if (test('skips delivery when the delivery marker cannot be written', () => { const testDir = createTestDir(); const transcript = createTranscript(testDir, 12);