Skip to content

Commit 28de7cc

Browse files
authored
fix: strip ANSI escape codes from session persistence hooks (anomalyco#642) (anomalyco#684)
Windows terminals emit control sequences (cursor movement, screen clearing) that leaked into session.tmp files and were injected verbatim into Claude's context on the next session start. Add a comprehensive stripAnsi() to utils.js that handles CSI, OSC, charset selection, and bare ESC sequences. Apply it in session-end.js (when extracting user messages from the transcript) and in session-start.js (safety net before injecting session content).
1 parent 9a478ad commit 28de7cc

4 files changed

Lines changed: 87 additions & 3 deletions

File tree

‎scripts/hooks/session-end.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const {
2121
readFile,
2222
writeFile,
2323
runCommand,
24+
stripAnsi,
2425
log
2526
} = require('../lib/utils');
2627

@@ -58,8 +59,9 @@ function extractSessionSummary(transcriptPath) {
5859
: Array.isArray(rawContent)
5960
? rawContent.map(c => (c && c.text) || '').join(' ')
6061
: '';
61-
if (text.trim()) {
62-
userMessages.push(text.trim().slice(0, 200));
62+
const cleaned = stripAnsi(text).trim();
63+
if (cleaned) {
64+
userMessages.push(cleaned.slice(0, 200));
6365
}
6466
}
6567

‎scripts/hooks/session-start.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const {
1515
findFiles,
1616
ensureDir,
1717
readFile,
18+
stripAnsi,
1819
log,
1920
output
2021
} = require('../lib/utils');
@@ -42,7 +43,8 @@ async function main() {
4243
const content = readFile(latest.path);
4344
if (content && !content.includes('[Session context goes here]')) {
4445
// Only inject if the session has actual content (not the blank template)
45-
output(`Previous session summary:\n${content}`);
46+
// Strip ANSI escape codes that may have leaked from terminal output (#642)
47+
output(`Previous session summary:\n${stripAnsi(content)}`);
4648
}
4749
}
4850

‎scripts/lib/utils.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,24 @@ function countInFile(filePath, pattern) {
464464
return matches ? matches.length : 0;
465465
}
466466

467+
/**
468+
* Strip all ANSI escape sequences from a string.
469+
*
470+
* Handles:
471+
* - CSI sequences: \x1b[ … <letter> (colors, cursor movement, erase, etc.)
472+
* - OSC sequences: \x1b] … BEL/ST (window titles, hyperlinks)
473+
* - Charset selection: \x1b(B
474+
* - Bare ESC + single letter: \x1b <letter> (e.g. \x1bM for reverse index)
475+
*
476+
* @param {string} str - Input string possibly containing ANSI codes
477+
* @returns {string} Cleaned string with all escape sequences removed
478+
*/
479+
function stripAnsi(str) {
480+
if (typeof str !== 'string') return '';
481+
// eslint-disable-next-line no-control-regex
482+
return str.replace(/\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([A-Z]|[A-Z])/g, '');
483+
}
484+
467485
/**
468486
* Search for pattern in file and return matching lines with line numbers
469487
*/
@@ -530,6 +548,9 @@ module.exports = {
530548
countInFile,
531549
grepFile,
532550

551+
// String sanitisation
552+
stripAnsi,
553+
533554
// Hook I/O
534555
readStdinJson,
535556
log,

‎tests/lib/utils.test.js‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2424,6 +2424,65 @@ function runTests() {
24242424
}
24252425
})) passed++; else failed++;
24262426

2427+
// ─── stripAnsi ───
2428+
console.log('\nstripAnsi:');
2429+
2430+
if (test('strips SGR color codes (\\x1b[...m)', () => {
2431+
assert.strictEqual(utils.stripAnsi('\x1b[31mRed text\x1b[0m'), 'Red text');
2432+
assert.strictEqual(utils.stripAnsi('\x1b[1;36mBold cyan\x1b[0m'), 'Bold cyan');
2433+
})) passed++; else failed++;
2434+
2435+
if (test('strips cursor movement sequences (\\x1b[H, \\x1b[2J, \\x1b[3J)', () => {
2436+
// These are the exact sequences reported in issue #642
2437+
assert.strictEqual(utils.stripAnsi('\x1b[H\x1b[2J\x1b[3JHello'), 'Hello');
2438+
assert.strictEqual(utils.stripAnsi('before\x1b[Hafter'), 'beforeafter');
2439+
})) passed++; else failed++;
2440+
2441+
if (test('strips cursor position sequences (\\x1b[row;colH)', () => {
2442+
assert.strictEqual(utils.stripAnsi('\x1b[5;10Hplaced'), 'placed');
2443+
})) passed++; else failed++;
2444+
2445+
if (test('strips erase line sequences (\\x1b[K, \\x1b[2K)', () => {
2446+
assert.strictEqual(utils.stripAnsi('line\x1b[Kend'), 'lineend');
2447+
assert.strictEqual(utils.stripAnsi('line\x1b[2Kend'), 'lineend');
2448+
})) passed++; else failed++;
2449+
2450+
if (test('strips OSC sequences (window title, hyperlinks)', () => {
2451+
// OSC terminated by BEL (\x07)
2452+
assert.strictEqual(utils.stripAnsi('\x1b]0;My Title\x07content'), 'content');
2453+
// OSC terminated by ST (\x1b\\)
2454+
assert.strictEqual(utils.stripAnsi('\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\'), 'link');
2455+
})) passed++; else failed++;
2456+
2457+
if (test('strips charset selection (\\x1b(B)', () => {
2458+
assert.strictEqual(utils.stripAnsi('\x1b(Bnormal'), 'normal');
2459+
})) passed++; else failed++;
2460+
2461+
if (test('strips bare ESC + letter (\\x1bM reverse index)', () => {
2462+
assert.strictEqual(utils.stripAnsi('line\x1bMup'), 'lineup');
2463+
})) passed++; else failed++;
2464+
2465+
if (test('handles mixed ANSI sequences in one string', () => {
2466+
const input = '\x1b[H\x1b[2J\x1b[1;36mSession\x1b[0m summary\x1b[K';
2467+
assert.strictEqual(utils.stripAnsi(input), 'Session summary');
2468+
})) passed++; else failed++;
2469+
2470+
if (test('returns empty string for non-string input', () => {
2471+
assert.strictEqual(utils.stripAnsi(null), '');
2472+
assert.strictEqual(utils.stripAnsi(undefined), '');
2473+
assert.strictEqual(utils.stripAnsi(42), '');
2474+
})) passed++; else failed++;
2475+
2476+
if (test('preserves string with no ANSI codes', () => {
2477+
assert.strictEqual(utils.stripAnsi('plain text'), 'plain text');
2478+
assert.strictEqual(utils.stripAnsi(''), '');
2479+
})) passed++; else failed++;
2480+
2481+
if (test('handles CSI with question mark parameter (DEC private modes)', () => {
2482+
// e.g. \x1b[?25h (show cursor), \x1b[?25l (hide cursor)
2483+
assert.strictEqual(utils.stripAnsi('\x1b[?25hvisible\x1b[?25l'), 'visible');
2484+
})) passed++; else failed++;
2485+
24272486
// Summary
24282487
console.log('\n=== Test Results ===');
24292488
console.log(`Passed: ${passed}`);

0 commit comments

Comments
 (0)