diff --git a/scripts/lib/shell-substitution.js b/scripts/lib/shell-substitution.js index a5dec6fbb..efe6a9be1 100644 --- a/scripts/lib/shell-substitution.js +++ b/scripts/lib/shell-substitution.js @@ -105,20 +105,36 @@ function parenDelta(ch) { return 0; } +// `$'...'` (ANSI-C quoting) opens only on an unescaped `$`: an odd run of +// backslashes before it makes the `$` literal and the quote a plain one. +function opensAnsiC(source, i) { + if (source[i - 1] !== '$') return false; + let backslashes = 0; + while (source[i - 2 - backslashes] === '\\') backslashes += 1; + return backslashes % 2 === 0; +} + +// Backslash escapes apply outside single quotes and inside `$'...'`. +function escapesActive(quotes) { + return !quotes.inSingle || quotes.ansiC; +} + /** - * Toggle quote state for a quote character at the current position. - * Returns true when `ch` opened or closed a quote. + * Quote state after the quote character at `source[i]`, as a new object, or + * null when it neither opens nor closes a quote. Callers consume escapes + * first, so a quote after a backslash here still closes (`'C:\'`, `"C:\\"`), + * while `\'` inside `$'...'` is consumed before it can close the string. */ -function toggleQuote(ch, prev, quotes) { - if (ch === "'" && !quotes.inDouble && prev !== '\\') { - quotes.inSingle = !quotes.inSingle; - return true; +function toggleQuote(source, i, quotes) { + const ch = source[i]; + if (ch === "'" && !quotes.inDouble) { + const inSingle = !quotes.inSingle; + return { ...quotes, inSingle, ansiC: inSingle && opensAnsiC(source, i) }; } - if (ch === '"' && !quotes.inSingle && prev !== '\\') { - quotes.inDouble = !quotes.inDouble; - return true; + if (ch === '"' && !quotes.inSingle) { + return { ...quotes, inDouble: !quotes.inDouble }; } - return false; + return null; } /** @@ -126,16 +142,19 @@ function toggleQuote(ch, prev, quotes) { * is at `start`, honoring quotes and escapes inside the span. */ function findParenSpanEnd(source, start) { - const quotes = { inSingle: false, inDouble: false }; + let quotes = { inSingle: false, inDouble: false, ansiC: false }; let depth = 1; let i = start; while (i < source.length && depth > 0) { const inner = source[i]; - if (inner === '\\' && !quotes.inSingle) { + if (inner === '\\' && escapesActive(quotes)) { i += 2; continue; } - if (!toggleQuote(inner, source[i - 1], quotes) && !quotes.inSingle && !quotes.inDouble) { + const toggled = toggleQuote(source, i, quotes); + if (toggled) { + quotes = toggled; + } else if (!quotes.inSingle && !quotes.inDouble) { depth += parenDelta(inner); } i += 1; @@ -161,17 +180,19 @@ function findBacktickEnd(source, start) { /** * Top-level scan step shared by the group extractors: escapes, quote state, - * `$(...)` and backtick spans. Returns the last index consumed so a `for` - * loop's `i++` resumes after it, or -1 when the caller must inspect `source[i]`. + * `$(...)` and backtick spans. Returns the quote state after `source[i]` and + * `skipped`, the last index consumed so a `for` loop's `i++` resumes after it, + * or -1 when the caller must inspect `source[i]`. */ function skipOuterSpan(source, i, quotes) { const ch = source[i]; - if (ch === '\\' && !quotes.inSingle) return i + 1; - if (toggleQuote(ch, source[i - 1], quotes)) return i; - if (quotes.inSingle || quotes.inDouble) return i; - if (ch === '$' && source[i + 1] === '(') return findParenSpanEnd(source, i + 2) - 1; - if (ch === '`') return findBacktickEnd(source, i + 1); - return -1; + if (ch === '\\' && escapesActive(quotes)) return { skipped: i + 1, quotes }; + const toggled = toggleQuote(source, i, quotes); + if (toggled) return { skipped: i, quotes: toggled }; + if (quotes.inSingle || quotes.inDouble) return { skipped: i, quotes }; + if (ch === '$' && source[i + 1] === '(') return { skipped: findParenSpanEnd(source, i + 2) - 1, quotes }; + if (ch === '`') return { skipped: findBacktickEnd(source, i + 1), quotes }; + return { skipped: -1, quotes }; } /** @@ -179,20 +200,23 @@ function skipOuterSpan(source, i, quotes) { * the body text and the index of the closing paren (or where input ran out). */ function readSubshellBody(source, start) { - const quotes = { inSingle: false, inDouble: false }; + let quotes = { inSingle: false, inDouble: false, ansiC: false }; let depth = 1; let body = ''; let i = start; while (i < source.length && depth > 0) { const inner = source[i]; - if (inner === '\\' && !quotes.inSingle) { + if (inner === '\\' && escapesActive(quotes)) { // Keep the escape and its operand together; a trailing backslash at the // end of an unterminated span is appended once and the scan stops. body += source.slice(i, i + 2); i = Math.min(i + 2, source.length); continue; } - if (!toggleQuote(inner, source[i - 1], quotes) && !quotes.inSingle && !quotes.inDouble) { + const toggled = toggleQuote(source, i, quotes); + if (toggled) { + quotes = toggled; + } else if (!quotes.inSingle && !quotes.inDouble) { depth += parenDelta(inner); if (depth === 0) break; } @@ -222,12 +246,13 @@ function readSubshellBody(source, start) { function extractSubshellGroups(input) { const source = String(input || ''); const groups = []; - const quotes = { inSingle: false, inDouble: false }; + let quotes = { inSingle: false, inDouble: false, ansiC: false }; for (let i = 0; i < source.length; i++) { - const skipped = skipOuterSpan(source, i, quotes); - if (skipped !== -1) { - i = skipped; + const step = skipOuterSpan(source, i, quotes); + quotes = step.quotes; + if (step.skipped !== -1) { + i = step.skipped; continue; } if (source[i] !== '(') continue; @@ -267,19 +292,21 @@ function opensBraceGroup(source, i) { * the body text and the index of the closing brace (or where input ran out). */ function readBraceBody(source, start) { - const quotes = { inSingle: false, inDouble: false }; + let quotes = { inSingle: false, inDouble: false, ansiC: false }; let depth = 1; let body = ''; let i = start; while (i < source.length && depth > 0) { const inner = source[i]; const prev = source[i - 1]; - if (inner === '\\' && !quotes.inSingle) { + if (inner === '\\' && escapesActive(quotes)) { body += source.slice(i, i + 2); i = Math.min(i + 2, source.length); continue; } - if (toggleQuote(inner, prev, quotes) || quotes.inSingle || quotes.inDouble) { + const toggled = toggleQuote(source, i, quotes); + if (toggled) quotes = toggled; + if (toggled || quotes.inSingle || quotes.inDouble) { body += inner; i += 1; continue; @@ -329,12 +356,13 @@ function readBraceBody(source, start) { function extractBraceGroups(input) { const source = String(input || ''); const groups = []; - const quotes = { inSingle: false, inDouble: false }; + let quotes = { inSingle: false, inDouble: false, ansiC: false }; for (let i = 0; i < source.length; i++) { - const skipped = skipOuterSpan(source, i, quotes); - if (skipped !== -1) { - i = skipped; + const step = skipOuterSpan(source, i, quotes); + quotes = step.quotes; + if (step.skipped !== -1) { + i = step.skipped; continue; } if (source[i] === '(') { diff --git a/scripts/lib/transcript-context.js b/scripts/lib/transcript-context.js index fc27fad5e..fd7397bf6 100644 --- a/scripts/lib/transcript-context.js +++ b/scripts/lib/transcript-context.js @@ -140,13 +140,13 @@ function readLatestContextTokens(transcriptPath, options = {}) { * @returns {{ windowTokens: number, inferred: boolean }} */ function resolveContextWindow(tokens, model) { + const env = (typeof process !== 'undefined' && process.env) || {}; + // Explicit window override wins: 400k models (e.g. Opus 4.x) match neither the // 200k default nor the 1M marker and would otherwise report ~double usage (#2290). - // Honor ECC's own knob and Claude Code's native CLAUDE_CODE_AUTO_COMPACT_WINDOW. - const env = (typeof process !== 'undefined' && process.env) || {}; - const envWindow = Number.parseInt(env.ECC_CONTEXT_WINDOW_TOKENS || env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10); - if (Number.isInteger(envWindow) && envWindow > 0) { - return { windowTokens: envWindow, inferred: false }; + const explicitWindow = Number.parseInt(env.ECC_CONTEXT_WINDOW_TOKENS || '', 10); + if (Number.isInteger(explicitWindow) && explicitWindow > 0) { + return { windowTokens: explicitWindow, inferred: false }; } if (typeof model === 'string' && model.includes(LARGE_WINDOW_MODEL_MARKER)) { @@ -166,6 +166,15 @@ function resolveContextWindow(tokens, model) { return { windowTokens: LARGE_CONTEXT_WINDOW_TOKENS, inferred: true }; } + // Claude Code's CLAUDE_CODE_AUTO_COMPACT_WINDOW is the harness auto-compact + // trigger point (e.g. 786432 on a 1M-window model), not the context window + // size. Honor it only as a last-resort fallback so it cannot mask the [1m] + // marker, known large-window families, or >200k observed tokens above. + const autoCompactWindow = Number.parseInt(env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10); + if (Number.isInteger(autoCompactWindow) && autoCompactWindow > 0) { + return { windowTokens: autoCompactWindow, inferred: false }; + } + return { windowTokens: STANDARD_CONTEXT_WINDOW_TOKENS, inferred: true }; } diff --git a/tests/hooks/gateguard-fact-force.test.js b/tests/hooks/gateguard-fact-force.test.js index a1148f24d..a0d16f056 100644 --- a/tests/hooks/gateguard-fact-force.test.js +++ b/tests/hooks/gateguard-fact-force.test.js @@ -3019,6 +3019,14 @@ function runTests() { passed++; else failed++; + if ( + test("denies rm -rf in a (...) group after an escaped apostrophe in $'...'", () => { + expectDestructiveDeny("echo $'it\\'s'; (rm -rf /tmp/junk)", 'ANSI-C string before subshell'); + }) + ) + passed++; + else failed++; + // Negative cases — literals and non-destructive commands must NOT // be promoted to destructive by the new grouping-body walker. diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index a5d47c8e2..c7416d493 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -226,6 +226,11 @@ function runTests() { assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); }) ? passed++ : failed++); + (test("blocks echo $'it\\'s'; (npm run dev) — escaped apostrophe does not close $'...'", () => { + const result = runScript("echo $'it\\'s'; (npm run dev)"); + assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); + }) ? passed++ : failed++); + (test('allows $(echo "(npm run dev)") — () inside double-quoted substitution body is literal', () => { const result = runScript('$(echo "(npm run dev)")'); assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); diff --git a/tests/hooks/suggest-compact.test.js b/tests/hooks/suggest-compact.test.js index c3aa91f13..bb25a372e 100644 --- a/tests/hooks/suggest-compact.test.js +++ b/tests/hooks/suggest-compact.test.js @@ -41,7 +41,12 @@ function runCompact(envOverrides = {}) { * Returns { code, stdout, stderr }. */ function runCompactWithInput(input, envOverrides = {}) { - const env = { ...process.env, ...envOverrides }; + const env = { + ...process.env, + ECC_CONTEXT_WINDOW_TOKENS: '', + CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', + ...envOverrides, + }; const result = spawnSync('node', [compactScript], { encoding: 'utf8', input: typeof input === 'string' ? input : JSON.stringify(input), @@ -830,10 +835,16 @@ function runTests() { const ctx = createContextContext(); const transcript = writeTranscriptFixture(230000, 'claude-opus-4-5[1m]'); try { - const silent = runCompactWithInput({ session_id: ctx.sessionId, transcript_path: transcript }); + const silent = runCompactWithInput( + { session_id: ctx.sessionId, transcript_path: transcript }, + { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '786432' } + ); assert.strictEqual(silent.stdout.trim(), '', `230k on a 1M window must stay silent. Got: "${silent.stdout}"`); writeTranscriptTokens(transcript, 260000, 'claude-opus-4-5[1m]'); - const fired = runCompactWithInput({ session_id: ctx.sessionId, transcript_path: transcript }); + const fired = runCompactWithInput( + { session_id: ctx.sessionId, transcript_path: transcript }, + { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '786432' } + ); assert.ok(fired.stdout.includes('26% of 1M window'), `260k on a 1M window should fire. Got: "${fired.stdout}"`); } finally { try { fs.unlinkSync(transcript); } catch (_err) { /* ignore */ } @@ -846,7 +857,10 @@ function runTests() { const ctx = createContextContext(); const transcript = writeTranscriptFixture(230000, 'claude-opus-4-5'); try { - const result = runCompactWithInput({ session_id: ctx.sessionId, transcript_path: transcript }); + const result = runCompactWithInput( + { session_id: ctx.sessionId, transcript_path: transcript }, + { CLAUDE_CODE_AUTO_COMPACT_WINDOW: '786432' } + ); // 230k would exceed the 160k standard threshold, but the observed size // implies a 1M window whose 250k default threshold is not reached yet. assert.strictEqual(result.stdout.trim(), '', `Expected 1M-window inference to keep run silent. Got: "${result.stdout}"`); diff --git a/tests/lib/shell-substitution.test.js b/tests/lib/shell-substitution.test.js index f64c90419..8bbc2b16a 100644 --- a/tests/lib/shell-substitution.test.js +++ b/tests/lib/shell-substitution.test.js @@ -154,6 +154,30 @@ test('double-quoted parens are literal (bash only honors $() there)', () => { test('extracts a bare (...) group while skipping an adjacent $()', () => { assert.deepStrictEqual(extractSubshellGroups('$(a) (b)'), ['b']); }); +test('a double-quoted string ending in an escaped backslash still closes', () => { + assert.deepStrictEqual(extractSubshellGroups('echo "C:\\\\"; (npm run dev)'), ['npm run dev']); +}); +test('a single-quoted string ending in a backslash still closes', () => { + assert.deepStrictEqual(extractSubshellGroups("echo 'C:\\'; (npm run dev)"), ['npm run dev']); +}); +test("an escaped apostrophe does not close a $'...' string", () => { + assert.deepStrictEqual(extractSubshellGroups("echo $'it\\'s'; (rm -rf /tmp/x)"), ['rm -rf /tmp/x']); +}); +test("an escaped $ before a quote opens a plain single-quoted string", () => { + assert.deepStrictEqual(extractSubshellGroups("echo \\$'C:\\'; (npm run dev)"), ['npm run dev']); +}); +test('a $() span ending a quote after a backslash still closes', () => { + assert.deepStrictEqual(extractSubshellGroups('x=$(echo "C:\\\\"); (npm run dev)'), ['npm run dev']); +}); +test('a (...) body with a quote ending in a backslash keeps its nested group', () => { + assert.deepStrictEqual(extractSubshellGroups("(echo 'C:\\'; (npm run dev))"), [ + "echo 'C:\\'; (npm run dev)", + 'npm run dev' + ]); +}); +test("a (...) body with an escaped apostrophe in $'...' still closes", () => { + assert.deepStrictEqual(extractSubshellGroups("(echo $'it\\'s'; npm run dev)"), ["echo $'it\\'s'; npm run dev"]); +}); console.log('\nextractSubshellGroups - security-relevant:'); test('surfaces a destructive command inside a subshell', () => { @@ -173,6 +197,15 @@ console.log('\nextractBraceGroups - basics:'); test('extracts a { ...; } body', () => { assert.deepStrictEqual(extractBraceGroups('{ npm run dev; }'), [' npm run dev; ']); }); +test('extracts a { ...; } body after a string ending in an escaped backslash', () => { + assert.deepStrictEqual(extractBraceGroups('echo "C:\\\\"; { npm run dev; }'), [' npm run dev; ']); +}); +test("extracts a { ...; } body after an escaped apostrophe in $'...'", () => { + assert.deepStrictEqual(extractBraceGroups("echo $'it\\'s'; { rm -rf /tmp/x; }"), [' rm -rf /tmp/x; ']); +}); +test('a { ...; } body with a quote ending in a backslash still closes', () => { + assert.deepStrictEqual(extractBraceGroups('{ echo "C:\\\\"; }; { npm run dev; }'), [' echo "C:\\\\"; ', ' npm run dev; ']); +}); test('nested brace group returns outer body then inner body', () => { assert.deepStrictEqual(extractBraceGroups('{ a; { b; }; }'), [' a; { b; }; ', ' b; ']); }); diff --git a/tests/lib/transcript-context.test.js b/tests/lib/transcript-context.test.js index 099b67658..b582aece1 100644 --- a/tests/lib/transcript-context.test.js +++ b/tests/lib/transcript-context.test.js @@ -21,6 +21,7 @@ const { DEFAULT_TRANSCRIPT_TAIL_BYTES, readFileTail, readLatestContextTokens, + resolveContextWindow, resolveContextWindowTokens, resolveContextThreshold, resolveContextInterval, @@ -285,6 +286,36 @@ test('treats an empty model id as standard window', () => { assert.strictEqual(resolveContextWindowTokens(100000, ''), STANDARD_CONTEXT_WINDOW_TOKENS); }); +// Pin both inputs so the precedence regression cannot depend on the harness +// running this test. Restore every variable even when an assertion fails. +for (const [label, tokens, model, explicitWindow, expectedWindow, inferred] of [ + ['[1m] marker', 180000, 'claude-opus-4-5[1m]', undefined, 1000000, false], + ['known large-window family', 180000, 'claude-fable-5', undefined, 1000000, false], + ['observed tokens above 200k', 220000, 'unknown-model', undefined, 1000000, true], + ['explicit ECC override', 220000, 'claude-opus-4-5[1m]', '400000', 400000, false], + ['auto-compact fallback', 180000, 'unknown-model', undefined, 786432, false], + ['invalid ECC override with marker', 180000, 'claude-opus-4-5[1m]', 'invalid', 1000000, false], +]) { + test(`${label} resolves correctly with an explicit auto-compact trigger`, () => { + const previousExplicit = process.env.ECC_CONTEXT_WINDOW_TOKENS; + const previousAutoCompact = process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW; + try { + if (explicitWindow === undefined) delete process.env.ECC_CONTEXT_WINDOW_TOKENS; + else process.env.ECC_CONTEXT_WINDOW_TOKENS = explicitWindow; + process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = '786432'; + assert.deepStrictEqual(resolveContextWindow(tokens, model), { + windowTokens: expectedWindow, + inferred, + }); + } finally { + if (previousExplicit === undefined) delete process.env.ECC_CONTEXT_WINDOW_TOKENS; + else process.env.ECC_CONTEXT_WINDOW_TOKENS = previousExplicit; + if (previousAutoCompact === undefined) delete process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW; + else process.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW = previousAutoCompact; + } + }); +} + // ── isContextWindowInferred ── console.log('\nisContextWindowInferred:');