diff --git a/scripts/hooks/evaluate-session.js b/scripts/hooks/evaluate-session.js index 6c9bc27bb..1b3f7932e 100644 --- a/scripts/hooks/evaluate-session.js +++ b/scripts/hooks/evaluate-session.js @@ -162,9 +162,16 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s 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 private observer directory. - const markerDir = path.join(getHomunculusDir(), 'delivery-markers'); + if (!claimDeliveryMarker(sessionId)) return; + output({ + decision: 'block', + reason: `[ContinuousLearning] Session has ${messageCount} messages - evaluate for extractable patterns. Save learned skills to: ${learnedSkillsPath}` + }); +} + +function claimDeliveryMarker(sessionId) { + // resolveSessionId sanitized the filename before this function is called. + const markerRoot = getHomunculusDir(); // 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 @@ -173,6 +180,15 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s // Stop for one turn, not later turns, so it cannot stand in for the // marker. try { + fs.mkdirSync(markerRoot, { recursive: true, mode: 0o700 }); + const canonicalRoot = fs.realpathSync(markerRoot); + const rootStat = fs.lstatSync(canonicalRoot); + if (!rootStat.isDirectory() + || (typeof process.getuid === 'function' && rootStat.uid !== process.getuid()) + || (process.platform !== 'win32' && (rootStat.mode & 0o022) !== 0)) { + throw new Error('observer root is not owned or permits shared writes'); + } + const markerDir = path.join(canonicalRoot, 'delivery-markers'); fs.mkdirSync(markerDir, { recursive: true, mode: 0o700 }); const stat = fs.lstatSync(markerDir); if (!stat.isDirectory() || stat.isSymbolicLink() @@ -180,25 +196,22 @@ function deliverStopNudge({ input, stdinData, messageCount, learnedSkillsPath, s || (typeof process.getuid === 'function' && stat.uid !== process.getuid())))) { throw new Error('delivery marker directory is not private'); } + const markerFile = path.join(markerDir, `${DELIVERY_MARKER_PREFIX}${sessionId}`); + try { + fs.writeFileSync(markerFile, `${new Date().toISOString()}\n`, { flag: 'wx', mode: 0o600 }); + } 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 false; + } } catch (err) { log(`[ContinuousLearning] Warning: could not record delivery marker, skipping delivery: ${err.message}`); - return; + return false; } - const markerFile = path.join(markerDir, `${DELIVERY_MARKER_PREFIX}${sessionId}`); - try { - fs.writeFileSync(markerFile, `${new Date().toISOString()}\n`, { flag: 'wx', mode: 0o600 }); - } 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}` - }); + return true; } /** diff --git a/scripts/hooks/quality-gate.js b/scripts/hooks/quality-gate.js index 733bffbea..838744f58 100755 --- a/scripts/hooks/quality-gate.js +++ b/scripts/hooks/quality-gate.js @@ -59,12 +59,13 @@ function log(msg) { * @param {string} filePath - Path to the edited file */ function maybeRunQualityGate(filePath) { - if (!filePath || !fs.existsSync(filePath)) { + if (!filePath) { return; } - // Resolve to absolute path so projectRoot-relative comparisons work - filePath = path.resolve(filePath); + // Use the existing file's canonical path for project-root comparisons and + // formatter arguments. A disappeared file fails closed in run(). + filePath = fs.realpathSync(filePath); const ext = path.extname(filePath).toLowerCase(); const fix = String(process.env.ECC_QUALITY_GATE_FIX || '').toLowerCase() === 'true'; diff --git a/tests/hooks/evaluate-session.test.js b/tests/hooks/evaluate-session.test.js index 56af081c8..23b030cac 100644 --- a/tests/hooks/evaluate-session.test.js +++ b/tests/hooks/evaluate-session.test.js @@ -553,6 +553,12 @@ function runTests() { stopPayload(transcript, sessionId, testDir), env )); assert.strictEqual(first.code, 0); + const markerStat = fs.statSync(marker); + assert.ok(markerStat.isFile()); + if (process.platform !== 'win32') { + assert.strictEqual(markerStat.mode & 0o777, 0o600); + assert.strictEqual(fs.statSync(path.dirname(marker)).mode & 0o777, 0o700); + } let parsed; try { parsed = JSON.parse(first.stdout); @@ -579,6 +585,30 @@ function runTests() { } })) passed++; else failed++; + if (test('refuses an observer root writable by other users', () => { + if (process.platform === 'win32') return; + const testDir = createTestDir(); + const transcript = createTranscript(testDir, 12); + const homunculusDir = fs.mkdtempSync(path.join(os.tmpdir(), 'eval-delivery-home-')); + const sessionId = 'delivery-unsafe-root-1'; + try { + registerLeaseFor(testDir, homunculusDir, sessionId); + fs.chmodSync(homunculusDir, 0o777); + const result = withOptInConfig(true, () => runEvaluatePayload( + stopPayload(transcript, sessionId, testDir), + { CLV2_HOMUNCULUS_DIR: homunculusDir, CLAUDE_PROJECT_DIR: testDir } + )); + assert.strictEqual(result.stdout, '', 'shared-write root must fail closed'); + assert.ok(result.stderr.includes('could not record delivery marker')); + assert.ok(!fs.existsSync(deliveryMarkerPath(homunculusDir, sessionId))); + assert.strictEqual(fs.statSync(homunculusDir).mode & 0o777, 0o777); + } finally { + fs.chmodSync(homunculusDir, 0o700); + 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); diff --git a/tests/lib/install-codex-config-preservation.test.js b/tests/lib/install-codex-config-preservation.test.js index 4c71adc63..586525963 100644 --- a/tests/lib/install-codex-config-preservation.test.js +++ b/tests/lib/install-codex-config-preservation.test.js @@ -269,8 +269,8 @@ for (const name of SHARED_FILES) { error.code === 'ELOOP' || /Refusing to inspect changed Codex configuration/.test(error.message) )); - assert.ok(fs.lstatSync(destination).isSymbolicLink()); - assert.equal(fs.readFileSync(destination, 'utf8'), '# User-owned linked configuration\n'); + assert.equal(fs.readlinkSync(destination), linkedFile, 'reinstall must retain the original symlink'); + assert.equal(fs.readFileSync(linkedFile, 'utf8'), '# User-owned linked configuration\n'); const retainedOperation = readInstallState(fixture.statePath).operations.find(operation => ( operation.destinationPath === destination && operation.ownership === 'managed' ));