: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
feat(tasks): instrument agent server boot phases (#88256)
Alessandro Pogliaghi1d259e4e5234
diff --git a/products/desktop/packages/agent-shadow/README.md b/products/desktop/packages/agent-shadow/README.mdnew file mode 100644index 000000000000..6f60e0b2908a--- /dev/null+++ b/products/desktop/packages/agent-shadow/README.md@@ -0,0 +1,11 @@+# Agent-server shadow observer++This Go process polls the agent-server health endpoint and emits one JSON record+when the session is ready or the request times out.++```bash+go run . --boot-id "$POSTHOG_TASK_RUN_ID" --health-url http://127.0.0.1:8080/health+```++The observer is read-only. It does not accept traffic, start sessions, change+repositories, call models, or clean up processes.diff --git a/products/desktop/packages/agent-shadow/go.mod b/products/desktop/packages/agent-shadow/go.modnew file mode 100644index 000000000000..1fa0cc584200--- /dev/null+++ b/products/desktop/packages/agent-shadow/go.mod@@ -0,0 +1,3 @@+module github.com/PostHog/posthog/products/desktop/packages/agent-shadow++go 1.23diff --git a/products/desktop/packages/agent-shadow/main.go b/products/desktop/packages/agent-shadow/main.gonew file mode 100644index 000000000000..9363b2dbab10--- /dev/null+++ b/products/desktop/packages/agent-shadow/main.go@@ -0,0 +1,157 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "flag"+ "fmt"+ "io"+ "net/http"+ "os"+ "time"+)++type config struct {+ BootID string+ HealthURL string+ PollInterval time.Duration+ Timeout time.Duration+}++type healthResponse struct {+ HasSession bool `json:"hasSession"`+ Readiness string `json:"readiness"`+ Boot bootSnapshot `json:"boot"`+}++type bootSnapshot struct {+ ContractVersion int `json:"contractVersion"`+ BootID string `json:"bootId"`+ TotalMS int `json:"totalMs"`+ PhasesMS map[string]int `json:"phasesMs"`+}++type shadowResult struct {+ ContractVersion int `json:"contractVersion"`+ BootID string `json:"bootId"`+ Outcome string `json:"outcome"`+ ObservedReadyMS int `json:"observedReadyMs"`+ ProductionMS int `json:"productionReadyMs"`+ PhasesMS map[string]int `json:"phasesMs,omitempty"`+ FailureClass string `json:"failureClass,omitempty"`+}++func main() {+ var cfg config+ flag.StringVar(&cfg.BootID, "boot-id", "", "task run identifier used to join production and shadow observations")+ flag.StringVar(&cfg.HealthURL, "health-url", "http://127.0.0.1:8080/health", "production agent-server health URL")+ flag.DurationVar(&cfg.PollInterval, "poll-interval", 100*time.Millisecond, "health observation interval")+ flag.DurationVar(&cfg.Timeout, "timeout", 5*time.Minute, "maximum observation duration")+ flag.Parse()++ if cfg.BootID == "" {+ fmt.Fprintln(os.Stderr, "--boot-id is required")+ os.Exit(2)+ }+ if cfg.PollInterval <= 0 {+ fmt.Fprintln(os.Stderr, "--poll-interval must be positive")+ os.Exit(2)+ }++ ctx, cancel := context.WithTimeout(context.Background(), cfg.Timeout)+ defer cancel()+ result := observe(ctx, http.DefaultClient, cfg, time.Now)+ if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {+ fmt.Fprintln(os.Stderr, "failed to encode shadow result")+ os.Exit(1)+ }+ if result.Outcome != "ready" {+ os.Exit(1)+ }+}++type httpDoer interface {+ Do(*http.Request) (*http.Response, error)+}++func observe(ctx context.Context, client httpDoer, cfg config, now func() time.Time) shadowResult {+ startedAt := now()+ ticker := time.NewTicker(cfg.PollInterval)+ defer ticker.Stop()++ for {+ health, err := readHealth(ctx, client, cfg.HealthURL)+ if err == nil && health.HasSession && health.Readiness == "ready" && health.Boot.BootID == cfg.BootID {+ if health.Boot.ContractVersion != 1 {+ return failed(cfg.BootID, startedAt, now(), "unsupported_contract")+ }+ return shadowResult{+ ContractVersion: 1,+ BootID: cfg.BootID,+ Outcome: "ready",+ ObservedReadyMS: elapsedMS(startedAt, now()),+ ProductionMS: health.Boot.TotalMS,+ PhasesMS: allowlistedPhases(health.Boot.PhasesMS),+ }+ }++ select {+ case <-ctx.Done():+ return failed(cfg.BootID, startedAt, now(), "timeout")+ case <-ticker.C:+ }+ }+}++func readHealth(ctx context.Context, client httpDoer, url string) (healthResponse, error) {+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return healthResponse{}, err+ }+ response, err := client.Do(request)+ if err != nil {+ return healthResponse{}, err+ }+ defer response.Body.Close()+ if response.StatusCode != http.StatusOK {+ _, _ = io.Copy(io.Discard, response.Body)+ return healthResponse{}, errors.New("health endpoint unavailable")+ }+ var health healthResponse+ if err := json.NewDecoder(io.LimitReader(response.Body, 64<<10)).Decode(&health); err != nil {+ return healthResponse{}, err+ }+ return health, nil+}++func allowlistedPhases(phases map[string]int) map[string]int {+ allowed := map[string]bool{+ "context_fetch": true,+ "acp_initialize": true,+ "repository_ready": true,+ "session_dependencies": true,+ "session_create": true,+ }+ result := make(map[string]int, len(allowed))+ for phase, duration := range phases {+ if allowed[phase] && duration >= 0 {+ result[phase] = duration+ }+ }+ return result+}++func failed(bootID string, startedAt, endedAt time.Time, class string) shadowResult {+ return shadowResult{+ ContractVersion: 1,+ BootID: bootID,+ Outcome: "failed",+ ObservedReadyMS: elapsedMS(startedAt, endedAt),+ FailureClass: class,+ }+}++func elapsedMS(startedAt, endedAt time.Time) int {+ return max(0, int(endedAt.Sub(startedAt)/time.Millisecond))+}diff --git a/products/desktop/packages/agent-shadow/main_test.go b/products/desktop/packages/agent-shadow/main_test.gonew file mode 100644index 000000000000..7e38cbf85038--- /dev/null+++ b/products/desktop/packages/agent-shadow/main_test.go@@ -0,0 +1,83 @@+package main++import (+ "context"+ "io"+ "net/http"+ "strings"+ "testing"+ "time"+)++type roundTripFunc func(*http.Request) (*http.Response, error)++func (fn roundTripFunc) Do(request *http.Request) (*http.Response, error) {+ return fn(request)+}++func TestObserveReadyContract(t *testing.T) {+ client := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`{+ "hasSession": true,+ "readiness": "ready",+ "boot": {+ "contractVersion": 1,+ "bootId": "run-1",+ "state": "ready",+ "totalMs": 1200,+ "phasesMs": {"acp_initialize": 300, "secret_phase": 99}+ }+ }`)),+ }, nil+ })+ now := time.Unix(10, 0)+ result := observe(context.Background(), client, config{+ BootID: "run-1", PollInterval: time.Millisecond,+ }, func() time.Time { return now })++ if result.Outcome != "ready" || result.ProductionMS != 1200 {+ t.Fatalf("unexpected result: %#v", result)+ }+ if _, present := result.PhasesMS["secret_phase"]; present {+ t.Fatal("non-allowlisted phase leaked into comparison record")+ }+}++func TestObserveIgnoresMismatchedBoot(t *testing.T) {+ client := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader(`{+ "hasSession": true,+ "readiness": "ready",+ "boot": {"contractVersion": 1, "bootId": "another-run"}+ }`)),+ }, nil+ })+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)+ defer cancel()+ result := observe(ctx, client, config{+ BootID: "run-1", PollInterval: time.Millisecond,+ }, time.Now)++ if result.FailureClass != "timeout" {+ t.Fatalf("expected timeout, got %#v", result)+ }+}++func TestObserveTimesOutWithoutCopyingErrors(t *testing.T) {+ client := roundTripFunc(func(*http.Request) (*http.Response, error) {+ return nil, context.DeadlineExceeded+ })+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)+ defer cancel()+ result := observe(ctx, client, config{+ BootID: "run-1", PollInterval: time.Millisecond,+ }, time.Now)++ if result.FailureClass != "timeout" {+ t.Fatalf("expected timeout, got %#v", result)+ }+}diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 989725d16c38..0d8b6ee3cf38 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -545,8 +545,16 @@ describe("AgentServer HTTP Mode", () => {expect(body).toEqual({status: "ok",hasSession: true,+ readiness: "ready",bootMs: expect.any(Number),sessionInitMs: expect.any(Number),+ boot: expect.objectContaining({+ contractVersion: 1,+ bootId: "test-run-id",+ state: "ready",+ totalMs: expect.any(Number),+ phasesMs: expect.any(Object),+ }),});}, 30000);diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex 607d883b5814..ccbc768b00a6 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -110,6 +110,7 @@ import { resolveGatewayProduct, resolveGatewayTarget } from "../utils/gateway";import { resolveGithubToken } from "../utils/github-token";import { Logger } from "../utils/logger";import { logAgentshRuntimeInfo } from "./agentsh-runtime";+import { AgentBootTracker } from "./boot-phases";import {normalizeCloudPromptContent,promptBlocksToText,@@ -129,6 +130,7 @@ import {validateCommandParams,} from "./schemas";import type { AgentServerConfig, ClaudeCodeConfig } from "./types";+import { waitForFile } from "./wait-for-file";const agentErrorClassificationSchema = z.enum(["upstream_stream_terminated",@@ -511,6 +513,7 @@ export class AgentServer {private sessionReadyBootMs?: number;private sessionInitMs?: number;private barrierReleasedAtMs?: number;+ private bootTracker: AgentBootTracker;private logger: Logger;private server: ServerType | null = null;private session: ActiveSession | null = null;@@ -641,6 +644,7 @@ export class AgentServer {constructor(config: AgentServerConfig) {this.config = config;+ this.bootTracker = new AgentBootTracker(config.runId);this.posthogExecPermissionRegexSource =config.posthogExecPermissionRegex ??DEFAULT_POSTHOG_EXEC_PERMISSION_REGEX_SOURCE;@@ -754,11 +758,14 @@ export class AgentServer {const app = new Hono();app.get("/health", (c) => {+ const boot = this.bootTracker.snapshot();return c.json({status: "ok",hasSession: !!this.session,+ readiness: boot.state,bootMs: this.sessionReadyBootMs,sessionInitMs: this.sessionInitMs,+ boot,});});@@ -1658,6 +1665,7 @@ export class AgentServer {return;}+ this.bootTracker = new AgentBootTracker(payload.run_id);this.initializationPromise = this._doInitializeSession(payload,sseController,@@ -1666,6 +1674,7 @@ export class AgentServer {try {await this.initializationPromise;} catch (error) {+ this.bootTracker.markFailed();const telemetry = this.initializingTelemetry;telemetry?.append(payload.run_id, {type: "notification",@@ -1750,19 +1759,26 @@ export class AgentServer {name: process.env.HOSTNAME || "cloud-sandbox",};- const [preTaskRun, preTask] = await Promise.all([- this.posthogAPI- .getTaskRun(payload.task_id, payload.run_id)- .catch((err) => {- this.logger.debug("Failed to fetch task run for session context", {- taskId: payload.task_id,- runId: payload.run_id,- error: err,- });- return null;- }),- this.fetchTaskForSessionContext(payload.task_id),- ]);+ const [preTaskRun, preTask] = await this.bootTracker.measure(+ "context_fetch",+ () =>+ Promise.all([+ this.posthogAPI+ .getTaskRun(payload.task_id, payload.run_id)+ .catch((err) => {+ this.logger.debug(+ "Failed to fetch task run for session context",+ {+ taskId: payload.task_id,+ runId: payload.run_id,+ error: err,+ },+ );+ return null;+ }),+ this.fetchTaskForSessionContext(payload.task_id),+ ]),+ );this.taskRepositories =preTask?.repositories ??(preTask?.repository ? [preTask.repository] : []);@@ -1927,10 +1943,14 @@ export class AgentServer {clientStream,);- const initializeResult = await clientConnection.initialize({- protocolVersion: PROTOCOL_VERSION,- clientCapabilities: {},- });+ const initializeResult = await this.bootTracker.measure(+ "acp_initialize",+ () =>+ clientConnection.initialize({+ protocolVersion: PROTOCOL_VERSION,+ clientCapabilities: {},+ }),+ );const steering = extractSteeringCapability(initializeResult);const conversationClear =extractConversationClearCapability(initializeResult);@@ -1985,7 +2005,9 @@ export class AgentServer {...this.buildClaudeCodeSessionMeta(runtimeAdapter),};- await this.waitForRepoReady();+ await this.bootTracker.measure("repository_ready", () =>+ this.waitForRepoReady(),+ );const existingPrCheckoutPromise =this.buildExistingPrCheckoutPromise(prUrl);// Overlap the best-effort PR checkout with the rest of session setup. The@@ -1998,86 +2020,96 @@ export class AgentServer {// `.posthog/skills/<runId>/...`, which is gitignored (untracked) in target// repos, so `git checkout` — which only updates tracked files — cannot// conflict with those writes or leave them associated with the wrong branch.- let nativeResume: { sessionId: string; warm: boolean } | null;let effectiveSessionMeta: typeof sessionMeta & {nativeGoal?: NonNullable<ResumeState["nativeGoal"]>;} = sessionMeta;- let sessionMcpServers: McpServerConnection[];- try {- await this.installSkillBundleArtifacts(- payload.task_id,- payload.run_id,- this.getArtifactsById(preTaskRun?.artifacts, pendingUserArtifactIds),- );-- nativeResume = await this.prepareNativeResume(- payload,- posthogAPI,- preTaskRun,- runtimeAdapter,- sessionCwd,- initialPermissionMode,- );-- sessionMcpServers = [- ...(this.config.mcpServers ?? []),- ...(await this.startMcpRelayServer()),- ];- } finally {- // Always consume the checkout result — on the success path this is the- // intended await; on a throw it ensures the in-flight checkout settles- // (and aborts its children) instead of mutating the tree in the- // background. checkoutExistingPullRequest never rejects.- if (existingPrCheckoutPromise) {- this.logExistingPrCheckoutResult(- prUrl,- await existingPrCheckoutPromise,- );- }- }+ const [nativeResume, sessionMcpServers] = await this.bootTracker.measure(+ "session_dependencies",+ async () => {+ try {+ await this.installSkillBundleArtifacts(+ payload.task_id,+ payload.run_id,+ this.getArtifactsById(+ preTaskRun?.artifacts,+ pendingUserArtifactIds,+ ),+ );+ const preparedNativeResume = await this.prepareNativeResume(+ payload,+ posthogAPI,+ preTaskRun,+ runtimeAdapter,+ sessionCwd,+ initialPermissionMode,+ );+ const preparedMcpServers: McpServerConnection[] = [+ ...(this.config.mcpServers ?? []),+ ...(await this.startMcpRelayServer()),+ ];+ return [preparedNativeResume, preparedMcpServers] as const;+ } finally {+ if (existingPrCheckoutPromise) {+ this.logExistingPrCheckoutResult(+ prUrl,+ await existingPrCheckoutPromise,+ );+ }+ }+ },+ );- let acpSessionId: string | null = null;- if (nativeResume) {- try {- await clientConnection.resumeSession({- sessionId: nativeResume.sessionId,- cwd: sessionCwd,- mcpServers: sessionMcpServers,- _meta: { ...effectiveSessionMeta, sessionId: nativeResume.sessionId },- });- acpSessionId = nativeResume.sessionId;- this.nativeResume = nativeResume;- this.logger.debug("ACP session resumed", {- acpSessionId,- runId: payload.run_id,- warm: nativeResume.warm,- });- } catch (error) {- // resumeState is still loaded, so the summary resume path takes over- // on the fresh session below.- this.logger.warn("Native resume failed; starting a fresh session", {- sessionId: nativeResume.sessionId,- error: error instanceof Error ? error.message : String(error),- });- }- }- if (!acpSessionId) {- const restoredNativeGoal =- this.getNativeGoalForFreshSession(runtimeAdapter);- effectiveSessionMeta = restoredNativeGoal- ? { ...sessionMeta, nativeGoal: restoredNativeGoal }- : sessionMeta;- const sessionResponse = await clientConnection.newSession({- cwd: sessionCwd,- mcpServers: sessionMcpServers,- _meta: effectiveSessionMeta,- });- acpSessionId = sessionResponse.sessionId;- this.logger.debug("ACP session created", {- acpSessionId,- runId: payload.run_id,- });- }+ const acpSessionId = await this.bootTracker.measure(+ "session_create",+ async () => {+ let sessionId: string | null = null;+ if (nativeResume) {+ try {+ await clientConnection.resumeSession({+ sessionId: nativeResume.sessionId,+ cwd: sessionCwd,+ mcpServers: sessionMcpServers,+ _meta: {+ ...effectiveSessionMeta,+ sessionId: nativeResume.sessionId,+ },+ });+ sessionId = nativeResume.sessionId;+ this.nativeResume = nativeResume;+ this.logger.debug("ACP session resumed", {+ acpSessionId: sessionId,+ runId: payload.run_id,+ warm: nativeResume.warm,+ });+ } catch (error) {+ // resumeState is still loaded, so the summary resume path takes over+ // on the fresh session below.+ this.logger.warn("Native resume failed; starting a fresh session", {+ sessionId: nativeResume.sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (!sessionId) {+ const restoredNativeGoal =+ this.getNativeGoalForFreshSession(runtimeAdapter);+ effectiveSessionMeta = restoredNativeGoal+ ? { ...sessionMeta, nativeGoal: restoredNativeGoal }+ : sessionMeta;+ const sessionResponse = await clientConnection.newSession({+ cwd: sessionCwd,+ mcpServers: sessionMcpServers,+ _meta: effectiveSessionMeta,+ });+ sessionId = sessionResponse.sessionId;+ this.logger.debug("ACP session created", {+ acpSessionId: sessionId,+ runId: payload.run_id,+ });+ }+ return sessionId;+ },+ );this.evaluatedPrUrls.clear();this.prAttributionChain = Promise.resolve();@@ -2112,6 +2144,7 @@ export class AgentServer {0,Date.now() - (this.barrierReleasedAtMs ?? Date.now()),);+ this.bootTracker.markReady();this.logger.debug("Session initialized successfully", {bootMs: this.sessionReadyBootMs,sessionInitMs: this.sessionInitMs,@@ -3623,40 +3656,28 @@ export class AgentServer {}const REPO_READY_TIMEOUT_MS = 5 * 60_000;- const POLL_MS = 100;- const startedAt = Date.now();- let loggedUnexpectedError = false;-- for (;;) {- try {- await access(readyFile);- this.barrierReleasedAtMs = Date.now();- this.logger.debug("Repo-ready barrier released", {- readyFile,- waitedMs: Date.now() - startedAt,- });- return;- } catch (err) {- const code = (err as NodeJS.ErrnoException)?.code;- if (code !== "ENOENT" && !loggedUnexpectedError) {- loggedUnexpectedError = true;- this.logger.debug("Repo-ready barrier access error; still polling", {- readyFile,- code,- error: err instanceof Error ? err.message : String(err),- });- }- }- if (Date.now() - startedAt > REPO_READY_TIMEOUT_MS) {- this.barrierReleasedAtMs = Date.now();- this.logger.warn("Repo-ready barrier timed out; proceeding", {+ const result = await waitForFile(readyFile, {+ timeoutMs: REPO_READY_TIMEOUT_MS,+ onError: (error) => {+ this.logger.debug("Repo-ready barrier check failed", {readyFile,- waitedMs: Date.now() - startedAt,+ code: error.code,+ message: error.message,});- return;- }- await new Promise((resolve) => setTimeout(resolve, POLL_MS));+ },+ });+ this.barrierReleasedAtMs = Date.now();+ if (result.timedOut) {+ this.logger.warn("Repo-ready barrier timed out; proceeding", {+ readyFile,+ waitedMs: result.waitedMs,+ });+ return;}+ this.logger.debug("Repo-ready barrier released", {+ readyFile,+ waitedMs: result.waitedMs,+ });}private async autoInitializeSession(): Promise<void> {diff --git a/products/desktop/packages/agent/src/server/boot-phases.test.ts b/products/desktop/packages/agent/src/server/boot-phases.test.tsnew file mode 100644index 000000000000..a6bec2c34947--- /dev/null+++ b/products/desktop/packages/agent/src/server/boot-phases.test.ts@@ -0,0 +1,55 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AgentBootTracker } from "./boot-phases";++afterEach(() => {+ vi.restoreAllMocks();+});++describe("AgentBootTracker", () => {+ it("records named phases and a ready terminal state", async () => {+ vi.spyOn(performance, "now")+ .mockReturnValueOnce(100)+ .mockReturnValueOnce(110)+ .mockReturnValueOnce(135)+ .mockReturnValueOnce(150)+ .mockReturnValueOnce(500);++ const tracker = new AgentBootTracker("run-1");+ await tracker.measure("context_fetch", async () => "ok");+ tracker.markReady();++ expect(tracker.snapshot()).toEqual({+ contractVersion: 1,+ bootId: "run-1",+ state: "ready",+ totalMs: 50,+ phasesMs: { context_fetch: 25 },+ });+ });++ it("attributes failures to the active phase without exposing the error", async () => {+ vi.spyOn(performance, "now")+ .mockReturnValueOnce(10)+ .mockReturnValueOnce(20)+ .mockReturnValueOnce(45)+ .mockReturnValueOnce(50)+ .mockReturnValueOnce(500);++ const tracker = new AgentBootTracker("run-2");+ await expect(+ tracker.measure("acp_initialize", async () => {+ throw new Error("sensitive provider response");+ }),+ ).rejects.toThrow("sensitive provider response");+ tracker.markFailed();++ expect(tracker.snapshot()).toEqual({+ contractVersion: 1,+ bootId: "run-2",+ state: "failed",+ failedPhase: "acp_initialize",+ totalMs: 40,+ phasesMs: { acp_initialize: 25 },+ });+ });+});diff --git a/products/desktop/packages/agent/src/server/boot-phases.ts b/products/desktop/packages/agent/src/server/boot-phases.tsnew file mode 100644index 000000000000..b45ae5131515--- /dev/null+++ b/products/desktop/packages/agent/src/server/boot-phases.ts@@ -0,0 +1,102 @@+export const AGENT_BOOT_CONTRACT_VERSION = 1;++export const AGENT_BOOT_PHASES = [+ "context_fetch",+ "acp_initialize",+ "repository_ready",+ "session_dependencies",+ "session_create",+] as const;++export type AgentBootPhase = (typeof AGENT_BOOT_PHASES)[number];+export type AgentBootState = "starting" | "ready" | "failed";++export interface AgentBootSnapshot {+ contractVersion: number;+ bootId: string;+ state: AgentBootState;+ currentPhase?: AgentBootPhase;+ failedPhase?: AgentBootPhase;+ totalMs: number;+ phasesMs: Partial<Record<AgentBootPhase, number>>;+}++export class AgentBootTracker {+ private readonly startedAt = performance.now();+ private state: AgentBootState = "starting";+ private currentPhase?: AgentBootPhase;+ private currentPhaseStartedAt?: number;+ private failedPhase?: AgentBootPhase;+ private totalMs?: number;+ private readonly phasesMs: Partial<Record<AgentBootPhase, number>> = {};++ constructor(private readonly bootId: string) {}++ async measure<T>(phase: AgentBootPhase, work: () => Promise<T>): Promise<T> {+ this.start(phase);+ try {+ return await work();+ } catch (error) {+ this.fail();+ throw error;+ } finally {+ this.finishCurrentPhase();+ }+ }++ markReady(): void {+ this.finishCurrentPhase();+ this.totalMs = this.elapsedMs();+ this.state = "ready";+ }++ markFailed(): void {+ this.fail();+ this.finishCurrentPhase();+ this.totalMs = this.elapsedMs();+ }++ snapshot(): AgentBootSnapshot {+ const phasesMs = { ...this.phasesMs };+ if (this.currentPhase && this.currentPhaseStartedAt !== undefined) {+ phasesMs[this.currentPhase] = Math.max(+ 0,+ Math.round(performance.now() - this.currentPhaseStartedAt),+ );+ }+ return {+ contractVersion: AGENT_BOOT_CONTRACT_VERSION,+ bootId: this.bootId,+ state: this.state,+ ...(this.currentPhase ? { currentPhase: this.currentPhase } : {}),+ ...(this.failedPhase ? { failedPhase: this.failedPhase } : {}),+ totalMs: this.totalMs ?? this.elapsedMs(),+ phasesMs,+ };+ }++ private elapsedMs(): number {+ return Math.max(0, Math.round(performance.now() - this.startedAt));+ }++ private start(phase: AgentBootPhase): void {+ this.finishCurrentPhase();+ this.currentPhase = phase;+ this.currentPhaseStartedAt = performance.now();+ }++ private fail(): void {+ this.state = "failed";+ if (this.currentPhase) this.failedPhase = this.currentPhase;+ }++ private finishCurrentPhase(): void {+ if (!this.currentPhase || this.currentPhaseStartedAt === undefined) return;+ this.phasesMs[this.currentPhase] = Math.max(+ 0,+ Math.round(performance.now() - this.currentPhaseStartedAt),+ );+ this.currentPhase = undefined;+ this.currentPhaseStartedAt = undefined;+ }+}diff --git a/products/desktop/packages/agent/src/server/wait-for-file.test.ts b/products/desktop/packages/agent/src/server/wait-for-file.test.tsnew file mode 100644index 000000000000..e21654e41bfd--- /dev/null+++ b/products/desktop/packages/agent/src/server/wait-for-file.test.ts@@ -0,0 +1,62 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { waitForFile } from "./wait-for-file";++const directories: string[] = [];++afterEach(async () => {+ await Promise.all(+ directories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++describe("waitForFile", () => {+ it("returns immediately for an existing sentinel", async () => {+ const directory = await temporaryDirectory();+ const path = join(directory, "ready");+ await writeFile(path, "");++ await expect(waitForFile(path, { timeoutMs: 100 })).resolves.toEqual({+ waitedMs: 0,+ timedOut: false,+ });+ });++ it("wakes on creation instead of waiting for the fallback poll", async () => {+ const directory = await temporaryDirectory();+ const path = join(directory, "ready");+ const waiting = waitForFile(path, {+ timeoutMs: 1_000,+ fallbackPollMs: 500,+ });++ await writeFile(path, "");++ const result = await waiting;+ expect(result.timedOut).toBe(false);+ expect(result.waitedMs).toBeLessThan(500);+ });++ it("returns a bounded timeout result", async () => {+ const directory = await temporaryDirectory();+ const path = join(directory, "never-ready");++ const result = await waitForFile(path, {+ timeoutMs: 10,+ fallbackPollMs: 100,+ });++ expect(result.timedOut).toBe(true);+ expect(result.waitedMs).toBeGreaterThanOrEqual(10);+ });+});++async function temporaryDirectory(): Promise<string> {+ const directory = await mkdtemp(join(tmpdir(), "agent-ready-"));+ directories.push(directory);+ return directory;+}diff --git a/products/desktop/packages/agent/src/server/wait-for-file.ts b/products/desktop/packages/agent/src/server/wait-for-file.tsnew file mode 100644index 000000000000..159de9312307--- /dev/null+++ b/products/desktop/packages/agent/src/server/wait-for-file.ts@@ -0,0 +1,80 @@+import { access, watch } from "node:fs";+import { basename, dirname } from "node:path";++export interface WaitForFileOptions {+ timeoutMs: number;+ fallbackPollMs?: number;+ onError?: (error: NodeJS.ErrnoException) => void;+}++export interface WaitForFileResult {+ waitedMs: number;+ timedOut: boolean;+}++export async function waitForFile(+ path: string,+ { timeoutMs, fallbackPollMs = 100, onError }: WaitForFileOptions,+): Promise<WaitForFileResult> {+ const startedAt = performance.now();+ let errorReported = false;+ const reportError = (error: NodeJS.ErrnoException): void => {+ if (errorReported) return;+ errorReported = true;+ onError?.(error);+ };+ if (await exists(path, reportError)) return { waitedMs: 0, timedOut: false };++ return await new Promise<WaitForFileResult>((resolve) => {+ let settled = false;+ let watcher: ReturnType<typeof watch> | undefined;++ const finish = (timedOut: boolean): void => {+ if (settled) return;+ settled = true;+ watcher?.close();+ clearInterval(poll);+ clearTimeout(timeout);+ const elapsedMs = Math.max(0, Math.round(performance.now() - startedAt));+ resolve({+ waitedMs: timedOut ? Math.max(timeoutMs, elapsedMs) : elapsedMs,+ timedOut,+ });+ };++ const check = (): void => {+ void exists(path, reportError).then((present) => {+ if (present) finish(false);+ });+ };++ const poll = setInterval(check, fallbackPollMs);+ const timeout = setTimeout(() => finish(true), timeoutMs);++ try {+ watcher = watch(dirname(path), (_event, filename) => {+ if (!filename || filename.toString() === basename(path)) check();+ });+ watcher.on("error", () => {+ watcher?.close();+ watcher = undefined;+ });+ } catch {+ watcher = undefined;+ }++ check();+ });+}++async function exists(+ path: string,+ onError?: (error: NodeJS.ErrnoException) => void,+): Promise<boolean> {+ return await new Promise<boolean>((resolve) => {+ access(path, (error) => {+ if (error && error.code !== "ENOENT") onError?.(error);+ resolve(!error);+ });+ });+}diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.tsindex ba805030da09..509725465543 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts@@ -317,6 +317,12 @@ describe("AgentService", () => {path: "/mock/appData/context-wiki/org-1/head1",commitsPath: "/api/organizations/org-1/context_layer/commits/",};+ const mountContextWiki = () =>+ (+ service as unknown as {+ mountContextWiki: (value: unknown) => Promise<unknown>;+ }+ ).mountContextWiki(credentials);const ENV_KEYS = ["POSTHOG_API_KEY",@@ -351,7 +357,7 @@ describe("AgentService", () => {}mockPrepareContextWiki.mockResolvedValueOnce(mount);- const wiki = await service["mountContextWiki"](credentials);+ const wiki = await mountContextWiki();expect(wiki).toEqual({path: mount.path,@@ -368,7 +374,7 @@ describe("AgentService", () => {process.env.POSTHOG_API_KEY = "synced-key";mockPrepareContextWiki.mockResolvedValueOnce(mount);- await service["mountContextWiki"](credentials);+ await mountContextWiki();expect(process.env.POSTHOG_CONTEXT_LAYER_PATH).toBeUndefined();expect(process.env.POSTHOG_CONTEXT_LAYER_COMMITS_PATH).toBeUndefined();diff --git a/products/tasks/backend/logic/services/docker_sandbox.py b/products/tasks/backend/logic/services/docker_sandbox.pyindex f9422dd969b1..4ef8840b6153 100644--- a/products/tasks/backend/logic/services/docker_sandbox.py+++ b/products/tasks/backend/logic/services/docker_sandbox.py@@ -1220,6 +1220,12 @@ class DockerSandbox(SandboxBase):def read_agent_server_session_init_ms(self) -> int | None:return self._read_health_session_init_ms(AGENT_SERVER_PORT)+ def read_agent_server_boot_phases_ms(self) -> dict[str, int]:+ return self._read_health_boot_phases_ms(AGENT_SERVER_PORT)++ def read_agent_server_boot_metrics(self) -> tuple[int | None, dict[str, int]]:+ return self._read_health_boot_metrics(AGENT_SERVER_PORT)+def create_snapshot(self, *, timeout_seconds: int | None = None) -> str:# timeout_seconds bounds Modal's snapshot RPC; docker commits have no equivalent knob.if not self.is_running():diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex da4571347dac..5df91f1c92da 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -689,6 +689,7 @@ class ModalSandbox(SandboxBase):self._app = type(self)._get_app_for_config(config)self._sandbox_url = sandbox_urlself.provision_diagnostics = None+ self._destroyed = False@propertydef sandbox_url(self) -> str | None:@@ -1041,7 +1042,7 @@ class ModalSandbox(SandboxBase):)def get_status(self) -> SandboxStatus:- return SandboxStatus.RUNNING if self._sandbox.poll() is None else SandboxStatus.SHUTDOWN+ return SandboxStatus.SHUTDOWN if self._destroyed or self._sandbox.poll() is not None else SandboxStatus.RUNNINGdef execute(self,@@ -1596,6 +1597,12 @@ class ModalSandbox(SandboxBase):def read_agent_server_session_init_ms(self) -> int | None:return self._read_health_session_init_ms(AGENT_SERVER_PORT)+ def read_agent_server_boot_phases_ms(self) -> dict[str, int]:+ return self._read_health_boot_phases_ms(AGENT_SERVER_PORT)++ def read_agent_server_boot_metrics(self) -> tuple[int | None, dict[str, int]]:+ return self._read_health_boot_metrics(AGENT_SERVER_PORT)+def _free_agent_server_port(self) -> None:self.execute("pkill -TERM -f agent-server 2>/dev/null || true; "@@ -1772,6 +1779,7 @@ class ModalSandbox(SandboxBase):def destroy(self) -> None:try:self._sandbox.terminate()+ self._destroyed = Truelogger.info(f"Destroyed sandbox {self.id}")except Exception as e:logger.exception(f"Failed to destroy sandbox: {e}")diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 6db141bfaef4..0cd5b8efd7be 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -554,6 +554,12 @@ class SandboxBase(ABC):def read_agent_server_session_init_ms(self) -> int | None:return None+ def read_agent_server_boot_phases_ms(self) -> dict[str, int]:+ return {}++ def read_agent_server_boot_metrics(self) -> tuple[int | None, dict[str, int]]:+ return None, {}+def read_cpu_usage_usec(self) -> int | None:return None@@ -572,6 +578,54 @@ class SandboxBase(ABC):except Exception:return None+ def _read_health_boot_metrics(self, port: int) -> tuple[int | None, dict[str, int]]:+ try:+ result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)+ payload = json.loads(result.stdout or "{}")+ session_init_ms = payload.get("sessionInitMs")+ raw_phases = payload.get("boot", {}).get("phasesMs", {})+ allowed_phases = {+ "context_fetch",+ "acp_initialize",+ "repository_ready",+ "session_dependencies",+ "session_create",+ }+ phases = (+ {+ phase: max(0, int(duration))+ for phase, duration in raw_phases.items()+ if phase in allowed_phases and isinstance(duration, int | float)+ }+ if isinstance(raw_phases, dict)+ else {}+ )+ return int(session_init_ms) if isinstance(session_init_ms, int | float) else None, phases+ except Exception:+ return None, {}++ def _read_health_boot_phases_ms(self, port: int) -> dict[str, int]:+ try:+ result = self.execute(f"curl -s --max-time 5 http://localhost:{port}/health", timeout_seconds=10)+ payload = json.loads(result.stdout or "{}")+ raw_phases = payload.get("boot", {}).get("phasesMs", {})+ allowed_phases = {+ "context_fetch",+ "acp_initialize",+ "repository_ready",+ "session_dependencies",+ "session_create",+ }+ if not isinstance(raw_phases, dict):+ return {}+ return {+ phase: max(0, int(duration))+ for phase, duration in raw_phases.items()+ if phase in allowed_phases and isinstance(duration, int | float)+ }+ except Exception:+ return {}+def __enter__(self) -> Self:return selfdiff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.pyindex b81e80736ea5..4405b057ed31 100644--- a/products/tasks/backend/logic/services/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py@@ -22,6 +22,7 @@ from products.tasks.backend.logic.services.modal_sandbox import (from products.tasks.backend.logic.services.sandbox import (SELF_DRIVING_ORIGIN_PRODUCTS,SandboxConfig,+ SandboxStatus,SandboxTemplate,SandboxWorkload,get_sandbox_class_for_backend,@@ -30,6 +31,18 @@ from products.tasks.backend.logic.services.sandbox import (from products.tasks.backend.models import Task+def test_destroy_updates_status_before_modal_termination_settles(mocker):+ handle = MagicMock(object_id="sb-test")+ handle.poll.return_value = None+ mocker.patch.object(ModalSandbox, "_get_app_for_config", return_value=MagicMock())+ sandbox = ModalSandbox(handle, SandboxConfig(name="test"))++ sandbox.destroy()++ assert sandbox.get_status() == SandboxStatus.SHUTDOWN+ handle.terminate.assert_called_once_with()++@pytest.fixturedef patched_modal(mocker):fake_sandbox = MagicMock()diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.pyindex 51257b7a49df..d5b75817ca92 100644--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py@@ -176,13 +176,14 @@ class MarkRepoReadyInput:release_barrier: bool = True-@dataclass+@frozenclass StartAgentServerOutput:sandbox_url: strconnect_token: str | None = Nonelaunch_ms: int | None = Noneready_wait_ms: int | None = Nonesession_init_ms: int | None = None+ boot_phases_ms: dict[str, int] = field(default_factory=dict)boot_total_ms: int | None = None@@ -510,7 +511,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:emit_agent_log(ctx.run_id, "debug", f"Agent server started at {input.sandbox_url}")activity.logger.info(f"Agent server started at {input.sandbox_url} for task {ctx.task_id}")- session_init_ms = sandbox.read_agent_server_session_init_ms()+ session_init_ms, boot_phases_ms = sandbox.read_agent_server_boot_metrics()if session_init_ms is not None:record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime@@ -525,6 +526,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:connect_token=input.sandbox_connect_token,ready_wait_ms=ready_timer.elapsed_ms,session_init_ms=session_init_ms,+ boot_phases_ms=boot_phases_ms,boot_total_ms=boot_total_ms,)@@ -641,7 +643,7 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOuemit_agent_log(ctx.run_id, "debug", f"Agent server ready at {input.sandbox_url}")activity.logger.info(f"Agent server ready at {input.sandbox_url} for task {ctx.task_id}")- session_init_ms = sandbox.read_agent_server_session_init_ms()+ session_init_ms, boot_phases_ms = sandbox.read_agent_server_boot_metrics()if session_init_ms is not None:record_agent_server_session_init_ms(session_init_ms, boot_path=input.boot_path, origin_product=ctx.origin_product, runtime=runtime@@ -656,5 +658,6 @@ def await_agent_server_ready(input: StartAgentServerInput) -> StartAgentServerOuconnect_token=input.sandbox_connect_token,ready_wait_ms=ready_timer.elapsed_ms,session_init_ms=session_init_ms,+ boot_phases_ms=boot_phases_ms,boot_total_ms=boot_total_ms,)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.pyindex f31156184a44..7e6341d48d2e 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py@@ -162,7 +162,7 @@ async def test_start_failure_does_not_report_network_enforcement_observation(mocasync def test_await_agent_server_ready_relaunches_on_activity_retries(mocker, attempt, expects_relaunch) -> None:context = _context()sandbox = mocker.Mock(id="sandbox-id")- sandbox.read_agent_server_session_init_ms.return_value = None+ sandbox.read_agent_server_boot_metrics.return_value = (None, {})mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Sandbox.get_by_id",return_value=sandbox,@@ -442,6 +442,7 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mockersandbox = mocker.Mock()sandbox.execute.return_value.stdout = ""sandbox.execute.return_value.stderr = ""+ sandbox.read_agent_server_boot_metrics.return_value = (None, {})mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Sandbox.get_by_id",return_value=sandbox,@@ -515,6 +516,7 @@ async def test_start_agent_server_forwards_imported_and_relayed_mcp_servers(mocksandbox = mocker.Mock()sandbox.execute.return_value.stdout = ""sandbox.execute.return_value.stderr = ""+ sandbox.read_agent_server_boot_metrics.return_value = (None, {})mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Sandbox.get_by_id",return_value=sandbox,@@ -573,6 +575,7 @@ async def test_start_agent_server_passes_initial_permission_mode(mocker) -> Nonesandbox = mocker.Mock()sandbox.execute.return_value.stdout = ""sandbox.execute.return_value.stderr = ""+ sandbox.read_agent_server_boot_metrics.return_value = (None, {})mocker.patch("products.tasks.backend.temporal.process_task.activities.start_agent_server.Sandbox.get_by_id",return_value=sandbox,diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 433ced90c7be..8e9cdb10a987 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -1625,6 +1625,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):"agent_launch_ms": sandbox_output.launch_ms,"agent_ready_wait_ms": agent_server_output.ready_wait_ms,"agent_session_init_ms": agent_server_output.session_init_ms,+ "agent_context_fetch_ms": agent_server_output.boot_phases_ms.get("context_fetch"),+ "agent_acp_initialize_ms": agent_server_output.boot_phases_ms.get("acp_initialize"),+ "agent_repository_ready_ms": agent_server_output.boot_phases_ms.get("repository_ready"),+ "agent_session_dependencies_ms": agent_server_output.boot_phases_ms.get("session_dependencies"),+ "agent_session_create_ms": agent_server_output.boot_phases_ms.get("session_create"),"loop_id": self.context.loop_id,"loop_trigger_id": self.context.loop_trigger_id,},diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.mdindex bb935ce5a00d..f03212aeb6c2 100644--- a/products/tasks/docs/INSTRUMENTATION.md+++ b/products/tasks/docs/INSTRUMENTATION.md@@ -139,22 +139,27 @@ Tracked when the workflow begins execution.Tracked after sandbox and agent server are provisioned.-| Property | Type | Description |-| ----------------------- | ------ | --------------------------------------------------------- |-| `run_id` | `str` | UUID of the run |-| `task_id` | `str` | UUID of the task |-| `sandbox_id` | `str` | Sandbox identifier |-| `sandbox_url` | `str` | URL of the sandbox |-| `used_snapshot` | `bool` | Whether a snapshot was used |-| `repository` | `str` | Repository in `org/repo` format |-| `boot_path` | `str` | Classic or overlapping clone boot |-| `boot_total_ms` | `int` | Infrastructure boot time, excluding setup agent execution |-| `sandbox_create_ms` | `int` | Sandbox creation time |-| `repo_clone_ms` | `int` | Repository clone time |-| `branch_checkout_ms` | `int` | Branch checkout time |-| `agent_launch_ms` | `int` | Agent server launch time |-| `agent_ready_wait_ms` | `int` | Time spent waiting for the agent server |-| `agent_session_init_ms` | `int` | Agent session initialization time |+| Property | Type | Description |+| ------------------------------- | ------ | --------------------------------------------------------- |+| `run_id` | `str` | UUID of the run |+| `task_id` | `str` | UUID of the task |+| `sandbox_id` | `str` | Sandbox identifier |+| `sandbox_url` | `str` | URL of the sandbox |+| `used_snapshot` | `bool` | Whether a snapshot was used |+| `repository` | `str` | Repository in `org/repo` format |+| `boot_path` | `str` | Classic or overlapping clone boot |+| `boot_total_ms` | `int` | Infrastructure boot time, excluding setup agent execution |+| `sandbox_create_ms` | `int` | Sandbox creation time |+| `repo_clone_ms` | `int` | Repository clone time |+| `branch_checkout_ms` | `int` | Branch checkout time |+| `agent_launch_ms` | `int` | Agent server launch time |+| `agent_ready_wait_ms` | `int` | Time spent waiting for the agent server |+| `agent_session_init_ms` | `int` | Agent session initialization time |+| `agent_context_fetch_ms` | `int` | Task and run context fetch time inside agent-server |+| `agent_acp_initialize_ms` | `int` | ACP process handshake time |+| `agent_repository_ready_ms` | `int` | Time waiting on the repository-ready barrier |+| `agent_session_dependencies_ms` | `int` | Skill, resume, relay, and PR checkout preparation |+| `agent_session_create_ms` | `int` | ACP session creation or resumption time |### Modal VM rollout payload