: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): add codex watchdog feedback and bound unchanged retries (#113685)
posthog[bot]e965d374ddb0
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 65ed43623fde..eed4b0b30db7 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -335,13 +335,15 @@ cd services/mcp && cp .env.example .envThen fill in the secrets. `POSTHOG_UI_APPS_TOKEN` and `POSTHOG_ANALYTICS_API_KEY` are public PostHog `phc_*` project keys — for local dev you can paste the same key you use for analytics, or leave them as the placeholder (analytics calls will no-op). Restart the `mcp` phrocs process after changing `.env`.-### Memory pressure during Claude validation+### Memory pressure during agent validationThe memory watchdog stops tool process trees before the sandbox reaches its memory limit. A process stop, including SIGKILL escalation, does not mean the task run died.-Cloud Claude sessions deliver each watchdog warning separately to subagents and their parent. Shell results with exit codes 137, 143, or 144 wait briefly for the watchdog's delayed record; an exit code alone is not treated as proof of an OOM.+Cloud Claude and Codex sessions deliver each watchdog warning separately to subagents and their parent. Codex uses native MCP tool hooks for shell calls, including the final result of an `exec_command` completed through `write_stdin`. Claude shell results with exit codes 137, 143, or 144 wait briefly for the watchdog's delayed record; an exit code alone is not treated as proof of an OOM. Codex hook payloads carry the command output without its exit status, so a Codex command counts as stopped when a kill record lands between its start and shortly after its end. A quick rerun of a long Codex command waits for that record before it starts.-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.+Codex trusts only the PostHog memory hooks through session configuration. It does not store hook trust in the user's config file. The local tools MCP server opts out of Codex's tool catalog cache, so a subagent thread starts it before its first shell command instead of lazily on its first MCP tool call. Codex hook payloads do not include an `exec_command` `workdir`, so a Codex retry count is keyed by the thread directory and the command text. Put `cd <directory> &&` in the command to scope a retry count to a directory.++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 shell command fails twice during observed watchdog interventions, the session rejects another unchanged attempt. This retry limit applies to every command, not only validation. Codex includes final background results in this limit. Claude background-result tools deliver warnings but lack the command text needed to count retries. Reduce the command's scope or concurrency, or report the memory limit. Validation recognition is best-effort and controls only the lock. It is 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.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.tsindex f05add0d6730..7ce5496903d0 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@@ -8,11 +8,15 @@ import type {import { afterEach, beforeEach, describe, expect, it } from "vitest";import { MemoryWatchdogKillReader } from "../../../server/memory-watchdog";import { Logger } from "../../../utils/logger";-import { createMemoryKillNoticeHook } from "./memory-kill-hook";+import {+ createMemoryKillNoticeHook,+ type MemoryKillNoticeHookOptions,+} from "./memory-kill-hook";import { VALIDATION_LOCK_PREFIX } from "./memory-validation";const GIB = 1024 ** 3;const STARTED_AT_SECONDS = 1_800_000_000;+const STARTED_AT_MS = STARTED_AT_SECONDS * 1000;function killRecord(pid: number, ts: number): string {return JSON.stringify({@@ -31,6 +35,7 @@ function shellInput(hookEventName: "PostToolUse" | "PostToolUseFailure",toolName = "Bash",error = "Exit code 137",+ toolUseId = "toolu_1",): PostToolUseHookInput | PostToolUseFailureHookInput {const input = {session_id: "s",@@ -38,7 +43,7 @@ function shellInput(cwd: "/tmp",tool_name: toolName,tool_input: { command: "pnpm test" },- tool_use_id: "toolu_1",+ tool_use_id: toolUseId,};return hookEventName === "PostToolUse"? { ...input, hook_event_name: hookEventName, tool_response: "" }@@ -52,10 +57,16 @@ type HookOutput = {describe("createMemoryKillNoticeHook", () => {let dir: string;let path: string;+ let nowMs: number;+ const clock: Pick<MemoryKillNoticeHookOptions, "startedAtMs" | "now"> = {+ startedAtMs: STARTED_AT_MS,+ now: () => nowMs,+ };beforeEach(async () => {dir = await mkdtemp(join(tmpdir(), "memory-kill-hook-"));path = join(dir, "events.jsonl");+ nowMs = STARTED_AT_MS;});afterEach(async () => {@@ -74,8 +85,8 @@ describe("createMemoryKillNoticeHook", () => {`${killRecord(7, STARTED_AT_SECONDS - 60)}\n${killRecord(8, STARTED_AT_SECONDS + 5)}\n`,);const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,reader: new MemoryWatchdogKillReader(path),- startedAtMs: STARTED_AT_SECONDS * 1000,killRecordWaitMs: 0,});const opts = { signal: new AbortController().signal };@@ -86,7 +97,7 @@ describe("createMemoryKillNoticeHook", () => {opts,)) as HookOutput;const second = await hook(- shellInput(hookEventName, toolName),+ shellInput(hookEventName, toolName, "Exit code 137", "toolu_2"),"toolu_2",opts,);@@ -116,8 +127,8 @@ describe("createMemoryKillNoticeHook", () => {return kills;};const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,reader,- startedAtMs: STARTED_AT_SECONDS * 1000,killRecordWaitMs: 60_000,killRecordPollMs: 1,});@@ -132,11 +143,51 @@ describe("createMemoryKillNoticeHook", () => {},);+ it("waits at the next attempt for the record of a run whose exit status is unknown", async () => {+ await writeFile(path, "");+ const reader = new MemoryWatchdogKillReader(path);+ const read = reader.readNewKills.bind(reader);+ let reads = 0;+ reader.readNewKills = async () => {+ const kills = await read();+ reads += 1;+ if (reads === 3) {+ await appendFile(path, `${killRecord(8, STARTED_AT_SECONDS + 12)}\n`);+ }+ return kills;+ };+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,+ reader,+ exitStatusInToolResponse: false,+ killRecordWaitMs: 60_000,+ killRecordPollMs: 1,+ });+ const opts = { signal: new AbortController().signal };+ const pre = {+ ...shellInput("PostToolUse"),+ hook_event_name: "PreToolUse" as const,+ };+ await hook(pre, "toolu_1", opts);+ nowMs += 10_000;+ await hook(shellInput("PostToolUse", "Bash", ""), "toolu_1", opts);+ nowMs += 1_000;++ const retry = (await hook(+ { ...pre, tool_use_id: "toolu_2" },+ "toolu_2",+ opts,+ )) as HookOutput;++ expect(retry.hookSpecificOutput?.additionalContext).toContain("(pid 8)");+ expect(reads).toBeGreaterThanOrEqual(4);+ });+it("retains a kill for each worker and the parent after another shell reads it", async () => {await writeFile(path, `${killRecord(8, STARTED_AT_SECONDS + 5)}\n`);const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,reader: new MemoryWatchdogKillReader(path),- startedAtMs: STARTED_AT_SECONDS * 1000,killRecordWaitMs: 0,});const opts = { signal: new AbortController().signal };@@ -178,8 +229,8 @@ describe("createMemoryKillNoticeHook", () => {async (command, smallerCommand) => {await writeFile(path, "");const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,reader: new MemoryWatchdogKillReader(path),- startedAtMs: STARTED_AT_SECONDS * 1000,killRecordWaitMs: 0,});const opts = { signal: new AbortController().signal };@@ -194,6 +245,7 @@ describe("createMemoryKillNoticeHook", () => {},});for (const pid of [8, 9]) {+ nowMs = STARTED_AT_MS + pid * 1000;await appendFile(path,`${killRecord(pid, STARTED_AT_SECONDS + pid)}\n`,@@ -201,6 +253,7 @@ describe("createMemoryKillNoticeHook", () => {const failure = {...shellInput("PostToolUseFailure", "Bash", "Exit code 144"),tool_input: { command: `${VALIDATION_LOCK_PREFIX}${command}` },+ tool_use_id: `toolu_${pid}`,};await hook(failure, `toolu_${pid}`, opts);if (pid === 8) {@@ -208,6 +261,7 @@ describe("createMemoryKillNoticeHook", () => {{...failure,agent_id: "another-worker",+ tool_use_id: "toolu_worker",},"toolu_worker",opts,@@ -252,4 +306,63 @@ describe("createMemoryKillNoticeHook", () => {}},);++ it("denies a third unchanged run of any command the watchdog stopped twice", async () => {+ await writeFile(path, "");+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ ...clock,+ reader: new MemoryWatchdogKillReader(path),+ killRecordWaitMs: 0,+ });+ const opts = { signal: new AbortController().signal };+ const command = "npx next build";+ const pre = {+ ...shellInput("PostToolUse"),+ hook_event_name: "PreToolUse" as const,+ tool_input: { command },+ };+ expect(await hook(pre, "toolu_1", opts)).toEqual({ continue: true });+ for (const pid of [8, 9]) {+ nowMs = STARTED_AT_MS + pid * 1000;+ await appendFile(path, `${killRecord(pid, STARTED_AT_SECONDS + pid)}\n`);+ if (pid === 8) {+ // A parallel unrelated result in the same agent reads the record first.+ const sibling = (await hook(+ {+ ...shellInput("PostToolUse", "Bash", "", "toolu_ls"),+ tool_input: { command: "ls" },+ },+ "toolu_ls",+ opts,+ )) as HookOutput;+ expect(sibling.hookSpecificOutput?.additionalContext).toContain(+ "(pid 8)",+ );+ }+ await hook(+ {+ ...shellInput("PostToolUseFailure", "Bash", "Exit code 143"),+ tool_input: { command },+ tool_use_id: `toolu_${pid}`,+ },+ `toolu_${pid}`,+ opts,+ );+ }+ expect(await hook(pre, "toolu_3", opts)).toMatchObject({+ hookSpecificOutput: { permissionDecision: "deny" },+ });+ expect(+ await hook(+ {+ ...pre,+ tool_input: {+ command: "NODE_OPTIONS=--max-old-space-size=2048 npx next build",+ },+ },+ "toolu_4",+ opts,+ ),+ ).toEqual({ continue: true });+ });});diff --git a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.tsindex d4b6fab38f08..278cf3659536 100644--- a/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts+++ b/packages/agent/packages/agent/src/adapters/claude/session/memory-kill-hook.ts@@ -13,12 +13,24 @@ const BYTES_PER_GIB = 1024 ** 3;// BashOutput and TaskOutput return the result of a background Bash command,// which the watchdog can stop after the Bash call itself has returned.const SHELL_RESULT_TOOLS = new Set(["Bash", "BashOutput", "TaskOutput"]);-const SIGNAL_EXIT_PATTERN = /exit[ _]?code"?\s*:?\s*(137|143|144)\b/i;+const SIGNAL_EXIT_PATTERN =+ /(?:exit[ _]?code"?\s*:?\s*|exited with code\s+)(137|143|144)\b/i;// The watchdog writes the kill record only after the process tree is gone// and memory is below the trigger. That takes up to two grace periods of// 2 seconds each, so the record can arrive after the shell has exited.const KILL_RECORD_WAIT_MS = 5_000;const KILL_RECORD_POLL_MS = 250;+// A kill belongs to a command when the record's timestamp falls between the+// command's start and the record delay after its end. The lead covers clock+// jitter when a command's start is only known from its result.+const KILL_RECORD_DELAY_MS = 6_000;+const KILL_RECORD_LEAD_MS = 1_000;+// A command that ran shorter than this cannot have been the memory-heavy one,+// so a fast rerun of it does not wait for a trailing kill record.+const MIN_STOPPABLE_RUN_MS = 2_000;+const RUN_RETENTION_MS = 60_000;+const MAX_RUNS = 200;+const MAX_KILLS = 100;function formatGib(bytes: number): string {return `${(bytes / BYTES_PER_GIB).toFixed(1)} GiB`;@@ -36,7 +48,7 @@ export function formatMemoryKillNotice(kills: ProcessKilledParams[]): string {...lines,"","This notice describes memory pressure shared by every agent in the sandbox; it does not identify which tool call was stopped.",- "Do not rerun a stopped validation command unchanged.",+ "Do not rerun a stopped command unchanged.","Run a smaller command instead: fewer test files, fewer parallel workers, or one package at a time.","Coordinate with the parent and other agents: run only one memory-heavy build, test suite, or typecheck at a time across all worktrees. Do not start another copy in the background.",].join("\n");@@ -47,6 +59,19 @@ export interface MemoryKillNoticeHookOptions {startedAtMs?: number;killRecordWaitMs?: number;killRecordPollMs?: number;+ // Codex hook payloads carry the command output without its exit status, so+ // a stopped command is recognized only by a kill record near its end.+ exitStatusInToolResponse?: boolean;+ now?: () => number;+}++interface CommandRun {+ retryKey: string;+ startedAtMs: number;+ endedAtMs?: number;+ // Undefined when the payload cannot show the exit status.+ endedBySignal?: boolean;+ stopped: boolean;}function endedBySignal(input: HookInput): boolean {@@ -60,6 +85,17 @@ function endedBySignal(input: HookInput): boolean {return SIGNAL_EXIT_PATTERN.test(text ?? "");}+function killId(kill: ProcessKilledParams): string {+ return `${kill.at}:${kill.pid}`;+}++function denyReason(validation: string | undefined): string {+ const scope = validation+ ? "This validation command has failed repeatedly during watchdog memory interventions. Do not retry it unchanged. Reduce its scope or worker count, or report that validation could not complete within the sandbox memory limit."+ : "The sandbox memory watchdog stopped this command twice. Do not retry it unchanged. Reduce its memory use, scope, or worker count, or report that it could not complete within the sandbox memory limit.";+ return `${scope} To run it in a different directory, start the command with \`cd <directory> &&\`.`;+}+// The Bash tool only sees an exit code when the watchdog stops its process// tree, so without this notice the agent reruns the same command.export const createMemoryKillNoticeHook = (@@ -69,19 +105,101 @@ export const createMemoryKillNoticeHook = (startedAtMs = Date.now(),killRecordWaitMs = KILL_RECORD_WAIT_MS,killRecordPollMs = KILL_RECORD_POLL_MS,+ exitStatusInToolResponse = true,+ now = Date.now,}: MemoryKillNoticeHookOptions = {},): HookCallback => {const killsById = new Map<string, ProcessKilledParams>();const delivered = new Map<string, Set<string>>();- const stoppedCommands = new Map<- string,- { failures: number; killIds: Set<string> }- >();+ const runs = new Map<string, CommandRun>();+ const failures = new Map<string, { count: number; killIds: Set<string> }>();+const readKills = async (): Promise<ProcessKilledParams[]> =>(await reader.readNewKills()).filter((kill) => Date.parse(kill.at) >= startedAtMs,);+ const stoppedBy = (run: CommandRun, kill: ProcessKilledParams): boolean => {+ if (run.endedAtMs === undefined || run.endedBySignal === false)+ return false;+ const killAtMs = Date.parse(kill.at);+ return (+ killAtMs >= run.startedAtMs - KILL_RECORD_LEAD_MS &&+ killAtMs <= run.endedAtMs + KILL_RECORD_DELAY_MS+ );+ };++ // Retry counting must not depend on which agent read a kill first: with+ // parallel tool calls, an unrelated result can read the record before the+ // stopped command's own result arrives.+ const attributeKills = (): void => {+ for (const run of runs.values()) {+ if (run.stopped) continue;+ const ids = [...killsById.values()]+ .filter((kill) => stoppedBy(run, kill))+ .map(killId);+ if (ids.length === 0) continue;+ run.stopped = true;+ const interventions = failures.get(run.retryKey) ?? {+ count: 0,+ killIds: new Set<string>(),+ };+ // One intervention counts once, however many runs of the key it ended.+ if (ids.some((id) => !interventions.killIds.has(id))) {+ interventions.count += 1;+ }+ for (const id of ids) interventions.killIds.add(id);+ failures.set(run.retryKey, interventions);+ }+ };++ const pruneRuns = (): void => {+ const cutoff = now() - RUN_RETENTION_MS;+ for (const [id, run] of runs) {+ if (run.endedAtMs !== undefined && run.endedAtMs < cutoff)+ runs.delete(id);+ }+ while (runs.size > MAX_RUNS) {+ const oldest = runs.keys().next().value;+ if (oldest === undefined) break;+ runs.delete(oldest);+ }+ };++ const refreshKills = async (): Promise<void> => {+ for (const kill of await readKills()) killsById.set(killId(kill), kill);+ while (killsById.size > MAX_KILLS) {+ const oldest = killsById.keys().next().value;+ if (oldest === undefined) break;+ killsById.delete(oldest);+ for (const consumerSeen of delivered.values())+ consumerSeen.delete(oldest);+ }+ pruneRuns();+ attributeKills();+ };++ const pollUntil = async (+ done: () => boolean,+ deadlineMs: number,+ signal: AbortSignal,+ ): Promise<void> => {+ while (!done() && now() < deadlineMs && !signal.aborted) {+ await sleep(killRecordPollMs);+ await refreshKills();+ }+ };++ const latestRun = (retryKey: string): CommandRun | undefined => {+ let latest: CommandRun | undefined;+ for (const run of runs.values()) {+ if (run.retryKey !== retryKey || run.endedAtMs === undefined) continue;+ if (latest?.endedAtMs === undefined || run.endedAtMs > latest.endedAtMs)+ latest = run;+ }+ return latest;+ };+return async (input: HookInput,toolUseId,@@ -105,61 +223,107 @@ export const createMemoryKillNoticeHook = (const command =typeof toolInput?.command === "string" ? toolInput.command : undefined;const validation = command && validationCommandKey(command);- const validationKey = validation && JSON.stringify([input.cwd, validation]);+ const retryKey =+ input.tool_name === "Bash" && command+ ? JSON.stringify([input.cwd, validation || command.trim()])+ : undefined;+ const runId = input.tool_use_id || toolUseId;++ const consumer = input.agent_id ?? input.session_id;+ const seen = delivered.get(consumer) ?? new Set<string>();+ delivered.set(consumer, seen);+ // Every worker needs the warning; a fast unrelated shell must not consume it.+ const takeUnseenKills = (): ProcessKilledParams[] => {+ const kills = [...killsById.values()].filter(+ (kill) => !seen.has(killId(kill)),+ );+ for (const kill of kills) seen.add(killId(kill));+ return kills;+ };+if (input.hook_event_name === "PreToolUse") {- if (input.tool_name !== "Bash" || !validationKey || !command)+ if (!retryKey || !command) return { continue: true };+ try {+ await refreshKills();+ const previous = latestRun(retryKey);+ if (+ !exitStatusInToolResponse &&+ previous?.endedAtMs !== undefined &&+ !previous.stopped &&+ previous.endedAtMs - previous.startedAtMs >= MIN_STOPPABLE_RUN_MS+ ) {+ await pollUntil(+ () => previous.stopped,+ previous.endedAtMs + killRecordWaitMs,+ signal,+ );+ }+ } catch (error) {+ logger.debug("Memory watchdog events read failed", {+ error: error instanceof Error ? error.message : String(error),+ });return { continue: true };- if ((stoppedCommands.get(validationKey)?.failures ?? 0) >= 2) {+ }+ if ((failures.get(retryKey)?.count ?? 0) >= 2) {return {continue: true,hookSpecificOutput: {hookEventName: "PreToolUse",permissionDecision: "deny",- permissionDecisionReason:- "This validation command has failed repeatedly during watchdog memory interventions. Do not retry it unchanged. Reduce its scope or worker count, or report that validation could not complete within the sandbox memory limit.",+ permissionDecisionReason: denyReason(validation || undefined),},};}+ if (runId) {+ runs.set(runId, { retryKey, startedAtMs: now(), stopped: false });+ }+ const kills = takeUnseenKills();+ if (!validation && kills.length === 0) return { continue: true };return {continue: true,hookSpecificOutput: {hookEventName: "PreToolUse",- updatedInput: { ...toolInput, command: serializeValidation(command) },+ ...(validation+ ? {+ updatedInput: {+ ...toolInput,+ command: serializeValidation(command),+ },+ }+ : {}),+ ...(kills.length > 0+ ? { additionalContext: formatMemoryKillNotice(kills) }+ : {}),},};}- const consumer = input.agent_id ?? input.session_id;- const seen = delivered.get(consumer) ?? new Set<string>();- delivered.set(consumer, seen);-- const pendingKills = async (): Promise<ProcessKilledParams[]> => {- for (const kill of await readKills()) {- killsById.set(`${kill.at}:${kill.pid}`, kill);- }- while (killsById.size > 100) {- const oldest = killsById.keys().next().value;- if (oldest === undefined) break;- killsById.delete(oldest);- for (const consumerSeen of delivered.values())- consumerSeen.delete(oldest);- }- // Every worker needs the warning; a fast unrelated shell must not consume it.- return [...killsById]- .filter(([id]) => !seen.has(id))- .map(([, kill]) => kill);- };+ let run: CommandRun | undefined;+ if (retryKey && runId) {+ run = runs.get(runId) ?? { retryKey, startedAtMs: now(), stopped: false };+ run.endedAtMs = now();+ run.endedBySignal = exitStatusInToolResponse+ ? endedBySignal(input)+ : undefined;+ runs.set(runId, run);+ }+ const hasUnseenKills = (): boolean =>+ [...killsById.keys()].some((id) => !seen.has(id));let kills: ProcessKilledParams[];try {- kills = await pendingKills();- if (kills.length === 0 && endedBySignal(input)) {- const deadline = Date.now() + killRecordWaitMs;- while (kills.length === 0 && Date.now() < deadline && !signal.aborted) {- await sleep(killRecordPollMs);- kills = await pendingKills();- }+ await refreshKills();+ const waitForRecord = run+ ? run.endedBySignal === true && !run.stopped+ : endedBySignal(input) && !hasUnseenKills();+ if (waitForRecord) {+ await pollUntil(+ () => (run ? run.stopped : hasUnseenKills()),+ now() + killRecordWaitMs,+ signal,+ );}+ kills = takeUnseenKills();} catch (error) {logger.debug("Memory watchdog events read failed", {error: error instanceof Error ? error.message : String(error),@@ -168,19 +332,6 @@ export const createMemoryKillNoticeHook = (}if (kills.length === 0) return { continue: true };- for (const kill of kills) seen.add(`${kill.at}:${kill.pid}`);- if (validationKey && endedBySignal(input)) {- const interventions = stoppedCommands.get(validationKey) ?? {- failures: 0,- killIds: new Set<string>(),- };- const ids = kills.map((kill) => `${kill.at}:${kill.pid}`);- if (ids.some((id) => !interventions.killIds.has(id))) {- interventions.failures += 1;- for (const id of ids) interventions.killIds.add(id);- }- stoppedCommands.set(validationKey, interventions);- }logger.info("Memory watchdog feedback delivered to hook", {agentId: input.agent_id ?? null,toolUseId,diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.tsindex ca6922552c51..fcb2c60a4a65 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.test.ts@@ -9,7 +9,7 @@ import type {PromptRequest,} from "@agentclientprotocol/sdk";import { RequestError } from "@agentclientprotocol/sdk";-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type {AppServerClientHandlers,AppServerRpc,@@ -21,6 +21,11 @@ import {} from "./codex-app-server-agent";import { sandboxPolicyFor } from "./session-config";+vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof fs>();+ return { ...actual, existsSync: vi.fn(actual.existsSync) };+});+// Required-field invariants the native codex app-server enforces on each request.const REQUIRED_FIELDS: Record<string, string[]> = {"thread/goal/clear": ["threadId"],@@ -40,6 +45,11 @@ function requiredFieldMissing();}+afterEach(() => {+ vi.unstubAllEnvs();+ vi.mocked(fs.existsSync).mockReset();+});+function makeStubRpc(responses: Record<string, unknown>) {let handlers: AppServerClientHandlers | undefined;const requests: Array<{ method: string; params?: unknown }> = [];@@ -5338,7 +5348,33 @@ describe("CodexAppServerAgent", () => {});it("refresh_session rebinds mcp_servers on the live thread, keeping local tools", async () => {+ vi.stubEnv("POSTHOG_TASK_RUN_ID", "run-1");+ const actualFs = await vi.importActual<typeof fs>("node:fs");+ vi.mocked(fs.existsSync).mockImplementation(+ (path) =>+ String(path).endsWith(+ "/adapters/codex-app-server/local-tools-mcp-server.js",+ ) || actualFs.existsSync(path),+ );const stub = makeStubRpc({+ "hooks/list": {+ data: [+ {+ hooks: [+ {+ key: "session:pre_tool_use:0:0",+ currentHash: "memory-hash",+ source: "sessionFlags",+ eventName: "preToolUse",+ matcher: "Bash|Agent",+ handlerType: "mcpTool",+ server: "posthog-code-tools",+ tool: "sandbox_memory_hook",+ },+ ],+ },+ ],+ },"thread/start": { thread: { id: "t" } },"thread/resume": { thread: { id: "t" } },});@@ -5378,6 +5414,17 @@ describe("CodexAppServerAgent", () => {)?.config?.mcp_servers ?? {};const resume = stub.requests.find((r) => r.method === "thread/resume");expect(resume?.params).toMatchObject({ threadId: "t" });+ for (const method of ["thread/start", "thread/resume"]) {+ expect(+ stub.requests.find((r) => r.method === method)?.params,+ ).toMatchObject({+ config: {+ "hooks.state": {+ "session:pre_tool_use:0:0": { trusted_hash: "memory-hash" },+ },+ },+ });+ }expect(mcpServersFor("thread/resume").posthog).toMatchObject({http_headers: { Authorization: "Bearer fresh" },});diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.tsindex 8d66c5344b5c..8ed88e74dcfa 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/codex-app-server-agent.ts@@ -49,6 +49,7 @@ import {} from "../../acp-extensions";import type { ModelInfo } from "../../gateway-models";import { DEFAULT_CODEX_MODEL } from "../../gateway-models";+import { isTaskRunSandbox } from "../../server/memory-watchdog";import type { ProcessSpawnedCallback } from "../../types";import { ALLOW_BYPASS } from "../../utils/common";import { Logger } from "../../utils/logger";@@ -92,6 +93,7 @@ import {} from "./mapping";import { toCodexMcpServers } from "./mcp-config";import { McpManager } from "./mcp-manager";+import { getMemoryKillHookTrust } from "./memory-kill-hook";import {APP_SERVER_METHODS,APP_SERVER_NOTIFICATIONS,@@ -579,6 +581,9 @@ export class CodexAppServerAgent extends BaseAcpAgent {{ gatePosthogExec: true },);const config = buildThreadConfig(mcpServers, this.additionalDirectories);+ if (config && localTools && cwd && isTaskRunSandbox(process.env)) {+ config["hooks.state"] = await getMemoryKillHookTrust(this.rpc, cwd);+ }const developerInstructions = this.threadSetup?.developerInstructions;await this.rpc.request(APP_SERVER_METHODS.THREAD_RESUME, {@@ -723,6 +728,12 @@ export class CodexAppServerAgent extends BaseAcpAgent {},);const config = buildThreadConfig(mcpServers, params.additionalDirectories);+ if (config && localTools && params.cwd && isTaskRunSandbox(process.env)) {+ config["hooks.state"] = await getMemoryKillHookTrust(+ this.rpc,+ params.cwd,+ );+ }const result = await this.rpc.request<{ thread?: AppServerThread }>(method,diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.tsindex 8c4c581da1b7..3a577b2cf711 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp-server.ts@@ -20,6 +20,11 @@ import {LOCAL_TOOLS_MCP_NAME,type LocalToolCtx,} from "@posthog/harness/extensions/local-tools";+import {+ MEMORY_KILL_HOOK_SERVER_OPTIONS,+ MEMORY_KILL_HOOK_TOOL_NAME,+ registerMemoryKillHook,+} from "./memory-kill-hook";function die(message: string): never {process.stderr.write(`[local-tools-mcp-server] ${message}\n`);@@ -60,14 +65,20 @@ const enabledNames = (process.env.POSTHOG_LOCAL_TOOLS_ENABLED ?? "").split(",").filter(Boolean);const tools = LOCAL_TOOLS.filter((t) => enabledNames.includes(t.name));-if (tools.length === 0) {+const memoryHookEnabled = enabledNames.includes(MEMORY_KILL_HOOK_TOOL_NAME);+if (tools.length === 0 && !memoryHookEnabled) {die("POSTHOG_LOCAL_TOOLS_ENABLED listed no known tools");}-const server = new McpServer({- name: LOCAL_TOOLS_MCP_NAME,- version: "1.0.0",-});+const server = new McpServer(+ {+ name: LOCAL_TOOLS_MCP_NAME,+ version: "1.0.0",+ },+ memoryHookEnabled ? MEMORY_KILL_HOOK_SERVER_OPTIONS : undefined,+);++if (memoryHookEnabled) registerMemoryKillHook(server);for (const t of tools) {server.tool(t.name, t.description, t.schema, async (args) =>diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.tsindex cf5c0bbc73f3..a48fd8cedc3a 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.test.ts@@ -6,12 +6,24 @@ import { buildLocalToolsServer } from "./local-tools-mcp";// succeed; nothing spawns the script — we only inspect the path.vi.mock("node:fs", async (importActual) => {const actual = await importActual<typeof import("node:fs")>();- return { ...actual, existsSync: vi.fn().mockReturnValue(true) };+ return {+ ...actual,+ existsSync: vi.fn().mockReturnValue(true),+ readFileSync: (...args: Parameters<typeof actual.readFileSync>) => {+ if (args[0] === "/tmp/agent-github-env") {+ throw Object.assign(new Error("No sandbox credentials in tests"), {+ code: "ENOENT",+ });+ }+ return actual.readFileSync(...args);+ },+ };});describe("buildLocalToolsServer", () => {const saved = {sandbox: process.env.IS_SANDBOX,+ taskRunId: process.env.POSTHOG_TASK_RUN_ID,ghToken: process.env.GH_TOKEN,githubToken: process.env.GITHUB_TOKEN,};@@ -20,12 +32,14 @@ describe("buildLocalToolsServer", () => {// The signed-git gate reads IS_SANDBOX and the token vars; clear them so each// case controls the cloud signal (meta.environment) and token explicitly.delete process.env.IS_SANDBOX;+ delete process.env.POSTHOG_TASK_RUN_ID;delete process.env.GH_TOKEN;delete process.env.GITHUB_TOKEN;});afterEach(() => {restore("IS_SANDBOX", saved.sandbox);+ restore("POSTHOG_TASK_RUN_ID", saved.taskRunId);restore("GH_TOKEN", saved.ghToken);restore("GITHUB_TOKEN", saved.githubToken);});@@ -85,6 +99,7 @@ describe("buildLocalToolsServer", () => {});it("returns a server but omits token env vars when no token is present", () => {+ process.env.POSTHOG_TASK_RUN_ID = "run-1";const server = buildLocalToolsServer({ cwd: "/repo" },{ environment: "cloud" },@@ -95,6 +110,11 @@ describe("buildLocalToolsServer", () => {expect(envNames).toContain("POSTHOG_LOCAL_TOOLS_CTX");expect(envNames).not.toContain("GH_TOKEN");expect(envNames).not.toContain("GITHUB_TOKEN");+ expect(+ server?.env+ .find((entry) => entry.name === "POSTHOG_LOCAL_TOOLS_ENABLED")+ ?.value.split(","),+ ).toContain("sandbox_memory_hook");});it("returns null when no cwd is present", () => {@@ -121,6 +141,7 @@ describe("buildLocalToolsServer", () => {expect(names).toContain("speak");// Signed-git tools are cloud-only and must not leak into a desktop run.expect(names).not.toContain("git_signed_commit");+ expect(names).not.toContain("sandbox_memory_hook");});it("still exposes show_actions on a desktop run with narration off", () => {diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.tsindex e7fb74046bc2..70afcfd64142 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/local-tools-mcp.ts@@ -14,8 +14,10 @@ import {type LocalToolGateMeta,resolveGithubToken,} from "@posthog/harness/extensions/local-tools";+import { isTaskRunSandbox } from "../../server/memory-watchdog";import { resolveBundledMcpScript } from "../../utils/resolve-bundled-script";import { resolveTaskId } from "../session-meta";+import { MEMORY_KILL_HOOK_TOOL_NAME } from "./memory-kill-hook";/*** Gate inputs the local-tools server needs beyond `LocalToolGateMeta`: the task id@@ -82,12 +84,10 @@ export function buildLocalToolsServer(taskRunId: meta?.taskRunId,baseBranch: meta?.baseBranch,};- const tools = enabledLocalTools(toolCtx, meta);- if (tools.length === 0) {+ const names = enabledLocalTools(toolCtx, meta).map((tool) => tool.name);+ if (isTaskRunSandbox(process.env)) names.push(MEMORY_KILL_HOOK_TOOL_NAME);+ if (names.length === 0) {return null;}- return toMcpServerStdio(- toolCtx,- tools.map((t) => t.name),- );+ return toMcpServerStdio(toolCtx, names);}diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.test.tsnew file mode 100644index 000000000000..c7839b99c02f--- /dev/null+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.test.ts@@ -0,0 +1,187 @@+import { appendFile, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { SyncHookJSONOutput } from "@anthropic-ai/claude-agent-sdk";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { expect, it, vi } from "vitest";+import { MemoryWatchdogKillReader } from "../../server/memory-watchdog";+import {+ getMemoryKillHookTrust,+ MEMORY_KILL_HOOK_SERVER_OPTIONS,+ MEMORY_KILL_HOOK_TOOL_NAME,+ registerMemoryKillHook,+} from "./memory-kill-hook";++it("trusts only session memory hooks without trusting user hooks", async () => {+ const hook = {+ key: "session:pre_tool_use:0:0",+ currentHash: "memory-pre-hash",+ source: "sessionFlags",+ eventName: "preToolUse",+ matcher: "Bash|Agent",+ handlerType: "mcpTool",+ server: "posthog-code-tools",+ tool: MEMORY_KILL_HOOK_TOOL_NAME,+ };+ const request = vi.fn().mockResolvedValue({+ data: [+ {+ hooks: [+ hook,+ {+ ...hook,+ key: "session:post_tool_use:0:0",+ eventName: "postToolUse",+ currentHash: "memory-post-hash",+ },+ { ...hook, key: "user:pre_tool_use:0:0", source: "user" },+ { ...hook, key: "other-tool", tool: "other_tool" },+ { ...hook, key: "other-server", server: "other-server" },+ { ...hook, key: "other-event", eventName: "stop" },+ ],+ },+ ],+ });+ expect(await getMemoryKillHookTrust({ request }, "/tmp/project")).toEqual({+ "session:pre_tool_use:0:0": { trusted_hash: "memory-pre-hash" },+ "session:post_tool_use:0:0": { trusted_hash: "memory-post-hash" },+ });+});++it("delivers Codex memory feedback and blocks an unchanged command after two stops over MCP", async () => {+ const dir = await mkdtemp(join(tmpdir(), "codex-memory-hook-"));+ const path = join(dir, "events.jsonl");+ const startedAtSeconds = 1_800_000_000;+ let nowMs = startedAtSeconds * 1000;+ const server = new McpServer(+ { name: "test", version: "1.0.0" },+ MEMORY_KILL_HOOK_SERVER_OPTIONS,+ );+ const client = new Client({ name: "test", version: "1.0.0" });+ try {+ await writeFile(path, "");+ registerMemoryKillHook(server, {+ reader: new MemoryWatchdogKillReader(path),+ startedAtMs: nowMs,+ killRecordWaitMs: 0,+ now: () => nowMs,+ });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ expect(client.getServerCapabilities()?.experimental).toMatchObject({+ "codex/tool-catalog-cache": { cacheable: false },+ });++ async function callHook(+ event: "PreToolUse" | "PostToolUse",+ command: string,+ {+ sessionId = "parent",+ toolName = "Bash",+ toolUseId = "exec-1",+ toolResponse,+ }: {+ sessionId?: string;+ toolName?: string;+ toolUseId?: string;+ toolResponse?: unknown;+ } = {},+ ): Promise<SyncHookJSONOutput> {+ const result = await client.callTool({+ name: MEMORY_KILL_HOOK_TOOL_NAME,+ arguments: {+ session_id: sessionId,+ cwd: "/tmp/project",+ hook_event_name: event,+ tool_name: toolName,+ tool_input: { command },+ tool_use_id: toolUseId,+ ...(event === "PostToolUse" ? { tool_response: toolResponse } : {}),+ },+ });+ expect(result.isError).not.toBe(true);+ const content = result.content as { type: string; text: string }[];+ return JSON.parse(content[0].text) as SyncHookJSONOutput;+ }++ const command = "npx next build";+ // Codex forwards the command output without the exit status header.+ for (const pid of [7, 8]) {+ const toolUseId = `exec-${pid}`;+ nowMs = (startedAtSeconds + pid - 1) * 1000;+ expect(await callHook("PreToolUse", command, { toolUseId })).toEqual({+ continue: true,+ });+ nowMs = (startedAtSeconds + pid) * 1000 - 500;+ await appendFile(+ path,+ `${JSON.stringify({+ event: "kill",+ ts: startedAtSeconds + pid,+ pid,+ comm: "bash",+ tree_rss: 22 * 1024 ** 3,+ current: 27 * 1024 ** 3,+ limit: 32 * 1024 ** 3,+ signal: "SIGKILL",+ })}\n`,+ );+ const output = await callHook("PostToolUse", command, {+ toolUseId,+ toolResponse: "Building...\n",+ });+ expect(output.hookSpecificOutput).toMatchObject({+ hookEventName: "PostToolUse",+ additionalContext: expect.stringContaining(`(pid ${pid})`),+ });+ }+ expect(+ (await callHook("PreToolUse", command)).hookSpecificOutput,+ ).toMatchObject({+ hookEventName: "PreToolUse",+ permissionDecision: "deny",+ });+ expect(await callHook("PreToolUse", `${command} --help`)).toEqual({+ continue: true,+ });+ expect(+ (+ await callHook("PostToolUse", "echo done", {+ sessionId: "worker",+ toolResponse: "done\n",+ })+ ).hookSpecificOutput,+ ).toMatchObject({ additionalContext: expect.stringContaining("(pid 7)") });+ expect(+ await callHook("PostToolUse", "echo done", {+ sessionId: "worker",+ toolResponse: "done\n",+ }),+ ).toEqual({ continue: true });+ expect(+ (+ await callHook("PostToolUse", "", {+ sessionId: "spawner",+ toolName: "spawn_agent",+ toolResponse: { agent_id: "worker" },+ })+ ).hookSpecificOutput,+ ).toMatchObject({ additionalContext: expect.stringContaining("(pid 8)") });+ expect(+ (await callHook("PreToolUse", "pnpm test")).hookSpecificOutput,+ ).toMatchObject({+ hookEventName: "PreToolUse",+ updatedInput: {+ command: expect.stringContaining("flock"),+ },+ });+ } finally {+ await client.close();+ await server.close();+ await rm(dir, { recursive: true, force: true });+ }+});diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.tsnew file mode 100644index 000000000000..66a46657fa5f--- /dev/null+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/memory-kill-hook.ts@@ -0,0 +1,124 @@+import type { ServerOptions } from "@modelcontextprotocol/sdk/server/index.js";+import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { tomlBasicString } from "@posthog/agent-contracts";+import { LOCAL_TOOLS_MCP_NAME } from "@posthog/harness/extensions/local-tools";+import { z } from "zod";+import { Logger } from "../../utils/logger";+import {+ createMemoryKillNoticeHook,+ type MemoryKillNoticeHookOptions,+} from "../claude/session/memory-kill-hook";+import type { AppServerRpc } from "./app-server-client";++export const MEMORY_KILL_HOOK_TOOL_NAME = "sandbox_memory_hook";++// Codex starts a subagent's MCP server lazily when it has that server's tool+// catalog cached, and a hook call does not wait for the server to start. A+// subagent that only runs shell commands would then never reach this hook.+// Opting out of the catalog cache makes every thread start the server eagerly.+export const MEMORY_KILL_HOOK_SERVER_OPTIONS: ServerOptions = {+ capabilities: {+ experimental: { "codex/tool-catalog-cache": { cacheable: false } },+ },+};++// Codex serializes sub-agent spawns as `spawn_agent` and only accepts `Agent`+// as a matcher alias, while the shared hook keys on the Claude tool name.+const HOOK_TOOL_NAMES: Record<string, string> = { spawn_agent: "Agent" };++interface ListedMemoryHook {+ key: string;+ currentHash: string;+ source: string;+ eventName: string;+ matcher: string | null;+ handlerType: string;+ server?: string;+ tool?: string;+}++export async function getMemoryKillHookTrust(+ rpc: Pick<AppServerRpc, "request">,+ cwd: string,+): Promise<Record<string, { trusted_hash: string }>> {+ const result = await rpc.request<{+ data: { hooks: ListedMemoryHook[] }[];+ }>("hooks/list", { cwds: [cwd] });+ return Object.fromEntries(+ result.data.flatMap(({ hooks }) =>+ hooks+ .filter(+ (hook) =>+ hook.source === "sessionFlags" &&+ hook.handlerType === "mcpTool" &&+ hook.server === LOCAL_TOOLS_MCP_NAME &&+ hook.tool === MEMORY_KILL_HOOK_TOOL_NAME &&+ hook.matcher === "Bash|Agent" &&+ ["preToolUse", "postToolUse"].includes(hook.eventName),+ )+ .map((hook) => [hook.key, { trusted_hash: hook.currentHash }]),+ ),+ );+}++export function buildMemoryKillHooksConfig(): string {+ const fields = [+ "session_id",+ "cwd",+ "hook_event_name",+ "tool_name",+ "tool_input",+ "tool_use_id",+ ];+ const events = ["PreToolUse", "PostToolUse"].map((event) => {+ const inputFields =+ event === "PostToolUse" ? [...fields, "tool_response"] : fields;+ const input = inputFields+ .map((field) => `${field} = ${tomlBasicString(`\${${field}}`)}`)+ .join(", ");+ return `${event} = [{ matcher = "Bash|Agent", hooks = [{ type = "mcp_tool", server = ${tomlBasicString(LOCAL_TOOLS_MCP_NAME)}, tool = ${tomlBasicString(MEMORY_KILL_HOOK_TOOL_NAME)}, input = { ${input} }, timeout = 10 }] }]`;+ });+ return `hooks={ ${events.join(", ")} }`;+}++export function registerMemoryKillHook(+ server: McpServer,+ options: MemoryKillNoticeHookOptions = {},+): void {+ const hook = createMemoryKillNoticeHook(new Logger({ debug: false }), {+ exitStatusInToolResponse: false,+ ...options,+ });+ server.tool(+ MEMORY_KILL_HOOK_TOOL_NAME,+ "Internal sandbox memory feedback for Codex tool hooks.",+ {+ session_id: z.string(),+ cwd: z.string(),+ hook_event_name: z.enum(["PreToolUse", "PostToolUse"]),+ tool_name: z.string(),+ tool_input: z.record(z.string(), z.unknown()),+ tool_use_id: z.string(),+ tool_response: z.unknown().optional(),+ },+ async (input, extra) => {+ const base = {+ ...input,+ tool_name: HOOK_TOOL_NAMES[input.tool_name] ?? input.tool_name,+ transcript_path: "",+ };+ const result = await hook(+ input.hook_event_name === "PreToolUse"+ ? { ...base, hook_event_name: "PreToolUse" }+ : {+ ...base,+ hook_event_name: "PostToolUse",+ tool_response: input.tool_response,+ },+ input.tool_use_id,+ { signal: extra.signal },+ );+ return { content: [{ type: "text", text: JSON.stringify(result) }] };+ },+ );+}diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.test.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.test.tsindex fa54c380cc87..bbdbd2a18ca0 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.test.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.test.ts@@ -201,6 +201,32 @@ describe("buildAppServerArgs", () => {expect(buildAppServerArgs(options, {})).not.toContain(idleTimeoutArg);});+ it.each([{}, { IS_SANDBOX: "1" }, { POSTHOG_TASK_RUN_ID: "run-1" }])(+ "enables memory hooks only in task sandboxes (%j)",+ (environment) => {+ const args = buildAppServerArgs(+ { binaryPath: "/bundle/codex" },+ environment,+ );+ const hooks = args.filter((arg) => arg.startsWith("hooks="));+ expect(hooks).toHaveLength(1);+ if (environment.POSTHOG_TASK_RUN_ID) {+ expect(args).toContain("features.hooks=true");+ expect(hooks[0]).toContain('PreToolUse = [{ matcher = "Bash|Agent"');+ expect(hooks[0]).toContain('PostToolUse = [{ matcher = "Bash|Agent"');+ expect(hooks[0]).toContain('type = "mcp_tool"');+ expect(hooks[0]).toContain('server = "posthog-code-tools"');+ expect(hooks[0]).toContain('tool = "sandbox_memory_hook"');+ expect(hooks[0]).toContain(`tool_input = "\${tool_input}"`);+ expect(hooks[0]).toContain(`tool_response = "\${tool_response}"`);+ expect(hooks[0]).not.toContain("agent_id");+ } else {+ expect(hooks).toEqual(["hooks={}"]);+ expect(args).not.toContain("features.hooks=true");+ }+ },+ );+it("pins the cloud BASH_ENV into tool shells for secondary checkouts", () => {const args = buildAppServerArgs({ binaryPath: "/bundle/codex" },diff --git a/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.ts b/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.tsindex 769a51b5b573..8744260d0007 100644--- a/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.ts+++ b/packages/agent/packages/agent/src/adapters/codex-app-server/spawn.ts@@ -7,8 +7,10 @@ import {applyContextWikiEnv,type ContextWikiEnv,} from "@posthog/harness/extensions/context-wiki";+import { isTaskRunSandbox } from "../../server/memory-watchdog";import type { ProcessSpawnedCallback } from "../../types";import { Logger } from "../../utils/logger";+import { buildMemoryKillHooksConfig } from "./memory-kill-hook";export interface ChatgptAuthTokens {accessToken: string;@@ -167,7 +169,9 @@ export function buildAppServerArgs(// PostHog owns these integrations. Do not run user hooks or send task data// to telemetry exporters from the user's Codex config.args.push("-c", "mcp_servers={}");- args.push("-c", "hooks={}");+ const taskRunSandbox = isTaskRunSandbox(environment);+ if (taskRunSandbox) args.push("-c", "features.hooks=true");+ args.push("-c", taskRunSandbox ? buildMemoryKillHooksConfig() : "hooks={}");args.push("-c", "notify=[]");args.push("-c", `otel.exporter="none"`);args.push("-c", `otel.metrics_exporter="none"`);