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.

feat(tasks): write agent instructions into sandbox harness files (#109957)

Georgiy Tarasov8905168cc464
diff --git a/packages/agent/packages/agent-contracts/src/domain-types.ts b/packages/agent/packages/agent-contracts/src/domain-types.ts
index c0e40ecb593a..064e6a5699f3 100644
--- a/packages/agent/packages/agent-contracts/src/domain-types.ts
+++ b/packages/agent/packages/agent-contracts/src/domain-types.ts
@@ -357,6 +357,7 @@ const storeSkillStubSchema = z.object({
export type StoreSkillStub = z.infer<typeof storeSkillStubSchema>;
const taskRunStateFields = {
+ agent_instructions: optionalField(z.string()),
ai_agent_name: optionalField(z.string()),
ai_stage: optionalField(z.string()),
auto_publish: optionalField(z.boolean()),
diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.ts
index 5a640f5f7bc7..38529f09239c 100644
--- a/packages/agent/packages/agent/src/server/agent-server.ts
+++ b/packages/agent/packages/agent/src/server/agent-server.ts
@@ -36,7 +36,10 @@ import { appendRichOutputPrompt } from "@posthog/agent-contracts/rich-output-pro
import { execGh } from "@posthog/git/gh";
import { getCurrentBranch, getRemoteUrl } from "@posthog/git/queries";
import { ghTokenEnv } from "@posthog/git/signed-commit";
-import { appendRepositoryConventionsForCodex } from "@posthog/harness/extensions/agent-instructions";
+import {
+ AgentInstructionFiles,
+ appendRepositoryConventionsForCodex,
+} from "@posthog/harness/extensions/agent-instructions";
import {
appendBenjaminGuidance,
appendSte100Guidance,
@@ -570,6 +573,7 @@ export class AgentServer {
private prewarmedStartupTurnPending = false;
private storeSkillsInstalledCount = 0;
private storeSkillsActivationResolved = false;
+ private agentInstructions: string | null = null;
private autoPublishStateResolved = false;
private warmReasoningEffortResolved = false;
private installedSkillBundles = new Set<string>();
@@ -2201,6 +2205,11 @@ export class AgentServer {
payload.run_id,
runState ?? null,
);
+ // Before the adapter starts: Claude and Codex read these files when the session opens.
+ this.agentInstructions = await new AgentInstructionFiles(this.logger).sync(
+ runState ?? null,
+ { taskId: payload.task_id, runId: payload.run_id },
+ );
const runStateSystemPrompt =
claudeCodeConfigSchema.shape.systemPrompt.safeParse(
@@ -4519,6 +4528,17 @@ export class AgentServer {
buildStoreSkillsInstructions(this.storeSkillsInstalledCount).trim(),
);
}
+ const instructions = await new AgentInstructionFiles(this.logger).sync(
+ state ?? null,
+ { taskId, runId },
+ );
+ if (instructions && instructions !== this.agentInstructions) {
+ // The session read its instruction files at prewarm, before this user was known.
+ context.push(instructions);
+ }
+ if (state) {
+ this.agentInstructions = instructions;
+ }
}
const autoPublishUpgrade = this.resolveAutoPublishFromState(state);
if (autoPublishUpgrade) {
diff --git a/packages/agent/packages/agent/src/server/pi-agent-server.ts b/packages/agent/packages/agent/src/server/pi-agent-server.ts
index b0ae213afd3b..2a2589f88682 100644
--- a/packages/agent/packages/agent/src/server/pi-agent-server.ts
+++ b/packages/agent/packages/agent/src/server/pi-agent-server.ts
@@ -18,6 +18,7 @@ import {
} from "@posthog/agent-contracts";
import { buildPosthogPropertyHeaderRecord } from "@posthog/agent-contracts/posthog-property-headers";
import type { TaskContext } from "@posthog/agent-contracts/task-context";
+import { AgentInstructionFiles } from "@posthog/harness/extensions/agent-instructions";
import { resolveContextWikiPath } from "@posthog/harness/extensions/context-wiki";
import {
buildStoreSkillsInstructions,
@@ -613,6 +614,11 @@ export class PiAgentServer {
{ taskId: payload.task_id, runId: payload.run_id },
this.logger,
);
+ // Before the Pi child starts: it reads ~/.pi/agent/AGENTS.md when it loads its resources.
+ await new AgentInstructionFiles(this.logger).sync(runState, {
+ taskId: payload.task_id,
+ runId: payload.run_id,
+ });
const taskSnapshotKind = taskRun
? typeof runState?.snapshot_kind === "string"
? runState.snapshot_kind
diff --git a/packages/agent/packages/harness/src/extensions/agent-instructions/index.ts b/packages/agent/packages/harness/src/extensions/agent-instructions/index.ts
index 372e59097bd9..f5a824ec3ec3 100644
--- a/packages/agent/packages/harness/src/extensions/agent-instructions/index.ts
+++ b/packages/agent/packages/harness/src/extensions/agent-instructions/index.ts
@@ -1,3 +1,11 @@
+export {
+ AgentInstructionFiles,
+ type AgentInstructionFilesLogger,
+ type AgentInstructionFilesOptions,
+ type AgentInstructionFilesSyncContext,
+ applyInstructionsBlock,
+ getAgentInstructionFilePaths,
+} from "./instruction-files";
export {
appendRepositoryConventionsForCodex,
buildAppendedInstructions,
diff --git a/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.test.ts b/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.test.ts
new file mode 100644
index 000000000000..e92321acbe66
--- /dev/null
+++ b/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.test.ts
@@ -0,0 +1,108 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ AgentInstructionFiles,
+ applyInstructionsBlock,
+ getAgentInstructionFilePaths,
+} from "./instruction-files";
+
+const logger = { info: vi.fn(), warn: vi.fn() };
+const context = { taskId: "task", runId: "run" };
+
+describe("agent instruction files", () => {
+ const dirs: string[] = [];
+
+ afterEach(async () => {
+ await Promise.all(
+ dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })),
+ );
+ });
+
+ async function homeDir(): Promise<string> {
+ const dir = await mkdtemp(join(tmpdir(), "agent-instructions-"));
+ dirs.push(dir);
+ return dir;
+ }
+
+ it.each([
+ ["creates the block in a missing file", null, "Use pnpm.", true, null],
+ [
+ "keeps foreign content around a replaced block",
+ "# Image rules\n\n<!-- posthog -->\nold\n<!-- /posthog -->\n",
+ "Use pnpm.",
+ true,
+ "# Image rules",
+ ],
+ [
+ "removes only the block when instructions are cleared",
+ "# Image rules\n\n<!-- posthog -->\nold\n<!-- /posthog -->\n",
+ null,
+ false,
+ "# Image rules",
+ ],
+ ])("%s", (_name, existing, instructions, hasNew, keeps) => {
+ const next = applyInstructionsBlock(existing, instructions) ?? "";
+ expect(next.includes("Use pnpm.")).toBe(hasNew);
+ expect(next.includes("old")).toBe(false);
+ if (keeps) {
+ expect(next).toContain(keeps);
+ }
+ });
+
+ it.each([
+ ["plain text", "Use pnpm."],
+ ["text containing a marker", "Use pnpm.\n<!-- /posthog -->\nOpen drafts."],
+ [
+ "text that rebuilds a marker once the inner one is removed",
+ "Use pnpm.\n<!-- /pos<!-- /posthog -->thog -->\nOpen drafts.",
+ ],
+ ])("deletes a file that only held the block with %s", (_name, text) => {
+ const written = applyInstructionsBlock(null, text);
+ expect(applyInstructionsBlock(written, null)).toBeNull();
+ });
+
+ it("also writes ~/.claude when the server's Claude config dir differs", () => {
+ const paths = getAgentInstructionFilePaths({
+ home: "/home/agent",
+ claudeConfigDir: "/custom/claude",
+ codexHome: "/home/agent/.codex",
+ });
+ expect(paths).toContain("/custom/claude/CLAUDE.md");
+ expect(paths).toContain("/home/agent/.claude/CLAUDE.md");
+ });
+
+ it("writes every harness's file, then clears them when the key or the run state is gone", async () => {
+ const home = await homeDir();
+ const paths = getAgentInstructionFilePaths({
+ home,
+ claudeConfigDir: join(home, ".claude"),
+ codexHome: join(home, ".codex"),
+ });
+ expect(paths).toEqual([
+ join(home, ".claude", "CLAUDE.md"),
+ join(home, ".codex", "AGENTS.md"),
+ join(home, ".pi", "agent", "AGENTS.md"),
+ ]);
+ await mkdir(join(home, ".claude"), { recursive: true });
+ await writeFile(paths[0], "# Baked into the image\n");
+ const files = new AgentInstructionFiles(logger, paths);
+
+ await files.sync({ agent_instructions: "Use pnpm." }, context);
+ for (const path of paths) {
+ expect(await readFile(path, "utf-8")).toContain("Use pnpm.");
+ }
+
+ // A failed run fetch clears them too: a snapshot's block can belong to another person.
+ for (const state of [{}, null]) {
+ await files.sync({ agent_instructions: "Use pnpm." }, context);
+ expect(await files.sync(state, context)).toBeNull();
+ expect(await readFile(paths[0], "utf-8")).toBe(
+ "# Baked into the image\n",
+ );
+ await expect(readFile(paths[1], "utf-8")).rejects.toThrow("ENOENT");
+ await expect(readFile(paths[2], "utf-8")).rejects.toThrow("ENOENT");
+ }
+ });
+});
diff --git a/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.ts b/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.ts
new file mode 100644
index 000000000000..31d6e7de50ae
--- /dev/null
+++ b/packages/agent/packages/harness/src/extensions/agent-instructions/instruction-files.ts
@@ -0,0 +1,141 @@
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+import type { TaskRunState } from "@posthog/agent-contracts";
+
+// The sandbox image may ship these files, so only the text between the markers is ever replaced.
+const BLOCK_START = "<!-- posthog -->";
+const BLOCK_END = "<!-- /posthog -->";
+const BLOCK_RE = new RegExp(
+ `\\n*${escapeRegExp(BLOCK_START)}[\\s\\S]*?${escapeRegExp(BLOCK_END)}\\n*`,
+ "g",
+);
+
+export interface AgentInstructionFilesOptions {
+ home?: string;
+ claudeConfigDir?: string;
+ codexHome?: string;
+}
+
+// Pi's dir is fixed at ~/.pi/agent because the Pi host environment allowlist drops the variable that moves it.
+export function getAgentInstructionFilePaths(
+ options: AgentInstructionFilesOptions = {},
+): string[] {
+ const home = options.home ?? homedir();
+ // `||`, not `??`: the adapters treat an empty variable as unset, and so must this.
+ const claudeConfigDir =
+ options.claudeConfigDir ??
+ (process.env.CLAUDE_CONFIG_DIR || join(home, ".claude"));
+ const codexHome =
+ options.codexHome ?? (process.env.CODEX_HOME || join(home, ".codex"));
+ // Subscription auth launches the Claude child with CLAUDE_CONFIG_DIR=~/.claude whatever the
+ // server's own value is, so both directories get the file.
+ const claudeDirs = [...new Set([claudeConfigDir, join(home, ".claude")])];
+ return [
+ ...claudeDirs.map((dir) => join(dir, "CLAUDE.md")),
+ join(codexHome, "AGENTS.md"),
+ join(home, ".pi", "agent", "AGENTS.md"),
+ ];
+}
+
+// Returns null when nothing is left, which means the file must be deleted.
+export function applyInstructionsBlock(
+ existing: string | null,
+ instructions: string | null,
+): string | null {
+ const rest = (existing ?? "").replace(BLOCK_RE, "\n\n").trim();
+ if (!instructions) {
+ return rest ? `${rest}\n` : null;
+ }
+ // A marker inside the text would end the block early, and a later clear would leave the rest behind.
+ // Removing one marker can join its neighbors into a new one, so repeat until none is left.
+ let body = instructions;
+ let previous: string;
+ do {
+ previous = body;
+ body = body.split(BLOCK_START).join("").split(BLOCK_END).join("");
+ } while (body !== previous);
+ body = body.trim();
+ const block = `${BLOCK_START}\n${body}\n${BLOCK_END}`;
+ return rest ? `${rest}\n\n${block}\n` : `${block}\n`;
+}
+
+export interface AgentInstructionFilesLogger {
+ info(message: string, data?: unknown): void;
+ warn(message: string, data?: unknown): void;
+}
+
+export interface AgentInstructionFilesSyncContext {
+ taskId: string;
+ runId: string;
+}
+
+export class AgentInstructionFiles {
+ constructor(
+ private readonly logger: AgentInstructionFilesLogger,
+ private readonly paths: string[] = getAgentInstructionFilePaths(),
+ ) {}
+
+ // A resumed snapshot carries the previous run's block, which can be another person's instructions.
+ // A failed fetch can't prove they apply to this run, so it clears them like a run without the key.
+ async sync(
+ runState: TaskRunState | null | undefined,
+ context: AgentInstructionFilesSyncContext,
+ ): Promise<string | null> {
+ const instructions = runState?.agent_instructions?.trim() || null;
+ const errors: { path: string; message: string }[] = [];
+ for (const path of this.paths) {
+ try {
+ await this.writeOne(path, instructions);
+ } catch (error) {
+ errors.push({
+ path,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (errors.length > 0) {
+ this.logger.warn("Failed to write agent instruction files", {
+ ...context,
+ errors,
+ });
+ } else if (instructions) {
+ this.logger.info("Wrote agent instruction files", {
+ ...context,
+ length: instructions.length,
+ });
+ }
+ return instructions;
+ }
+
+ private async writeOne(
+ path: string,
+ instructions: string | null,
+ ): Promise<void> {
+ const existing = await readFile(path, "utf-8").catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") {
+ return null;
+ }
+ throw error;
+ },
+ );
+ const next = applyInstructionsBlock(existing, instructions);
+ if (next === existing) {
+ return;
+ }
+ if (next === null) {
+ await rm(path, { force: true });
+ return;
+ }
+ await mkdir(dirname(path), { recursive: true });
+ // A harness reading the file mid-write must see the old or the new content, never half of it.
+ const tmpPath = `${path}.${process.pid}.tmp`;
+ await writeFile(tmpPath, next, "utf-8");
+ await rename(tmpPath, path);
+ }
+}
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}