Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

fix(hooks): apply CLAUDE_MEM_SKIP_BASH_PATTERNS in the server runtime (#6750)

Kevin6af2081d618b
diff --git a/src/cli/handlers/observation.ts b/src/cli/handlers/observation.ts
index bd02cdabc..6ee99047f 100644
--- a/src/cli/handlers/observation.ts
+++ b/src/cli/handlers/observation.ts
@@ -11,6 +11,7 @@ import { shouldTrackProject } from '../../shared/should-track-project.js';
import { shouldSkipAgentObservation } from '../../shared/should-skip-agent-observation.js';
import { loadFromFileOnce } from '../../shared/hook-settings.js';
import { isToolSkipped } from '../../shared/is-tool-skipped.js';
+import { isShellCommandSkipped } from '../../shared/shell-command-skip.js';
import { normalizePlatformSource } from '../../shared/platform-source.js';
import { resolveRuntimeContext, logServerFallback } from '../../services/hooks/runtime-selector.js';
import { isServerClientError, type ServerRecordEventRequest } from '../../services/hooks/server-client.js';
@@ -107,6 +108,11 @@ export const observationHandler: EventHandler = {
logger.debug('HOOK', 'Server runtime: tool excluded by CLAUDE_MEM_SKIP_TOOLS', { toolName });
return { continue: true, suppressOutput: true, exitCode: HOOK_EXIT_CODES.SUCCESS };
}
+ // CLAUDE_MEM_SKIP_BASH_PATTERNS is applied there too, for the same reason.
+ if (isShellCommandSkipped(toolName, toolInput, loadFromFileOnce())) {
+ logger.debug('HOOK', 'Server runtime: command excluded by CLAUDE_MEM_SKIP_BASH_PATTERNS', { toolName });
+ return { continue: true, suppressOutput: true, exitCode: HOOK_EXIT_CODES.SUCCESS };
+ }
const event: ServerRecordEventRequest = {
projectId: runtime.projectId,
contentSessionId: sessionId,
diff --git a/src/services/worker/http/shared.ts b/src/services/worker/http/shared.ts
index 8f243f820..dcc3392f3 100644
--- a/src/services/worker/http/shared.ts
+++ b/src/services/worker/http/shared.ts
@@ -7,6 +7,7 @@ import { stripMemoryTags } from '../../../utils/tag-stripping.js';
import { isProjectExcluded } from '../../../utils/project-filter.js';
import { shouldSkipAgentObservation } from '../../../shared/should-skip-agent-observation.js';
import { isToolSkipped } from '../../../shared/is-tool-skipped.js';
+import { isShellCommandSkipped } from '../../../shared/shell-command-skip.js';
import { SettingsDefaultsManager } from '../../../shared/SettingsDefaultsManager.js';
import { isObserverCaptureEnabled } from '../../../shared/observer-capture.js';
import { USER_SETTINGS_PATH } from '../../../shared/paths.js';
@@ -58,87 +59,6 @@ const HERMES_FILTER_TOOL_NAMES = new Map([
['terminal', 'Bash'], ['read_file', 'Read'], ['write_file', 'Write'], ['patch', 'Edit'],
]);
-// Compile each CLAUDE_MEM_SKIP_BASH_PATTERNS value once, not per observation:
-// ingestObservation runs on the hot path. A cached `null` marks a value that
-// failed to compile, so an invalid regex warns once instead of on every Bash
-// command until the setting is fixed.
-const bashPatternCache = new Map<string, RegExp | null>();
-
-function getBashSkipPattern(pattern: string): RegExp | null {
- const cached = bashPatternCache.get(pattern);
- if (cached !== undefined) return cached;
-
- let compiled: RegExp | null = null;
- try {
- compiled = new RegExp(pattern);
- } catch (error) {
- logger.warn('INGEST', 'Invalid CLAUDE_MEM_SKIP_BASH_PATTERNS regex — ignoring', {
- pattern,
- error: error instanceof Error ? error.message : String(error),
- });
- }
- bashPatternCache.set(pattern, compiled);
- return compiled;
-}
-
-// This is deliberately not a shell parser. When syntax is ambiguous across
-// Bash and PowerShell, retain the observation rather than drop part of it.
-function simpleCommandSegments(command: string): string[] | null {
- const segments: string[] = [];
- let start = 0;
- let quote: "'" | '"' | null = null;
- for (let i = 0; i < command.length; i++) {
- const char = command[i];
- // cmd.exe expands %VAR% even inside quotes; ^ and ! also have shell-
- // specific meanings. Without the actual shell, don't guess their effect.
- if ('%^!'.includes(char)) return null;
- if (quote === "'") {
- // cmd.exe does not treat single quotes as quoting. Shell operators or
- // a double quote here could change command boundaries or redirect IO.
- if ('&|;\n\r"<>(){}'.includes(char)) return null;
- if (char === "'") quote = null;
- continue;
- }
- if (char === '`' || char === '\\' || char === '$') return null;
- if (quote === '"') {
- if (char === '\n' || char === '\r') return null;
- if (char === '"') quote = null;
- continue;
- }
- if (char === "'" || char === '"') {
- quote = char;
- continue;
- }
- if ('<>(){}#'.includes(char)) return null;
- if (';|&\n\r'.includes(char)) {
- const segment = command.slice(start, i).trim();
- if (segment) segments.push(segment);
- if ((char === '|' || char === '&') && command[i + 1] === char) i++;
- start = i + 1;
- }
- }
- if (quote) return null;
- const last = command.slice(start).trim();
- if (last) segments.push(last);
- return segments.length ? segments : null;
-}
-
-// The shell command CLAUDE_MEM_SKIP_BASH_PATTERNS is matched against. Claude
-// Code sends `Bash` + `command` (Cursor and Windsurf adapters normalize to the
-// same shape); the Codex transcript watcher sends `exec_command` + `cmd`; on
-// Windows the primary shell arrives as `PowerShell` + `command` (issue #4745 —
-// without this branch the setting silently did nothing there); Antigravity's
-// agy sends `run_command`, and its adapter copies `CommandLine` to `command`.
-function shellCommandOf(toolName: string, toolInput: unknown): string {
- if (!toolInput || typeof toolInput !== 'object') return '';
- const input = toolInput as { command?: unknown; cmd?: unknown };
- const command =
- toolName === 'Bash' || toolName === 'PowerShell' || toolName === 'run_command' ? input.command
- : toolName === 'exec_command' ? input.cmd
- : undefined;
- return typeof command === 'string' ? command : '';
-}
-
export function setIngestContext(next: IngestContext): void {
ctx = next;
}
@@ -296,18 +216,8 @@ export async function ingestObservation(payload: ObservationPayload, handoff: In
return { ok: true, status: 'skipped', reason: 'tool_excluded' };
}
- const skipBashPatterns = settings.CLAUDE_MEM_SKIP_BASH_PATTERNS.trim();
- const command = skipBashPatterns ? shellCommandOf(filterToolName, payload.toolInput) : '';
- if (command) {
- // A bad user regex never throws here — getBashSkipPattern returns null, so the
- // command is captured as if no pattern was set.
- const pattern = getBashSkipPattern(skipBashPatterns);
- const segments = settings.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT === 'true'
- ? simpleCommandSegments(command)
- : [command];
- if (pattern && pattern.test(command) && segments && segments.every(segment => pattern.test(segment))) {
- return { ok: true, status: 'skipped', reason: 'bash_pattern_excluded' };
- }
+ if (isShellCommandSkipped(filterToolName, payload.toolInput, settings)) {
+ return { ok: true, status: 'skipped', reason: 'bash_pattern_excluded' };
}
// #2736 — defense in depth: the hook handler already filters subagent
diff --git a/src/shared/shell-command-skip.ts b/src/shared/shell-command-skip.ts
new file mode 100644
index 000000000..e1f687cc1
--- /dev/null
+++ b/src/shared/shell-command-skip.ts
@@ -0,0 +1,105 @@
+// CLAUDE_MEM_SKIP_BASH_PATTERNS matching, shared by every capture path so the
+// setting means the same thing whichever runtime the user picked: the worker
+// ingest path (src/services/worker/http/shared.ts) and the PostToolUse hook's
+// server-runtime branch (src/cli/handlers/observation.ts), which sends events
+// straight to the server and never passes through worker ingest.
+
+import { logger } from '../utils/logger.js';
+
+// Compile each CLAUDE_MEM_SKIP_BASH_PATTERNS value once, not per observation:
+// ingestObservation runs on the hot path. A cached `null` marks a value that
+// failed to compile, so an invalid regex warns once instead of on every Bash
+// command until the setting is fixed.
+const bashPatternCache = new Map<string, RegExp | null>();
+
+function getBashSkipPattern(pattern: string): RegExp | null {
+ const cached = bashPatternCache.get(pattern);
+ if (cached !== undefined) return cached;
+
+ let compiled: RegExp | null = null;
+ try {
+ compiled = new RegExp(pattern);
+ } catch (error) {
+ logger.warn('INGEST', 'Invalid CLAUDE_MEM_SKIP_BASH_PATTERNS regex — ignoring', {
+ pattern,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ bashPatternCache.set(pattern, compiled);
+ return compiled;
+}
+
+// This is deliberately not a shell parser. When syntax is ambiguous across
+// Bash and PowerShell, retain the observation rather than drop part of it.
+function simpleCommandSegments(command: string): string[] | null {
+ const segments: string[] = [];
+ let start = 0;
+ let quote: "'" | '"' | null = null;
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i];
+ // cmd.exe expands %VAR% even inside quotes; ^ and ! also have shell-
+ // specific meanings. Without the actual shell, don't guess their effect.
+ if ('%^!'.includes(char)) return null;
+ if (quote === "'") {
+ // cmd.exe does not treat single quotes as quoting. Shell operators or
+ // a double quote here could change command boundaries or redirect IO.
+ if ('&|;\n\r"<>(){}'.includes(char)) return null;
+ if (char === "'") quote = null;
+ continue;
+ }
+ if (char === '`' || char === '\\' || char === '$') return null;
+ if (quote === '"') {
+ if (char === '\n' || char === '\r') return null;
+ if (char === '"') quote = null;
+ continue;
+ }
+ if (char === "'" || char === '"') {
+ quote = char;
+ continue;
+ }
+ if ('<>(){}#'.includes(char)) return null;
+ if (';|&\n\r'.includes(char)) {
+ const segment = command.slice(start, i).trim();
+ if (segment) segments.push(segment);
+ if ((char === '|' || char === '&') && command[i + 1] === char) i++;
+ start = i + 1;
+ }
+ }
+ if (quote) return null;
+ const last = command.slice(start).trim();
+ if (last) segments.push(last);
+ return segments.length ? segments : null;
+}
+
+// The shell command CLAUDE_MEM_SKIP_BASH_PATTERNS is matched against. Claude
+// Code sends `Bash` + `command` (Cursor and Windsurf adapters normalize to the
+// same shape); the Codex transcript watcher sends `exec_command` + `cmd`; on
+// Windows the primary shell arrives as `PowerShell` + `command` (issue #4745 —
+// without this branch the setting silently did nothing there); Antigravity's
+// agy sends `run_command`, and its adapter copies `CommandLine` to `command`.
+function shellCommandOf(toolName: string, toolInput: unknown): string {
+ if (!toolInput || typeof toolInput !== 'object') return '';
+ const input = toolInput as { command?: unknown; cmd?: unknown };
+ const command =
+ toolName === 'Bash' || toolName === 'PowerShell' || toolName === 'run_command' ? input.command
+ : toolName === 'exec_command' ? input.cmd
+ : undefined;
+ return typeof command === 'string' ? command : '';
+}
+
+export function isShellCommandSkipped(
+ toolName: string,
+ toolInput: unknown,
+ settings: { CLAUDE_MEM_SKIP_BASH_PATTERNS?: string; CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT?: string },
+): boolean {
+ const skipBashPatterns = (settings.CLAUDE_MEM_SKIP_BASH_PATTERNS ?? '').trim();
+ const command = skipBashPatterns ? shellCommandOf(toolName, toolInput) : '';
+ if (!command) return false;
+ // A bad user regex never throws here — getBashSkipPattern returns null, so the
+ // command is captured as if no pattern was set.
+ const pattern = getBashSkipPattern(skipBashPatterns);
+ const segments = settings.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT === 'true'
+ ? simpleCommandSegments(command)
+ : [command];
+ return !!pattern && pattern.test(command) && !!segments && segments.every(segment => pattern.test(segment));
+}
diff --git a/tests/cli/handlers/observation-subagent-skip.test.ts b/tests/cli/handlers/observation-subagent-skip.test.ts
index c68d39e08..d04c5b728 100644
--- a/tests/cli/handlers/observation-subagent-skip.test.ts
+++ b/tests/cli/handlers/observation-subagent-skip.test.ts
@@ -282,4 +282,31 @@ describe('observationHandler — subagent observation filtering (#2736)', () =>
expect(recordEventLog.length).toBe(0);
expect((await spooled()).length).toBe(0);
});
+
+ it('honors CLAUDE_MEM_SKIP_BASH_PATTERNS on the server runtime', async () => {
+ mockRuntime = serverRuntime();
+ mockSettings.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat)\\b';
+ const { observationHandler } = await import('../../../src/cli/handlers/observation.js');
+
+ const skipped = await observationHandler.execute(baseInput()); // command 'ls'
+ expect(skipped.continue).toBe(true);
+ expect(recordEventLog).toHaveLength(0);
+
+ await observationHandler.execute(baseInput({ toolInput: { command: 'git status' } }));
+ expect(recordEventLog).toHaveLength(1);
+ expect((await spooled()).length).toBe(0);
+ });
+
+ it('applies CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT on the server runtime', async () => {
+ mockRuntime = serverRuntime();
+ mockSettings.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat)\\b';
+ mockSettings.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
+ const { observationHandler } = await import('../../../src/cli/handlers/observation.js');
+
+ await observationHandler.execute(baseInput({ toolInput: { command: 'ls && cat a' } }));
+ expect(recordEventLog).toHaveLength(0);
+
+ await observationHandler.execute(baseInput({ toolInput: { command: 'cat a && rm -rf b' } }));
+ expect(recordEventLog).toHaveLength(1);
+ });
});