mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 00:05:27 +00:00
fix(continuous-learning): flush Stop JSON before exit so the nudge is not truncated
The Stop nudge JSON was written with console.log and main() called process.exit(0) immediately after. When stdout is a pipe the write is asynchronous, so the exit can truncate the payload and the model never sees the nudge. deliverStopNudge now returns whether it delivered, and writes the JSON with process.stdout.write and exits from the flush callback; main() exits immediately only when nothing was delivered. Test: new case in tests/hooks/evaluate-session.test.js forces every stdout write to be asynchronous with a preload, so the race reproduces deterministically. It fails on the old code (empty stdout) and passes with this fix. Full evaluate-session suite: 26/26 pass.
This commit is contained in:
1 parent
f6357e73ee
commit
f64a9b5d04
2 files changed
+81
-13
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user