diff --git a/hooks/hooks.json b/hooks/hooks.json index 80c38a360..791a910c6 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -240,7 +240,6 @@ { "type": "command", "command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=(process.env.CLAUDE_CONFIG_DIR||'').trim()||p.join(o.homedir(),'.claude');if(d==='~')d=o.homedir();else if(d.charAt(0)==='~'&&(d.charAt(1)==='/'||d.charCodeAt(1)===92))d=p.join(o.homedir(),d.slice(2));try{if(o.platform()==='linux'){var v=f.readFileSync('/proc/version','utf8').toLowerCase();if(v.includes('microsoft')){var b=String.fromCharCode(92),m=d.match(/^([A-Za-z]):/);if(m&&(d.charAt(2)==='/'||d.charAt(2)===b)){var dl=m[1].toLowerCase();d='/mnt/'+dl+d.slice(2).split(b).join('/')}}}}catch(_){}d=p.resolve(d);function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i { }); async function main() { - // Parse stdin JSON to get transcript_path + // Parse stdin JSON once; the parsed payload is reused by the delivery + // gates below (event name, stop_hook_active, cwd). + let input = null; let transcriptPath = null; try { - const input = JSON.parse(stdinData); + input = JSON.parse(stdinData); transcriptPath = input.transcript_path; } catch { // Fallback: try env var for backwards compatibility @@ -59,6 +76,10 @@ async function main() { // Default configuration let minSessionLength = 10; let learnedSkillsPath = getLearnedSkillsDir(); + // Delivery to the model is explicitly opt-in and off by default: a Stop + // hook that blocks the stop is user-visible behavior, so it must never + // turn on silently. + let stopNudgeOptIn = false; // Load config if exists const configContent = readFile(configFile); @@ -66,6 +87,7 @@ async function main() { try { const config = JSON.parse(configContent); minSessionLength = config.min_session_length ?? 10; + stopNudgeOptIn = config.stop_nudge_opt_in === true; if (config.learned_skills_path) { // Handle ~ in path @@ -92,9 +114,98 @@ async function main() { process.exit(0); } - // Signal to Claude that session should be evaluated for extractable patterns + // Signal to Claude that session should be evaluated for extractable patterns. + // The log lines below go to stderr (the debug log) only. Whether the + // model ever sees the signal is decided by deliverStopNudge, which fails + // closed: any gate miss means stderr only, exit 0, no stdout. 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); } + +/** + * Deliver the evaluation signal to the model, or deliver nothing. + * + * A Stop hook reaches the model only through the native Stop contract: + * 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. + */ +function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, stopNudgeOptIn }) { + if (!stopNudgeOptIn) { + log('[ContinuousLearning] Stop nudge opt-in is off, skipping delivery'); + return; + } + // 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; + } + // 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; + } + // 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; + } + if (!hasRegisteredSessionLease(input, sessionId)) { + log('[ContinuousLearning] Skipping delivery: no SessionStart lease for this session'); + return; + } + // The session id is sanitized upstream by resolveSessionId, so the + // marker filename cannot traverse out of the temp dir. + const markerFile = path.join(getTempDir(), `${DELIVERY_MARKER_PREFIX}${sessionId}`); + // Claim the marker atomically: 'wx' fails when a nudge was already + // delivered (EEXIST) and closes the check-then-create gap. Any other + // write failure fails closed: without a marker, a later Stop would stay + // eligible, so skipping delivery is the only shape that keeps the + // once-per-session promise. stop_hook_active bounds only the re-fired + // Stop for one turn, not later turns, so it cannot stand in for the + // marker. + try { + fs.writeFileSync(markerFile, `${new Date().toISOString()}\n`, { flag: 'wx' }); + } catch (err) { + if (err.code === 'EEXIST') { + log('[ContinuousLearning] Stop nudge already delivered for this session, skipping'); + } else { + log(`[ContinuousLearning] Warning: could not record delivery marker, skipping delivery: ${err.message}`); + } + return; + } + output({ + decision: 'block', + reason: `[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns. Save learned skills to: ${learnedSkillsPath}` + }); +} + +/** + * The registered-native-lifecycle check: the session must hold a lease + * written by SessionStart under the ECC project context (including alias + * contexts for roots that moved mid-session). A Stop payload for a session + * that never went through SessionStart is not a registered ECC session, + * and its nudge must not reach the model. + */ +function hasRegisteredSessionLease(input, sessionId) { + try { + const cwd = (input && typeof input.cwd === 'string' && input.cwd) || process.cwd(); + const context = resolveProjectContext(cwd); + const contexts = [context, ...getAliasContexts(context)]; + return contexts.some(ctx => + listSessionLeases(ctx).some(file => path.basename(file) === `${sessionId}.json`) + ); + } catch (err) { + log(`[ContinuousLearning] Session lease check failed: ${err.message}`); + return false; + } +} diff --git a/skills/continuous-learning/SKILL.md b/skills/continuous-learning/SKILL.md index 9fe24a46e..5447f78a0 100644 --- a/skills/continuous-learning/SKILL.md +++ b/skills/continuous-learning/SKILL.md @@ -90,9 +90,41 @@ Add to your `~/.claude/settings.json`: } ``` +The shell entry above only counts messages and logs to stderr; it never +delivers a nudge to the model and does not read `stop_nudge_opt_in`. +Delivery requires the JavaScript evaluator +(`scripts/hooks/evaluate-session.js`) registered through the plugin +hooks, which also registers the SessionStart hook that writes the lease +delivery depends on. + +## Stop Delivery (opt-in) + +By default the Stop hook only logs to stderr (the debug log); the model +never sees the signal. To actually deliver it, set +`"stop_nudge_opt_in": true` in `config.json`. Delivery then works through +the native Stop contract (`decision: "block"` + `reason`) and only when +every gate passes: + +- the session reached the message threshold; +- the session holds a lease written by SessionStart (the registered + native lifecycle check: unregistered sessions never deliver); +- this is a first Stop, not a re-fired one (`stop_hook_active` passes + through untouched, so the hook cannot loop); +- no nudge was already delivered for this session (once per session); +- the delivery marker was recorded: if the marker cannot be written, + delivery is skipped rather than sent without once-per-session + protection; +- the hook is registered synchronously: an async Stop registration cannot + block, so the delivery entry must not carry `"async": true`. + +Stop fires whenever Claude finishes responding, not only when the session +closes. Blocking the first eligible Stop gives the model one extra turn +to extract patterns and save them; later Stops in the same session pass +through without ending the session by themselves. + ## Why Stop Hook? -- **Lightweight**: Runs once at session end +- **Lightweight**: Runs when Claude finishes responding - **Non-blocking**: Doesn't add latency to every message - **Complete context**: Has access to full session transcript diff --git a/skills/continuous-learning/config.json b/skills/continuous-learning/config.json index 1094b7e24..3c99c79e2 100644 --- a/skills/continuous-learning/config.json +++ b/skills/continuous-learning/config.json @@ -1,5 +1,6 @@ { "min_session_length": 10, + "stop_nudge_opt_in": false, "extraction_threshold": "medium", "auto_approve": false, "learned_skills_path": "~/.claude/skills/learned/", diff --git a/tests/hooks/evaluate-session.test.js b/tests/hooks/evaluate-session.test.js index 45a69c0b8..b7cb86ccd 100644 --- a/tests/hooks/evaluate-session.test.js +++ b/tests/hooks/evaluate-session.test.js @@ -65,7 +65,8 @@ function createTranscript(dir, messageCount) { /** * Run evaluate-session.js with stdin providing the transcript_path. * Uses spawnSync to capture both stdout and stderr regardless of exit code. - * Returns { code, stdout, stderr }. + * Returns { code, stdout, stderr }; code is null when the child did not + * exit normally (spawn failure, signal, timeout), never coerced to 0. */ function runEvaluate(stdinJson) { const result = spawnSync('node', [evaluateScript], { @@ -75,7 +76,7 @@ function runEvaluate(stdinJson) { env: isolatedEnv(), }); return { - code: result.status || 0, + code: result.error || result.signal ? null : result.status, stdout: result.stdout || '', stderr: result.stderr || '', }; @@ -424,6 +425,279 @@ function runTests() { } })) passed++; else failed++; + // ── Stop delivery contract: opt-in + registered lease + loop protection ── + // The bug: the script logged its signal to stderr only, so the model never + // saw it. Delivery must emit exactly one valid Stop JSON payload, and only + // when every gate passes: explicit opt-in, a session lease registered + // through the native SessionStart lifecycle, a first (not re-fired) Stop, + // and no earlier delivery for this session. + console.log('\nStop delivery contract (opt-in + lease + loop protection):'); + + const observerSessions = require(path.join(__dirname, '..', '..', 'scripts', 'lib', 'observer-sessions')); + const deliveryConfigPath = path.join(__dirname, '..', '..', 'skills', 'continuous-learning', 'config.json'); + + // Test session ids below are already sanitized-safe (lowercase, digits, + // hyphens), so the delivery marker filename is a plain concatenation. + function deliveryMarkerPath(sessionId) { + return path.join(os.tmpdir(), `claude-continuous-learning-delivered-${sessionId}`); + } + + function runEvaluatePayload(payload, extraEnv = {}, dropKeys = []) { + const env = isolatedEnv(extraEnv); + for (const key of dropKeys) delete env[key]; + const result = spawnSync('node', [evaluateScript], { + encoding: 'utf8', + input: JSON.stringify(payload), + timeout: 10000, + env, + }); + // A spawn failure, signal, or timeout must never read as success. + return { + code: result.error || result.signal ? null : result.status, + stdout: result.stdout || '', + stderr: result.stderr || '', + }; + } + + function withOptInConfig(value, fn) { + let originalContent = null; + try { + originalContent = fs.readFileSync(deliveryConfigPath, 'utf8'); + } catch { + // Config file may not exist + } + try { + const config = originalContent ? JSON.parse(originalContent) : {}; + config.stop_nudge_opt_in = value; + fs.writeFileSync(deliveryConfigPath, JSON.stringify(config, null, 2)); + return fn(); + } finally { + if (originalContent !== null) { + fs.writeFileSync(deliveryConfigPath, originalContent, 'utf8'); + } else { + try { fs.unlinkSync(deliveryConfigPath); } catch { /* best-effort */ } + } + } + } + + // Register a SessionStart lease for this session using the repo's own + // helpers, so the child process finds exactly what SessionStart writes. + function registerLeaseFor(workDir, homunculusDir, sessionId) { + const prevHomunculus = process.env.CLV2_HOMUNCULUS_DIR; + const prevProjectDir = process.env.CLAUDE_PROJECT_DIR; + process.env.CLV2_HOMUNCULUS_DIR = homunculusDir; + process.env.CLAUDE_PROJECT_DIR = workDir; + try { + const context = observerSessions.resolveProjectContext(workDir); + return observerSessions.writeSessionLease(context, sessionId, { hook: 'SessionStart' }); + } finally { + if (prevHomunculus === undefined) delete process.env.CLV2_HOMUNCULUS_DIR; + else process.env.CLV2_HOMUNCULUS_DIR = prevHomunculus; + if (prevProjectDir === undefined) delete process.env.CLAUDE_PROJECT_DIR; + else process.env.CLAUDE_PROJECT_DIR = prevProjectDir; + } + } + + function stopPayload(transcript, sessionId, workDir, overrides = {}) { + return { + session_id: sessionId, + transcript_path: transcript, + cwd: workDir, + hook_event_name: 'Stop', + stop_hook_active: false, + ...overrides, + }; + } + + if (test('emits no stdout when opt-in is off, even for a long session', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + try { + const result = runEvaluatePayload(stopPayload(transcript, 'delivery-optoff-1', testDir)); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'Model must receive nothing when opt-in is off'); + assert.ok(result.stderr.includes('evaluate'), 'Stderr log line is unchanged'); + } finally { + cleanupTestDir(testDir); + } + })) passed++; else failed++; + + if (test('emits no stdout when opt-in is on but no session lease is registered', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + try { + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, 'delivery-nolease-1', testDir), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir } + )); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'Unregistered sessions must not reach the model'); + } finally { + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + + if (test('emits one valid Stop block JSON with opt-in + lease, then nothing on repeat', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-ok-1'; + const marker = deliveryMarkerPath(sessionId); + try { + fs.rmSync(marker, { force: true }); + registerLeaseFor(testDir, homunculusDir, sessionId); + const env = { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir }; + const first = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir), env + )); + assert.strictEqual(first.code, 0); + let parsed; + try { + parsed = JSON.parse(first.stdout); + } catch { + assert.fail(`Stdout must be a single valid JSON document. Got: ${first.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}` + ); + assert.ok( + parsed.reason.includes(ISOLATED_HOME) && parsed.reason.includes('learned'), + `Reason must name where learned skills go. Got: ${parsed.reason}` + ); + const second = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir), env + )); + assert.strictEqual(second.stdout, '', 'Second Stop for the same session must not re-deliver'); + } 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); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-marker-fail-1'; + const marker = deliveryMarkerPath(sessionId); + // A regular file as TMPDIR makes the marker path uncreatable (ENOTDIR) + // even as root, so the write fails while no marker exists. + const notADir = path.join(testDir, 'not-a-dir'); + try { + fs.rmSync(marker, { force: true }); + fs.writeFileSync(notADir, 'not a directory\n'); + registerLeaseFor(testDir, homunculusDir, sessionId); + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir, TMPDIR: notADir, TEMP: notADir, TMP: notADir } + )); + assert.strictEqual(result.stdout, '', 'A failed marker write must fail closed, never deliver'); + assert.ok(result.stderr.includes('could not record delivery marker'), 'Marker failure must be logged'); + } finally { + fs.rmSync(marker, { force: true }); + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + + if (test('stop:evaluate-session registration is synchronous (no async flag)', () => { + const hooksConfig = JSON.parse(fs.readFileSync( + path.join(__dirname, '..', '..', 'hooks', 'hooks.json'), 'utf8' + )); + let entry = null; + for (const group of hooksConfig.hooks.Stop) { + for (const hook of group.hooks || []) { + if (typeof hook.command === 'string' && hook.command.includes('stop:evaluate-session')) { + entry = hook; + } + } + } + assert.ok(entry, 'stop:evaluate-session must be registered in hooks.json'); + assert.notStrictEqual(entry.async, true, 'An async Stop registration cannot block, so delivery must stay synchronous'); + })) passed++; else failed++; + + if (test('emits no stdout when stop_hook_active is true, even with opt-in + lease', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-loop-1'; + const marker = deliveryMarkerPath(sessionId); + try { + fs.rmSync(marker, { force: true }); + registerLeaseFor(testDir, homunculusDir, sessionId); + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir, { stop_hook_active: true }), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir } + )); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'A re-fired Stop must pass through, never re-block'); + } finally { + fs.rmSync(marker, { force: true }); + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + + if (test('emits no stdout for a short session, even with opt-in + lease', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 5); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-short-1'; + try { + registerLeaseFor(testDir, homunculusDir, sessionId); + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir } + )); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'Below-threshold sessions must not deliver'); + assert.ok(result.stderr.includes('too short'), 'Short session still logs as too short'); + } finally { + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + + if (test('emits no stdout when the payload event is not Stop', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-wrongevent-1'; + try { + registerLeaseFor(testDir, homunculusDir, sessionId); + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir, { hook_event_name: 'PreToolUse' }), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir } + )); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'Delivery is Stop-only; other events must not trigger it'); + } finally { + cleanupTestDir(testDir); + fs.rmSync(homunculusDir, { recursive: true, force: true }); + } + })) passed++; else failed++; + + if (test('emits no stdout when no session id is available, even with opt-in', () => { + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + try { + const payload = stopPayload(transcript, undefined, testDir); + delete payload.session_id; + const result = withOptInConfig(true, () => runEvaluatePayload( + payload, {}, ['CLAUDE_SESSION_ID', 'ECC_SESSION_ID'] + )); + assert.strictEqual(result.code, 0); + assert.strictEqual(result.stdout, '', 'Without a session id there is nothing to bind delivery to'); + } finally { + cleanupTestDir(testDir); + } + })) passed++; else failed++; + // Summary console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); process.exit(failed > 0 ? 1 : 0); diff --git a/tests/hooks/hooks.test.js b/tests/hooks/hooks.test.js index db469d34d..733ee2ac0 100644 --- a/tests/hooks/hooks.test.js +++ b/tests/hooks/hooks.test.js @@ -3950,13 +3950,17 @@ async function runTests() { // ─── Round 23: Bug fixes & high-priority gap coverage ─── // Helper: create a patched evaluate-session.js wrapper that resolves - // require('../lib/utils') to the real utils.js and uses a custom config path + // require('../lib/...') to the real lib files and uses a custom config path const realUtilsPath = path.resolve(__dirname, '..', '..', 'scripts', 'lib', 'utils.js'); + const realHookSessionPath = path.resolve(__dirname, '..', '..', 'scripts', 'lib', 'hook-session.js'); + const realObserverSessionsPath = path.resolve(__dirname, '..', '..', 'scripts', 'lib', 'observer-sessions.js'); function createEvalWrapper(testDir, configPath) { const wrapperScript = path.join(testDir, 'eval-wrapper.js'); let src = fs.readFileSync(path.join(scriptsDir, 'evaluate-session.js'), 'utf8'); - // Patch require to use absolute path (the temp dir doesn't have ../lib/utils) + // Patch requires to use absolute paths (the temp dir doesn't have ../lib/*) src = src.replace(/require\('\.\.\/lib\/utils'\)/, `require(${JSON.stringify(realUtilsPath)})`); + src = src.replace(/require\('\.\.\/lib\/hook-session'\)/, `require(${JSON.stringify(realHookSessionPath)})`); + src = src.replace(/require\('\.\.\/lib\/observer-sessions'\)/, `require(${JSON.stringify(realObserverSessionsPath)})`); // Patch config file path to point to our test config src = src.replace(/const configFile = path\.join\(scriptDir.*?config\.json'\);/, `const configFile = ${JSON.stringify(configPath)};`); fs.writeFileSync(wrapperScript, src);