/* eslint-disable no-unused-vars -- Integration shards share fixtures; each shard uses a subset. */
import { createServer, type Server } from "node:http";
import { createHash } from "node:crypto";
import {
  existsSync,
  mkdtempSync,
  mkdirSync,
  readFileSync,
  readdirSync,
  rmSync,
  symlinkSync,
  writeFileSync,
} from "node:fs";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BestAgentError, createRandomId } from "@best-agent/foundation";
import {
  defineSkill,
  type ArtifactObligation,
  type EventEnvelope,
  type Item,
  type ProviderTurnActionPolicy,
  type ThreadEvidenceRecord,
  type ThreadMetadata,
  type ThreadId,
  type ToolInputValue,
  type TurnId,
} from "@best-agent/protocol";
import { LocalApprovalStore } from "../core/approval-store.js";
import {
  LocalThreadStore,
  REPLAY_TOOL_INPUT_ASSET_CONTENT_TYPE,
  type SaveRunCheckpointInput,
  type UpdateRunCheckpointInput,
} from "../core/thread-store.js";
import { DEFAULT_ALLOWED_TOOLS, createDefaultRuntimePolicy } from "../policy/runtime-policy.js";
import {
  createModelProvider,
  type ModelProvider,
  type ProviderDecisionOutput,
} from "../provider/model-provider.js";
import type { ConversationMessage } from "../provider/provider-conversation.js";
import { createDefaultToolRegistry, type ToolDefinition } from "../tool/registry.js";
import { AgentRuntime } from "./agent-runtime.js";

const storageRoots: string[] = [];
const servers: Server[] = [];
const approvalShellAction = "node --version";
const approvalShellPrompt = `tool:shell ${approvalShellAction}`;
const structuredToolCapabilities = {
  defaultDecisionTransport: "native_tools",
  supportedDecisionTransports: ["native_tools"],
  supportsBackgroundJobs: false,
  supportsNativeWebSearch: false,
  supportsPauseResume: false,
  supportsResumableStream: false,
  supportsWebhookCompletion: false,
} as const;

function stableToolInputDigestForTest(value: ToolInputValue): string {
  return createHash("sha256")
    .update(JSON.stringify(sortToolInputValueForTest(value)))
    .digest("hex");
}

function sortToolInputValueForTest(value: ToolInputValue): ToolInputValue {
  if (Array.isArray(value)) {
    return value.map((item) => sortToolInputValueForTest(item));
  }
  if (value && typeof value === "object") {
    return Object.fromEntries(
      Object.entries(value)
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([key, child]) => [key, sortToolInputValueForTest(child)]),
    ) as ToolInputValue;
  }
  return value;
}

function providerContextText(input: {
  messages: ConversationMessage[];
  systemPrompt?: string;
}): string {
  return [input.systemPrompt ?? "", ...input.messages.map((message) => message.content)].join("\n");
}

function phaseResultDecision(
  phaseName: "build" | "change" | "explore" | "inspect" | "plan" | "verify",
  summary: string,
  options:
    | "blocked"
    | "inconclusive"
    | "satisfied"
    | "unsatisfied"
    | {
        model?: string;
        provider?: "anthropic" | "google" | "openai";
        verdictStatus?: "blocked" | "inconclusive" | "satisfied" | "unsatisfied";
      } = {},
): ProviderDecisionOutput {
  const resolvedOptions = typeof options === "string" ? { verdictStatus: options } : options;
  return {
    kind: "phase_result",
    model: resolvedOptions.model ?? "test-provider",
    phaseResult: {
      ...(resolvedOptions.verdictStatus
        ? {
            candidateVerdict: {
              status: resolvedOptions.verdictStatus,
              summary,
            },
          }
        : {}),
      phaseName,
      summary,
    },
    provider: resolvedOptions.provider ?? "openai",
  };
}

afterEach(() => {
  vi.restoreAllMocks();
  while (servers.length > 0) {
    servers.pop()?.close();
  }
  while (storageRoots.length > 0) {
    rmSync(storageRoots.pop() as string, { force: true, recursive: true });
  }
});

function createDeferred<T>() {
  let resolve!: (value: T | PromiseLike<T>) => void;
  let reject!: (reason?: unknown) => void;
  const promise = new Promise<T>((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, reject, resolve };
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

const replayCheckpointProviderConfig = {
  apiKey: "runtime-a-secret",
  kind: "openai",
  model: "replay-model",
} as const;

function createReplayCheckpointProvider(toolCall: {
  input: ToolInputValue;
  toolName: string;
}): ModelProvider {
  let decideCount = 0;
  return {
    capabilities: structuredToolCapabilities,
    config: { ...replayCheckpointProviderConfig },
    async decide() {
      decideCount += 1;
      if (decideCount === 1) {
        return {
          kind: "tool",
          model: "replay-model",
          provider: "openai",
          reasoning: `Run ${toolCall.toolName} before answering.`,
          toolCalls: [toolCall],
        };
      }
      return {
        kind: "respond",
        model: "replay-model",
        provider: "openai",
        text: "tool finished",
      };
    },
    async generate() {
      throw new Error("generate should not be called");
    },
  };
}

function expectProviderRouteConfigRedacted(
  payload:
    | {
        kind?: string;
        routeConfigOverride?: {
          apiKey?: string;
          kind?: string;
          model?: string;
        };
      }
    | undefined,
  kind: string,
): void {
  expect(payload).toMatchObject({
    kind,
    routeConfigOverride: {
      kind: "openai",
      model: "replay-model",
    },
  });
  expect(payload?.routeConfigOverride?.apiKey).toBeUndefined();
  expect(JSON.stringify(payload)).not.toContain(replayCheckpointProviderConfig.apiKey);
}

async function assertProviderToolCheckpointRedacted(
  kind: "tool-dispatch" | "tool-output",
): Promise<void> {
  const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-${kind}-redaction-`);
  const storageRoot = join(workspaceRoot, "state");
  storageRoots.push(workspaceRoot);
  writeFileSync(join(workspaceRoot, "README.md"), "# replay\n");

  if (kind === "tool-dispatch") {
    const releaseTool = createDeferred<void>();
    const store = new LocalThreadStore({ storageRoot });
    const tools = createDefaultToolRegistry({
      extraTools: [
        {
          capabilities() {
            return [];
          },
          description: "Slow tool that keeps tool-dispatch pending for checkpoint inspection.",
          async execute() {
            await releaseTool.promise;
            return "slow tool finished";
          },
          executionClass: "read-only",
          idempotent: true,
          inputSchema: {
            additionalProperties: false,
            properties: {},
            type: "object",
          },
          name: "slow-read",
          source: "plugin",
        },
      ],
    });
    const agentProfiles = [
      {
        description: "Slow tool profile.",
        loopKind: "simple" as const,
        name: "slow-tool",
        source: "user" as const,
        tools: ["slow-read"],
      },
    ];
    const runtime = new AgentRuntime({
      agentProfiles,
      cwd: workspaceRoot,
      provider: {
        capabilities: structuredToolCapabilities,
        config: { ...replayCheckpointProviderConfig },
        async decide(input) {
          const latestToolMessage = [...input.messages]
            .reverse()
            .find((message) => message.role === "tool" && message.toolName === "slow-read");
          if (latestToolMessage) {
            return {
              kind: "respond",
              model: "replay-model",
              provider: "openai",
              text: "tool finished",
            };
          }
          return {
            input: {},
            kind: "tool",
            model: "replay-model",
            provider: "openai",
            reasoning: "Use the slow tool before answering.",
            toolName: "slow-read",
          };
        },
        async generate() {
          throw new Error("generate should not be called");
        },
      },
      storageRoot,
      tools,
    });

    const { thread } = await runtime.startThread();
    const pending = runtime.runTurn({
      agentProfile: "slow-tool",
      threadId: thread.id,
      prompt: "Use the slow tool before answering.",
    });

    try {
      await expect
        .poll(async () => (await store.listRuns(thread.id)).length, { timeout: 5_000 })
        .toBeGreaterThan(0);
      const activeRun = (await store.listRuns(thread.id)).at(-1);
      expect(activeRun).toBeTruthy();
      await expect
        .poll(async () => (await store.getPendingRunCheckpointByTurn(activeRun!.turnId))?.kind, {
          timeout: 5_000,
        })
        .toBe("tool-dispatch");
      const checkpoint = await store.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expectProviderRouteConfigRedacted(
        checkpoint?.payload as
          | {
              kind?: string;
              routeConfigOverride?: {
                apiKey?: string;
                kind?: string;
                model?: string;
              };
            }
          | undefined,
        "tool-dispatch",
      );
    } finally {
      releaseTool.resolve();
      const result = await pending;
      expect(result.turn.status).toBe("completed");
      await runtime.close();
      store.close();
    }
    return;
  }

  const store = new DelayedPersistedCheckpointStore({ storageRoot }, kind);
  const runtime = new AgentRuntime({
    cwd: workspaceRoot,
    provider: createReplayCheckpointProvider({
      input: { path: "README.md" },
      toolName: "read-file",
    }),
    storageRoot,
    store,
  });

  const { thread } = await runtime.startThread();
  const pending = runtime.runTurn({
    threadId: thread.id,
    prompt: "Read README.md before answering.",
  });

  try {
    await store.checkpointPersisted.promise;
    const activeRun = (await store.listRuns(thread.id)).at(-1);
    expect(activeRun).toBeTruthy();

    const checkpoint = activeRun
      ? await store.getPendingRunCheckpointByTurn(activeRun.turnId)
      : undefined;
    expect(checkpoint?.kind).toBe(kind);
    expectProviderRouteConfigRedacted(
      checkpoint?.payload as
        | {
            kind?: string;
            routeConfigOverride?: {
              apiKey?: string;
              kind?: string;
              model?: string;
            };
          }
        | undefined,
      kind,
    );
  } finally {
    store.checkpointRelease.resolve();
    const result = await pending;
    expect(result.turn.status).toBe("completed");
    await runtime.close();
  }
}

class DelayedResponseCheckpointStore extends LocalThreadStore {
  readonly checkpointCompletion = createDeferred<void>();
  responseCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (input.kind === "response-output") {
      this.responseCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (input.completedAt && checkpointId === this.responseCheckpointId) {
      await this.checkpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedCompletedTurnStatusStore extends LocalThreadStore {
  readonly turnCompletion = createDeferred<void>();
  readonly turnCompletionStarted = createDeferred<void>();
  #blocked = false;

  async updateTurnStatus(
    turnId: Parameters<LocalThreadStore["updateTurnStatus"]>[0],
    status: Parameters<LocalThreadStore["updateTurnStatus"]>[1],
    completedAt?: Parameters<LocalThreadStore["updateTurnStatus"]>[2],
    input?: Parameters<LocalThreadStore["updateTurnStatus"]>[3],
  ) {
    if (!this.#blocked && status === "completed") {
      this.#blocked = true;
      this.turnCompletionStarted.resolve();
      await this.turnCompletion.promise;
    }
    return super.updateTurnStatus(turnId, status, completedAt, input);
  }
}

class DelayedFailedTurnStatusStore extends LocalThreadStore {
  readonly turnFailure = createDeferred<void>();
  readonly turnFailureStarted = createDeferred<void>();
  #blocked = false;

  async updateTurnStatus(
    turnId: Parameters<LocalThreadStore["updateTurnStatus"]>[0],
    status: Parameters<LocalThreadStore["updateTurnStatus"]>[1],
    completedAt?: Parameters<LocalThreadStore["updateTurnStatus"]>[2],
    input?: Parameters<LocalThreadStore["updateTurnStatus"]>[3],
  ) {
    if (!this.#blocked && status === "failed") {
      this.#blocked = true;
      this.turnFailureStarted.resolve();
      await this.turnFailure.promise;
    }
    return super.updateTurnStatus(turnId, status, completedAt, input);
  }
}

class DelayedVerificationVerdictCheckpointStore extends LocalThreadStore {
  readonly checkpointCompletion = createDeferred<void>();
  readonly providerRequestSave = createDeferred<void>();
  readonly providerRequestSaveStarted = createDeferred<void>();
  verificationCheckpointId?: string;
  #blockedProviderRequest = false;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (
      !this.#blockedProviderRequest &&
      this.verificationCheckpointId &&
      input.kind === "provider-request"
    ) {
      this.#blockedProviderRequest = true;
      this.providerRequestSaveStarted.resolve();
      await this.providerRequestSave.promise;
    }
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (input.kind === "verification-verdict") {
      this.verificationCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (input.completedAt && checkpointId === this.verificationCheckpointId) {
      await this.checkpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedAttachmentStore extends LocalThreadStore {
  readonly attachmentWrite = createDeferred<void>();

  async putAttachment(...args: Parameters<LocalThreadStore["putAttachment"]>) {
    await this.attachmentWrite.promise;
    return super.putAttachment(...args);
  }
}

class DelayedVerificationVerdictAppendStore extends LocalThreadStore {
  readonly verdictAppend = createDeferred<void>();
  verificationCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (input.kind === "verification-verdict") {
      this.verificationCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async appendVerdictRecord(
    ...args: Parameters<LocalThreadStore["appendVerdictRecord"]>
  ): ReturnType<LocalThreadStore["appendVerdictRecord"]> {
    await this.verdictAppend.promise;
    return super.appendVerdictRecord(...args);
  }
}

class DelayedToolResultAppendStore extends LocalThreadStore {
  readonly toolResultAppend = createDeferred<void>();

  async appendItems(...args: Parameters<LocalThreadStore["appendItems"]>) {
    const [items] = args;
    if (items.some((item) => item.kind === "tool-result")) {
      await this.toolResultAppend.promise;
    }
    return super.appendItems(...args);
  }
}

class DelayedWaitRequestControlAppendStore extends LocalThreadStore {
  readonly controlAppend = createDeferred<void>();
  readonly controlAppendStarted = createDeferred<void>();
  #blocked = false;

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    readonly action: "action-requested" | "approval-requested",
  ) {
    super(options);
  }

  async appendItems(...args: Parameters<LocalThreadStore["appendItems"]>) {
    const [items] = args;
    if (
      !this.#blocked &&
      items.some((item) => item.kind === "control" && item.action === this.action)
    ) {
      this.#blocked = true;
      this.controlAppendStarted.resolve();
      await this.controlAppend.promise;
    }
    return super.appendItems(...args);
  }
}

class DelayedApprovalResolutionCheckpointStore extends LocalThreadStore {
  readonly resolutionUpdate = createDeferred<void>();
  readonly resolutionUpdateStarted = createDeferred<void>();
  #blocked = false;

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    const payload = input.payload as { kind?: string; resolution?: unknown } | undefined;
    if (!this.#blocked && payload?.kind === "approval" && payload.resolution) {
      this.#blocked = true;
      this.resolutionUpdateStarted.resolve();
      await this.resolutionUpdate.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedApprovalReviewSaveStore extends LocalApprovalStore {
  readonly reviewSave = createDeferred<void>();
  readonly reviewSaveStarted = createDeferred<void>();
  #blocked = false;

  async saveReviewRequest(
    ...args: Parameters<LocalApprovalStore["saveReviewRequest"]>
  ): ReturnType<LocalApprovalStore["saveReviewRequest"]> {
    if (!this.#blocked) {
      this.#blocked = true;
      this.reviewSaveStarted.resolve();
      await this.reviewSave.promise;
    }
    return super.saveReviewRequest(...args);
  }
}

class DelayedSubagentJoinCheckpointCompletionStore extends LocalThreadStore {
  readonly joinCheckpointCompletion = createDeferred<void>();
  readonly joinCheckpointCompletionStarted = createDeferred<void>();
  joinCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (!this.joinCheckpointId && input.kind === "subagent-join") {
      this.joinCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (input.completedAt && checkpointId === this.joinCheckpointId) {
      this.joinCheckpointCompletionStarted.resolve();
      await this.joinCheckpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedSubagentJoinCheckpointSaveStore extends LocalThreadStore {
  readonly joinCheckpointSave = createDeferred<void>();
  readonly joinCheckpointSaveStarted = createDeferred<void>();
  #blocked = false;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (!this.#blocked && input.kind === "subagent-join") {
      this.#blocked = true;
      this.joinCheckpointSaveStarted.resolve();
      await this.joinCheckpointSave.promise;
    }
    return super.saveRunCheckpoint(input, ...rest);
  }
}

class FailProviderRequestCheckpointCompletionStore extends LocalThreadStore {
  #failed = false;
  providerRequestCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (!this.providerRequestCheckpointId && input.kind === "provider-request") {
      this.providerRequestCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (!this.#failed && input.completedAt && checkpointId === this.providerRequestCheckpointId) {
      this.#failed = true;
      throw new Error("provider request checkpoint completion failed");
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedProviderRequestCheckpointCompletionStore extends LocalThreadStore {
  readonly checkpointCompletion = createDeferred<void>();
  readonly checkpointCompletionStarted = createDeferred<void>();
  providerRequestCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (!this.providerRequestCheckpointId && input.kind === "provider-request") {
      this.providerRequestCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (
      input.completedAt &&
      (!this.providerRequestCheckpointId || checkpointId === this.providerRequestCheckpointId)
    ) {
      this.checkpointCompletionStarted.resolve();
      await this.checkpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedProviderRequestReplayableMarkStore extends LocalThreadStore {
  readonly replayableMark = createDeferred<void>();
  readonly replayableMarkStarted = createDeferred<void>();
  #blocked = false;
  replayablePayload?: { kind?: string; requestKind?: string };

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    const payload = input.payload as { kind?: string; requestKind?: string } | undefined;
    if (
      !this.#blocked &&
      payload?.kind === "provider-request" &&
      (payload.requestKind === "decide" || payload.requestKind === "generate")
    ) {
      this.#blocked = true;
      this.replayablePayload = payload;
      this.replayableMarkStarted.resolve();
      await this.replayableMark.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedRepairReplayableMarkStore extends LocalThreadStore {
  readonly repairReplayableMark = createDeferred<void>();
  readonly repairReplayableMarkStarted = createDeferred<void>();
  #blocked = false;

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    private readonly repairCode: "PROVIDER_DECISION_INVALID" | "PROVIDER_NO_ACTION",
  ) {
    super(options);
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    const payload = input.payload as
      | {
          kind?: string;
          correctionTrace?: { code?: string };
          requestKind?: string;
        }
      | undefined;
    if (
      !this.#blocked &&
      payload?.kind === "provider-request" &&
      (payload.requestKind === "decide" || payload.requestKind === "generate") &&
      payload.correctionTrace?.code === this.repairCode
    ) {
      this.#blocked = true;
      this.repairReplayableMarkStarted.resolve();
      await this.repairReplayableMark.promise;
    }

    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedOwnedProviderRequestCheckpointCompletionStore extends LocalThreadStore {
  readonly checkpointCompletion = createDeferred<void>();
  readonly checkpointCompletionStarted = createDeferred<void>();
  providerRequestCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (!this.providerRequestCheckpointId && input.kind === "provider-request") {
      this.providerRequestCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (input.completedAt && checkpointId === this.providerRequestCheckpointId) {
      this.checkpointCompletionStarted.resolve();
      await this.checkpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedWaitCheckpointCompletionStore extends LocalThreadStore {
  readonly checkpointCompletion = createDeferred<void>();
  readonly checkpointCompletionStarted = createDeferred<void>();
  waitCheckpointId?: string;

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    readonly waitKind: SaveRunCheckpointInput["kind"],
  ) {
    super(options);
  }

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (input.kind !== this.waitKind && this.waitCheckpointId) {
      const pending = await super.getPendingRunCheckpointByTurn(input.turnId);
      if (pending?.id === this.waitCheckpointId) {
        this.checkpointCompletionStarted.resolve();
        await this.checkpointCompletion.promise;
      }
    }
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (input.kind === this.waitKind) {
      this.waitCheckpointId = checkpoint.id;
    }
    return checkpoint;
  }

  async updateRunCheckpoint(
    checkpointId: string,
    input: UpdateRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["updateRunCheckpoint"]> extends [any, any, ...infer R]
      ? R
      : never
  ) {
    if (input.completedAt && checkpointId === this.waitCheckpointId) {
      this.checkpointCompletionStarted.resolve();
      await this.checkpointCompletion.promise;
    }
    return super.updateRunCheckpoint(checkpointId as never, input, ...rest);
  }
}

class DelayedProviderRequestSupersedeStore extends LocalThreadStore {
  readonly checkpointSupersede = createDeferred<void>();
  readonly checkpointSupersedeStarted = createDeferred<void>();
  waitCheckpointId?: string;

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (input.kind === "provider-request" && this.waitCheckpointId) {
      const pending = await super.getPendingRunCheckpointByTurn(input.turnId);
      if (pending?.id === this.waitCheckpointId) {
        this.checkpointSupersedeStarted.resolve();
        await this.checkpointSupersede.promise;
      }
    }
    return super.saveRunCheckpoint(input, ...rest);
  }
}

class DelayedCheckpointSaveStore extends LocalThreadStore {
  readonly checkpointSave = createDeferred<void>();
  readonly checkpointSaveStarted = createDeferred<void>();
  #blocked = false;

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    readonly checkpointKind: SaveRunCheckpointInput["kind"],
  ) {
    super(options);
  }

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (!this.#blocked && input.kind === this.checkpointKind) {
      this.#blocked = true;
      this.checkpointSaveStarted.resolve();
      await this.checkpointSave.promise;
    }
    return super.saveRunCheckpoint(input, ...rest);
  }
}

class DelayedPersistedCheckpointStore extends LocalThreadStore {
  readonly checkpointPersisted = createDeferred<void>();
  readonly checkpointRelease = createDeferred<void>();
  #blocked = false;

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    readonly checkpointKind: SaveRunCheckpointInput["kind"],
  ) {
    super(options);
  }

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    const checkpoint = await super.saveRunCheckpoint(input, ...rest);
    if (!this.#blocked && input.kind === this.checkpointKind) {
      this.#blocked = true;
      this.checkpointPersisted.resolve();
      await this.checkpointRelease.promise;
    }
    return checkpoint;
  }
}

class CapturingToolOutputCheckpointStore extends LocalThreadStore {
  readonly toolOutputPayloads: ThreadMetadata[] = [];

  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (input.kind === "tool-output") {
      this.toolOutputPayloads.push(input.payload);
    }
    return super.saveRunCheckpoint(input, ...rest);
  }
}

class FailingToolOutputCheckpointStore extends LocalThreadStore {
  async saveRunCheckpoint(
    input: SaveRunCheckpointInput,
    ...rest: Parameters<LocalThreadStore["saveRunCheckpoint"]> extends [any, ...infer R] ? R : never
  ) {
    if (input.kind === "tool-output") {
      throw new Error("checkpoint write failed");
    }
    return super.saveRunCheckpoint(input, ...rest);
  }
}

class FailingSecondReplayInputAssetStore extends LocalThreadStore {
  #replayInputAssetWrites = 0;

  async putAttachment(...args: Parameters<LocalThreadStore["putAttachment"]>) {
    const [input] = args;
    if (input.contentType === REPLAY_TOOL_INPUT_ASSET_CONTENT_TYPE) {
      this.#replayInputAssetWrites += 1;
      if (this.#replayInputAssetWrites === 2) {
        await new Promise<void>((resolve) => setTimeout(resolve, 0));
        throw new Error("replay input asset write failed");
      }
    }
    return super.putAttachment(...args);
  }
}

class DelayedCompactionFollowUpClearStore extends LocalThreadStore {
  readonly followUpClear = createDeferred<void>();
  readonly followUpClearStarted = createDeferred<void>();
  #blocked = false;

  async updateThreadMetadata(
    threadId: Parameters<LocalThreadStore["updateThreadMetadata"]>[0],
    input: Parameters<LocalThreadStore["updateThreadMetadata"]>[1],
  ) {
    if (
      !this.#blocked &&
      input.metadata &&
      Object.prototype.hasOwnProperty.call(input.metadata, "pendingCompactionFollowUpOperation") &&
      input.metadata.pendingCompactionFollowUpOperation === undefined
    ) {
      this.#blocked = true;
      this.followUpClearStarted.resolve();
      await this.followUpClear.promise;
    }
    return super.updateThreadMetadata(threadId, input);
  }
}

class FailOnceProjectionSnapshotStore extends LocalThreadStore {
  #failed = false;
  readonly #failKind: "thread-events" | "thread-runs";

  constructor(
    options: ConstructorParameters<typeof LocalThreadStore>[0],
    failKind: "thread-events" | "thread-runs" = "thread-runs",
  ) {
    super(options);
    this.#failKind = failKind;
  }

  async saveProjectionSnapshot(input: Parameters<LocalThreadStore["saveProjectionSnapshot"]>[0]) {
    if (
      !this.#failed &&
      input.kind === this.#failKind &&
      (input.status ?? "healthy") === "healthy"
    ) {
      this.#failed = true;
      throw new Error(`projection ${input.kind} write failed`);
    }
    return super.saveProjectionSnapshot(input);
  }
}

describe("agent runtime provider checkpoint content hygiene", () => {
  it("stores large tool outputs as trace artifacts and keeps transcript previews compact", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-tool-trace-`);
    storageRoots.push(storageRoot);

    const runtime = new AgentRuntime({ storageRoot });
    const { thread } = await runtime.startThread();
    const largeOutput = "x".repeat(5_000);

    const result = await runtime.runTurn({
      threadId: thread.id,
      prompt: `tool:echo ${largeOutput}`,
    });
    expect(result.turn.status).toBe("completed");

    const resumed = await runtime.resumeThread(thread.id);
    const history = await runtime.getThreadHistory({ threadId: thread.id });
    const toolResult = resumed.items.find(
      (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-result" }> =>
        item.kind === "tool-result",
    );
    expect(toolResult).toMatchObject({
      kind: "tool-result",
      traceAssetId: expect.any(String),
    });
    expect(toolResult?.output.length ?? 0).toBeLessThan(largeOutput.length);
    expect(toolResult?.output).toContain("[truncated]");

    const traceAsset = history.assets.find((asset) => asset.id === toolResult?.traceAssetId);
    expect(traceAsset?.kind).toBe("artifact");
    const tracePath = join(
      storageRoot,
      "threads",
      thread.id,
      "artifacts",
      result.turn.id,
      traceAsset?.name ?? "",
    );
    expect(readFileSync(tracePath, "utf8")).toBe(largeOutput);
  });

  it("feeds trace previews instead of raw large tool outputs to provider follow-ups", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-tool-followup-trace-`);
    storageRoots.push(storageRoot);
    const largeOutput = "x".repeat(5_000);
    let decideCount = 0;
    let followUpToolContent = "";
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            reasoning: "Read a large external payload.",
            toolCalls: [
              {
                input: largeOutput,
                toolName: "echo",
              },
            ],
          };
        }
        followUpToolContent =
          [...input.messages].reverse().find((message) => message.role === "tool")?.content ?? "";
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "large output handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "large output handled",
        };
      },
    };

    const runtime = new AgentRuntime({ provider, storageRoot });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "inspect external data" });

    expect(result.turn.status).toBe("completed");
    expect(followUpToolContent.length).toBeLessThan(largeOutput.length);
    expect(followUpToolContent).toContain("[truncated]");
    expect(followUpToolContent).toContain("Full tool output persisted as a thread artifact.");
    expect(followUpToolContent).not.toContain(largeOutput);
  });

  it("omits persisted write content from provider follow-up tool inputs", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-write-followup-input-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const largeContent = "line\n".repeat(2_000);
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  content: largeContent,
                  path: "out.txt",
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "write content handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "write content handled",
        };
      },
    };

    const runtime = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "write a large file" });

    expect(result.turn.status).toBe("completed");
    expect(readFileSync(join(workspaceRoot, "out.txt"), "utf8")).toBe(largeContent);
    expect(followUpToolInput).toEqual({
      content: expect.stringContaining("content omitted from provider follow-up"),
      path: "out.txt",
    });
    expect(JSON.stringify(followUpToolInput)).not.toContain(largeContent);

    const resumed = await runtime.resumeThread(thread.id);
    const toolCall = resumed.items.find(
      (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-call" }> =>
        item.kind === "tool-call" && item.toolName === "write-workspace",
    );
    expect(toolCall?.input).toBe(
      `out.txt|[content omitted: ${Buffer.byteLength(largeContent, "utf8")} bytes]`,
    );
    expect(toolCall?.input).not.toContain(largeContent);
  });

  it("omits failed write-workspace content from provider follow-up tool inputs", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-failed-write-followup-input-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    mkdirSync(join(workspaceRoot, "src"), { recursive: true });
    const largeContent = "failed write payload\n".repeat(1_000);
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    let followUpToolOutcome: string | undefined;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  content: largeContent,
                  path: "src",
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        followUpToolOutcome = [...input.messages]
          .reverse()
          .find(
            (message): message is Extract<ConversationMessage, { role: "tool" }> =>
              message.role === "tool" && message.toolName === "write-workspace",
          )?.outcome;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "failed write handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "failed write handled",
        };
      },
    };

    const runtime = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "write to a directory" });

    expect(result.turn.status).toBe("completed");
    expect(followUpToolOutcome).toBe("error");
    expect(followUpToolInput).toEqual({
      content: expect.stringContaining("content omitted from provider follow-up"),
      path: "src",
    });
    expect(JSON.stringify(followUpToolInput)).not.toContain(largeContent);
  });

  it("omits invalid write-workspace content from failed tool-call history", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-invalid-write-history-`);
    storageRoots.push(storageRoot);
    const largeContent = "invalid write payload\n".repeat(1_000);
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  content: largeContent,
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "invalid write handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "invalid write handled",
        };
      },
    };

    const runtime = new AgentRuntime({ provider, storageRoot });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "write invalid content" });

    expect(result.turn.status).toBe("completed");
    expect(JSON.stringify(followUpToolInput)).toContain("content omitted from provider follow-up");
    expect(JSON.stringify(followUpToolInput)).not.toContain(largeContent);

    const resumed = await runtime.resumeThread(thread.id);
    const toolCall = resumed.items.find(
      (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-call" }> =>
        item.kind === "tool-call" && item.toolName === "write-workspace",
    );
    expect(toolCall?.input).toContain("content omitted from provider follow-up");
    expect(toolCall?.input).not.toContain(largeContent);
    expect(JSON.stringify(toolCall?.historyInput)).not.toContain(largeContent);
  });

  it("omits long content-like plugin tool input from provider follow-up and tool-call history", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-plugin-input-history-`);
    storageRoots.push(storageRoot);
    const largeContent = "plugin payload\n".repeat(1_000);
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    const pluginTool: ToolDefinition<{ input: string; path: string }> = {
      capabilities() {
        return [];
      },
      description: "Accepts plugin content.",
      execute() {
        return "plugin ok";
      },
      executionClass: "read-only",
      idempotent: true,
      inputSchema: {
        additionalProperties: false,
        properties: {
          input: { type: "string" },
          path: { type: "string" },
        },
        required: ["input", "path"],
        type: "object",
      },
      name: "plugin-content",
      source: "plugin",
    };
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            input: {
              input: largeContent,
              path: "notes.txt",
            },
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolName: "plugin-content",
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "plugin handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "plugin handled",
        };
      },
    };

    const runtime = new AgentRuntime({
      agentProfiles: [
        {
          allowedTools: ["plugin-content"],
          description: "Plugin content profile.",
          name: "plugin-content-profile",
          source: "user",
        },
      ],
      provider,
      storageRoot,
      tools: createDefaultToolRegistry({ extraTools: [pluginTool] }),
    });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({
      agentProfile: "plugin-content-profile",
      threadId: thread.id,
      prompt: "send plugin content",
    });

    expect(result.turn.status).toBe("completed");
    expect(JSON.stringify(followUpToolInput)).toContain("content omitted from provider follow-up");
    expect(JSON.stringify(followUpToolInput)).not.toContain(largeContent);

    const resumed = await runtime.resumeThread(thread.id);
    const toolCall = resumed.items.find(
      (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-call" }> =>
        item.kind === "tool-call" && item.toolName === "plugin-content",
    );
    expect(toolCall?.input).toContain("content omitted from provider follow-up");
    expect(toolCall?.input).not.toContain(largeContent);
    expect(JSON.stringify(toolCall?.historyInput)).not.toContain(largeContent);
  });

  it("omits alias-shaped invalid write content from failed tool-call history", async () => {
    const storageRoot = mkdtempSync(`${tmpdir()}/best-agent-invalid-alias-write-history-`);
    storageRoots.push(storageRoot);
    const largeContent = "alias payload\n".repeat(1_000);
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  file: "out.txt",
                  text: largeContent,
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "invalid alias write handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "invalid alias write handled",
        };
      },
    };

    const runtime = new AgentRuntime({ provider, storageRoot });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({
      threadId: thread.id,
      prompt: "write invalid alias content",
    });

    expect(result.turn.status).toBe("completed");
    expect(followUpToolInput).toMatchObject({
      file: "out.txt",
      text: expect.stringContaining("content omitted from provider follow-up"),
    });
    expect(JSON.stringify(followUpToolInput)).not.toContain(largeContent);

    const resumed = await runtime.resumeThread(thread.id);
    const toolCall = resumed.items.find(
      (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-call" }> =>
        item.kind === "tool-call" && item.toolName === "write-workspace",
    );
    expect(toolCall?.input).toContain("content omitted from provider follow-up");
    expect(toolCall?.input).not.toContain(largeContent);
    expect(JSON.stringify(toolCall?.historyInput)).not.toContain(largeContent);
  });

  it("omits completed content tool inputs from subsequent tool checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-safe-completed-checkpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const store = new CapturingToolOutputCheckpointStore({ storageRoot });
    const largeContent = "checkpoint payload\n".repeat(1_000);
    let decideCount = 0;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  content: largeContent,
                  path: "out.txt",
                },
                toolName: "write-workspace",
              },
              {
                input: {
                  path: "out.txt",
                },
                toolName: "read-file",
              },
            ],
          };
        }
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "checkpoint content handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "checkpoint content handled",
        };
      },
    };

    const runtime = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot, store });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "write then read" });

    expect(result.turn.status).toBe("completed");
    const readCheckpointPayload = store.toolOutputPayloads.find(
      (payload) => payload.toolName === "read-file",
    );
    expect(readCheckpointPayload).toBeDefined();
    const completedToolCalls = readCheckpointPayload?.completedToolCalls as
      | Array<{ toolInput?: ToolInputValue; toolName?: string }>
      | undefined;
    expect(completedToolCalls?.[0]).toMatchObject({
      toolInput: {
        content: expect.stringContaining("content omitted from provider follow-up"),
        path: "out.txt",
      },
      toolName: "write-workspace",
    });
    expect(JSON.stringify(readCheckpointPayload)).not.toContain(largeContent);
  });

  it("omits active content tool input from tool-output checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-safe-active-checkpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const store = new CapturingToolOutputCheckpointStore({ storageRoot });
    const largeContent = "active checkpoint payload\n".repeat(1_000);
    let decideCount = 0;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  content: largeContent,
                  path: "out.txt",
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "checkpoint content handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "checkpoint content handled",
        };
      },
    };

    const runtime = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot, store });
    const { thread } = await runtime.startThread();
    const result = await runtime.runTurn({ threadId: thread.id, prompt: "write a file" });

    expect(result.turn.status).toBe("completed");
    const writeCheckpointPayload = store.toolOutputPayloads.find(
      (payload) => payload.toolName === "write-workspace",
    );
    expect(writeCheckpointPayload).toBeDefined();
    expect(writeCheckpointPayload?.toolInput).toMatchObject({
      content: expect.stringContaining("content omitted from provider follow-up"),
      path: "out.txt",
    });
    expect(JSON.stringify(writeCheckpointPayload?.toolInput)).not.toContain(largeContent);
    expect(JSON.stringify(writeCheckpointPayload)).not.toContain(largeContent);
    expect(JSON.stringify(writeCheckpointPayload)).not.toContain("sha256:");
  });

  it("omits process-session-write stdin from provider history and checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-process-write-history-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const store = new CapturingToolOutputCheckpointStore({ storageRoot });
    const stdin = "secret stdin\n".repeat(1_000);
    const processSessionWriteTool: ToolDefinition<{ input: string; sessionId: string }> = {
      capabilities() {
        return [];
      },
      description: "Write input to a running process session stdin.",
      execute(input) {
        return `Wrote ${Buffer.byteLength(input.input, "utf8")} bytes to process session ${input.sessionId}.`;
      },
      executionClass: "read-only",
      formatInput(input) {
        return `${input.sessionId} (${Buffer.byteLength(input.input, "utf8")} bytes)`;
      },
      idempotent: false,
      inputSchema: {
        additionalProperties: false,
        properties: {
          input: { type: "string" },
          sessionId: { type: "string" },
        },
        required: ["sessionId", "input"],
        type: "object",
      },
      name: "process-session-write",
      replayPolicy: "never",
      source: "built-in",
      summarize(input) {
        return `Tool process-session-write wrote ${Buffer.byteLength(input.input, "utf8")} bytes to process session ${input.sessionId}.`;
      },
    };
    let decideCount = 0;
    let followUpToolInput: ToolInputValue | undefined;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            input: {
              input: stdin,
              sessionId: "proc_test",
            },
            model: "test-provider",
            provider: "openai",
            toolName: "process-session-write",
          };
        }
        followUpToolInput = [...input.messages]
          .reverse()
          .find((message) => message.role === "assistant")?.toolCalls?.[0]?.input;
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "stdin handled",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "stdin handled",
        };
      },
    };

    const runtime = new AgentRuntime({
      cwd: workspaceRoot,
      provider,
      storageRoot,
      store,
      tools: createDefaultToolRegistry({ extraTools: [processSessionWriteTool], noBuiltIns: true }),
    });
    try {
      const { thread } = await runtime.startThread();
      const result = await runtime.runTurn({ threadId: thread.id, prompt: "write stdin" });

      expect(result.turn.status).toBe("completed");
      expect(followUpToolInput).toMatchObject({
        input: expect.stringContaining("content omitted from provider follow-up"),
        sessionId: "proc_test",
      });
      expect(JSON.stringify(followUpToolInput)).not.toContain(stdin);
      const writeCheckpointPayload = store.toolOutputPayloads.find(
        (payload) => payload.toolName === "process-session-write",
      );
      expect(writeCheckpointPayload?.toolInput).toMatchObject({
        input: expect.stringContaining("content omitted from provider follow-up"),
        sessionId: "proc_test",
      });
      expect(JSON.stringify(writeCheckpointPayload)).not.toContain(stdin);

      const resumed = await runtime.resumeThread(thread.id);
      const toolCall = resumed.items.find(
        (item): item is Extract<(typeof resumed.items)[number], { kind: "tool-call" }> =>
          item.kind === "tool-call" && item.toolName === "process-session-write",
      );
      expect(toolCall?.historyInput).toEqual({
        inputBytes: Buffer.byteLength(stdin, "utf8"),
        sessionId: "proc_test",
      });
      expect(JSON.stringify(toolCall)).not.toContain(stdin);
    } finally {
      await runtime.close();
    }
  });

  it("omits active content tool input from approval checkpoints while preserving replay input", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-approval-content-checkpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const content = "approval checkpoint payload\n".repeat(1_000);
    let approvalId: string | undefined;
    let executedContent: string | undefined;
    let decideCount = 0;
    const gatedWriteWorkspaceTool: ToolDefinition<{ content: string; path: string }> = {
      capabilities(_input, context) {
        return [
          {
            action: "read",
            group: "filesystem",
            path: join(dirname(context.cwd), "approval-gate.txt"),
          },
        ];
      },
      description: "Write a file after an approval-gated capability.",
      executionClass: "workspace-mutation",
      idempotent: false,
      inputSchema: {
        additionalProperties: false,
        properties: {
          content: { type: "string" },
          path: { type: "string" },
        },
        required: ["path", "content"],
        type: "object",
      },
      name: "write-workspace",
      async execute(input) {
        executedContent = input.content;
        writeFileSync(join(workspaceRoot, input.path), input.content);
        return join(workspaceRoot, input.path);
      },
      source: "built-in",
    };
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            input: {
              content,
              path: "approved.txt",
            },
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolName: "write-workspace",
          };
        }
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "approval write completed",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "approval write completed",
        };
      },
    };

    const tools = createDefaultToolRegistry({
      extraTools: [gatedWriteWorkspaceTool],
      noBuiltIns: true,
    });
    const runtimeA = new AgentRuntime({
      approvalTimeoutMs: 1_000,
      cwd: workspaceRoot,
      provider,
      storageRoot,
      tools,
    });
    runtimeA.subscribe(({ event }) => {
      if (event.type === "approval.requested") {
        approvalId = event.approval.id;
      }
    });
    const { thread } = await runtimeA.startThread();
    const pendingA = runtimeA
      .runTurn({ threadId: thread.id, prompt: "write after approval" })
      .catch(() => undefined);

    const store = new LocalThreadStore({ storageRoot });
    let runtimeB: AgentRuntime | undefined;
    try {
      await expect.poll(() => approvalId, { timeout: 5_000 }).toBeTruthy();
      const activeRun = (await store.listRuns(thread.id)).at(-1);
      expect(activeRun).toBeTruthy();
      const checkpoint = await store.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expect(checkpoint?.kind).toBe("approval-wait");
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(content);
      expect(checkpoint?.payload).toMatchObject({
        activeReplayToolInputAssetId: expect.any(String),
        activeReplayToolInputDigest: expect.any(String),
        toolInput: {
          content: expect.stringContaining("content omitted from provider follow-up"),
          path: "approved.txt",
        },
        toolName: "write-workspace",
      });

      runtimeB = new AgentRuntime({
        approvalTimeoutMs: 1_000,
        cwd: workspaceRoot,
        provider,
        storageRoot,
        tools,
      });
      await runtimeB.respondToApprovalWithScope(approvalId as any, "allow", "once");
      await expect
        .poll(async () => (await runtimeB!.resumeThread(thread.id)).turns.at(-1)?.status, {
          timeout: 5_000,
        })
        .toBe("completed");

      expect(executedContent).toBe(content);
      expect(readFileSync(join(workspaceRoot, "approved.txt"), "utf8")).toBe(content);
      expect(
        await store.readAssetData(checkpoint?.payload.activeReplayToolInputAssetId as never),
      ).toBeUndefined();
    } finally {
      await pendingA;
      await runtimeA.close();
      await runtimeB?.close();
      store.close();
    }
  });

  it("assetizes pending content tool inputs in action checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-action-pending-checkpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const content = "pending action checkpoint payload\n".repeat(1_000);
    let actionId: string | undefined;
    let decideCount = 0;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  questions: [
                    {
                      id: "ready",
                      kind: "choice",
                      options: [{ label: "Yes" }, { label: "No" }],
                      question: "Continue?",
                    },
                  ],
                },
                toolName: "ask-user",
              },
              {
                input: {
                  content,
                  path: "after-action.txt",
                },
                toolName: "write-workspace",
              },
            ],
          };
        }
        expect(input.messages.at(-1)?.content ?? "").toContain("Tool write-workspace returned:");
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "action pending write completed",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "action pending write completed",
        };
      },
    };

    const runtimeA = new AgentRuntime({
      approvalTimeoutMs: 1_000,
      cwd: workspaceRoot,
      provider,
      storageRoot,
    });
    let runtimeB: AgentRuntime | undefined;
    runtimeA.subscribe(({ event }) => {
      if (event.type === "action.required") {
        actionId = event.actionId;
      }
    });
    const { thread } = await runtimeA.startThread();
    const pendingA = runtimeA
      .runTurn({ threadId: thread.id, prompt: "ask then write" })
      .catch(() => undefined);

    const store = new LocalThreadStore({ storageRoot });
    try {
      await expect.poll(() => actionId, { timeout: 5_000 }).toBeTruthy();
      const activeRun = (await store.listRuns(thread.id)).at(-1);
      expect(activeRun).toBeTruthy();
      const checkpoint = await store.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expect(checkpoint?.kind).toBe("action-wait");
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(content);
      const pendingCalls = checkpoint?.payload.pendingToolCalls as
        | Array<{
            replayToolInputAssetId?: string;
            replayToolInputDigest?: string;
            toolInput?: ToolInputValue;
            toolName?: string;
          }>
        | undefined;
      expect(pendingCalls?.[0]).toMatchObject({
        replayToolInputAssetId: expect.any(String),
        replayToolInputDigest: expect.any(String),
        toolInput: {
          content: expect.stringContaining("content omitted from provider follow-up"),
          path: "after-action.txt",
        },
        toolName: "write-workspace",
      });

      runtimeB = new AgentRuntime({
        approvalTimeoutMs: 1_000,
        cwd: workspaceRoot,
        provider,
        storageRoot,
      });
      await runtimeB.respondToAction(actionId as any, { ready: "Yes" });
      await expect
        .poll(async () => (await runtimeB!.resumeThread(thread.id)).turns.at(-1)?.status, {
          timeout: 5_000,
        })
        .toBe("completed");

      expect(readFileSync(join(workspaceRoot, "after-action.txt"), "utf8")).toBe(content);
      expect(await store.readAssetData(pendingCalls?.[0]?.replayToolInputAssetId as never)).toBe(
        undefined,
      );
    } finally {
      await pendingA;
      await runtimeA.close();
      await runtimeB?.close();
      store.close();
    }
  });

  it("assetizes pending plugin content inputs in action checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-action-plugin-pending-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const content = "pending plugin checkpoint payload\n".repeat(1_000);
    let actionId: string | undefined;
    let decideCount = 0;
    const pluginTool: ToolDefinition<{ input: string; path: string }> = {
      capabilities() {
        return [];
      },
      description: "Accepts plugin content.",
      executionClass: "read-only",
      idempotent: true,
      inputSchema: {
        additionalProperties: false,
        properties: {
          input: { type: "string" },
          path: { type: "string" },
        },
        required: ["input", "path"],
        type: "object",
      },
      name: "plugin-content",
      execute(input) {
        return `read ${input.path}`;
      },
      source: "plugin",
    };
    const tools = createDefaultToolRegistry({ extraTools: [pluginTool] });
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        if (decideCount === 1) {
          return {
            kind: "tool",
            model: "test-provider",
            provider: "openai",
            toolCalls: [
              {
                input: {
                  questions: [
                    {
                      id: "ready",
                      kind: "choice",
                      options: [{ label: "Yes" }, { label: "No" }],
                      question: "Continue?",
                    },
                  ],
                },
                toolName: "ask-user",
              },
              {
                input: {
                  input: content,
                  path: "plugin.txt",
                },
                toolName: "plugin-content",
              },
            ],
          };
        }
        return {
          kind: "respond",
          model: "test-provider",
          provider: "openai",
          text: "plugin pending completed",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "plugin pending completed",
        };
      },
    };

    const runtimeA = new AgentRuntime({
      agentProfiles: [
        {
          allowedTools: ["ask-user", "plugin-content"],
          description: "Plugin action profile.",
          name: "plugin-action-profile",
          source: "user",
        },
      ],
      approvalTimeoutMs: 1_000,
      cwd: workspaceRoot,
      provider,
      storageRoot,
      tools,
    });
    runtimeA.subscribe(({ event }) => {
      if (event.type === "action.required") {
        actionId = event.actionId;
      }
    });
    const { thread } = await runtimeA.startThread();
    const pendingA = runtimeA
      .runTurn({
        agentProfile: "plugin-action-profile",
        threadId: thread.id,
        prompt: "ask then run plugin",
      })
      .catch(() => undefined);

    const store = new LocalThreadStore({ storageRoot });
    try {
      await expect.poll(() => actionId, { timeout: 5_000 }).toBeTruthy();
      const activeRun = (await store.listRuns(thread.id)).at(-1);
      expect(activeRun).toBeTruthy();
      const checkpoint = await store.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expect(checkpoint?.kind).toBe("action-wait");
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(content);
      const pendingCalls = checkpoint?.payload.pendingToolCalls as
        | Array<{
            replayToolInputAssetId?: string;
            replayToolInputDigest?: string;
            toolInput?: ToolInputValue;
            toolName?: string;
          }>
        | undefined;
      expect(pendingCalls?.[0]).toMatchObject({
        replayToolInputAssetId: expect.any(String),
        replayToolInputDigest: expect.any(String),
        toolInput: {
          input: expect.stringContaining("content omitted from provider follow-up"),
          path: "plugin.txt",
        },
        toolName: "plugin-content",
      });
      expect(
        (await store.readAssetData(pendingCalls?.[0]?.replayToolInputAssetId as never))?.toString(
          "utf8",
        ),
      ).toBe(JSON.stringify({ input: content, path: "plugin.txt" }));
    } finally {
      if (actionId) {
        await runtimeA.respondToAction(actionId as any, { ready: "Yes" }).catch(() => undefined);
      }
      await pendingA;
      await runtimeA.close();
      store.close();
    }
  });

  it("omits process-session-write stdin from tool-dispatch checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-process-write-dispatch-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const releaseTool = createDeferred<void>();
    const stdin = "dispatch stdin\n".repeat(1_000);
    const processSessionWriteTool: ToolDefinition<{ input: string; sessionId: string }> = {
      capabilities() {
        return [];
      },
      description: "Slow process stdin writer.",
      executionClass: "read-only",
      idempotent: false,
      inputSchema: {
        additionalProperties: false,
        properties: {
          input: { type: "string" },
          sessionId: { type: "string" },
        },
        required: ["sessionId", "input"],
        type: "object",
      },
      name: "process-session-write",
      replayPolicy: "never",
      async execute(input) {
        await releaseTool.promise;
        return `Wrote ${Buffer.byteLength(input.input, "utf8")} bytes to ${input.sessionId}.`;
      },
      source: "built-in",
    };
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        if (
          input.messages.some(
            (message) => message.role === "tool" && message.toolName === "process-session-write",
          )
        ) {
          return {
            kind: "respond",
            model: "test-provider",
            provider: "openai",
            text: "stdin dispatch completed",
          };
        }
        return {
          input: {
            input: stdin,
            sessionId: "proc_dispatch",
          },
          kind: "tool",
          model: "test-provider",
          provider: "openai",
          toolName: "process-session-write",
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "stdin dispatch completed",
        };
      },
    };
    const tools = createDefaultToolRegistry({
      extraTools: [processSessionWriteTool],
      noBuiltIns: true,
    });
    const runtime = new AgentRuntime({
      agentProfiles: [
        {
          description: "Allows process stdin writes.",
          name: "process-writer",
          source: "user",
          tools: ["process-session-write"],
        },
      ],
      cwd: workspaceRoot,
      policy: createDefaultRuntimePolicy({ cwd: workspaceRoot }).overlay({
        allowedTools: ["process-session-write"],
      }),
      provider,
      storageRoot,
      tools,
    });
    const store = new LocalThreadStore({ storageRoot });
    const { thread } = await runtime.startThread();
    const pending = runtime.runTurn({
      agentProfile: "process-writer",
      threadId: thread.id,
      prompt: "write stdin",
    });

    try {
      await expect
        .poll(async () => (await store.listRuns(thread.id)).at(-1), { timeout: 5_000 })
        .toBeTruthy();
      const activeRun = (await store.listRuns(thread.id)).at(-1);
      await expect
        .poll(async () => (await store.getPendingRunCheckpointByTurn(activeRun!.turnId))?.kind, {
          timeout: 5_000,
        })
        .toBe("tool-dispatch");
      const checkpoint = await store.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expect(checkpoint?.payload).toMatchObject({
        kind: "tool-dispatch",
        replayPolicy: "never",
        toolInput: {
          input: expect.stringContaining("content omitted from provider follow-up"),
          sessionId: "proc_dispatch",
        },
        toolName: "process-session-write",
      });
      expect(checkpoint?.payload.activeReplayToolInputAssetId).toBeUndefined();
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(stdin);

      releaseTool.resolve();
      const result = await pending;
      expect(result.turn.status).toBe("completed");
    } finally {
      releaseTool.resolve();
      await pending.catch(() => undefined);
      await runtime.close();
      store.close();
    }
  });

  it("assetizes pending content tool inputs in tool-output checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-pending-content-checkpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const contentA = "first checkpoint payload\n".repeat(1_000);
    const contentB = "pending checkpoint payload\n".repeat(1_000);
    let decideCount = 0;
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        const lastMessage = input.messages.at(-1)?.content ?? "";
        if (lastMessage.includes("Tool write-workspace returned:")) {
          return {
            kind: "respond",
            model: "test-provider",
            provider: "openai",
            text: "both files written",
          };
        }
        return {
          kind: "tool",
          model: "test-provider",
          provider: "openai",
          toolCalls: [
            {
              input: {
                content: contentA,
                path: "a.txt",
              },
              toolName: "write-workspace",
            },
            {
              input: {
                content: contentB,
                path: "b.txt",
              },
              toolName: "write-workspace",
            },
          ],
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "both files written",
        };
      },
    };

    const storeA = new DelayedPersistedCheckpointStore({ storageRoot }, "tool-output");
    const runtimeA = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot, store: storeA });
    const { thread } = await runtimeA.startThread();
    const pending = runtimeA.runTurn({ threadId: thread.id, prompt: "write both files" });

    let runtimeB: AgentRuntime | undefined;
    try {
      await storeA.checkpointPersisted.promise;
      const activeRun = (await storeA.listRuns(thread.id)).at(-1);
      expect(activeRun).toBeTruthy();
      const checkpoint = await storeA.getPendingRunCheckpointByTurn(activeRun!.turnId);
      expect(checkpoint?.kind).toBe("tool-output");
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(contentA);
      expect(JSON.stringify(checkpoint?.payload)).not.toContain(contentB);
      const pendingCalls = checkpoint?.payload.pendingToolCalls as
        | Array<{
            replayToolInputAssetId?: string;
            replayToolInputDigest?: string;
            toolInput?: ToolInputValue;
            toolName?: string;
          }>
        | undefined;
      expect(pendingCalls?.[0]).toMatchObject({
        replayToolInputAssetId: expect.any(String),
        replayToolInputDigest: expect.any(String),
        toolInput: {
          content: expect.stringContaining("content omitted from provider follow-up"),
          path: "b.txt",
        },
        toolName: "write-workspace",
      });
      expect(await storeA.listThreadAssets(thread.id)).toHaveLength(0);
      const activeAttempt = (await storeA.listRunAttempts(activeRun!.id)).at(-1);
      expect(activeAttempt).toBeTruthy();
      await storeA.updateRunAttempt(activeAttempt!.id, {
        lastHeartbeatAt: "2000-01-01T00:00:00.000Z",
      });

      runtimeB = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot });
      const resumed = await runtimeB.resumeThread(thread.id);

      expect(resumed.turns.at(-1)?.status).toBe("completed");
      expect(readFileSync(join(workspaceRoot, "a.txt"), "utf8")).toBe(contentA);
      expect(readFileSync(join(workspaceRoot, "b.txt"), "utf8")).toBe(contentB);
      expect(decideCount).toBe(2);
    } finally {
      storeA.checkpointRelease.resolve();
      await pending.catch(() => undefined);
      await runtimeA.close();
      await runtimeB?.close();
    }
  });

  it("preserves already-assetized pending content inputs across multiple tool-output checkpoints", async () => {
    const workspaceRoot = mkdtempSync(`${tmpdir()}/best-agent-pending-content-recheckpoint-`);
    const storageRoot = join(workspaceRoot, "state");
    storageRoots.push(workspaceRoot);
    const contentA = "first replay payload\n".repeat(1_000);
    const contentB = "second replay payload\n".repeat(1_000);
    const contentC = "third replay payload\n".repeat(1_000);
    let decideCount = 0;
    let followUpInputDigests: Array<string | undefined> = [];
    const provider: ModelProvider = {
      capabilities: structuredToolCapabilities,
      config: {
        kind: "openai",
        model: "test-provider",
      },
      async decide(input): Promise<ProviderDecisionOutput> {
        decideCount += 1;
        const lastMessage = input.messages.at(-1)?.content ?? "";
        if (lastMessage.includes("Tool write-workspace returned:")) {
          followUpInputDigests =
            [...input.messages]
              .reverse()
              .find((message) => message.role === "assistant")
              ?.toolCalls?.map((toolCall) => toolCall.inputStableDigest) ?? [];
          return {
            kind: "respond",
            model: "test-provider",
            provider: "openai",
            text: "all files written",
          };
        }
        return {
          kind: "tool",
          model: "test-provider",
          provider: "openai",
          toolCalls: [
            {
              input: {
                content: contentA,
                path: "a.txt",
              },
              toolName: "write-workspace",
            },
            {
              input: {
                content: contentB,
                path: "b.txt",
              },
              toolName: "write-workspace",
            },
            {
              input: {
                content: contentC,
                path: "c.txt",
              },
              toolName: "write-workspace",
            },
          ],
        };
      },
      async generate() {
        return {
          model: "test-provider",
          provider: "openai",
          text: "all files written",
        };
      },
    };

    const storeA = new DelayedPersistedCheckpointStore({ storageRoot }, "tool-output");
    const runtimeA = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot, store: storeA });
    const { thread } = await runtimeA.startThread();
    const pendingA = runtimeA.runTurn({ threadId: thread.id, prompt: "write three files" });

    let storeB: DelayedPersistedCheckpointStore | undefined;
    let runtimeB: AgentRuntime | undefined;
    let runtimeC: AgentRuntime | undefined;
    let pendingB: ReturnType<AgentRuntime["resumeThread"]> | undefined;
    try {
      await storeA.checkpointPersisted.promise;
      const activeRunA = (await storeA.listRuns(thread.id)).at(-1);
      expect(activeRunA).toBeTruthy();
      const checkpointA = await storeA.getPendingRunCheckpointByTurn(activeRunA!.turnId);
      expect(checkpointA?.kind).toBe("tool-output");
      const pendingCallsA = checkpointA?.payload.pendingToolCalls as
        | Array<{
            replayToolInputAssetId?: string;
            replayToolInputDigest?: string;
            toolInput?: ToolInputValue;
            toolName?: string;
          }>
        | undefined;
      const bAssetId = pendingCallsA?.[0]?.replayToolInputAssetId;
      const cAssetId = pendingCallsA?.[1]?.replayToolInputAssetId;
      const cDigest = pendingCallsA?.[1]?.replayToolInputDigest;
      expect(bAssetId).toEqual(expect.any(String));
      expect(cAssetId).toEqual(expect.any(String));
      expect(cDigest).toEqual(expect.any(String));
      expect(checkpointA?.payload.toolInputStableDigest).toBe(
        stableToolInputDigestForTest({ content: contentA, path: "a.txt" }),
      );
      expect(JSON.stringify(checkpointA?.payload)).not.toContain(contentC);
      const activeAttemptA = (await storeA.listRunAttempts(activeRunA!.id)).at(-1);
      expect(activeAttemptA).toBeTruthy();
      await storeA.updateRunAttempt(activeAttemptA!.id, {
        lastHeartbeatAt: "2000-01-01T00:00:00.000Z",
      });

      storeB = new DelayedPersistedCheckpointStore({ storageRoot }, "tool-output");
      runtimeB = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot, store: storeB });
      pendingB = runtimeB.resumeThread(thread.id);

      await storeB.checkpointPersisted.promise;
      const activeRunB = (await storeB.listRuns(thread.id)).at(-1);
      expect(activeRunB).toBeTruthy();
      const checkpointB = await storeB.getPendingRunCheckpointByTurn(activeRunB!.turnId);
      expect(checkpointB?.kind).toBe("tool-output");
      const pendingCallsB = checkpointB?.payload.pendingToolCalls as
        | Array<{
            replayToolInputAssetId?: string;
            replayToolInputDigest?: string;
            toolInput?: ToolInputValue;
            toolName?: string;
          }>
        | undefined;
      const completedCallsB = checkpointB?.payload.completedToolCalls as
        | Array<{ inputStableDigest?: string; toolName?: string }>
        | undefined;
      expect(completedCallsB?.[0]?.inputStableDigest).toBe(
        stableToolInputDigestForTest({ content: contentA, path: "a.txt" }),
      );
      expect(pendingCallsB?.[0]).toMatchObject({
        replayToolInputAssetId: cAssetId,
        replayToolInputDigest: cDigest,
        toolInput: {
          content: expect.stringContaining("content omitted from provider follow-up"),
          path: "c.txt",
        },
        toolName: "write-workspace",
      });
      expect(JSON.stringify(checkpointB?.payload)).not.toContain(contentC);
      expect(await storeB.readAssetData(bAssetId as never)).toBeUndefined();
      const activeAttemptB = (await storeB.listRunAttempts(activeRunB!.id)).at(-1);
      expect(activeAttemptB).toBeTruthy();
      await storeB.updateRunAttempt(activeAttemptB!.id, {
        lastHeartbeatAt: "2000-01-01T00:00:00.000Z",
      });

      runtimeC = new AgentRuntime({ cwd: workspaceRoot, provider, storageRoot });
      const resumed = await runtimeC.resumeThread(thread.id);

      expect(resumed.turns.at(-1)?.status).toBe("completed");
      expect(readFileSync(join(workspaceRoot, "a.txt"), "utf8")).toBe(contentA);
      expect(readFileSync(join(workspaceRoot, "b.txt"), "utf8")).toBe(contentB);
      expect(readFileSync(join(workspaceRoot, "c.txt"), "utf8")).toBe(contentC);
      expect(await storeB.readAssetData(cAssetId as never)).toBeUndefined();
      expect(decideCount).toBe(2);
      expect(followUpInputDigests[0]).toBe(
        stableToolInputDigestForTest({ content: contentA, path: "a.txt" }),
      );
      expect(followUpInputDigests[1]).toBe(
        stableToolInputDigestForTest({ content: contentB, path: "b.txt" }),
      );
    } finally {
      storeA.checkpointRelease.resolve();
      storeB?.checkpointRelease.resolve();
      await pendingA.catch(() => undefined);
      await pendingB?.catch(() => undefined);
      await runtimeA.close();
      await runtimeB?.close();
      await runtimeC?.close();
    }
  });
});
