Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): guard validation through command wrappers (#110620)

Alessandro Pogliaghi9bd76f0a1638
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 2a96d02f76e4..a456d009d314 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -343,6 +343,11 @@ Cloud Claude sessions deliver each watchdog warning separately to subagents and
Common build, test, and typecheck commands share a sandbox-wide lock, including commands started in the background. When another validation command holds the lock, the shell returns exit code 75 and asks the agent to wait. After the same validation command fails twice during observed watchdog interventions, the session rejects another unchanged attempt. Reduce the command's scope or concurrency, or report the validation limit. This guard is best-effort command recognition, not a resource limit for arbitrary shell programs.
+The guard recognizes validation through `timeout`, `npx`, `hogli`, `.codex/with-flox`, and `flox activate -- bash -c '…'`.
+It preserves the command's directory, arguments, and inline shell body when identifying retries.
+Script names such as `backend:test` and `build-storybook`, shell continuations, and command substitutions are recognized. Heredoc bodies are skipped before scanning subsequent commands.
+It does not inspect script files: invoke validation directly or through a supported wrapper instead of hiding it in `bash script.sh`.
+
### Local agent packages
Cloud tasks use the published `@posthog/agent` package by default. Set `LOCAL_POSTHOG_CODE_MONOREPO_ROOT` only when you need to test local agent changes.
diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts
index 16459f67a960..f05add0d6730 100644
--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.test.ts
@@ -151,9 +151,31 @@ describe("createMemoryKillNoticeHook", () => {
}
});
- it.each(["pnpm test", "cd /tmp/project && pnpm test"])(
+ it.each([
+ ["pnpm test", "pnpm test tests/small.test.ts"],
+ [
+ "cd /tmp/project && pnpm test",
+ "cd /tmp/project && pnpm test tests/small.test.ts",
+ ],
+ ["timeout 1m pnpm test", "timeout 1m pnpm test tests/small.test.ts"],
+ ["npx tsgo --noEmit", "npx tsgo --noEmit -p tsconfig.small.json"],
+ ["hogli test tests", "hogli test tests/unit"],
+ ['out="$(pnpm test)"', 'out="$(pnpm test tests/small.test.ts)"'],
+ [
+ "timeout 1m \\\n pnpm backend:test",
+ "timeout 1m \\\n pnpm backend:test tests/unit",
+ ],
+ [
+ "cat <<'EOF'\nliteral\nEOF\npnpm test",
+ "cat <<'EOF'\nliteral\nEOF\npnpm test tests/unit",
+ ],
+ [
+ 'flox activate -- bash -c "pnpm test"',
+ 'flox activate -- bash -c "pnpm test tests/small.test.ts"',
+ ],
+ ])(
"serializes %s and scopes retry limits to its directory",
- async (command) => {
+ async (command, smallerCommand) => {
await writeFile(path, "");
const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {
reader: new MemoryWatchdogKillReader(path),
@@ -178,7 +200,7 @@ describe("createMemoryKillNoticeHook", () => {
);
const failure = {
...shellInput("PostToolUseFailure", "Bash", "Exit code 144"),
- tool_input: pre.tool_input,
+ tool_input: { command: `${VALIDATION_LOCK_PREFIX}${command}` },
};
await hook(failure, `toolu_${pid}`, opts);
if (pid === 8) {
@@ -202,14 +224,14 @@ describe("createMemoryKillNoticeHook", () => {
});
expect(
await hook(
- { ...pre, tool_input: { command: `${command} tests/small.test.ts` } },
+ { ...pre, tool_input: { command: smallerCommand } },
"toolu_4",
opts,
),
).toMatchObject({
hookSpecificOutput: {
updatedInput: {
- command: `${VALIDATION_LOCK_PREFIX}${command} tests/small.test.ts`,
+ command: `${VALIDATION_LOCK_PREFIX}${smallerCommand}`,
},
},
});
diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts
index f99eb9b1c8df..6d45513fdeb7 100644
--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.test.ts
@@ -14,8 +14,81 @@ describe("validationCommandKey", () => {
["uv run pytest tests/unit", "uv run pytest tests/unit"],
["cargo test --jobs 1", "cargo test --jobs 1"],
["go build ./cmd/demo", "go build ./cmd/demo"],
+ ...[
+ "timeout 90s pnpm --filter=frontend typescript:check",
+ "timeout --signal TERM --kill-after=5s 2m pnpm test",
+ "env CI=1 timeout -k 5s 2m npx --no-install tsgo --noEmit",
+ "cd frontend && npx -y --package typescript tsc --noEmit",
+ "hogli test tests/unit",
+ ".codex/with-flox hogli test tests/unit",
+ 'flox activate -- bash -c "pnpm test tests/unit"',
+ "flox activate --dir . -- bash -lc 'cd frontend && npx tsgo --noEmit'",
+ "bash -c 'pnpm test tests/unit | tail -10'",
+ 'bash -c "pnpm test \\"tests/with spaces.test.ts\\""',
+ 'env CI=1 pnpm test "tests/a;b.test.ts"',
+ "/usr/bin/timeout 1m /usr/bin/npx tsgo --noEmit",
+ 'echo "example; pnpm test" && pnpm build',
+ "pnpm --filter @example/tasks run backend:test",
+ "timeout 1m pnpm backend:test",
+ "pnpm --filter @example/storybook build-storybook",
+ "pnpm turbo run lint backend:test --filter=@example/tasks",
+ "pnpm -w backend:test",
+ "npm run --workspace @example/tasks backend:test",
+ "npm exec -- tsc --noEmit",
+ "pnpm exec tsgo --noEmit",
+ "timeout 90s \\\n pnpm test",
+ "cd frontend && \\\n pnpm test",
+ "uv run \\\n pytest tests/unit",
+ "npx \\\n tsgo --noEmit",
+ 'bash -c "pnpm \\\n test"',
+ "pn\\\npm test",
+ 'result="$(pnpm test)"',
+ 'echo "$(pnpm test)"',
+ 'echo "$(echo "$(pnpm test)")"',
+ "result=`pnpm test`",
+ 'echo "`pnpm test`"',
+ "cat <<'EOF'\npnpm build\nEOF\npnpm test",
+ "cat <<-EOF\n\tpnpm build\n\tEOF\npnpm test",
+ "cat <<FIRST <<'SECOND'\npnpm build\nFIRST\nnpx tsgo\nSECOND\npnpm test",
+ "cat <<EOF | cat\nliteral\nEOF\npnpm test",
+ ].map((command): [string, string] => [command, command]),
+ [
+ "timeout 1m npx tsgo --noEmit 2>&1 | tail -5",
+ "timeout 1m npx tsgo --noEmit",
+ ],
+ ["hogli test tests/unit > /tmp/results.log &", "hogli test tests/unit"],
+ [
+ 'out="$(pnpm test 2>&1)"; echo "$out" | tail -20',
+ 'out="$(pnpm test 2>&1)"',
+ ],
+ ["cat <<EOF\npnpm build\nEOF\ngit status", undefined],
+ ["cat <<EOF\npnpm test", undefined],
+ ["cat <<< 'pnpm test'", undefined],
+ ["echo '$(pnpm test)'", undefined],
+ ["echo '`pnpm test`'", undefined],
+ ['echo "\\$(pnpm test)"', undefined],
+ ["'pn\\\npm' test", undefined],
+ ["npm exec -- echo test", undefined],
+ ["pnpm --filter test run start", undefined],
+ ["npm run --workspace test start", undefined],
+ ["pnpm run start test", undefined],
+ ["pnpm turbo run lint --filter test", undefined],
+ [
+ "pnpm test > /tmp/results.log tests/unit",
+ "pnpm test > /tmp/results.log tests/unit",
+ ],
["git status", undefined],
['echo "pnpm test"', undefined],
+ ['echo "example; pnpm test"', undefined],
+ ["printf '%s\\n' 'timeout 1m npx tsgo --noEmit'", undefined],
+ ["# pnpm test\ngit status", undefined],
+ ["cat <<'EOF'\npnpm test\nEOF", undefined],
+ ["bash /tmp/check.sh", undefined],
+ ["bash -c 'echo \"example; pnpm test\"'", undefined],
+ ["timeout 1m echo pnpm test", undefined],
+ ["npx --yes prettier --check .", undefined],
+ ["flox activate -- bash -c 'git status'", undefined],
+ ["hogli status", undefined],
["cat test-output.txt", undefined],
])("recognizes validation scope in %s", (command, expected) => {
expect(validationCommandKey(command)).toBe(expected);
diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts
index d46a83f79aa4..b9c53dd68bce 100644
--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts
+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-validation.ts
@@ -1,5 +1,278 @@
-const VALIDATION_COMMAND =
- /(?:^|[;&|()\n])\s*(?:(?:env|exec|time)\s+)?(?:(?:pnpm|npm|yarn|bun)\b[^;&|\n]*\b(?:test|build|typecheck|typescript:check)\b[^;&|\n]*|(?:uv\s+run\s+)?(?:pytest|jest|vitest|tsc|tsgo)\b[^;&|\n]*|(?:cargo|go)\s+(?:test|build|check)\b[^;&|\n]*)/;
+function shellGroupEnd(
+ command: string,
+ start: number,
+ close: string,
+ depth = 0,
+): number {
+ if (depth >= 32) return command.length;
+ for (let index = start; index < command.length; index++) {
+ const char = command[index];
+ if (char === "\\" && close !== "'") {
+ index++;
+ } else if (char === close) {
+ return index + 1;
+ } else if (close !== "'") {
+ if (command.startsWith("$(", index)) {
+ index = shellGroupEnd(command, index + 2, ")", depth + 1) - 1;
+ } else if (char === "`" || (close === ")" && /['"(]/.test(char))) {
+ index =
+ shellGroupEnd(
+ command,
+ index + 1,
+ char === "(" ? ")" : char,
+ depth + 1,
+ ) - 1;
+ }
+ }
+ }
+ return command.length;
+}
+
+function shellWordEnd(command: string, start: number): number {
+ let index = start;
+ while (index < command.length && !/[\s;&|()<>]/.test(command[index])) {
+ const char = command[index];
+ if (char === "\\") {
+ index += 2;
+ } else if (command.startsWith("$(", index)) {
+ index = shellGroupEnd(command, index + 2, ")");
+ } else if (/["'`]/.test(char)) {
+ index = shellGroupEnd(command, index + 1, char);
+ } else {
+ index++;
+ }
+ }
+ return index;
+}
+
+function hasValidationSubstitution(word: string, depth: number): boolean {
+ let doubleQuoted = false;
+ for (let index = 0; index < word.length; index++) {
+ const char = word[index];
+ if (char === "\\") {
+ index++;
+ } else if (char === "'" && !doubleQuoted) {
+ index = shellGroupEnd(word, index + 1, "'") - 1;
+ } else if (char === '"') {
+ doubleQuoted = !doubleQuoted;
+ } else if (char === "`" || word.startsWith("$(", index)) {
+ const start = index + (char === "`" ? 1 : 2);
+ const end = shellGroupEnd(word, start, char === "`" ? "`" : ")");
+ if (
+ validationCommandEnd(word.slice(start, end - 1), depth + 1) !==
+ undefined
+ )
+ return true;
+ index = end - 1;
+ }
+ }
+ return false;
+}
+
+function unquote(word: string): string {
+ return word.replace(
+ /'([^']*)'|"((?:\\[\s\S]|[^"\\])*)"|\\([\s\S])/g,
+ (
+ _,
+ single: string | undefined,
+ double: string | undefined,
+ escaped: string,
+ ) =>
+ single ??
+ double?.replace(/\\([$`"\\\n])/g, (_, char: string) =>
+ char === "\n" ? "" : char,
+ ) ??
+ (escaped === "\n" ? "" : escaped),
+ );
+}
+
+function skipOptions(words: string[], valueOptions: string[] = []): string[] {
+ let index = 0;
+ while (words[index]?.startsWith("-")) {
+ const option = words[index++];
+ if (option === "--") break;
+ if (valueOptions.includes(option)) index++;
+ }
+ return words.slice(index);
+}
+
+function isValidationScript(script: string | undefined): boolean {
+ return /(?:^|[:-])(?:test|build|typecheck|typescript:check)(?:[:-]|$)/.test(
+ script ?? "",
+ );
+}
+
+function isValidationCommand(words: string[], depth: number): boolean {
+ if (depth >= 8 || words.length === 0) return false;
+ const [head, ...args] = words;
+ const executable = head.split("/").at(-1);
+ if (/^[A-Za-z_]\w*=/.test(head)) {
+ return isValidationCommand(args, depth + 1);
+ }
+ switch (executable) {
+ case "env":
+ case "exec":
+ case "time":
+ return isValidationCommand(
+ skipOptions(args, ["-u", "--unset", "-C", "--chdir", "-a"]),
+ depth + 1,
+ );
+ case "timeout": {
+ const [duration, ...command] = skipOptions(args, [
+ "-s",
+ "--signal",
+ "-k",
+ "--kill-after",
+ ]);
+ return (
+ /^\d+(?:\.\d+)?[smhd]?$/.test(duration ?? "") &&
+ isValidationCommand(command, depth + 1)
+ );
+ }
+ case "npx":
+ return isValidationCommand(
+ skipOptions(args, ["-p", "--package"]),
+ depth + 1,
+ );
+ case "flox": {
+ const separator = args.indexOf("--");
+ return (
+ args[0] === "activate" &&
+ separator !== -1 &&
+ isValidationCommand(args.slice(separator + 1), depth + 1)
+ );
+ }
+ case "with-flox":
+ return isValidationCommand(args, depth + 1);
+ case "bash":
+ case "sh":
+ case "zsh": {
+ const index = args.findIndex((arg) => /^-[a-z]*c[a-z]*$/.test(arg));
+ return (
+ index !== -1 &&
+ args.slice(0, index).every((arg) => /^-[a-z]+$/.test(arg)) &&
+ validationCommandEnd(args[index + 1] ?? "", depth + 1) !== undefined
+ );
+ }
+ case "uv":
+ return args[0] === "run" && isValidationCommand(args.slice(1), depth + 1);
+ case "pnpm":
+ case "npm":
+ case "yarn":
+ case "bun":
+ case "hogli": {
+ const valueOptions = [
+ "--filter",
+ "--filter-prod",
+ "-F",
+ "--dir",
+ "-C",
+ "--prefix",
+ "--cwd",
+ "--workspace",
+ ...(executable === "npm" ? ["-w"] : []),
+ ];
+ const command = skipOptions(args, valueOptions);
+ if (["exec", "dlx", "x", "turbo"].includes(command[0])) {
+ return isValidationCommand(
+ command[0] === "turbo"
+ ? command
+ : skipOptions(command.slice(1), ["-p", "--package"]),
+ depth + 1,
+ );
+ }
+ const script =
+ command[0] === "run"
+ ? skipOptions(command.slice(1), valueOptions)[0]
+ : command[0];
+ return isValidationScript(script);
+ }
+ case "turbo": {
+ let tasks = args;
+ while (tasks.length) {
+ const [task, ...rest] = skipOptions(tasks, [
+ "--filter",
+ "--cwd",
+ "--concurrency",
+ ]);
+ if (isValidationScript(task)) return true;
+ tasks = rest;
+ }
+ return false;
+ }
+ case "pytest":
+ case "jest":
+ case "vitest":
+ case "tsc":
+ case "tsgo":
+ return true;
+ case "cargo":
+ case "go":
+ return /^(?:test|build|check)$/.test(args[0] ?? "");
+ default:
+ return false;
+ }
+}
+
+function validationCommandEnd(command: string, depth = 0): number | undefined {
+ if (depth >= 8) return undefined;
+ let words: string[] = [];
+ let end = 0;
+ let redirectTarget = false;
+ let substitution = false;
+ let heredoc: boolean | undefined;
+ const heredocs: { delimiter: string; stripTabs: boolean }[] = [];
+ for (let index = 0; index <= command.length; ) {
+ const operator =
+ /^(?:#[^\n]*|\d*(?:<<<|<<-?|[<>]+)(?:&\d+)?|[;&|()\n])/.exec(
+ command.slice(index),
+ );
+ if (/[^\S\n]/.test(command[index] ?? "")) {
+ index++;
+ continue;
+ }
+ const next = operator
+ ? index + operator[0].length
+ : shellWordEnd(command, index);
+ const raw = index === command.length ? "\n" : command.slice(index, next);
+ index = next + (index === command.length ? 1 : 0);
+ if (raw.startsWith("#") || /^(?:\\\n)+$/.test(raw)) continue;
+ if (/^[;&|()\n]$/.test(raw)) {
+ if (substitution || isValidationCommand(words, depth)) return end;
+ words = [];
+ redirectTarget = false;
+ if (raw === "\n") {
+ for (const { delimiter, stripTabs } of heredocs.splice(0)) {
+ while (index < command.length) {
+ const newline = command.indexOf("\n", index);
+ const lineEnd = newline === -1 ? command.length : newline;
+ const line = command.slice(index, lineEnd);
+ index = lineEnd + 1;
+ if ((stripTabs ? line.replace(/^\t+/, "") : line) === delimiter)
+ break;
+ }
+ }
+ }
+ } else if (/^\d*[<>]/.test(raw)) {
+ if (/^\d*<<-?$/.test(raw)) heredoc = raw.endsWith("-");
+ redirectTarget = !raw.includes("&");
+ } else if (heredoc !== undefined) {
+ heredocs.push({ delimiter: unquote(raw), stripTabs: heredoc });
+ heredoc = undefined;
+ redirectTarget = false;
+ } else if (redirectTarget) {
+ substitution ||= hasValidationSubstitution(raw, depth);
+ if (substitution) end = next;
+ redirectTarget = false;
+ } else {
+ const word = unquote(raw);
+ words.push(word);
+ substitution ||= hasValidationSubstitution(raw, depth);
+ end = next;
+ }
+ }
+ return undefined;
+}
export const VALIDATION_LOCK_PREFIX = [
"exec {__posthog_validation_lock_fd}>/tmp/posthog-memory-validation.lock",
@@ -14,12 +287,8 @@ export function validationCommandKey(command: string): string | undefined {
const original = command.startsWith(VALIDATION_LOCK_PREFIX)
? command.slice(VALIDATION_LOCK_PREFIX.length)
: command;
- const validation = VALIDATION_COMMAND.exec(original);
- if (!validation) return undefined;
- return (
- original.slice(0, validation.index) +
- validation[0].replace(/\s+\d*>{1,2}.*$/, "")
- ).trim();
+ const end = validationCommandEnd(original);
+ return end === undefined ? undefined : original.slice(0, end).trim();
}
export function serializeValidation(command: string): string {