From 4b9853c561ea3d89c92b8be8fade85f5238b3df8 Mon Sep 17 00:00:00 2001 From: collissimo <148455189+collissimo@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:57:39 +0100 Subject: [PATCH] feat(sim): add native cross-harness Self-Improvement Memory Previously, harness self-improvement memory (SIM) only ran through Claude Code hooks and CLI scripts, leaving Codex, Antigravity (ACP), OpenCode, and other T3 Code providers without shared rule injection, read-before-write enforcement, anti-self-grading, live runtime telemetry, or cross-provider auditing. This adds native, file-backed cross-harness SIM integration to T3 Code with zero SQLite migrations and full format-v2 / schema-3 byte-for-byte parity with standalone sim.mjs: - SimStore, SimService, and SimAuditService in apps/server/src/sim/ sharing ~/.claude/sim/ (envelope-only harness field, read-only loads without lock/rewrite, symlink and mode preservation, CLI fork self-grade auditing, and configurable on-demand advisor escalation via ServerSettings.sim.advisorModelSelection). - Native MCP toolkit (sim_read, sim_write, sim_apply_harness_change) deriving caller identity server-side, enforcing per-epoch read-before-write and fork-family anti-self-grading, and gating live harness edits on full-access/default mode and workspace/harnessDir confinement. - Filtered, epoch-cached thread instruction injection (<4KB Codex-safe sections) for Codex, ACP, and OpenCode, plus ACP threadInstructions passthrough. - SimObserverReactor tracking restart-safe context epochs in t3-epochs.json and logging cross-provider harness/runtime signals to telemetry.jsonl. Co-Authored-By: Antigravity (gemini-4-neon) with Claude Opus 5.5 and Claude Fable 5.2 --- FORK.md | 54 +- apps/server/src/mcp/McpHttpServer.ts | 5 + .../src/mcp/toolkits/sim/handlers.test.ts | 516 +++ apps/server/src/mcp/toolkits/sim/handlers.ts | 455 +++ apps/server/src/mcp/toolkits/sim/tools.ts | 188 + .../Adapters/AcpThreadInstructions.test.ts | 134 + .../Adapters/ClaudeAdapterV2.test.ts | 2 + .../Adapters/ClaudeAdapterV2.ts | 1 + .../orchestration-v2/RunExecutionService.ts | 35 +- .../src/provider/AgentContextBudget.test.ts | 8 +- apps/server/src/server.ts | 12 + apps/server/src/serverSettings.ts | 1 + apps/server/src/sim/SimAuditService.test.ts | 453 +++ apps/server/src/sim/SimAuditService.ts | 1454 +++++++ apps/server/src/sim/SimContracts.ts | 747 ++++ apps/server/src/sim/SimInstructions.test.ts | 418 ++ apps/server/src/sim/SimInstructions.ts | 626 +++ apps/server/src/sim/SimIntegration.test.ts | 776 ++++ .../server/src/sim/SimObserverReactor.test.ts | 535 +++ apps/server/src/sim/SimObserverReactor.ts | 607 +++ apps/server/src/sim/SimService.test.ts | 348 ++ apps/server/src/sim/SimService.ts | 268 ++ apps/server/src/sim/SimStore.test.ts | 773 ++++ apps/server/src/sim/SimStore.ts | 3382 +++++++++++++++++ packages/contracts/src/settings.ts | 48 + packages/provider-acp/src/server/adapter.ts | 4 + .../server/orchestrationInstructions.test.ts | 72 + .../src/server/orchestrationInstructions.ts | 25 +- .../src/server/v2/adapter.ts | 1 + packages/shared/src/serverSettings.ts | 19 + 30 files changed, 11954 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/mcp/toolkits/sim/handlers.test.ts create mode 100644 apps/server/src/mcp/toolkits/sim/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/sim/tools.ts create mode 100644 apps/server/src/orchestration-v2/Adapters/AcpThreadInstructions.test.ts create mode 100644 apps/server/src/sim/SimAuditService.test.ts create mode 100644 apps/server/src/sim/SimAuditService.ts create mode 100644 apps/server/src/sim/SimContracts.ts create mode 100644 apps/server/src/sim/SimInstructions.test.ts create mode 100644 apps/server/src/sim/SimInstructions.ts create mode 100644 apps/server/src/sim/SimIntegration.test.ts create mode 100644 apps/server/src/sim/SimObserverReactor.test.ts create mode 100644 apps/server/src/sim/SimObserverReactor.ts create mode 100644 apps/server/src/sim/SimService.test.ts create mode 100644 apps/server/src/sim/SimService.ts create mode 100644 apps/server/src/sim/SimStore.test.ts create mode 100644 apps/server/src/sim/SimStore.ts diff --git a/FORK.md b/FORK.md index 7902ff64c3928..76c6f021824bd 100644 --- a/FORK.md +++ b/FORK.md @@ -110,7 +110,7 @@ check. - Do not delete upstream code or workflows just because the fork does not use them; each deletion conflicts on sync when upstream edits that file. - `agentContextBudget.json` stays equal to upstream's. `AgentContextBudget.test.ts` leaves fork-only - MCP tools out of its measurement, so add new ones to its filter. + MCP tools out of its measurement (`script` and the SIM tools today), so add new ones to its filter. ## Fork features @@ -190,8 +190,8 @@ are listed under Lineage in the thread details. server would drop. - Orchestrator threads are the server setting `orchestratorThreads` (thread IDs), again so the fork adds no database migration. The server reads it per turn: the thread gets the instructions in - `orchestratorModeInstructions.ts` (Claude: system prompt; Codex: additional context; other - providers get none yet) and its `delegate_task` calls default to the worker model, also on a + `orchestratorModeInstructions.ts` (Claude: system prompt; Codex: additional context; ACP and + OpenCode: thread instructions; other providers get none yet) and its `delegate_task` calls default to the worker model, also on a linked environment. - The instructions are measured by neither `agentContextBudget.json` nor the `mcp-tool-use` eval: both build the text for an ordinary thread, which is unchanged. @@ -201,3 +201,51 @@ Code: `packages/shared/src/orchestratorMode.ts`, `apps/web/src/lib/orchestratorMode.ts`, `apps/web/src/components/orchestrator/`, `withWorkerModel` in `apps/server/src/mcp/OrchestratorMcpService.ts`. + +### Self-Improvement Memory (SIM) + +Agents keep one shared record of the changes they make to their own harness (`AGENTS.md`, +`CLAUDE.md`, notes, hooks): what each change was meant to fix, what it predicted, and whether it +worked. It is a native, cross-provider port of the self-improvement memory from Yu et al. 2026 +([arXiv:2611.18856](https://arxiv.org/abs/2611.18856)) and of the standalone +`~/.claude/sim/sim.mjs`. Both use the same files in `~/.claude/sim/`, so the CLI and T3 Code see +one record: `sim.jsonl` (the hash-chained journal, format v2, the source of truth), `sim.json` +(rebuilt from the journal), `telemetry.jsonl` (the signals below) and `t3-epochs.json` (context +epochs per thread). Nothing lives in SQLite, so the fork adds no database migration. + +- Settings are the server setting `sim`: `enabled`, `simDir` and `harnessDir` (default + `~/.claude/sim` and `~/.claude`), `injectRules`, `ruleFiles`, `providerOverrides` (on or off per + provider) and `advisorModelSelection`. The advisor defaults to `claudeAgent` / + `claude-fable-5-2`; any available model works (for example `antigravity` / `gemini-4-argon`), + and `null` turns it off. It never runs by itself: SIM only suggests a `delegate_task` with + `role: "design"` for the hard cases, such as an attempt that keeps failing or rules that + conflict across models or harnesses. +- The MCP tools `sim_read`, `sim_write` and `sim_apply_harness_change` work in every provider. The + server takes the caller from `McpInvocationContext`, never from tool arguments, and refuses a + write or harness edit until the same thread has read `index` or `by_file` (plus the relevant + entries) in its current context epoch. `sim_apply_harness_change` edits one harness file inside + the configured `harnessDir` (following existing dotfiles symlinks in place while preserving file + modes) or the thread's workspace and records the attempt in one step; live edits require a + `full-access` thread in `default` mode, while `dryRun` previews the diff in any mode. No + self-grading: on the MCP path, a `fixed` result from the attempt's own thread, its native + subagents, or its forks and side chats stays `not confirmed`. Only an independent `delegate_task` + grader or a later session settles a prediction. (A fork calling standalone `sim.mjs observe` + directly from a shell cannot be blocked by the unmodified CLI, so `sim_read` with `action: + "audit"` flags standing `fixed` observations whose author shares fork/side-chat lineage.) +- Codex, ACP (Antigravity) and OpenCode get the universal rules, filtered by harness, model and + project, plus a short guide to the SIM tools, as thread instructions. The text is frozen in memory + per context epoch, so prompt caches stay warm, and split under Codex's 4,000-byte limit per entry. + Claude Code reads `~/.claude/AGENTS.md` itself, so T3 injects no SIM sections into Claude turns. + ACP passes `threadInstructions` through for this, which also gives ACP threads orchestrator mode. +- `SimObserverReactor` watches every thread while the server runs. A compaction, a context + handoff or a new provider conversation (`/clear`, fresh context, or provider switch, tracked in + `t3-epochs.json` across server restarts) starts a new context epoch, so the agent must read + again before it writes. It logs to `telemetry.jsonl`: harness edits that ended a turn without a + recorded attempt (also through `full-access` file edits and shell redirects in any provider), + direct edits of the SIM record files, checkpoint rollbacks, model switches after the first turn, + runs a person stopped and followed up, completed review tasks, and models seen for the first + time. `SimAuditService` reads it back for the audit. + +Code: `apps/server/src/sim/`, `apps/server/src/mcp/toolkits/sim/`, +`packages/contracts/src/settings.ts` (`sim`), +`packages/provider-core/src/server/orchestrationInstructions.ts` (ACP thread instructions). diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 0c28268292700..ddad422b5f7cd 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -90,6 +90,8 @@ import { import * as ScriptRunner from "../script/ScriptRunner.ts"; import * as ScriptHandlers from "./toolkits/script/handlers.ts"; import { ScriptToolkit } from "./toolkits/script/tools.ts"; +import * as SimHandlers from "./toolkits/sim/handlers.ts"; +import { SimToolkit } from "./toolkits/sim/tools.ts"; import * as HtmlHandlers from "./toolkits/html/handlers.ts"; import { MessageToolkit } from "./toolkits/message/tools.ts"; import * as MessageHandlers from "./toolkits/message/handlers.ts"; @@ -1343,6 +1345,8 @@ export const layerScriptToolkit = toolkitRegistration(ScriptToolkit, ScriptHandl Layer.provide(McpServer.McpServer.layer), ); +export const layerSimToolkit = toolkitRegistration(SimToolkit, SimHandlers.layer); + export const layerAttachmentToolkit = toolkitRegistration( AttachmentToolkit, AttachmentHandlers.layer, @@ -1415,6 +1419,7 @@ export const layerTools = Layer.mergeAll( layerDeviceToolkit, layerHtmlToolkit, layerScriptToolkit, + layerSimToolkit, layerMessageToolkit, ); diff --git a/apps/server/src/mcp/toolkits/sim/handlers.test.ts b/apps/server/src/mcp/toolkits/sim/handlers.test.ts new file mode 100644 index 0000000000000..1c9638542dfa5 --- /dev/null +++ b/apps/server/src/mcp/toolkits/sim/handlers.test.ts @@ -0,0 +1,516 @@ +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + type OrchestrationProjectShell, + type OrchestrationV2ThreadShell, + ProviderInstanceId, + ProviderThreadId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { ProjectionStoreV2 } from "../../../orchestration-v2/ProjectionStore.ts"; +import { ProjectStoreV2 } from "../../../orchestration-v2/ProjectStore.ts"; +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import { + type SimCallerContext, + SimAuditService, + SimService, + SimServiceError, + type SimWriteRequest, +} from "../../../sim/SimContracts.ts"; +import { advertisedJsonSchema } from "../../advertisedJsonSchema.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { liveThreadShell } from "../../McpToolAccess.testkit.ts"; +import * as SimHandlers from "./handlers.ts"; +import { SimToolkit } from "./tools.ts"; + +const environmentId = EnvironmentId.make("environment:sim"); +const parentId = ThreadId.make("thread:parent"); +const callerId = ThreadId.make("thread:caller"); +const runId = RunId.make("run:mcp-test"); +const providerThreadId = ProviderThreadId.make("provider-thread:caller"); + +type Lineage = OrchestrationV2ThreadShell["lineage"]; +const forkOf = (parent: ThreadId, extra: Partial = {}): Lineage => ({ + rootThreadId: parentId, + parentThreadId: parent, + relationshipToParent: "fork", + ...extra, +}); + +interface Setup { + readonly caller?: "thread" | "client"; + readonly shells?: ReadonlyArray; + readonly authors?: ReadonlyArray; + readonly failWith?: SimServiceError; +} + +const setup = (options: Setup = {}) => { + const reads: Array<{ caller: SimCallerContext; action: string }> = []; + const writes: Array<{ caller: SimCallerContext; request: SimWriteRequest }> = []; + const applies: Array<{ caller: SimCallerContext; dryRun: boolean }> = []; + const recent: Array<{ + threadId: string; + runId?: string | undefined; + workspaceRoot?: string | undefined; + files: ReadonlyArray; + }> = []; + const shells = new Map( + (options.shells ?? [liveThreadShell(callerId)]).map((shell) => [shell.id, shell]), + ); + const fail = options.failWith === undefined ? undefined : Effect.fail(options.failWith); + + const records = { + thread: undefined, + runs: [ + { + id: runId, + threadId: callerId, + modelSelection: { instanceId: ProviderInstanceId.make("claude"), model: "claude-opus-5-5" }, + providerThreadId, + }, + ], + providerThreads: [ + { + id: providerThreadId, + driver: "claudeAgent", + nativeThreadRef: { + driver: "claudeAgent", + nativeId: "native-claude-session", + strength: "strong", + }, + }, + ], + }; + + const scope: McpInvocationContext.McpInvocationScope = { + environmentId, + requestNamespace: "provider:sim", + thread: + options.caller === "client" + ? undefined + : { + threadId: callerId, + providerSessionId: "internal-provider-session-uuid", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: + options.caller === "client" + ? { sessionId: "oauth-session", label: "Outside", access: "full-access" } + : undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }; + + const layer = McpToolAccess.HandlersLayer.layer(SimHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + Layer.succeed(McpInvocationContext.McpInvocationContext, scope), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null), + }), + Layer.mock(ProjectionStoreV2)({ + getThreadRecords: (() => + Effect.succeed(records)) as unknown as ProjectionStoreV2["Service"]["getThreadRecords"], + }), + Layer.mock(ProjectStoreV2)({ + getShell: () => + Effect.succeedSome({ + title: "Harness Lab", + workspaceRoot: "/work/harness-lab", + } as OrchestrationProjectShell), + }), + Layer.mock(SimService)({ + read: (caller, request) => { + reads.push({ caller, action: request.action }); + return fail ?? Effect.succeed({ text: `read ${request.action}` }); + }, + write: (caller, request) => { + writes.push({ caller, request }); + return ( + fail ?? + Effect.succeed( + request.action === "observe" && request.input.selfGradeReason !== undefined + ? { + text: "observed", + settled: false, + unconfirmedReason: request.input.selfGradeReason, + } + : { text: `wrote ${request.action}`, attemptId: "A7", problemId: "P3" }, + ) + ); + }, + applyHarnessChange: (caller, request) => { + applies.push({ caller, dryRun: request.dryRun === true }); + return ( + fail ?? + Effect.succeed({ + dryRun: request.dryRun === true, + file: "~/.claude/AGENTS.md", + text: request.dryRun === true ? "preview" : "applied", + ...(request.dryRun === true ? { diffPreview: "+ new rule" } : { attemptId: "A8" }), + }) + ); + }, + findAttemptAuthorSessions: () => Effect.succeed(options.authors ?? []), + recordRecentAttemptInTurn: (input) => Effect.sync(() => void recent.push(input)), + }), + Layer.mock(SimAuditService)({ + audit: () => + Effect.succeed({ + text: "audit report", + window: { since: "2026-11-01", source: "days" }, + threadsScanned: 4, + claudeSessionsScanned: 0, + sim: { + journalBroken: null, + driftCount: 0, + uncoveredCount: 1, + liveRules: 3, + openPredictions: 2, + missedLiveRules: 0, + }, + signals: { + verbalCorrections: 1, + unrecordedHarnessEdits: 0, + checkpointRollbacks: 0, + midThreadModelSwitches: 0, + interruptedWithSteer: 0, + delegatedReviews: 0, + newlyObservedModels: [], + }, + }), + inspectThread: (_caller, prefix) => Effect.succeed({ threadId: prefix, text: "thread" }), + markAuditDone: () => + Effect.succeed({ lastAuditAt: "2026-11-19", statePath: "/state", text: "audit done" }), + }), + ), + ), + ); + + const call = (name: Name, params: unknown) => + Effect.gen(function* () { + const toolkit = yield* SimToolkit; + return yield* toolkit.handle(name, params as never).pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result as Record | undefined), + ); + }).pipe(Effect.provide(layer)); + + return { call, reads, writes, applies, recent }; +}; + +it.effect("derives caller identity from server state, never from the provider session id", () => + Effect.gen(function* () { + const thread = setup({ + shells: [ + { + ...liveThreadShell(callerId), + activeProviderThreadId: providerThreadId, + worktreePath: "/work/worktree-branch", + }, + ], + }); + expect(yield* thread.call("sim_read", { action: "index" })).toEqual({ + action: "index", + text: "read index", + }); + expect(thread.reads[0]?.caller).toMatchObject({ + sessionId: `t3:${callerId}`, + alsoSessionId: "cc:native-claude-session", + threadId: callerId, + activeRunId: runId, + driver: "claudeAgent", + model: "claude-opus-5-5", + projectName: "Harness Lab", + workspaceRoot: "/work/worktree-branch", + }); + expect(JSON.stringify(thread.reads[0]?.caller)).not.toContain("internal-provider-session-uuid"); + + const mainCheckout = setup({ + shells: [{ ...liveThreadShell(callerId), activeProviderThreadId: providerThreadId }], + }); + yield* mainCheckout.call("sim_read", { action: "index" }); + expect(mainCheckout.reads[0]?.caller.workspaceRoot).toBe("/work/harness-lab"); + + const outside = setup({ caller: "client" }); + yield* outside.call("sim_read", { action: "check" }); + expect(outside.reads[0]?.caller).toEqual({ sessionId: "client:oauth-session" }); + }), +); + +it.effect("routes audit and inspect_thread to the audit service", () => + Effect.gen(function* () { + const { call, reads } = setup(); + expect(yield* call("sim_read", { action: "audit", days: 7 })).toMatchObject({ + action: "audit", + text: "audit report", + summary: { threadsScanned: 4, sim: { openPredictions: 2 } }, + }); + expect(yield* call("sim_read", { action: "inspect_thread", threadId: " thread:x " })).toEqual({ + action: "inspect_thread", + text: "thread", + }); + expect(yield* call("sim_read", { action: "inspect_thread" })).toMatchObject({ + code: "invalid_request", + }); + expect(reads).toEqual([]); + }), +); + +it.effect("maps every sim_write action to its request and ignores a caller-supplied author", () => + Effect.gen(function* () { + const { call, writes, recent } = setup(); + const cases: ReadonlyArray, SimWriteRequest]> = [ + [ + { + action: "attempt", + problem: "P3", + changeAction: "add", + what: "rule", + why: "reason", + files: ["~/.claude/AGENTS.md"], + by: "t3:spoofed", + session: "t3:spoofed", + }, + { + action: "attempt", + input: expect.objectContaining({ + problem: "P3", + action: "add", + what: "rule", + why: "reason", + files: ["~/.claude/AGENTS.md"], + }), + }, + ], + [ + { action: "observe", attempt: "A1", result: "missed", evidence: "log", source: "log" }, + { + action: "observe", + input: expect.objectContaining({ attempt: "A1", result: "missed", source: "log" }), + }, + ], + [ + { action: "amend", amendTarget: "A1", field: "why", value: "better", reason: "typo" }, + { action: "amend", target: "A1", field: "why", value: "better", reason: "typo" }, + ], + [ + { action: "retract", attempt: "A1", reason: "wrong", outcome: 2 }, + { action: "retract", attempt: "A1", reason: "wrong", outcome: 2, undo: undefined }, + ], + [ + { action: "link", a: "P1", kind: "refines", b: "P2" }, + { action: "link", a: "P1", kind: "refines", b: "P2" }, + ], + [ + { action: "merge", from: "P1", into: "P2" }, + { action: "merge", from: "P1", into: "P2" }, + ], + [ + { action: "carry", fromHarness: "claude", toHarness: "codex" }, + expect.objectContaining({ action: "carry", fromHarness: "claude", toHarness: "codex" }), + ], + ]; + for (const [params] of cases) yield* call("sim_write", params); + + expect(writes.map(({ request }) => request)).toEqual(cases.map(([, request]) => request)); + for (const { caller, request } of writes) { + expect(caller.sessionId).toBe(`t3:${callerId}`); + expect(JSON.stringify(request)).not.toContain("spoofed"); + } + expect(recent).toEqual([ + { + threadId: callerId, + runId, + workspaceRoot: "/work/harness-lab", + files: ["~/.claude/AGENTS.md"], + }, + ]); + expect(yield* call("sim_write", { action: "mark_audit_done" })).toEqual({ + action: "mark_audit_done", + text: "audit done", + }); + expect(yield* call("sim_write", { action: "attempt", what: "rule" })).toMatchObject({ + code: "invalid_request", + message: "attempt needs changeAction, why.", + }); + expect(writes).toHaveLength(cases.length); + }), +); + +it.effect("refuses sim_write and live harness edits from outside clients", () => + Effect.gen(function* () { + const { call, writes, applies } = setup({ caller: "client" }); + expect(yield* call("sim_write", { action: "merge", from: "P1", into: "P2" })).toMatchObject({ + code: "thread_credential_required", + }); + expect( + yield* call("sim_apply_harness_change", { + file: "~/.claude/AGENTS.md", + content: "x", + dryRun: true, + attempt: { action: "add", what: "w", why: "y" }, + }), + ).toMatchObject({ code: "thread_credential_required" }); + expect(writes).toEqual([]); + expect(applies).toEqual([]); + }), +); + +it.effect("marks a fixed grade from the change's own fork family as a self-grade", () => + Effect.gen(function* () { + const parent = liveThreadShell(parentId); + const siblingId = ThreadId.make("thread:sibling"); + const sibling = { ...liveThreadShell(siblingId), lineage: forkOf(parentId) }; + const observe = { + action: "observe", + attempt: "A1", + result: "fixed", + evidence: "ok", + source: "user", + }; + const selfGrade = (lineage: Lineage, authors: ReadonlyArray) => + Effect.gen(function* () { + const { call, writes } = setup({ + shells: [parent, sibling, { ...liveThreadShell(callerId), lineage }], + authors, + }); + const result = yield* call("sim_write", observe); + const request = writes[0]?.request; + return { + result, + reason: request?.action === "observe" ? request.input.selfGradeReason : "not observed", + }; + }); + + const fork = yield* selfGrade(forkOf(parentId), [`t3:${parentId}`]); + expect(fork.reason).toBe(SimHandlers.SELF_GRADE_REASON); + expect(fork.result).toMatchObject({ + settled: false, + unconfirmedReason: SimHandlers.SELF_GRADE_REASON, + }); + expect( + (yield* selfGrade(forkOf(parentId, { sideChat: true }), [`t3:${parentId}`])).reason, + ).toBe(SimHandlers.SELF_GRADE_REASON); + expect((yield* selfGrade(forkOf(parentId), ["cc:x", `t3:${siblingId}`])).reason).toBe( + SimHandlers.SELF_GRADE_REASON, + ); + + const delegated = yield* selfGrade(forkOf(parentId, { relationshipToParent: "subagent" }), [ + `t3:${parentId}`, + ]); + expect(delegated.reason).toBeUndefined(); + expect( + (yield* selfGrade( + { rootThreadId: callerId, parentThreadId: null, relationshipToParent: null }, + [`t3:${parentId}`], + )).reason, + ).toBeUndefined(); + }), +); + +it.effect( + "allows dry runs in any mode and live harness edits only in full-access/default mode", + () => + Effect.gen(function* () { + const params = (dryRun: boolean) => ({ + file: "~/.claude/AGENTS.md", + oldText: "a", + newText: "b", + dryRun, + attempt: { action: "revise", what: "w", why: "y", files: ["~/.claude/notes/x.md"] }, + }); + const inMode = (modes: Parameters[1]) => + setup({ shells: [liveThreadShell(callerId, modes)] }); + + const plan = inMode({ interactionMode: "plan" }); + expect(yield* plan.call("sim_apply_harness_change", params(true))).toEqual({ + dryRun: true, + file: "~/.claude/AGENTS.md", + text: "preview", + diffPreview: "+ new rule", + }); + expect(yield* plan.call("sim_apply_harness_change", params(false))).toMatchObject({ + code: "capability_denied", + }); + for (const restricted of [ + { runtimeMode: "approval-required" as const }, + { runtimeMode: "auto-accept-edits" as const }, + { runtimeMode: "auto" as const }, + ]) { + const harness = inMode(restricted); + expect(yield* harness.call("sim_apply_harness_change", params(true))).toMatchObject({ + dryRun: true, + }); + expect(yield* harness.call("sim_apply_harness_change", params(false))).toMatchObject({ + code: "capability_denied", + }); + expect(harness.applies).toEqual([{ caller: expect.anything(), dryRun: true }]); + } + expect(plan.recent).toEqual([]); + + const live = inMode({ runtimeMode: "full-access", interactionMode: "default" }); + expect(yield* live.call("sim_apply_harness_change", params(false))).toMatchObject({ + dryRun: false, + attemptId: "A8", + }); + expect(live.recent).toEqual([ + { + threadId: callerId, + runId, + workspaceRoot: "/work/harness-lab", + files: ["~/.claude/AGENTS.md", "~/.claude/notes/x.md"], + }, + ]); + }), +); + +it.effect("returns SimServiceError as OrchestratorMcpFailure codes", () => + Effect.gen(function* () { + const cases = [ + ["forbidden_path", "capability_denied"], + ["disabled", "capability_denied"], + ["not_found", "invalid_request"], + ["validation", "invalid_request"], + ["seen_required", "invalid_request"], + ["drift", "invalid_request"], + ["journal_broken", "orchestration_error"], + ["io", "orchestration_error"], + ] as const; + for (const [simCode, code] of cases) { + const { call } = setup({ + failWith: new SimServiceError({ code: simCode, problems: [`problem ${simCode}`] }), + }); + expect(yield* call("sim_read", { action: "index" })).toMatchObject({ + _tag: "OrchestratorMcpFailure", + code, + message: `problem ${simCode}`, + }); + } + }), +); + +it("advertises compact flat schemas without any caller identity field", () => { + for (const tool of Object.values(SimToolkit.tools)) { + const schema = advertisedJsonSchema(tool) as { + type: string; + properties: Record; + }; + expect(schema.type).toBe("object"); + expect(schema.properties).not.toHaveProperty("by"); + expect(schema.properties).not.toHaveProperty("session"); + expect(JSON.stringify(schema)).not.toContain('anyOf":[{"type":"null"'); + expect(JSON.stringify(schema).length).toBeLessThan(3_000); + } + expect( + (advertisedJsonSchema(SimToolkit.tools.sim_apply_harness_change) as { required: unknown }) + .required, + ).toEqual(["file", "attempt"]); +}); diff --git a/apps/server/src/mcp/toolkits/sim/handlers.ts b/apps/server/src/mcp/toolkits/sim/handlers.ts new file mode 100644 index 0000000000000..2573c0ead4578 --- /dev/null +++ b/apps/server/src/mcp/toolkits/sim/handlers.ts @@ -0,0 +1,455 @@ +import { + type OrchestrationV2ThreadShell, + OrchestratorMcpFailure, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type { Tool } from "effect/ai"; + +import { ProjectionStoreV2 } from "../../../orchestration-v2/ProjectionStore.ts"; +import { ProjectStoreV2 } from "../../../orchestration-v2/ProjectStore.ts"; +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; +import { + type SimCallerContext, + type SimErrorCode, + SimAuditService, + SimService, + type SimServiceError, + type SimWriteRequest, +} from "../../../sim/SimContracts.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { assertFullAccess, loadCaller } from "../../threadAccess.ts"; +import { SimToolkit } from "./tools.ts"; + +type WriteParams = Tool.Parameters; +type ApplyParams = Tool.Parameters; +type Threads = ThreadManagement.ThreadManagementService["Service"]; + +const CLAUDE_DRIVER = "claudeAgent"; +const MAX_FORK_HOPS = 16; +export const SELF_GRADE_REASON = "same fork or side-chat lineage as the change"; + +const isThreadId = Schema.is(ThreadId); + +const SIM_FAILURE_CODES: Record = { + forbidden_path: "capability_denied", + disabled: "capability_denied", + not_found: "invalid_request", + validation: "invalid_request", + seen_required: "invalid_request", + drift: "invalid_request", + journal_broken: "orchestration_error", + io: "orchestration_error", +}; + +const simFailure = (error: SimServiceError) => + new OrchestratorMcpFailure({ + code: SIM_FAILURE_CODES[error.code], + message: error.message || `SIM request failed (${error.code}).`, + }); + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); + +const requireFields =

( + action: string, + params: P, + keys: ReadonlyArray, +): Effect.Effect< + P & { readonly [Key in K]-?: Exclude }, + OrchestratorMcpFailure +> => { + const absent = keys.filter((key) => params[key] === undefined); + return absent.length === 0 + ? Effect.succeed(params as P & { readonly [Key in K]-?: Exclude }) + : Effect.fail(invalid(`${action} needs ${absent.map(String).join(", ")}.`)); +}; + +const shellOf = (threads: Threads, threadId: ThreadId) => + threads.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null)); + +/** The parent a fork or side chat shares its change history with; delegated children have none. */ +const forkParent = (shell: OrchestrationV2ThreadShell | null) => { + const lineage = shell?.lineage; + return lineage !== undefined && + lineage.parentThreadId !== null && + (lineage.relationshipToParent === "fork" || lineage.sideChat === true) + ? lineage.parentThreadId + : null; +}; + +/** `threadId` followed by its fork and side-chat ancestors, nearest first. */ +const forkChain = Effect.fn("SimHandlers.forkChain")(function* ( + threads: Threads, + threadId: ThreadId, + shell: OrchestrationV2ThreadShell | null, +) { + const chain = [threadId]; + let parent = forkParent(shell); + while (parent !== null && chain.length <= MAX_FORK_HOPS && !chain.includes(parent)) { + chain.push(parent); + parent = forkParent(yield* shellOf(threads, parent)); + } + return chain; +}); + +/** + * Whether an attempt author shares a fork or side-chat family with the caller. The caller's own + * thread is left to `SimService`, which compares sessions itself. + */ +const sharesForkFamily = Effect.fn("SimHandlers.sharesForkFamily")(function* ( + threads: Threads, + callerChain: ReadonlyArray, + authorSessions: ReadonlyArray, +) { + for (const session of authorSessions) { + const authorId = session.startsWith("t3:") ? session.slice(3) : ""; + if (!isThreadId(authorId) || authorId === callerChain[0]) continue; + if (callerChain.includes(authorId)) return true; + const authorChain = yield* forkChain(threads, authorId, yield* shellOf(threads, authorId)); + if (authorChain.some((id) => callerChain.includes(id))) return true; + } + return false; +}); + +interface ResolvedCaller { + readonly context: SimCallerContext; + readonly shell: OrchestrationV2ThreadShell | null; + readonly forkChain: ReadonlyArray; +} + +interface OptionalStores { + readonly projections: Option.Option; + readonly projectStore: Option.Option; +} + +/** Identity comes only from the authenticated invocation and server state, never from arguments. */ +const resolveCaller = Effect.fn("SimHandlers.resolveCaller")(function* (stores?: OptionalStores) { + const scope = yield* McpInvocationContext.McpInvocationContext; + if (scope.thread === undefined) { + return { + context: { + sessionId: scope.client === undefined ? "unknown" : `client:${scope.client.sessionId}`, + }, + shell: null, + forkChain: [], + } satisfies ResolvedCaller; + } + const { threadId, providerInstanceId, subagent } = scope.thread; + const threads = yield* ThreadManagement.ThreadManagementService; + const shell = yield* shellOf(threads, threadId); + const chain = yield* forkChain(threads, threadId, shell); + + const projections = + stores !== undefined && Option.isSome(stores.projections) + ? stores.projections + : yield* Effect.serviceOption(ProjectionStoreV2); + const records = Option.isNone(projections) + ? null + : yield* projections.value + .getThreadRecords(threadId, ["runs", "providerThreads"]) + .pipe(Effect.orElseSucceed(() => null)); + const activeRunId = shell?.activeRunId ?? undefined; + const run = + records?.runs.find((candidate) => candidate.id === activeRunId) ?? + records?.runs.findLast((candidate) => candidate.id === shell?.latestRunId) ?? + records?.runs.at(-1); + const providerThreadId = shell?.activeProviderThreadId ?? run?.providerThreadId ?? null; + const providerThread = + providerThreadId === null + ? undefined + : records?.providerThreads.find((candidate) => candidate.id === providerThreadId); + const nativeRef = providerThread?.nativeThreadRef; + const alsoSessionId = + nativeRef?.driver === CLAUDE_DRIVER && nativeRef.nativeId + ? `cc:${nativeRef.nativeId}` + : undefined; + + const projectId = shell?.projectId; + const projectStore = + stores !== undefined && Option.isSome(stores.projectStore) + ? stores.projectStore + : yield* Effect.serviceOption(ProjectStoreV2); + const project = + projectId === undefined || Option.isNone(projectStore) + ? undefined + : Option.getOrUndefined( + yield* projectStore.value + .getShell(projectId) + .pipe(Effect.orElseSucceed(() => Option.none())), + ); + + return { + context: { + sessionId: `t3:${threadId}`, + alsoSessionId, + forkFamilySessionIds: chain.slice(1).map((id) => `t3:${id}`), + threadId, + activeRunId, + providerInstanceId, + driver: providerThread?.driver, + model: run?.modelSelection.model ?? shell?.modelSelection.model, + projectId, + projectName: project?.title, + workspaceRoot: shell?.worktreePath ?? project?.workspaceRoot ?? undefined, + subagent, + }, + shell, + forkChain: chain, + } satisfies ResolvedCaller; +}); + +const recordRecentAttempt = ( + { threadId, activeRunId, workspaceRoot }: SimCallerContext, + files: ReadonlyArray, +) => + threadId === undefined + ? Effect.void + : SimService.use((sim) => + sim.recordRecentAttemptInTurn({ threadId, runId: activeRunId, workspaceRoot, files }), + ).pipe(Effect.ignore); + +const attemptInput = (params: WriteParams) => + requireFields("attempt", params, ["changeAction", "what", "why"]).pipe( + Effect.map((p): SimWriteRequest => ({ + action: "attempt", + input: { + problem: p.problem, + new: p.new, + action: p.changeAction, + what: p.what, + why: p.why, + files: p.files, + anchor: p.anchor, + supersedes: p.supersedes, + depends_on: p.depends_on, + predicted: p.predicted, + expect: p.expect, + policy: p.policy, + domain: p.domain, + harness: p.harness, + accepted: p.accepted, + rejected_because: p.rejected_because, + unanswered: p.unanswered, + backfilled: p.backfilled, + round: p.round, + sample: p.sample, + }, + })), + ); + +const observeInput = Effect.fn("SimHandlers.observeInput")(function* ( + params: WriteParams, + caller: ResolvedCaller, +) { + const p = yield* requireFields("observe", params, ["attempt", "result", "evidence", "source"]); + let selfGradeReason: string | undefined; + if (p.result === "fixed" && caller.forkChain.length > 0) { + const sim = yield* SimService; + const threads = yield* ThreadManagement.ThreadManagementService; + const authors = yield* sim.findAttemptAuthorSessions(p.attempt); + if (yield* sharesForkFamily(threads, caller.forkChain, authors)) { + selfGradeReason = SELF_GRADE_REASON; + } + } + return { + action: "observe", + input: { + attempt: p.attempt, + target: p.target, + result: p.result, + evidence: p.evidence, + source: p.source, + policy: p.policy, + domain: p.domain, + harness: p.harness, + date: p.date, + selfGradeReason, + }, + } satisfies SimWriteRequest; +}); + +const writeRequest = ( + action: Exclude, + params: WriteParams, + caller: ResolvedCaller, +): Effect.Effect< + SimWriteRequest, + OrchestratorMcpFailure, + SimService | ThreadManagement.ThreadManagementService +> => { + switch (action) { + case "attempt": + return attemptInput(params); + case "observe": + return observeInput(params, caller); + case "amend": + return requireFields("amend", params, ["amendTarget", "field", "value", "reason"]).pipe( + Effect.map((p) => ({ + action: "amend" as const, + target: p.amendTarget, + field: p.field, + value: p.value, + reason: p.reason, + })), + ); + case "retract": + return requireFields("retract", params, ["attempt", "reason"]).pipe( + Effect.map((p) => ({ + action: "retract" as const, + attempt: p.attempt, + outcome: p.outcome, + reason: p.reason, + undo: p.undo, + })), + ); + case "link": + return requireFields("link", params, ["a", "kind", "b"]).pipe( + Effect.map((p) => ({ action: "link" as const, a: p.a, kind: p.kind, b: p.b })), + ); + case "merge": + return requireFields("merge", params, ["from", "into"]).pipe( + Effect.map((p) => ({ action: "merge" as const, from: p.from, into: p.into })), + ); + case "carry": + return Effect.succeed({ + action: "carry", + fromPolicy: params.fromPolicy, + toPolicy: params.toPolicy, + fromDomain: params.fromDomain, + toDomain: params.toDomain, + fromHarness: params.fromHarness, + toHarness: params.toHarness, + date: params.date, + note: params.note, + }); + } +}; + +const definedOnly = (value: T) => + Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as { + [K in keyof T]: Exclude; + }; + +const makeApplyHarnessChange = (stores: OptionalStores) => + Effect.fn("SimHandlers.applyHarnessChange")(function* (params: ApplyParams) { + if (params.dryRun !== true) { + const access = yield* loadCaller(); + yield* assertFullAccess( + access, + `Live sim_apply_harness_change requires full-access/default mode (this caller is limited to ${access.limits.runtimeMode}/${access.limits.interactionMode}), because it writes harness files directly on disk. Call sim_apply_harness_change with dryRun: true to propose the change instead.`, + ); + } + const caller = yield* resolveCaller(stores); + const sim = yield* SimService; + const result = yield* sim + .applyHarnessChange(caller.context, params) + .pipe(Effect.mapError(simFailure)); + if (!result.dryRun) { + yield* recordRecentAttempt(caller.context, [ + ...new Set([result.file, ...(params.attempt.files ?? [])]), + ]); + } + return definedOnly(result); + }); + +export const layer = McpToolAccess.toLayer( + SimToolkit, + Effect.gen(function* () { + // Capture optional stores at registration time so McpHttpServer's per-request service + // scoping still gives handlers access to ProjectionStoreV2 and ProjectStoreV2. + const stores: OptionalStores = { + projections: yield* Effect.serviceOption(ProjectionStoreV2), + projectStore: yield* Effect.serviceOption(ProjectStoreV2), + }; + const applyHarnessChange = makeApplyHarnessChange(stores); + return { + sim_read: McpToolAccess.reads((params) => + Effect.gen(function* () { + const { context } = yield* resolveCaller(stores); + if (params.action === "audit") { + const audit = yield* SimAuditService; + const report = yield* audit + .audit(context, { + since: params.since, + days: params.days, + limit: params.limit, + includeClaudeLogs: params.includeClaudeLogs, + }) + .pipe(Effect.mapError(simFailure)); + return definedOnly({ + action: params.action, + text: report.text, + advisorEscalation: report.advisorEscalation, + summary: { + window: report.window, + threadsScanned: report.threadsScanned, + claudeSessionsScanned: report.claudeSessionsScanned, + sim: report.sim, + signals: report.signals, + }, + }); + } + if (params.action === "inspect_thread") { + if (params.threadId === undefined || params.threadId.trim() === "") { + return yield* invalid("inspect_thread needs threadId."); + } + const audit = yield* SimAuditService; + const inspection = yield* audit + .inspectThread(context, params.threadId.trim()) + .pipe(Effect.mapError(simFailure)); + return { action: params.action, text: inspection.text }; + } + const sim = yield* SimService; + const result = yield* sim + .read(context, { + action: params.action, + ids: params.ids, + brief: params.brief, + query: params.query, + file: params.file, + policy: params.policy, + harness: params.harness, + page: params.page, + }) + .pipe(Effect.mapError(simFailure)); + return definedOnly({ + action: params.action, + text: result.text, + failed: result.failed, + advisorEscalation: result.advisorEscalation, + }); + }), + ), + sim_write: McpToolAccess.actsAsCaller((params) => + Effect.gen(function* () { + const caller = yield* resolveCaller(stores); + if (params.action === "mark_audit_done") { + const audit = yield* SimAuditService; + const done = yield* audit + .markAuditDone(caller.context) + .pipe(Effect.mapError(simFailure)); + return { action: params.action, text: done.text }; + } + const request = yield* writeRequest(params.action, params, caller); + const sim = yield* SimService; + const result = yield* sim + .write(caller.context, request) + .pipe(Effect.mapError(simFailure)); + if (params.action === "attempt") { + yield* recordRecentAttempt(caller.context, params.files ?? []); + } + return definedOnly({ action: params.action, ...result }); + }), + ), + sim_apply_harness_change: McpToolAccess.either( + (params) => params.dryRun === true, + McpToolAccess.readsAsCaller(applyHarnessChange), + McpToolAccess.actsAsCaller(applyHarnessChange), + ), + }; + }), +); diff --git a/apps/server/src/mcp/toolkits/sim/tools.ts b/apps/server/src/mcp/toolkits/sim/tools.ts new file mode 100644 index 0000000000000..d15253ea3ac6e --- /dev/null +++ b/apps/server/src/mcp/toolkits/sim/tools.ts @@ -0,0 +1,188 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import { + SIM_ACTIONS, + SIM_DEPENDS, + SIM_LINK_KINDS, + SIM_RESULTS, + SIM_SOURCES, + SimAuditService, + SimService, +} from "../../../sim/SimContracts.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +export const SIM_TOOL_NAMES: ReadonlySet = new Set([ + "sim_read", + "sim_write", + "sim_apply_harness_change", +]); + +const shared = { + failure: OrchestratorMcpFailure, + failureMode: "return" as const, + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + SimService, + SimAuditService, + ], +}; + +const Strings = Schema.Array(Schema.String); +const ChangeAction = Schema.Literals(SIM_ACTIONS); + +const attemptFields = { + problem: Schema.optionalKey(Schema.String), + new: Schema.optionalKey(Schema.String), + what: Schema.optionalKey(Schema.String), + why: Schema.optionalKey(Schema.String), + files: Schema.optionalKey(Strings), + anchor: Schema.optionalKey(Schema.String), + supersedes: Schema.optionalKey(Strings), + depends_on: Schema.optionalKey(Schema.Array(Schema.Literals(SIM_DEPENDS))), + predicted: Schema.optionalKey(Strings), + expect: Schema.optionalKey(Schema.String), + policy: Schema.optionalKey(Schema.String), + domain: Schema.optionalKey(Schema.String), + harness: Schema.optionalKey(Schema.String), +}; + +const SimReadTool = Tool.make("sim_read", { + ...shared, + description: + "Read the SIM record of harness changes (AGENTS.md, CLAUDE.md, notes, hooks). Actions: index, show (ids, brief), brief_all, find (query), by_file (file), check, review (policy, harness), audit (since|days, limit, includeClaudeLogs), inspect_thread (threadId). Reading records server-side read state that harness edits and SIM writes require.", + parameters: Schema.Struct({ + action: Schema.Literals([ + "index", + "show", + "brief_all", + "find", + "by_file", + "check", + "review", + "audit", + "inspect_thread", + ]), + ids: Schema.optionalKey(Strings), + brief: Schema.optionalKey(Schema.Boolean), + query: Schema.optionalKey(Schema.String), + file: Schema.optionalKey(Schema.String), + policy: Schema.optionalKey(Schema.String), + harness: Schema.optionalKey(Schema.String), + page: Schema.optionalKey(Schema.Int), + since: Schema.optionalKey(Schema.String), + days: Schema.optionalKey(Schema.Number), + limit: Schema.optionalKey(Schema.Int), + includeClaudeLogs: Schema.optionalKey(Schema.Boolean), + threadId: Schema.optionalKey(Schema.String), + }), + success: Schema.Struct({ + action: Schema.String, + text: Schema.String, + failed: Schema.optionalKey(Schema.Boolean), + advisorEscalation: Schema.optionalKey(Schema.Unknown), + summary: Schema.optionalKey(Schema.Unknown), + }), +}) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true); + +const SimWriteTool = Tool.make("sim_write", { + ...shared, + description: + "Record SIM entries. attempt: changeAction, what, why, problem or new (root cause), files, predicted, expect. observe: attempt (A-id), result, evidence, source. amend: amendTarget, field, value, reason. retract: attempt, reason, outcome?, undo?. link: a, kind, b. merge: from, into. carry: from*/to* policy|domain|harness. mark_audit_done. The server sets session identity; a `fixed` you grade on your own thread's or fork's change stays not confirmed.", + parameters: Schema.Struct({ + action: Schema.Literals([ + "attempt", + "observe", + "amend", + "retract", + "link", + "merge", + "carry", + "mark_audit_done", + ]), + ...attemptFields, + changeAction: Schema.optionalKey(ChangeAction), + accepted: Schema.optionalKey(Schema.Boolean), + rejected_because: Schema.optionalKey(Schema.String), + unanswered: Schema.optionalKey(Schema.Boolean), + backfilled: Schema.optionalKey(Schema.Boolean), + round: Schema.optionalKey(Schema.String), + sample: Schema.optionalKey(Schema.String), + attempt: Schema.optionalKey(Schema.String), + target: Schema.optionalKey(Schema.String), + result: Schema.optionalKey(Schema.Literals(SIM_RESULTS)), + evidence: Schema.optionalKey(Schema.String), + source: Schema.optionalKey(Schema.Literals(SIM_SOURCES)), + date: Schema.optionalKey(Schema.String), + amendTarget: Schema.optionalKey(Schema.String), + field: Schema.optionalKey(Schema.String), + value: Schema.optionalKey(Schema.Union([Schema.String, Strings])), + reason: Schema.optionalKey(Schema.String), + outcome: Schema.optionalKey(Schema.Int), + undo: Schema.optionalKey(Schema.Boolean), + a: Schema.optionalKey(Schema.String), + b: Schema.optionalKey(Schema.String), + kind: Schema.optionalKey(Schema.Literals(SIM_LINK_KINDS)), + from: Schema.optionalKey(Schema.String), + into: Schema.optionalKey(Schema.String), + fromPolicy: Schema.optionalKey(Schema.String), + toPolicy: Schema.optionalKey(Schema.String), + fromDomain: Schema.optionalKey(Schema.String), + toDomain: Schema.optionalKey(Schema.String), + fromHarness: Schema.optionalKey(Schema.String), + toHarness: Schema.optionalKey(Schema.String), + note: Schema.optionalKey(Schema.String), + }), + success: Schema.Struct({ + action: Schema.String, + text: Schema.String, + problemId: Schema.optionalKey(Schema.String), + attemptId: Schema.optionalKey(Schema.String), + settled: Schema.optionalKey(Schema.Boolean), + unconfirmedReason: Schema.optionalKey(Schema.String), + }), +}) + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +const SimApplyHarnessChangeTool = Tool.make("sim_apply_harness_change", { + ...shared, + description: + "Edit one harness file inside the configured harness directory or workspace (AGENTS.md, CLAUDE.md, notes, hooks, skills, agents, commands, output-styles) and record its SIM attempt in one call. Replace oldText with newText, or write content (append to add it). Needs a prior sim_read of index or by_file (plus relevant entries) in this context; refuses drift and SIM record files. Live edits require full-access/default mode; dryRun previews the diff in any mode.", + parameters: Schema.Struct({ + file: Schema.String, + oldText: Schema.optionalKey(Schema.String), + newText: Schema.optionalKey(Schema.String), + content: Schema.optionalKey(Schema.String), + append: Schema.optionalKey(Schema.Boolean), + dryRun: Schema.optionalKey(Schema.Boolean), + attempt: Schema.Struct({ + ...attemptFields, + action: ChangeAction, + what: Schema.String, + why: Schema.String, + }), + }), + success: Schema.Struct({ + dryRun: Schema.Boolean, + file: Schema.String, + text: Schema.String, + brief: Schema.optionalKey(Schema.String), + predictionLine: Schema.optionalKey(Schema.String), + diffPreview: Schema.optionalKey(Schema.String), + problemId: Schema.optionalKey(Schema.String), + attemptId: Schema.optionalKey(Schema.String), + }), +}) + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, true) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + +export const SimToolkit = Toolkit.make(SimReadTool, SimWriteTool, SimApplyHarnessChangeTool); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpThreadInstructions.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpThreadInstructions.test.ts new file mode 100644 index 0000000000000..88f7d24566141 --- /dev/null +++ b/apps/server/src/orchestration-v2/Adapters/AcpThreadInstructions.test.ts @@ -0,0 +1,134 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ThreadId, +} from "@t3tools/contracts"; +import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import { AcpProviderCapabilitiesV2, makeAcpAdapterV2 } from "@t3tools/provider-acp/server/adapter"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as DocumentText from "../../provider/DocumentText.ts"; +import { makeTurnInput } from "./AcpAdapterV2.testkit.ts"; + +const platform = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer); +const layerTest = Layer.mergeAll( + DocumentText.layer.pipe(Layer.provide(platform)), + platform, + IdAllocator.layer, + McpProviderSessions.layer, + TestProviderHost.layer().pipe(Layer.provide(platform)), +); + +it.live("ACP delivers thread instructions on the first turn and again only when they change", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const promptTexts: Array = []; + const instanceId = ProviderInstanceId.make("acp-test-thread-instructions"); + const threadId = ThreadId.make("thread-acp-thread-instructions"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ProviderDriverKind.make("acp-test"), + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: (runtimeInput) => + Effect.gen(function* () { + const context = yield* Layer.build( + AcpSessionRuntime.layer({ + ...runtimeInput, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: runtimeInput.cwd, + }, + authMethodId: "test", + }).pipe( + Layer.provide( + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + ), + ), + ); + const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( + Effect.provide(context), + ); + return { + ...runtime, + prompt: (payload) => + Effect.sync(() => { + promptTexts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + return { stopReason: "end_turn" as const }; + }), + }; + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-thread-instructions"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const runTurn = (ordinal: number, threadInstructions: ReadonlyArray) => + Effect.gen(function* () { + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + threadInstructions, + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + return promptTexts.at(-1) ?? ""; + }); + + const rules = ["## Rules A\n\nFirst rule.", "## Rules B\n\nSecond rule."]; + const first = yield* runTurn(1, rules); + assert.include(first, "## Rules A\n\nFirst rule.\n\n## Rules B\n\nSecond rule."); + + const second = yield* runTurn(2, rules); + assert.notInclude(second, ""); + assert.notInclude(second, "First rule."); + + const third = yield* runTurn(3, ["## Rules A\n\nChanged rule."]); + assert.include( + third, + "The following T3 thread instructions replace earlier T3 thread instructions:\n## Rules A\n\nChanged rule.", + ); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index d9aac2242402e..b5b30e48c8200 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -92,6 +92,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts"; import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts"; import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts"; +import { SimToolkit } from "../../mcp/toolkits/sim/tools.ts"; import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts"; import { ThemeToolkit } from "../../mcp/toolkits/theme/tools.ts"; import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts"; @@ -743,6 +744,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { ...Object.values(PreviewControlsToolkit.tools), ...Object.values(HtmlToolkit.tools), ...Object.values(MessageToolkit.tools), + ...Object.values(SimToolkit.tools), ] .filter((tool) => Context.get(tool.annotations, Tool.Readonly)) .map((tool) => `mcp__t3-code__${tool.name}`) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 78320e789ba4d..b16fb07f4de3c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2478,6 +2478,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__html_preview", "mcp__t3-code__html_render", "mcp__t3-code__send_to_user", + "mcp__t3-code__sim_read", ]; // request_secret can wait an hour; exceed Claude's default 60 s timeout. diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index aeab9bdf39a3b..3ea94afeef8d8 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -60,10 +60,13 @@ import { makeProviderFailure, makeProviderFailureTurnItem, } from "@t3tools/provider-core/server/failure"; +import * as ProjectStore from "./ProjectStore.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { userFacingDatabaseErrorMessage } from "./UserFacingErrors.ts"; +import { SimService } from "../sim/SimContracts.ts"; +import { createSimInstructionCache, resolveSimThreadInstructions } from "../sim/SimInstructions.ts"; export interface ProviderEventRoutingState { readonly ownedThreadIds: ReadonlySet; @@ -723,6 +726,9 @@ export const layer: Layer.Layer< const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver; const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics; const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const simService = yield* Effect.serviceOption(SimService); + const projectStore = yield* Effect.serviceOption(ProjectStore.ProjectStoreV2); + const simInstructionCache = createSimInstructionCache(); const writeFinalRunEvents = Effect.fn("RunExecutionService.writeFinalRunEvents")( function* (input: { @@ -2210,15 +2216,30 @@ export const layer: Layer.Layer< input.run.threadId, ); const threadInstructions = yield* serverSettings.getSettings.pipe( - Effect.map((settings) => - isOrchestratorThread(settings, input.appThread.id) - ? orchestratorModeInstructions({ - workerModel: orchestratorWorkerModelSelection(settings, input.appThread)?.model, - }) - : undefined, + Effect.flatMap((settings) => + Effect.gen(function* () { + const orchestrator = isOrchestratorThread(settings, input.appThread.id) + ? orchestratorModeInstructions({ + workerModel: orchestratorWorkerModelSelection(settings, input.appThread)?.model, + }) + : []; + const simSections = yield* resolveSimThreadInstructions({ + cache: simInstructionCache, + simService, + projectStore, + settings: settings.sim, + threadId: input.appThread.id, + projectId: input.appThread.projectId, + providerInstanceId: input.modelSelection.instanceId, + driver: input.providerThread.driver ?? input.session.driver, + model: input.modelSelection.model, + }); + const combined = [...orchestrator, ...simSections]; + return combined.length === 0 ? undefined : combined; + }), ), Effect.catch((cause) => - Effect.logWarning("Failed to read orchestrator mode settings.", { cause }).pipe( + Effect.logWarning("Failed to read thread instruction settings.", { cause }).pipe( Effect.as(undefined), ), ), diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 31a9e22e58030..b0310ccbaf3a8 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -16,6 +16,8 @@ import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; import { SCRIPT_TOOL_NAME } from "../mcp/toolkits/script/tools.ts"; +import { SIM_TOOL_NAMES } from "../mcp/toolkits/sim/tools.ts"; +import { SimAuditService, SimService } from "../sim/SimContracts.ts"; import { CLAUDE_PROVIDER, makeClaudeQueryOptions, @@ -83,6 +85,8 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(ServerEnvironment)({}), Layer.mock(ServerSecretStore)({}), Layer.mock(ServerSettingsService)({}), + Layer.mock(SimAuditService)({}), + Layer.mock(SimService)({}), Layer.mock(SourceControlRepositoryService)({}), Layer.mock(ThreadIssueService)({}), Layer.mock(ThreadLaunchService)({}), @@ -147,9 +151,9 @@ it.effect("agent context matches the committed budget", () => // The model sees these fields. outputSchema and annotations are protocol metadata. mcpToolListJsonBytes: utf8Bytes( JSON.stringify( - // Fork-only tool: left out so the budget file stays equal to upstream's and never conflicts. + // Fork-only tools: left out so the budget file stays equal to upstream's and never conflicts. mcp.tools - .filter(({ tool }) => tool.name !== SCRIPT_TOOL_NAME) + .filter(({ tool }) => tool.name !== SCRIPT_TOOL_NAME && !SIM_TOOL_NAMES.has(tool.name)) .map(({ tool }) => ({ name: tool.name, description: tool.description, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d86e9f10f8666..9e151453cba23 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -9,6 +9,9 @@ import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReact import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; import * as ScheduledRunArchiveReactor from "./scheduledTasks/ScheduledRunArchiveReactor.ts"; +import * as SimAuditService from "./sim/SimAuditService.ts"; +import * as SimObserverReactor from "./sim/SimObserverReactor.ts"; +import * as SimService from "./sim/SimService.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -734,6 +737,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(ScheduledRunArchiveReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* SimObserverReactor.SimObserverReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(SimObserverReactor.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, @@ -747,6 +756,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(SecretResolver.layer), // Above the settings it writes when a theme is applied. Layer.provideMerge(EnvironmentTheme.layer), + Layer.provideMerge(SimService.layer), Layer.provideMerge(layerServerSettings), Layer.provideMerge(layerSourceControlProviderRegistry), Layer.provideMerge(layerGit), @@ -872,6 +882,8 @@ const layerMakeRoutes = Layer.mergeAll( McpHttpServer.layer.pipe( Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry), Layer.provide(McpOAuth.layerMcpClientAuthenticator), + Layer.provide(SimAuditService.layer), + Layer.provide(ProjectionStoreV2.layer), ), // Follows delegated tasks running in linked environments, including after a restart. Layer.effectDiscard( diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index e720fea50886d..3dcef4eceaa08 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -548,6 +548,7 @@ const ATOMIC_SETTINGS_KEYS: ReadonlySet = new Set([ "reviewGuideModelSelection", "textGenerationModelSelection", "fallbackModelSelection", + "advisorModelSelection", "pullRequestMergeMethod", // Empty by default, these hold one whole value, which a managed policy can default. ...Object.entries(DEFAULT_SERVER_SETTINGS).flatMap(([key, value]) => diff --git a/apps/server/src/sim/SimAuditService.test.ts b/apps/server/src/sim/SimAuditService.test.ts new file mode 100644 index 0000000000000..51aba10d3beb1 --- /dev/null +++ b/apps/server/src/sim/SimAuditService.test.ts @@ -0,0 +1,453 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import { ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as SimAuditServiceLive from "./SimAuditService.ts"; +import { SimAuditService, SimService, resolveSimPaths } from "./SimContracts.ts"; +import * as SimServiceLive from "./SimService.ts"; +import * as SimStore from "./SimStore.ts"; + +const RULE = "Always run the build before you claim done."; +const at = (day: number, minute = 0) => + `2026-11-${String(day).padStart(2, "0")}T10:${String(minute).padStart(2, "0")}:00.000Z`; + +function sandbox() { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sim-test-")); + const harnessDir = NodePath.join(root, "claude"); + NodeFS.mkdirSync(NodePath.join(harnessDir, "notes"), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(harnessDir, "AGENTS.md"), `# Rules\n- ${RULE}\n`); + const layer = SimAuditServiceLive.layer.pipe( + Layer.provideMerge(SimServiceLive.layer), + Layer.provideMerge(ServerSettings.layerTest({ sim: { harnessDir } })), + Layer.provideMerge(SqlitePersistence.layerMemory), + ); + return { + root, + harnessDir, + paths: resolveSimPaths({ harnessDir }), + layer, + [Symbol.dispose]: () => NodeFS.rmSync(root, { recursive: true, force: true }), + }; +} + +interface SeedThread { + readonly id: string; + readonly title: string; + readonly provider: string; + readonly parent?: string; + readonly relationship?: "subagent" | "fork"; + readonly sideChat?: boolean; + readonly runs: ReadonlyArray<{ + readonly model: string; + readonly provider?: string; + readonly status?: string; + readonly user?: string; + }>; + readonly assistant?: string; +} + +const seedThread = Effect.fn("test.seedThread")(function* (thread: SeedThread, day: number) { + const sql = yield* SqlClient.SqlClient; + const payload = { + id: thread.id, + title: thread.title, + providerInstanceId: thread.provider, + modelSelection: { instanceId: thread.provider, model: thread.runs[0]?.model ?? "unknown" }, + worktreePath: "/work/repo", + ...(thread.parent + ? { + lineage: { + parentThreadId: thread.parent, + relationshipToParent: thread.relationship ?? "subagent", + ...(thread.sideChat ? { sideChat: true } : {}), + }, + } + : {}), + }; + yield* sql` + INSERT INTO orchestration_v2_projection_threads + (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json) + VALUES (${thread.id}, 'project-1', ${thread.title}, ${thread.provider}, 'full-access', 'default', ${at(day)}, ${at(day, 30)}, ${JSON.stringify(payload)})`; + for (const [index, run] of thread.runs.entries()) { + const ordinal = index + 1; + const runId = `${thread.id}:run:${ordinal}`; + const provider = run.provider ?? thread.provider; + const messageId = `${runId}:user`; + yield* sql` + INSERT INTO orchestration_v2_projection_runs + (run_id, thread_id, ordinal, provider, status, requested_at, payload_json) + VALUES (${runId}, ${thread.id}, ${ordinal}, ${provider}, ${run.status ?? "completed"}, ${at(day, ordinal)}, + ${JSON.stringify({ providerInstanceId: provider, modelSelection: { instanceId: provider, model: run.model }, userMessageId: messageId })})`; + if (run.user) { + yield* sql` + INSERT INTO orchestration_v2_projection_messages + (message_id, thread_id, run_id, role, streaming, created_at, updated_at, payload_json) + VALUES (${messageId}, ${thread.id}, ${runId}, 'user', 0, ${at(day, ordinal)}, ${at(day, ordinal)}, + ${JSON.stringify({ text: `be terse, wrong instead${run.user}` })})`; + } + } + if (thread.assistant) { + yield* sql` + INSERT INTO orchestration_v2_projection_messages + (message_id, thread_id, run_id, role, streaming, created_at, updated_at, payload_json) + VALUES (${`${thread.id}:assistant`}, ${thread.id}, NULL, 'assistant', 0, ${at(day, 20)}, ${at(day, 20)}, + ${JSON.stringify({ text: thread.assistant })})`; + } +}); + +const seedItem = Effect.fn("test.seedItem")(function* ( + threadId: string, + type: string, + payload: object, + day: number, +) { + const sql = yield* SqlClient.SqlClient; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json) + VALUES (${`${threadId}:${type}:${JSON.stringify(payload).length}`}, ${threadId}, ${`${threadId}:run:1`}, 1, ${type}, 'completed', ${at(day, 5)}, ${JSON.stringify({ type, ...payload })})`; +}); + +const seedEvent = Effect.fn("test.seedEvent")(function* ( + threadId: string, + type: string, + payload: object, + day: number, +) { + const sql = yield* SqlClient.SqlClient; + yield* sql` + INSERT INTO orchestration_v2_events (event_id, thread_id, event_type, occurred_at, payload_json) + VALUES (${`${threadId}:${type}`}, ${threadId}, ${type}, ${at(day, 10)}, ${JSON.stringify(payload)})`; +}); + +const auditor = { sessionId: "t3:auditor", threadId: ThreadId.make("auditor") }; + +const seedWorld = (harnessDir: string) => + Effect.gen(function* () { + const sim = yield* SimService; + // SIM already knows claude-opus-5-5 and has thread-recorded edited a note. + NodeFS.writeFileSync( + NodePath.join(harnessDir, "notes", "build-notes.md"), + "## Build\nRun the build first.\n", + ); + const recorder = { + sessionId: "t3:thread-recorded", + threadId: ThreadId.make("thread-recorded"), + model: "claude-opus-5-5", + driver: "claudeAgent", + workspaceRoot: "/work/repo", + }; + yield* sim.read(recorder, { action: "index" }); + yield* sim.applyHarnessChange(recorder, { + file: "~/.claude/AGENTS.md", + oldText: `- ${RULE}\n`, + newText: `- ${RULE}\n- Always quote the failing build output.\n`, + attempt: { + new: "Agents paraphrase failing build output instead of quoting it", + action: "add", + what: "Quote rule", + why: "Paraphrased errors hid causes", + anchor: "quote the failing build output", + depends_on: ["model"], + predicted: ["paraphrased-build-errors"], + expect: "Errors appear verbatim", + }, + }); + yield* seedThread( + { + id: "thread-claude", + title: "Fix the login form", + provider: "claudeAgent", + runs: [ + { model: "claude-opus-5-5", user: "Fix the login form" }, + { + model: "gpt-5", + provider: "codex", + user: "Nein, das ist falsch, ich meinte das Passwortfeld", + }, + ], + }, + 10, + ); + yield* seedItem( + "thread-claude", + "file_change", + { fileName: NodePath.join(harnessDir, "AGENTS.md") }, + 10, + ); + yield* seedThread( + { + id: "thread-codex", + title: "Refactor parser", + provider: "codex", + runs: [ + { model: "gpt-5", status: "interrupted", user: "Refactor the parser" }, + { model: "gpt-5", user: "Stop, keep the old API instead" }, + ], + }, + 11, + ); + yield* seedEvent( + "thread-codex", + "checkpoint.rollback-requested", + { checkpointId: "checkpoint-7" }, + 11, + ); + yield* seedThread( + { + id: "thread:delegated-task:review-1", + title: "Review the parser refactor", + provider: "antigravity", + parent: "thread-codex", + runs: [{ model: "gemini-4-ultra", user: "Review the diff for bugs" }], + assistant: "Found 2 issues: the old API lost its default export.", + }, + 12, + ); + yield* seedThread( + { + id: "thread-recorded", + title: "Notes", + provider: "claudeAgent", + runs: [{ model: "claude-opus-5-5", user: "Tidy notes" }], + }, + 12, + ); + yield* seedItem( + "thread-recorded", + "command_execution", + { input: `echo hi >> ${NodePath.join(harnessDir, "notes", "build-notes.md")}` }, + 12, + ); + yield* seedThread( + { + id: "thread-self", + title: "[SIM-AUDIT] weekly", + provider: "claudeAgent", + runs: [{ model: "claude-opus-5-5", user: "nein, wrong" }], + }, + 12, + ); + yield* seedThread( + { + id: "auditor", + title: "Audit", + provider: "claudeAgent", + runs: [ + { model: "claude-opus-5-5", user: "a" }, + { model: "claude-opus-5-5", user: "nein, falsch" }, + ], + }, + 12, + ); + yield* sim.recordTelemetry({ + ts: at(13), + kind: "new_model_observed", + providerInstanceId: "kimi", + model: "kimi-k3", + }); + yield* sim.recordTelemetry({ + ts: at(13), + kind: "checkpoint_rollback", + threadId: "thread-other", + checkpointId: "c-1", + }); + }); + +describe("SimAuditService", () => { + it.effect( + "aggregates corrections, harness edits and runtime signals across every provider", + () => { + const sb = sandbox(); + return Effect.gen(function* () { + yield* seedWorld(sb.harnessDir); + const projects = NodePath.join(sb.harnessDir, "projects"); + NodeFS.mkdirSync(NodePath.join(projects, "-work-repo"), { recursive: true }); + NodeFS.mkdirSync(NodePath.join(projects, "-tmp-sandbox"), { recursive: true }); + const transcript = [ + { + type: "user", + timestamp: at(14), + cwd: "/work/repo", + message: { content: "Add caching" }, + }, + { + type: "assistant", + timestamp: at(14, 1), + message: { + model: "claude-opus-5-5", + content: [ + { + type: "tool_use", + name: "Edit", + input: { file_path: NodePath.join(sb.harnessDir, "AGENTS.md") }, + }, + ], + }, + }, + { + type: "user", + timestamp: at(14, 2), + message: { content: "why did you change AGENTS.md? that's not what I asked" }, + }, + ]; + NodeFS.writeFileSync( + NodePath.join(projects, "-work-repo", "session-1.jsonl"), + transcript.map((row) => JSON.stringify(row)).join("\n"), + ); + NodeFS.writeFileSync( + NodePath.join(projects, "-tmp-sandbox", "session-2.jsonl"), + transcript.map((row) => JSON.stringify(row)).join("\n"), + ); + + const audit = yield* SimAuditService; + const report = yield* audit.audit(auditor, { since: "2026-11-01" }); + + expect(report.threadsScanned).toBe(4); + expect(report.claudeSessionsScanned).toBe(1); + expect(report.signals).toMatchObject({ + verbalCorrections: 3, + checkpointRollbacks: 2, + midThreadModelSwitches: 1, + interruptedWithSteer: 1, + delegatedReviews: 1, + unrecordedHarnessEdits: 2, + }); + expect(report.signals.newlyObservedModels.map((item) => item.model).sort()).toEqual([ + "gemini-4-ultra", + "gpt-5", + "kimi-k3", + ]); + expect(report.sim).toMatchObject({ journalBroken: null, liveRules: 1, openPredictions: 1 }); + expect(report.text).toContain( + "SWITCH thread-claude: claudeAgent/claude-opus-5-5 -> codex/gpt-5", + ); + expect(report.text).toMatch(/INTERRUPTED .*then: "Stop, keep the old API instead"/); + expect(report.text).toMatch( + /REVIEW thread:delegated-task:review-1 \[antigravity\/gemini-4-ultra\].*default export/, + ); + expect(report.text).toMatch( + /t3 thread-recorded .* recorded: ~\/\.claude\/notes\/build-notes\.md/, + ); + expect(report.text).toMatch(/t3 thread-claude .* UNRECORDED\?: ~\/\.claude\/AGENTS\.md/); + expect(report.text).toContain( + 'U2 (followup-correction): "Nein, das ist falsch, ich meinte das Passwortfeld"', + ); + expect(report.text).not.toContain("thread-self"); + expect(report.text).not.toContain("session-2"); + expect(report.advisorEscalation?.candidates.map((candidate) => candidate.kind)).toContain( + "new_model_generation", + ); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }, + ); + + it.effect("inspects one thread turn by turn and keeps a watermark for the next audit", () => { + const sb = sandbox(); + return Effect.gen(function* () { + yield* seedWorld(sb.harnessDir); + const audit = yield* SimAuditService; + const inspection = yield* audit.inspectThread(auditor, "thread-co"); + expect(inspection.threadId).toBe("thread-codex"); + expect(inspection.text.split("\n")).toEqual([ + "Thread thread-codex | Refactor parser | models: codex/gpt-5 | runs: 2 | user turns: 2 | has interrupted runs", + "run 1 [codex/gpt-5] interrupted", + "U1 [2026-11-11 10:01:00]: Refactor the parser", + "run 2 [codex/gpt-5] completed", + "U2 [2026-11-11 10:02:00]: Stop, keep the old API instead", + "ROLLBACK requested to checkpoint-7", + ]); + expect((yield* Effect.flip(audit.inspectThread(auditor, "thread-"))).code).toBe("validation"); + expect((yield* Effect.flip(audit.inspectThread(auditor, "nope"))).code).toBe("not_found"); + + const done = yield* audit.markAuditDone(auditor); + expect(JSON.parse(NodeFS.readFileSync(done.statePath, "utf8"))).toEqual({ + last_audit_at: done.lastAuditAt, + by: "t3:auditor", + }); + const next = yield* audit.audit(auditor, { includeClaudeLogs: false }); + expect(next.window.source).toBe(`watermark (${done.lastAuditAt})`); + expect(SimStore.isTestSimDir(sb.paths)).toBe(true); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }); + + it.effect( + "flags standing fixed observations from a fork thread recorded via CLI, while allowing delegated children", + () => { + const sb = sandbox(); + return Effect.gen(function* () { + yield* seedWorld(sb.harnessDir); + // Simulate a fork thread and an independent delegated child in SQLite. + yield* seedThread( + { + id: "thread-fork", + title: "Fork of recorded", + provider: "codex", + parent: "thread-recorded", + relationship: "fork", + runs: [{ model: "gpt-5", user: "Check build output" }], + }, + 13, + ); + yield* seedThread( + { + id: "thread-delegate-grader", + title: "Independent grader", + provider: "codex", + parent: "thread-recorded", + relationship: "subagent", + runs: [{ model: "gpt-5", user: "Verify build quoting" }], + }, + 13, + ); + // Write observations directly through SimStore without MCP forkFamilySessionIds (like CLI sim.mjs). + const sim = yield* SimService; + yield* sim.write( + { sessionId: "t3:thread-fork", model: "gpt-5", driver: "codex" }, + { + action: "observe", + input: { + attempt: "A1", + target: "paraphrased-build-errors", + result: "fixed", + evidence: "Fork ran CLI sim.mjs observe fixed directly", + source: "test", + }, + }, + ); + yield* sim.write( + { sessionId: "t3:thread-delegate-grader", model: "gpt-5", driver: "codex" }, + { + action: "observe", + input: { + attempt: "A1", + target: "paraphrased-build-errors", + result: "fixed", + evidence: "Delegated grader independently verified verbatim build output", + source: "test", + }, + }, + ); + + const audit = yield* SimAuditService; + const report = yield* audit.audit(auditor, { + since: "2026-11-01", + includeClaudeLogs: false, + }); + expect(report.text).toContain( + "FORK SELF-GRADE A1 (P1) outcome 1: fixed by t3:thread-fork (same fork/side-chat family as t3:thread-recorded", + ); + expect(report.text).not.toContain("t3:thread-delegate-grader"); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }, + ); +}); diff --git a/apps/server/src/sim/SimAuditService.ts b/apps/server/src/sim/SimAuditService.ts new file mode 100644 index 0000000000000..d4876e0a9f586 --- /dev/null +++ b/apps/server/src/sim/SimAuditService.ts @@ -0,0 +1,1454 @@ +// @effect-diagnostics nodeBuiltinImport:off globalDate:off - reads Claude Code transcripts and gate logs like sim-audit.mjs, whose timestamps are plain ISO strings. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ServerSettings from "../serverSettings.ts"; +import { + SimAuditService, + SimService, + SimServiceError, + classifyHarnessPath, + type SimAuditOptions, + type SimAuditReport, + type SimCallerContext, + type SimResolvedPaths, + type SimState, + type SimTelemetryEvent, +} from "./SimContracts.ts"; +import { detectShellWriteTargets } from "./SimObserverReactor.ts"; +import * as SimStore from "./SimStore.ts"; + +const isSimServiceError = Schema.is(SimServiceError); + +const DEFAULT_DAYS = 7; +const DEFAULT_LIMIT = 25; +const THREAD_LIMIT = 2_000; +const CHUNK = 400; +const INSPECT_LINES = 200; +const MAX_FORK_HOPS = 16; +const AUDIT_MARKER = "[SIM-AUDIT]"; + +const SKIP_USER_PREFIXES = [ + "", + "", + "", + "", + "This session is being continued from a previous conversation", + "Continue where you left off", + "Delegated task node:", + "Context handoff (", + "Note: the T3 server restarted", +]; + +// Bilingual cues for follow-up corrections (turn >= 2): a pre-filter; the audit agent reads context. +const FOLLOWUP_CORRECTION_RE = + /\b(nein|falsch|nicht so|stimmt nicht|das ist nicht|das war nicht|vergessen|vergiss|stattdessen|ich meinte|warum hast du|wieso hast du|hör auf|bitte nicht|schon wieder|immer noch|nochmal|rückgängig|mach das nicht|lass das|wrong|instead|i meant|why did you|you forgot|don't do|do not do|stop doing|not what i|this is not|that is not|that's not|rollback|revert|still broken|again you)\b/i; +// Stronger cues that indicate a recurring failure even on turn 1. +const FIRST_TURN_FRICTION_RE = + /\b(schon wieder|wieder kaputt|wieder falsch|hat wieder nicht|warum hast du vorhin|wieso hast du vorhin|failed again|broke again)\b/i; +const BASH_WRITE_OP_RE = + /(?:(?])>{1,2}\|?|\btee\b|\bsed\b[^|\n]*(?:-i|--in-place)|\bperl\b[^|\n]*-[a-zA-Z]*i|\b(?:cp|mv|ln|install|rsync)\b|(?:writeFile|appendFile|write_text|open\s*\([^)]*['"][wax+]))/; +const REVIEW_RE = + /\b(review|reviewer|re-check|recheck|audit|verify|verification|prüf\w*|gegenprüf\w*)\b/i; + +const MODEL_EVENT_TYPES = ["thread.model-selection-updated", "thread.provider-switched"]; +const AUDIT_EVENT_TYPES = ["checkpoint.rollback-requested", ...MODEL_EVENT_TYPES]; + +type Data = Record; + +function parseJson(text: unknown): Data { + if (typeof text !== "string") return {}; + try { + const parsed = JSON.parse(text) as unknown; + return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Data) + : {}; + } catch { + return {}; + } +} + +const str = (value: unknown): string | undefined => + typeof value === "string" && value ? value : undefined; +const record = (value: unknown): Data => + value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Data) : {}; + +function squashText(text: unknown, max = 240) { + const flat = String(text ?? "") + .replace(/\s+/g, " ") + .trim(); + return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat; +} + +/** The user's own words: mechanical wrappers stripped, as sim-audit.mjs does. */ +function extractUserText(content: unknown): string { + let raw = ""; + if (typeof content === "string") raw = content; + else if (Array.isArray(content)) { + raw = content + .map(record) + .filter((part) => part.type === "text" && typeof part.text === "string") + .map((part) => String(part.text)) + .join("\n"); + } + let text = raw.trim(); + if (!text) return ""; + text = text + .replace(/[\s\S]*?<\/t3_code_instructions>/g, "") + .replace(/[\s\S]*?<\/assistant_citations>/g, "") + .replace(/[\s\S]*?<\/system_context>/g, "") + .replace(/[\s\S]*?<\/runtime_info>/g, "") + .trim(); + const userRequest = text.match(/([\s\S]*?)<\/user_request>/); + if (userRequest) text = (userRequest[1] ?? "").trim(); + text = text.replace(/^(?:\[assistant-quote-\d+\]\s*)+/g, "").trim(); + if (!text || SKIP_USER_PREFIXES.some((prefix) => text.startsWith(prefix))) return ""; + return text; +} + +interface Flag { + readonly turn: number; + readonly kind: "followup-correction" | "turn1-friction"; + readonly excerpt: string; +} + +function flagMessage(turn: number, text: string): Flag | null { + if (turn >= 2 && FOLLOWUP_CORRECTION_RE.test(text)) { + return { turn, kind: "followup-correction", excerpt: squashText(text) }; + } + if (turn === 1 && FIRST_TURN_FRICTION_RE.test(text)) + return { turn, kind: "turn1-friction", excerpt: squashText(text) }; + return null; +} + +/** Path-like tokens a shell command writes to; the caller decides which are harness files. */ +function bashWriteTargets(command: string): Array { + const found = new Set(detectShellWriteTargets(command)); + if (!BASH_WRITE_OP_RE.test(command)) return [...found]; + if ( + /^\s*(?:[A-Z_]+=\S+\s+)*node\s+[^\n|;&>]*\bsim(?:-audit)?\.mjs\b/.test(command) && + !/(?])>{1,2}/.test(command) + ) { + return [...found]; + } + const noHeredoc = command.replace( + /(<<-?\s*['"]?([A-Za-z_]\w*)['"]?[^\n]*\n)[\s\S]*?(?:\n[ \t]*\2(?=\n|$)|$)/g, + "$1", + ); + for (const match of noHeredoc.matchAll(/(?:"([^"\n]+)"|'([^'\n]+)'|([^\s"'|;&<>()]+))/g)) { + const token = (match[1] ?? match[2] ?? match[3] ?? "").trim(); + if (!token || /[$*{]/.test(token) || token.includes("/backups/") || /\.bak(?:-|$)/.test(token)) + continue; + if (!/^(?:\/|~\/|\.claude\/|(?:AGENTS|CLAUDE)\.md$)/.test(token)) continue; + found.add(token); + } + return [...found]; +} + +function inferProject(cwd: string | null, dirName: string) { + if (cwd) { + const clean = cwd.replace(/\/+$/, ""); + if (clean.includes("/.t3/scratch")) return "scratch"; + const worktree = clean.match(/\/\.t3\/worktrees\/([^/]+)/); + if (worktree?.[1]) return worktree[1]; + return NodePath.basename(clean) || clean; + } + return dirName.replace(/^-+/, "").split("-").slice(-2).join("-") || dirName; +} + +interface HarnessEdit { + readonly source: "t3" | "claude" | "telemetry"; + readonly session: string; + readonly date: string; + readonly provider: string; + readonly model: string; + readonly files: ReadonlyArray; + readonly record: boolean; + readonly recorded: boolean; +} + +interface FlaggedSession { + readonly source: "t3" | "claude"; + readonly session: string; + readonly date: string; + readonly project: string; + readonly provider: string; + readonly model: string; + readonly userTurns: number; + readonly flags: ReadonlyArray; +} + +interface ClaudeTranscript { + readonly sessionId: string; + readonly project: string; + readonly model: string; + readonly lastTs: string | null; + readonly userTurns: number; + readonly isAuditSelf: boolean; + readonly harnessEdits: ReadonlyArray; + readonly flags: ReadonlyArray; +} + +function claudeRoots(paths: SimResolvedPaths): Array { + const roots = [NodePath.join(paths.harnessDir, "projects")]; + if (paths.harnessDir === NodePath.join(paths.homeDir, ".claude")) { + try { + for (const name of NodeFS.readdirSync(paths.homeDir)) { + if (/^\.claude-/.test(name)) roots.push(NodePath.join(paths.homeDir, name, "projects")); + } + } catch { + // an unreadable home adds no roots + } + } + return roots.filter((dir) => NodeFS.existsSync(dir)); +} + +function parseTranscript( + filePath: string, + dirName: string, + sinceMs: number, + isHarness: (file: string, cwd: string | null) => boolean, +): ClaudeTranscript | null { + let raw: string; + try { + raw = NodeFS.readFileSync(filePath, "utf8"); + } catch { + return null; + } + const users: Array<{ turn: number; ts: string | null; text: string }> = []; + const edits = new Set(); + const models = new Map(); + let cwd: string | null = null; + let lastTs: string | null = null; + let isAuditSelf = false; + const inWindow = (ts: unknown) => { + if (typeof ts !== "string") return true; + const ms = Date.parse(ts); + return !Number.isFinite(ms) || ms >= sinceMs; + }; + for (const line of raw.split("\n")) { + if (!line) continue; + const row = parseJson(line); + if (!Object.keys(row).length) continue; + if (!cwd && str(row.cwd)) cwd = str(row.cwd) ?? null; + const ts = str(row.timestamp); + if (ts && (!lastTs || ts > lastTs)) lastTs = ts; + const message = record(row.message); + if (row.type === "user" && !row.isMeta && !row.isSidechain) { + const text = extractUserText(message.content); + if (text) { + if (users.length === 0 && text.includes(AUDIT_MARKER)) isAuditSelf = true; + users.push({ turn: users.length + 1, ts: ts ?? null, text }); + } + } else if (row.type === "assistant" && !row.isSidechain) { + const model = str(message.model) ?? str(row.requestedModel); + if (model) models.set(model, (models.get(model) ?? 0) + 1); + if (Array.isArray(message.content) && inWindow(ts)) { + for (const block of message.content.map(record)) { + if (block.type !== "tool_use") continue; + const input = record(block.input); + if (["Write", "Edit", "MultiEdit"].includes(String(block.name))) { + const file = str(input.file_path); + if (file && isHarness(file, cwd)) edits.add(file); + } else if (block.name === "Bash") { + for (const file of bashWriteTargets(String(input.command ?? ""))) + if (isHarness(file, cwd)) edits.add(file); + } + } + } + } + } + let model = "unknown"; + let best = 0; + for (const [name, hits] of models) { + if (hits > best) { + best = hits; + model = name; + } + } + const flags = users + .filter((msg) => inWindow(msg.ts)) + .flatMap((msg) => flagMessage(msg.turn, msg.text) ?? []); + return { + sessionId: NodePath.basename(filePath, ".jsonl"), + project: inferProject(cwd, dirName), + model, + lastTs, + userTurns: users.length, + isAuditSelf, + harnessEdits: [...edits], + flags, + }; +} + +interface GateLog { + readonly present: boolean; + readonly total: number; + readonly counts: Record; + readonly notable: ReadonlyArray<{ + time: string; + outcome: string; + session: string; + target: string; + }>; +} + +function readGateLog(filePath: string, sinceMs: number): GateLog { + const counts: Record = {}; + const notable: Array<{ time: string; outcome: string; session: string; target: string }> = []; + let lines: Array; + try { + lines = NodeFS.readFileSync(filePath, "utf8").split("\n").filter(Boolean); + } catch { + return { present: false, total: 0, counts, notable }; + } + let total = 0; + for (const line of lines) { + const entry = parseJson(line); + if (!Object.keys(entry).length) continue; + const ts = Date.parse(String(entry.time ?? "")); + if (Number.isFinite(ts) && ts < sinceMs) continue; + total += 1; + const outcome = String(entry.outcome ?? "unknown"); + counts[outcome] = (counts[outcome] ?? 0) + 1; + if (!["allowed", "stamped"].includes(outcome)) { + notable.push({ + time: String(entry.time ?? ""), + outcome, + session: String(entry.session ?? "none").slice(0, 12), + target: String(entry.file ?? entry.repo ?? ""), + }); + } + } + return { present: true, total, counts, notable }; +} + +function scanClaudeLogs( + paths: SimResolvedPaths, + sinceMs: number, + excludeSessions: ReadonlySet, + isHarness: (file: string, cwd: string | null) => boolean, +) { + const transcripts: Array = []; + let excludedSelf = 0; + for (const root of claudeRoots(paths)) { + for (const dir of NodeFS.readdirSync(root)) { + if (dir.startsWith("-tmp-")) continue; + const fullDir = NodePath.join(root, dir); + let files: Array; + try { + files = NodeFS.statSync(fullDir).isDirectory() ? NodeFS.readdirSync(fullDir) : []; + } catch { + continue; + } + for (const file of files) { + if (!file.endsWith(".jsonl")) continue; + const filePath = NodePath.join(fullDir, file); + try { + if (NodeFS.statSync(filePath).mtimeMs < sinceMs) continue; + } catch { + continue; + } + if (excludeSessions.has(file.slice(0, -".jsonl".length))) { + excludedSelf += 1; + continue; + } + const parsed = parseTranscript(filePath, dir, sinceMs, isHarness); + if (!parsed || parsed.userTurns === 0) continue; + if (parsed.isAuditSelf) { + excludedSelf += 1; + continue; + } + transcripts.push(parsed); + } + } + } + return { transcripts, excludedSelf }; +} + +function readWatermark(paths: SimResolvedPaths): string | null { + const saved = parseJson( + NodeFS.existsSync(paths.auditStatePath) + ? NodeFS.readFileSync(paths.auditStatePath, "utf8") + : "", + ); + const at = str(saved.last_audit_at); + return at && Number.isFinite(Date.parse(at)) ? at : null; +} + +function writeWatermark(paths: SimResolvedPaths, nowMs: number, by: string): string { + const now = new Date(nowMs).toISOString(); + NodeFS.mkdirSync(NodePath.dirname(paths.auditStatePath), { recursive: true }); + NodeFS.writeFileSync( + paths.auditStatePath, + `${JSON.stringify({ last_audit_at: now, by }, null, 2)}\n`, + ); + return now; +} + +function resolveSince(options: SimAuditOptions, paths: SimResolvedPaths, nowMs: number) { + const window = resolveWindow(options, paths, nowMs); + return { ...window, sinceIso: new Date(window.sinceMs).toISOString() }; +} + +function resolveWindow(options: SimAuditOptions, paths: SimResolvedPaths, nowMs: number) { + if (options.since !== undefined) { + const ms = Date.parse( + options.since.length === 10 ? `${options.since}T00:00:00Z` : options.since, + ); + if (!Number.isFinite(ms)) { + throw new SimServiceError({ + code: "validation", + problems: [`invalid since value: ${options.since}`], + }); + } + return { sinceMs: ms, source: `since ${options.since}` }; + } + if (options.days !== undefined) { + if (!Number.isFinite(options.days) || options.days <= 0) { + throw new SimServiceError({ + code: "validation", + problems: [`invalid days value: ${options.days}`], + }); + } + return { sinceMs: nowMs - options.days * 86_400_000, source: `last ${options.days}d` }; + } + const watermark = readWatermark(paths); + if (watermark) return { sinceMs: Date.parse(watermark), source: `watermark (${watermark})` }; + return { sinceMs: nowMs - DEFAULT_DAYS * 86_400_000, source: `default last ${DEFAULT_DAYS}d` }; +} + +/** Every session id the SIM record names as a writer, without its `cc:`/`t3:` kind. */ +function simWriters(state: SimState): Set { + const out = new Set(); + const add = (id: string | undefined) => { + if (id && id !== "unknown") out.add(SimStore.bare(id)); + }; + for (const attempt of SimStore.allAttempts(state)) { + add(attempt.by); + add(attempt.also); + add(attempt.sample); + for (const obs of attempt.observations) { + add(obs.by); + add(obs.also); + add(obs.sample); + } + } + return out; +} + +interface ThreadRow { + readonly thread_id: string; + readonly project_id: string; + readonly title: string; + readonly default_provider: string; + readonly updated_at: string; + readonly payload_json: string; +} +interface RunRow { + readonly run_id: string; + readonly thread_id: string; + readonly ordinal: number; + readonly provider: string; + readonly status: string; + readonly requested_at: string; + readonly completed_at: string | null; + readonly payload_json: string; +} +interface MessageRow { + readonly message_id: string; + readonly thread_id: string; + readonly run_id: string | null; + readonly role: string; + readonly created_at: string; + readonly payload_json: string; +} +interface TurnItemRow { + readonly thread_id: string; + readonly run_id: string | null; + readonly type: string; + readonly updated_at: string; + readonly ordinal: number; + readonly payload_json: string; +} +interface EventRow { + readonly thread_id: string; + readonly run_id: string | null; + readonly event_type: string; + readonly occurred_at: string; + readonly payload_json: string; +} +interface ProjectRow { + readonly project_id: string; + readonly title: string; + readonly workspace_root: string; +} +interface ProviderThreadRow { + readonly thread_id: string; + readonly provider: string; + readonly payload_json: string; +} + +interface RunInfo { + readonly runId: string; + readonly ordinal: number; + readonly status: string; + readonly requestedAt: string; + readonly provider: string; + readonly model: string; + readonly userMessageId: string | undefined; +} + +const runInfo = (row: RunRow): RunInfo => { + const payload = parseJson(row.payload_json); + const selection = record(payload.modelSelection); + return { + runId: row.run_id, + ordinal: row.ordinal, + status: row.status, + requestedAt: row.requested_at, + provider: str(payload.providerInstanceId) ?? str(selection.instanceId) ?? row.provider, + model: str(selection.model) ?? "unknown", + userMessageId: str(payload.userMessageId), + }; +}; + +const chunks = (items: ReadonlyArray) => { + const out: Array> = []; + for (let i = 0; i < items.length; i += CHUNK) out.push(items.slice(i, i + CHUNK)); + return out; +}; + +const groupBy = (rows: ReadonlyArray) => { + const map = new Map>(); + for (const row of rows) map.set(row.thread_id, [...(map.get(row.thread_id) ?? []), row]); + return map; +}; + +function candidateFixedT3Threads(state: SimState): Array { + const ids = new Set(); + const add = (value: string | undefined) => { + if (value?.startsWith("t3:")) ids.add(value.slice(3)); + }; + for (const attempt of SimStore.allAttempts(state)) { + if (attempt.retracted) continue; + const fixes = attempt.observations.filter( + (obs) => !obs.retracted && obs.result === "fixed" && obs.source !== "self", + ); + if (fixes.length === 0) continue; + add(attempt.by); + add(attempt.also); + add(attempt.sample); + for (const obs of fixes) { + add(obs.by); + add(obs.also); + } + } + return [...ids]; +} + +function forkParentFromPayload(payloadJson: string): string | null { + const lineage = record(parseJson(payloadJson).lineage); + const parent = str(lineage.parentThreadId); + if (!parent) return null; + return lineage.relationshipToParent === "fork" || lineage.sideChat === true ? parent : null; +} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const sim = yield* SimService; + const serverSettings = yield* ServerSettings.ServerSettingsService; + + const ioError = (cause: unknown) => + new SimServiceError({ + code: "io", + problems: [cause instanceof Error ? cause.message : String(cause)], + }); + + const tableNames = sql<{ + readonly name: string; + }>`SELECT name FROM sqlite_master WHERE type = 'table'`.pipe( + Effect.map((rows) => new Set(rows.map((row) => row.name))), + ); + + const byThreads = ( + ids: ReadonlyArray, + query: (chunk: ReadonlyArray) => Effect.Effect, E>, + ) => Effect.forEach(chunks(ids), query).pipe(Effect.map((parts) => parts.flat())); + + const readDatabase = Effect.fn("SimAuditService.readDatabase")(function* ( + sinceIso: string, + forkCandidateIds: ReadonlyArray, + ) { + const tables = yield* tableNames; + const has = (name: string) => tables.has(name); + const threads = has("orchestration_v2_projection_threads") + ? yield* sql` + SELECT thread_id, project_id, title, default_provider, updated_at, payload_json + FROM orchestration_v2_projection_threads + WHERE updated_at >= ${sinceIso} AND deleted_at IS NULL + ORDER BY updated_at DESC + LIMIT ${THREAD_LIMIT}` + : []; + const ids = threads.map((row) => row.thread_id); + const runs = has("orchestration_v2_projection_runs") + ? yield* byThreads( + ids, + (chunk) => sql` + SELECT run_id, thread_id, ordinal, provider, status, requested_at, completed_at, payload_json + FROM orchestration_v2_projection_runs + WHERE thread_id IN ${sql.in(chunk)} + ORDER BY thread_id, ordinal`, + ) + : []; + const messages = has("orchestration_v2_projection_messages") + ? yield* byThreads( + ids, + (chunk) => sql` + SELECT message_id, thread_id, run_id, role, created_at, payload_json + FROM orchestration_v2_projection_messages + WHERE thread_id IN ${sql.in(chunk)} AND role IN ('user', 'assistant') AND streaming = 0 + ORDER BY thread_id, created_at, message_id`, + ) + : []; + const items = has("orchestration_v2_projection_turn_items") + ? yield* byThreads( + ids, + (chunk) => sql` + SELECT thread_id, run_id, type, updated_at, ordinal, payload_json + FROM orchestration_v2_projection_turn_items + WHERE thread_id IN ${sql.in(chunk)} AND type IN ('file_change', 'command_execution') + AND updated_at >= ${sinceIso} + ORDER BY thread_id, ordinal`, + ) + : []; + const events = has("orchestration_v2_events") + ? yield* byThreads( + ids, + (chunk) => sql` + SELECT thread_id, run_id, event_type, occurred_at, payload_json + FROM orchestration_v2_events + WHERE thread_id IN ${sql.in(chunk)} AND event_type IN ${sql.in(AUDIT_EVENT_TYPES)} + AND occurred_at >= ${sinceIso} + ORDER BY sequence`, + ) + : []; + const projects = has("projection_projects") + ? yield* sql`SELECT project_id, title, workspace_root FROM projection_projects` + : []; + const providerThreads = has("orchestration_v2_projection_provider_threads") + ? yield* byThreads( + ids, + (chunk) => sql` + SELECT thread_id, provider, payload_json + FROM orchestration_v2_projection_provider_threads + WHERE thread_id IN ${sql.in(chunk)}`, + ) + : []; + const forkParents = new Map(); + if (has("orchestration_v2_projection_threads") && forkCandidateIds.length > 0) { + let frontier = [...new Set(forkCandidateIds)]; + for (let hop = 0; hop < MAX_FORK_HOPS && frontier.length > 0; hop += 1) { + const rows = yield* byThreads( + frontier, + (chunk) => sql<{ readonly thread_id: string; readonly payload_json: string }>` + SELECT thread_id, payload_json + FROM orchestration_v2_projection_threads + WHERE thread_id IN ${sql.in(chunk)}`, + ); + const next: Array = []; + for (const id of frontier) { + if (!forkParents.has(id)) forkParents.set(id, null); + } + for (const row of rows) { + const parent = forkParentFromPayload(row.payload_json); + forkParents.set(row.thread_id, parent); + if (parent && !forkParents.has(parent)) next.push(parent); + } + frontier = [...new Set(next)]; + } + } + return { threads, runs, messages, items, events, projects, providerThreads, forkParents }; + }); + + const audit: SimAuditService["Service"]["audit"] = Effect.fn("SimAuditService.audit")(function* ( + caller: SimCallerContext, + options: SimAuditOptions = {}, + ) { + const settings = yield* serverSettings.getSettings.pipe(Effect.mapError(ioError)); + if (!settings.sim.enabled) { + return yield* new SimServiceError({ + code: "disabled", + problems: ["SIM is turned off in settings"], + }); + } + const snapshot = yield* sim.getStateSnapshot(); + if (!snapshot) + return yield* new SimServiceError({ code: "disabled", problems: ["SIM is not available"] }); + const { state, paths } = snapshot; + const nowMs = yield* Clock.currentTimeMillis; + const { sinceMs, sinceIso, source } = yield* Effect.try({ + try: () => resolveSince(options, paths, nowMs), + catch: (cause) => (isSimServiceError(cause) ? cause : ioError(cause)), + }); + const limit = Math.max(1, options.limit ?? DEFAULT_LIMIT); + const db = yield* readDatabase(sinceIso, candidateFixedT3Threads(state)).pipe( + NodeSqliteClient.readOnly, + Effect.mapError(ioError), + ); + const telemetry = (yield* sim.readTelemetry(sinceMs)).filter( + (event) => !caller.threadId || !("threadId" in event) || event.threadId !== caller.threadId, + ); + const observed = yield* sim.getObservedModels(); + return yield* Effect.try({ + try: () => + buildReport({ + caller, + options, + paths, + state, + broken: snapshot.broken, + sinceMs, + source, + limit, + db, + telemetry, + observed, + advisor: settings.sim, + }), + catch: ioError, + }); + }); + + const inspectThread: SimAuditService["Service"]["inspectThread"] = Effect.fn( + "SimAuditService.inspectThread", + )(function* (_caller, threadIdPrefix) { + const wanted = threadIdPrefix.trim(); + if (!wanted) + return yield* new SimServiceError({ + code: "validation", + problems: ["give a thread id or its prefix"], + }); + const read = Effect.gen(function* () { + const tables = yield* tableNames; + if (!tables.has("orchestration_v2_projection_threads")) return null; + const matches = yield* sql` + SELECT thread_id, project_id, title, default_provider, updated_at, payload_json + FROM orchestration_v2_projection_threads + WHERE thread_id = ${wanted} OR substr(thread_id, 1, ${wanted.length}) = ${wanted} + ORDER BY CASE WHEN thread_id = ${wanted} THEN 0 ELSE 1 END, updated_at DESC + LIMIT 10`; + const exact = matches.find((row) => row.thread_id === wanted); + if (!exact && matches.length !== 1) return { matches, thread: null }; + const thread = exact ?? matches[0]!; + const id = thread.thread_id; + const runs = tables.has("orchestration_v2_projection_runs") + ? yield* sql` + SELECT run_id, thread_id, ordinal, provider, status, requested_at, completed_at, payload_json + FROM orchestration_v2_projection_runs WHERE thread_id = ${id} ORDER BY ordinal` + : []; + const messages = tables.has("orchestration_v2_projection_messages") + ? yield* sql` + SELECT message_id, thread_id, run_id, role, created_at, payload_json + FROM orchestration_v2_projection_messages + WHERE thread_id = ${id} AND role IN ('user', 'assistant') ORDER BY created_at, message_id` + : []; + const items = tables.has("orchestration_v2_projection_turn_items") + ? yield* sql` + SELECT thread_id, run_id, type, updated_at, ordinal, payload_json + FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${id} AND type IN ('file_change', 'command_execution', 'dynamic_tool', 'subagent') + ORDER BY ordinal` + : []; + const events = tables.has("orchestration_v2_events") + ? yield* sql` + SELECT thread_id, run_id, event_type, occurred_at, payload_json + FROM orchestration_v2_events + WHERE thread_id = ${id} AND event_type IN ${sql.in(AUDIT_EVENT_TYPES)} ORDER BY sequence` + : []; + return { matches, thread, runs, messages, items, events }; + }); + const found = yield* read.pipe(NodeSqliteClient.readOnly, Effect.mapError(ioError)); + if (!found || (!found.thread && !found.matches.length)) { + return yield* new SimServiceError({ + code: "not_found", + problems: [`no T3 thread matching "${wanted}"`], + }); + } + if (!found.thread || !("runs" in found)) { + return yield* new SimServiceError({ + code: "validation", + problems: [ + `several threads match "${wanted}": ${found.matches.map((row) => row.thread_id).join(", ")}`, + ], + }); + } + return { + threadId: found.thread.thread_id, + text: renderInspection(found.thread, found.runs, found.messages, found.items, found.events), + }; + }); + + const markAuditDone: SimAuditService["Service"]["markAuditDone"] = Effect.fn( + "SimAuditService.markAuditDone", + )(function* (caller) { + const paths = yield* sim.resolvePaths(); + const nowMs = yield* Clock.currentTimeMillis; + const now = yield* Effect.try({ + try: () => writeWatermark(paths, nowMs, caller.sessionId || "unknown"), + catch: ioError, + }); + return { + lastAuditAt: now, + statePath: paths.auditStatePath, + text: `marked audit done at ${now} (${paths.auditStatePath})`, + }; + }); + + return SimAuditService.of({ audit, inspectThread, markAuditDone }); +}); + +export const layer = Layer.effect(SimAuditService, make); + +interface ReportInput { + readonly caller: SimCallerContext; + readonly options: SimAuditOptions; + readonly paths: SimResolvedPaths; + readonly state: SimState; + readonly broken: string | null; + readonly sinceMs: number; + readonly source: string; + readonly limit: number; + readonly db: { + readonly threads: ReadonlyArray; + readonly runs: ReadonlyArray; + readonly messages: ReadonlyArray; + readonly items: ReadonlyArray; + readonly events: ReadonlyArray; + readonly projects: ReadonlyArray; + readonly providerThreads: ReadonlyArray; + readonly forkParents: ReadonlyMap; + }; + readonly telemetry: ReadonlyArray; + readonly observed: ReadonlySet; + readonly advisor: Parameters[1]; +} + +interface Switch { + readonly threadId: string; + readonly from: string; + readonly to: string; +} +interface Interrupt { + readonly threadId: string; + readonly interruptedRunId: string; + readonly followup: string; + readonly model: string; +} +interface Review { + readonly threadId: string; + readonly title: string; + readonly model: string; + readonly excerpt: string; +} + +function buildReport(input: ReportInput): SimAuditReport { + const { caller, paths, state, sinceMs, limit, db } = input; + const allowTmp = SimStore.isTestSimDir(paths); + const kindOf = (file: string, cwd: string | null) => + classifyHarnessPath(file, paths, cwd ?? paths.homeDir, { allowTmp }); + const writers = simWriters(state); + const projects = new Map(db.projects.map((row) => [row.project_id, row])); + const runsBy = groupBy(db.runs); + const messagesBy = groupBy(db.messages); + const itemsBy = groupBy(db.items); + const eventsBy = groupBy(db.events); + const claudeNativeIdsByThread = new Map>(); + const allT3ClaudeNativeIds = new Set(); + for (const row of db.providerThreads) { + const nativeRef = record(parseJson(row.payload_json).nativeThreadRef); + const nativeId = str(nativeRef.nativeId); + if (nativeId && (str(nativeRef.driver) === "claudeAgent" || row.provider === "claudeAgent")) { + const set = claudeNativeIdsByThread.get(row.thread_id) ?? new Set(); + set.add(nativeId); + claudeNativeIdsByThread.set(row.thread_id, set); + allT3ClaudeNativeIds.add(nativeId); + } + } + + const flagged: Array = []; + const edits: Array = []; + const rollbacks = new Map(); + const switches = new Map(); + const interrupts = new Map(); + const reviews = new Map(); + const freshModels = new Map(); + let threadsScanned = 0; + let excludedSelf = 0; + + const noteModel = (providerInstanceId: string, model: string) => { + if (!model || model === "unknown" || input.observed.has(model)) return; + freshModels.set(`${providerInstanceId}::${model}`, { providerInstanceId, model }); + }; + + for (const thread of db.threads) { + if (caller.threadId && thread.thread_id === caller.threadId) { + excludedSelf += 1; + continue; + } + const payload = parseJson(thread.payload_json); + const messages = messagesBy.get(thread.thread_id) ?? []; + const users = messages + .filter((row) => row.role === "user") + .map((row) => ({ row, text: extractUserText(parseJson(row.payload_json).text) })) + .filter((entry) => entry.text); + if (thread.title.includes(AUDIT_MARKER) || users[0]?.text.includes(AUDIT_MARKER)) { + excludedSelf += 1; + continue; + } + threadsScanned += 1; + const runs = (runsBy.get(thread.thread_id) ?? []).map(runInfo); + const lastRun = runs[runs.length - 1]; + const provider = + lastRun?.provider ?? str(payload.providerInstanceId) ?? thread.default_provider; + const model = lastRun?.model ?? str(record(payload.modelSelection).model) ?? "unknown"; + const project = projects.get(thread.project_id); + const cwd = str(payload.worktreePath) ?? project?.workspace_root ?? null; + const date = thread.updated_at.slice(0, 10); + + const flags = users.flatMap((entry, index) => + Date.parse(entry.row.created_at) >= sinceMs ? (flagMessage(index + 1, entry.text) ?? []) : [], + ); + if (flags.length) { + flagged.push({ + source: "t3", + session: thread.thread_id, + date, + project: project?.title ?? thread.project_id, + provider, + model, + userTurns: users.length, + flags, + }); + } + + for (const run of runs) + if (Date.parse(run.requestedAt) >= sinceMs) noteModel(run.provider, run.model); + for (let i = 1; i < runs.length; i += 1) { + const before = runs[i - 1]!; + const after = runs[i]!; + if (Date.parse(after.requestedAt) < sinceMs) continue; + const from = `${before.provider}/${before.model}`; + const to = `${after.provider}/${after.model}`; + if (from !== to) + switches.set(`${thread.thread_id}|${from}|${to}`, { threadId: thread.thread_id, from, to }); + if (before.status === "interrupted") { + const followup = + users.find((entry) => entry.row.message_id === after.userMessageId)?.text ?? ""; + interrupts.set(before.runId, { + threadId: thread.thread_id, + interruptedRunId: before.runId, + followup: squashText(followup, 160), + model: `${before.provider}/${before.model}`, + }); + } + } + + for (const event of eventsBy.get(thread.thread_id) ?? []) { + const eventPayload = parseJson(event.payload_json); + if (event.event_type === "checkpoint.rollback-requested") { + const checkpointId = str(eventPayload.checkpointId) ?? event.occurred_at; + rollbacks.set(`${thread.thread_id}|${checkpointId}`, { + threadId: thread.thread_id, + checkpointId, + date: event.occurred_at.slice(0, 10), + }); + } else if (MODEL_EVENT_TYPES.includes(event.event_type)) { + const prior = [...runs].reverse().find((run) => run.requestedAt <= event.occurred_at); + const selection = record(eventPayload.modelSelection); + const toProvider = str(eventPayload.providerInstanceId) ?? str(selection.instanceId); + const toModel = str(selection.model); + if (!prior || !toModel) continue; + const from = `${prior.provider}/${prior.model}`; + const to = `${toProvider ?? prior.provider}/${toModel}`; + if (from !== to) + switches.set(`${thread.thread_id}|${from}|${to}`, { + threadId: thread.thread_id, + from, + to, + }); + } + } + + const harnessFiles = new Set(); + const recordFiles = new Set(); + for (const item of itemsBy.get(thread.thread_id) ?? []) { + const itemPayload = parseJson(item.payload_json); + const changePaths = Array.isArray(itemPayload.changes) + ? itemPayload.changes.map((entry) => str(record(entry).path)) + : []; + const targets = + item.type === "file_change" + ? [str(itemPayload.fileName), ...changePaths].filter((file): file is string => !!file) + : bashWriteTargets(String(itemPayload.input ?? "")); + for (const file of targets) { + const kind = kindOf(file, cwd); + const canonical = SimStore.resolveCallerFile( + file, + { sessionId: "", ...(cwd ? { workspaceRoot: cwd } : {}) }, + paths, + ); + if (kind === "harness") harnessFiles.add(canonical); + else if (kind === "record") recordFiles.add(canonical); + } + } + const nativeIds = claudeNativeIdsByThread.get(thread.thread_id); + const recorded = + writers.has(thread.thread_id) || + (nativeIds !== undefined && [...nativeIds].some((id) => writers.has(id))); + if (harnessFiles.size) { + edits.push({ + source: "t3", + session: thread.thread_id, + date, + provider, + model, + files: [...harnessFiles], + record: false, + recorded, + }); + } + if (recordFiles.size) { + edits.push({ + source: "t3", + session: thread.thread_id, + date, + provider, + model, + files: [...recordFiles], + record: true, + recorded: false, + }); + } + + const lineage = record(payload.lineage); + const delegated = + !!str(lineage.parentThreadId) || thread.thread_id.startsWith("thread:delegated-task:"); + if (delegated && (REVIEW_RE.test(thread.title) || REVIEW_RE.test(users[0]?.text ?? ""))) { + const lastAssistant = [...messages].reverse().find((row) => row.role === "assistant"); + reviews.set(thread.thread_id, { + threadId: thread.thread_id, + title: thread.title, + model: `${provider}/${model}`, + excerpt: squashText(lastAssistant ? parseJson(lastAssistant.payload_json).text : "", 300), + }); + } + } + + for (const event of input.telemetry) { + switch (event.kind) { + case "unrecorded_harness_edit": + case "direct_sim_record_edit": { + const isRecord = event.kind === "direct_sim_record_edit"; + const known = edits.some( + (edit) => + edit.session === event.threadId && + edit.record === isRecord && + event.files.every((file) => edit.files.includes(file)), + ); + if (!known) { + edits.push({ + source: "telemetry", + session: event.threadId, + date: event.ts.slice(0, 10), + provider: event.providerInstanceId ?? "unknown", + model: event.model ?? "unknown", + files: event.files, + record: isRecord, + recorded: false, + }); + } + break; + } + case "checkpoint_rollback": { + const checkpointId = event.checkpointId ?? event.ts; + rollbacks.set(`${event.threadId}|${checkpointId}`, { + threadId: event.threadId, + checkpointId, + date: event.ts.slice(0, 10), + }); + break; + } + case "mid_thread_model_switch": { + const from = `${event.fromProvider ?? "?"}/${event.fromModel ?? "?"}`; + const to = `${event.toProvider ?? "?"}/${event.toModel ?? "?"}`; + switches.set(`${event.threadId}|${from}|${to}`, { threadId: event.threadId, from, to }); + break; + } + case "interrupted_with_steer": { + const key = event.interruptedRunId ?? `${event.threadId}|${event.ts}`; + if (!interrupts.has(key)) { + interrupts.set(key, { + threadId: event.threadId, + interruptedRunId: key, + followup: squashText(event.reason ?? "", 160), + model: `${event.providerInstanceId ?? "?"}/${event.model ?? "?"}`, + }); + } + break; + } + case "new_model_observed": + noteModel(event.providerInstanceId, event.model); + break; + case "delegated_review_completed": { + const key = event.childThreadId ?? event.threadId; + if (!reviews.has(key)) { + reviews.set(key, { + threadId: key, + title: event.title ?? "delegated review", + model: `${event.providerInstanceId ?? "?"}/${event.model ?? "?"}`, + excerpt: squashText(event.excerpt ?? "", 300), + }); + } + break; + } + } + } + + let claudeSessionsScanned = 0; + let simGateLog: GateLog | null = null; + if (input.options.includeClaudeLogs !== false) { + const exclude = new Set([ + ...[caller.sessionId, caller.alsoSessionId] + .filter((id): id is string => !!id && id.startsWith("cc:")) + .map(SimStore.bare), + ...allT3ClaudeNativeIds, + ]); + const scan = scanClaudeLogs(paths, sinceMs, exclude, (file, cwd) => kindOf(file, cwd) !== null); + excludedSelf += scan.excludedSelf; + claudeSessionsScanned = scan.transcripts.length; + for (const transcript of scan.transcripts) { + const date = (transcript.lastTs ?? new Date(sinceMs).toISOString()).slice(0, 10); + if (transcript.harnessEdits.length) { + edits.push({ + source: "claude", + session: transcript.sessionId, + date, + provider: "claudeAgent", + model: transcript.model, + files: transcript.harnessEdits.map((file) => + SimStore.resolveCallerFile(file, { sessionId: "" }, paths), + ), + record: false, + recorded: writers.has(transcript.sessionId), + }); + } + if (transcript.flags.length) { + flagged.push({ + source: "claude", + session: transcript.sessionId, + date, + project: transcript.project, + provider: "claudeAgent", + model: transcript.model, + userTurns: transcript.userTurns, + flags: transcript.flags, + }); + } + } + simGateLog = readGateLog(NodePath.join(paths.harnessDir, "state", "sim-gate.log"), sinceMs); + } + + // Detect standing fixed observations recorded by a fork/side-chat via CLI sim.mjs (which lacks lineage awareness). + const forkRootOf = (threadId: string): string => { + let current = threadId; + const visited = new Set([current]); + for (let hop = 0; hop < MAX_FORK_HOPS; hop += 1) { + const parent = db.forkParents.get(current); + if (!parent || visited.has(parent)) break; + visited.add(parent); + current = parent; + } + return current; + }; + const forkSelfGrades: Array<{ + attemptId: string; + problemId: string; + outcomeIndex: number; + author: string; + observer: string; + }> = []; + for (const problem of state.problems) { + for (const attempt of problem.attempts) { + if (attempt.retracted) continue; + const authorThreads = [attempt.by, attempt.also, attempt.sample] + .filter((id): id is string => typeof id === "string" && id.startsWith("t3:")) + .map((id) => id.slice(3)); + if (authorThreads.length === 0) continue; + const authorRoots = new Set(authorThreads.map(forkRootOf)); + attempt.observations.forEach((obs, index) => { + if (obs.retracted || obs.result !== "fixed" || obs.source === "self") return; + const obsThreads = [obs.by, obs.also] + .filter((id): id is string => typeof id === "string" && id.startsWith("t3:")) + .map((id) => id.slice(3)); + if (obsThreads.some((id) => authorThreads.includes(id))) return; + if (obsThreads.some((id) => authorRoots.has(forkRootOf(id)))) { + forkSelfGrades.push({ + attemptId: attempt.id, + problemId: problem.id, + outcomeIndex: index + 1, + author: attempt.by, + observer: obs.by, + }); + } + }); + } + } + + // SIM health + const health = SimStore.inspectHarness(state, paths); + const live = SimStore.allAttempts(state).filter((attempt) => attempt.live); + const open = live.filter((attempt) => attempt.pending.length > 0 || attempt.missed.length > 0); + const missed = live.filter((attempt) => attempt.missed.length > 0); + const problemOf = (attemptId: string) => + SimStore.findAttempt(state, attemptId)?.problem.id ?? "?"; + const newModels = [...freshModels.values()]; + const escalationTelemetry: Array = [ + ...input.telemetry, + ...newModels.map((item) => ({ + ts: new Date(sinceMs).toISOString(), + kind: "new_model_observed" as const, + providerInstanceId: item.providerInstanceId, + model: item.model, + })), + ...edits + .filter((edit) => !edit.record && !edit.recorded && edit.source === "t3") + .map((edit) => ({ + ts: `${edit.date}T00:00:00.000Z`, + kind: "unrecorded_harness_edit" as const, + threadId: edit.session, + files: edit.files, + })), + ]; + const advisorEscalation = SimStore.buildAdvisorEscalation( + state, + input.advisor, + health, + escalationTelemetry, + ); + + const sortedFlagged = flagged.sort( + (a, b) => b.flags.length - a.flags.length || b.date.localeCompare(a.date), + ); + const sortedEdits = edits.sort((a, b) => b.date.localeCompare(a.date)); + const out: Array = []; + const since = new Date(sinceMs).toISOString(); + out.push(`SIM Audit (window: ${input.source}, from ${since.slice(0, 16)}Z)`); + out.push( + `Scope: T3 threads of every provider and model${input.options.includeClaudeLogs === false ? "" : ", plus Claude Code transcripts and gate logs"}.`, + ); + out.push( + `T3 threads scanned: ${threadsScanned}; Claude Code sessions scanned: ${claudeSessionsScanned} (excluded ${excludedSelf} self/audit runs)`, + ); + out.push(""); + out.push("== 1. SIM Health =="); + if (input.broken) out.push(`CRITICAL: journal damaged (${input.broken})`); + out.push( + `Live rules: ${live.length} | With open predictions: ${open.length} | Live rules with misses: ${missed.length} | Drift: ${health.drift.length} | Uncovered: ${health.uncovered.length}`, + ); + for (const item of health.drift) out.push(` DRIFT ${item.attempt.id}: ${item.reason}`); + for (const unit of health.uncovered) + out.push(` NO RECORD ${unit.file}: ${unit.text ? squashText(unit.text, 80) : "hook"}`); + for (const attempt of missed) { + out.push( + ` MISSED ${attempt.id} (${problemOf(attempt.id)}) ${attempt.files[0] ?? ""}, missed: ${attempt.missed.join(", ")}`, + ); + } + for (const item of forkSelfGrades) { + out.push( + ` FORK SELF-GRADE ${item.attemptId} (${item.problemId}) outcome ${item.outcomeIndex}: fixed by ${item.observer} (same fork/side-chat family as ${item.author}; retract or verify from an independent session)`, + ); + } + out.push(""); + out.push("== 2. T3 Runtime Signals =="); + out.push( + `Checkpoint rollbacks: ${rollbacks.size} | Mid-thread model switches: ${switches.size} | Interrupted then steered: ${interrupts.size} | Delegated reviews: ${reviews.size}`, + ); + for (const item of [...rollbacks.values()].slice(0, limit)) + out.push(` ROLLBACK ${item.date} ${item.threadId} -> ${item.checkpointId}`); + for (const item of [...switches.values()].slice(0, limit)) + out.push(` SWITCH ${item.threadId}: ${item.from} -> ${item.to}`); + for (const item of [...interrupts.values()].slice(0, limit)) { + out.push( + ` INTERRUPTED ${item.threadId} [${item.model}]${item.followup ? `, then: "${item.followup}"` : ""}`, + ); + } + for (const item of [...reviews.values()].slice(0, limit)) { + out.push( + ` REVIEW ${item.threadId} [${item.model}] ${squashText(item.title, 80)}${item.excerpt ? `: ${item.excerpt}` : ""}`, + ); + } + out.push(""); + const harnessEdits = sortedEdits.filter((edit) => !edit.record); + const recordEdits = sortedEdits.filter((edit) => edit.record); + out.push(`== 3. Harness Edits (${harnessEdits.length}) ==`); + if (!harnessEdits.length) out.push(" none"); + for (const edit of harnessEdits) { + out.push( + ` ${edit.date} ${edit.source} ${edit.session} [${edit.provider}/${edit.model}] ${edit.recorded ? "recorded" : "UNRECORDED?"}: ${edit.files.join(", ")}`, + ); + } + for (const edit of recordEdits) { + out.push( + ` DIRECT RECORD EDIT ${edit.date} ${edit.source} ${edit.session} [${edit.provider}/${edit.model}]: ${edit.files.join(", ")}`, + ); + } + out.push(""); + out.push( + `== 4. Candidate Correction / Friction Sessions (${flagged.length} total, showing ${Math.min(limit, flagged.length)}) ==`, + ); + if (!flagged.length) out.push(" none"); + for (const session of sortedFlagged.slice(0, limit)) { + const inspect = + session.source === "t3" + ? `inspect thread ${session.session}` + : `sim-audit.mjs --session ${session.session.slice(0, 8)}`; + out.push( + ` ${session.date} ${session.source} ${session.session} [${session.project}, ${session.provider}/${session.model}, ${session.userTurns} user turns] -> ${inspect}`, + ); + for (const flag of session.flags.slice(0, 3)) + out.push(` U${flag.turn} (${flag.kind}): "${flag.excerpt}"`); + } + out.push(""); + out.push(`== 5. Models Not Yet In SIM (${newModels.length}) ==`); + if (!newModels.length) out.push(" none"); + for (const item of newModels) + out.push( + ` ${item.model} (${item.providerInstanceId}): review live rules under it, and carry if it is a new generation`, + ); + if (simGateLog) { + out.push(""); + out.push("== 6. Gate Telemetry (in window) =="); + const counts = Object.entries(simGateLog.counts) + .map(([key, value]) => `${key}=${value}`) + .join(", "); + out.push( + `sim-gate.log: ${simGateLog.present ? `${simGateLog.total} events (${counts || "none"})` : "not present yet"}`, + ); + for (const note of simGateLog.notable.slice(-10)) { + out.push( + ` [${note.time.slice(0, 16)}] ${note.outcome} session=${note.session} ${note.target}`, + ); + } + } + out.push(""); + out.push("== 7. Recently Changed Live Rules With Open Predictions (last 10) =="); + for (const attempt of [...open].sort((a, b) => b.round.localeCompare(a.round)).slice(0, 10)) { + out.push( + ` ${attempt.id} (${problemOf(attempt.id)}, ${attempt.round}) ${attempt.files[0] ?? ""}, open: ${attempt.pending.join(", ") || "none"}`, + ); + } + if (advisorEscalation) { + out.push(""); + out.push("== 8. Advisor Escalation =="); + for (const candidate of advisorEscalation.candidates) + out.push(` ${candidate.kind}: ${candidate.summary}`); + out.push(` ${advisorEscalation.guidance}`); + } + + return { + text: out.join("\n"), + window: { since, source: input.source }, + threadsScanned, + claudeSessionsScanned, + sim: { + journalBroken: input.broken, + driftCount: health.drift.length, + uncoveredCount: health.uncovered.length, + liveRules: live.length, + openPredictions: open.length, + missedLiveRules: missed.length, + }, + signals: { + verbalCorrections: flagged.reduce((sum, session) => sum + session.flags.length, 0), + unrecordedHarnessEdits: harnessEdits.filter((edit) => !edit.recorded).length, + checkpointRollbacks: rollbacks.size, + midThreadModelSwitches: switches.size, + interruptedWithSteer: interrupts.size, + delegatedReviews: reviews.size, + newlyObservedModels: newModels, + }, + ...(advisorEscalation ? { advisorEscalation } : {}), + }; +} + +function renderInspection( + thread: ThreadRow, + runRows: ReadonlyArray, + messages: ReadonlyArray, + items: ReadonlyArray, + events: ReadonlyArray, +): string { + const runs = runRows.map(runInfo); + const entries: Array<{ at: string; order: number; line: string }> = []; + let userTurn = 0; + for (const run of runs) { + entries.push({ + at: run.requestedAt, + order: 0, + line: `run ${run.ordinal} [${run.provider}/${run.model}] ${run.status}`, + }); + } + for (const row of messages) { + const text = parseJson(row.payload_json).text; + if (row.role === "user") { + const own = extractUserText(text); + if (!own) continue; + userTurn += 1; + entries.push({ + at: row.created_at, + order: 1, + line: `U${userTurn} [${row.created_at.slice(0, 19).replace("T", " ")}]: ${squashText(own, 600)}`, + }); + } else { + entries.push({ at: row.created_at, order: 3, line: ` assistant: ${squashText(text, 400)}` }); + } + } + for (const item of items) { + const payload = parseJson(item.payload_json); + const detail = + item.type === "file_change" + ? `file_change(${squashText(payload.fileName, 120)})` + : item.type === "command_execution" + ? `command(${squashText(payload.input, 120)})` + : `${item.type}(${squashText(payload.title ?? payload.toolName ?? "", 80)})`; + entries.push({ at: item.updated_at, order: 2, line: ` tool: ${detail}` }); + } + for (const event of events) { + const payload = parseJson(event.payload_json); + const line = + event.event_type === "checkpoint.rollback-requested" + ? `ROLLBACK requested to ${str(payload.checkpointId) ?? "?"}` + : `MODEL ${event.event_type}: ${str(payload.providerInstanceId) ?? "?"}/${str(record(payload.modelSelection).model) ?? "?"}`; + entries.push({ at: event.occurred_at, order: 4, line }); + } + entries.sort((a, b) => a.at.localeCompare(b.at) || a.order - b.order); + const lines = entries.map((entry) => entry.line); + const models = + [...new Set(runs.map((run) => `${run.provider}/${run.model}`))].join(", ") || + thread.default_provider; + const header = `Thread ${thread.thread_id} | ${thread.title} | models: ${models} | runs: ${runs.length} | user turns: ${userTurn}${runs.some((run) => run.status === "interrupted") ? " | has interrupted runs" : ""}`; + const shown = lines.slice(0, INSPECT_LINES); + return [ + header, + ...shown, + ...(lines.length > shown.length ? [`... (${lines.length - shown.length} more lines)`] : []), + ].join("\n"); +} diff --git a/apps/server/src/sim/SimContracts.ts b/apps/server/src/sim/SimContracts.ts new file mode 100644 index 0000000000000..97900fbdb347a --- /dev/null +++ b/apps/server/src/sim/SimContracts.ts @@ -0,0 +1,747 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import type { + ModelSelection, + ProjectId, + ProviderInstanceId, + RunId, + ServerSettings, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export const SIM_ACTIONS = ["add", "revise", "replace", "remove"] as const; +export type SimAction = (typeof SIM_ACTIONS)[number]; + +export const SIM_DEPENDS = ["model", "environment", "project", "user"] as const; +export type SimDepend = (typeof SIM_DEPENDS)[number]; + +export const SIM_RESULTS = [ + "fixed", + "missed", + "regressed", + "misfired", + "inconclusive", + "kept", +] as const; +export type SimResult = (typeof SIM_RESULTS)[number]; + +export const SIM_SOURCES = ["user", "log", "test", "self"] as const; +export type SimSource = (typeof SIM_SOURCES)[number]; + +export const SIM_LINK_KINDS = ["refines", "refined-by", "related", "conflicts"] as const; +export type SimLinkKind = (typeof SIM_LINK_KINDS)[number]; + +export const SIM_LINK_INVERSE: Readonly> = { + refines: "refined-by", + "refined-by": "refines", + related: "related", + conflicts: "conflicts", +}; + +/** Journal event format version. Stays 2 for full replay compatibility with standalone sim.mjs. */ +export const SIM_FORMAT = 2; +/** sim.json schema version, matching standalone sim.mjs byte-for-byte. */ +export const SIM_SCHEMA = 3; +export const SIM_GENESIS = "genesis"; +export const SIM_UNKNOWN = "unknown"; +export const SIM_TEXT_LIMIT = 1000; +export const SIM_NAME_LIMIT = 300; +export const SIM_DEFAULT_PAGE_CHARS = 20_000; +export const SIM_INDEX_BUDGET = 6_000; +export const SIM_FULL_BUDGET = 40_000; + +export type SimSettingsConfig = ServerSettings["sim"]; + +export interface SimAmendmentRecord { + readonly seq: number; + readonly field: string; + readonly reason: string; + readonly was: unknown; +} + +export interface SimRetractionRecord { + readonly seq: number; + readonly reason: string; +} + +export interface SimRestorationRecord { + readonly seq: number; + readonly reason: string; + readonly retracted_because: string; +} + +export interface SimObservation { + date: string; + result: SimResult; + evidence: string; + source: SimSource; + policy: string; + domain: string; + harness?: string; + sample: string; + by: string; + also?: string; + target?: string; + retracted?: SimRetractionRecord; + restored?: SimRestorationRecord; +} + +export interface SimAttempt { + id: string; + round: string; + sample: string; + by: string; + also?: string; + accepted: boolean; + backfilled: boolean; + action: SimAction; + what: string; + why: string; + files: Array; + anchor: string | null; + supersedes: Array; + depends_on: Array; + predicted: Array; + expect: string | null; + policy: string; + domain: string; + harness?: string; + considered: Array; + observations: Array; + recorded?: { by: string; day: string }; + unanswered?: boolean; + rejected_because?: string; + retracted?: SimRetractionRecord; + restored?: SimRestorationRecord; + amended?: Array; + missed: Array; + fixed: Array; + pending: Array; + passed: number; + total: number; + superseded_by: string | null; + live: boolean; +} + +export interface SimProblemLink { + id: string; + kind: SimLinkKind; +} + +export interface SimProblem { + id: string; + name: string; + opened_round: string; + former_names: Array; + related: Array; + attempts: Array; + amended?: Array; +} + +export interface SimCarrySide { + policy?: string; + domain?: string; + harness?: string; +} + +export interface SimCarryEntry { + date: string; + from: SimCarrySide; + into: SimCarrySide; + note?: string; +} + +export interface SimState { + schema: number; + next_id: number; + next_attempt: number; + events: number; + head: string; + carried_from: Array; + aliases: Record; + problems: Array; +} + +export type SimJournalOp = "attempt" | "observe" | "merge" | "link" | "carry" | "amend" | "retract"; + +/** + * Journal line envelope. `harness` lives on the top-level envelope (never in `data` for + * attempt/observe) so unmodified standalone `sim.mjs` (format v2) replays every T3 event + * cleanly without tripping `unknownFields` on `event.data`. + */ +export interface SimJournalEvent { + readonly seq: number; + readonly ts: string; + readonly day: string; + readonly by: string; + readonly also?: string; + readonly harness?: string; + readonly v: number; + readonly op: SimJournalOp; + readonly data: Record; + readonly prev: string; +} + +export type SimErrorCode = + | "validation" + | "seen_required" + | "journal_broken" + | "forbidden_path" + | "drift" + | "not_found" + | "io" + | "disabled"; + +export class SimServiceError extends Schema.TaggedError()("SimServiceError", { + code: Schema.Literals([ + "validation", + "seen_required", + "journal_broken", + "forbidden_path", + "drift", + "not_found", + "io", + "disabled", + ]), + problems: Schema.Array(Schema.String), +}) { + override get message(): string { + return this.problems.join("\n"); + } +} + +export interface SimResolvedPaths { + readonly homeDir: string; + readonly harnessDir: string; + readonly simDir: string; + readonly backupsDir: string; + readonly journalPath: string; + readonly recordPath: string; + readonly lockPath: string; + readonly seenDir: string; + readonly epochsPath: string; + readonly telemetryPath: string; + readonly auditStatePath: string; +} + +export function expandHomeString(rawPath: string, homeDir: string = NodeOS.homedir()): string { + return String(rawPath ?? "") + .trim() + .replace(/^~(?=\/|$)/, homeDir) + .replace(/^\$(?:HOME|\{HOME\})(?=\/|$)/, homeDir); +} + +export function resolveSimPaths( + settings?: Partial>, + homeDir: string = NodeOS.homedir(), +): SimResolvedPaths { + const configuredSim = settings?.simDir?.trim() ?? ""; + const configuredHarness = settings?.harnessDir?.trim() ?? ""; + const simDir = configuredSim + ? NodePath.resolve(expandHomeString(configuredSim, homeDir)) + : configuredHarness + ? NodePath.join(NodePath.resolve(expandHomeString(configuredHarness, homeDir)), "sim") + : NodePath.join(homeDir, ".claude", "sim"); + const harnessDir = configuredHarness + ? NodePath.resolve(expandHomeString(configuredHarness, homeDir)) + : configuredSim + ? NodePath.dirname(simDir) + : NodePath.join(homeDir, ".claude"); + return { + homeDir, + harnessDir, + simDir, + backupsDir: NodePath.join(harnessDir, "backups", "sim"), + journalPath: NodePath.join(simDir, "sim.jsonl"), + recordPath: NodePath.join(simDir, "sim.json"), + lockPath: NodePath.join(simDir, "sim.lock"), + seenDir: NodePath.join(simDir, "seen"), + epochsPath: NodePath.join(simDir, "t3-epochs.json"), + telemetryPath: NodePath.join(simDir, "telemetry.jsonl"), + auditStatePath: NodePath.join(harnessDir, "state", "sim-audit-state.json"), + }; +} + +/** Store harness paths in one canonical spelling matching standalone sim.mjs. */ +export function canonicalHarnessFile( + file: string, + paths: Pick, +): string { + let value = String(file) + .trim() + .replace(/^\$(?:HOME|\{HOME\})\//, "~/"); + const harnessPrefix = `${paths.harnessDir}/`; + const homePrefix = `${paths.homeDir}/`; + if (value.startsWith(harnessPrefix)) { + return `~/.claude/${value.slice(harnessPrefix.length)}`; + } + if (value.startsWith(homePrefix)) { + value = `~/${value.slice(homePrefix.length)}`; + } + return value; +} + +export function expandHarnessFile( + file: string, + paths: Pick, +): string { + const trimmed = String(file).trim(); + if (trimmed.startsWith("~/.claude/")) { + return NodePath.join(paths.harnessDir, trimmed.slice("~/.claude/".length)); + } + if (trimmed.startsWith("~/")) { + return NodePath.join(paths.homeDir, trimmed.slice(2)); + } + return trimmed; +} + +function canonicalRealPath(rawPath: string, cwd: string | undefined, homeDir: string): string { + const expanded = expandHomeString(rawPath, homeDir); + let current = NodePath.resolve(cwd || "/", expanded); + const tail: Array = []; + while (!NodeFS.existsSync(current)) { + const parent = NodePath.dirname(current); + if (parent === current) break; + tail.unshift(NodePath.basename(current)); + current = parent; + } + try { + current = NodeFS.realpathSync(current); + } catch { + // Keep resolved path when realpath is unavailable. + } + return tail.length ? NodePath.join(current, ...tail) : current; +} + +function isUnderDir(target: string, dir: string): boolean { + const rel = NodePath.relative(dir, target); + return ( + rel !== "" && + !rel.startsWith("..") && + !rel.startsWith(NodePath.sep) && + !NodePath.isAbsolute(rel) + ); +} + +const HARNESS_TOP_FILES = new Set([ + "AGENTS.md", + "CLAUDE.md", + "settings.json", + "settings.local.json", +]); +const HARNESS_DIRS = new Set(["notes", "hooks", "skills", "agents", "commands", "output-styles"]); +const PROJECT_CLAUDE_DIRS = new Set(["hooks", "skills", "agents", "commands", "output-styles"]); +const RECORD_FILES = new Set([ + "sim.json", + "sim.jsonl", + "sim.lock", + "telemetry.jsonl", + "t3-epochs.json", +]); + +export function isPathWithinRoot( + rawPath: string, + rootDir: string, + cwd: string | undefined, + homeDir: string = NodeOS.homedir(), +): boolean { + if (!rawPath.trim() || !rootDir.trim()) return false; + const target = canonicalRealPath(rawPath, cwd, homeDir); + const root = canonicalRealPath(rootDir, "/", homeDir); + return target === root || isUnderDir(target, root); +} + +/** + * Classify a file path as a protected SIM record file ("record"), an agent harness file ("harness"), + * or an ordinary workspace file (null). Matches `sim-gate.mjs` semantics. + */ +export function classifyHarnessPath( + rawPath: string, + paths: Pick, + cwd?: string, + options?: { readonly allowTmp?: boolean }, +): "record" | "harness" | null { + if (!rawPath || !rawPath.trim()) return null; + const target = canonicalRealPath(rawPath, cwd, paths.homeDir); + const harness = canonicalRealPath(paths.harnessDir, "/", paths.homeDir); + const simDir = canonicalRealPath(paths.simDir, "/", paths.homeDir); + + if (target === simDir) return "record"; + if (isUnderDir(target, simDir)) { + const rel = NodePath.relative(simDir, target); + const parts = rel.split(NodePath.sep); + if (parts[0] === "seen" || RECORD_FILES.has(rel)) { + return "record"; + } + if ((rel.endsWith(".mjs") || rel.endsWith(".sh")) && !rel.endsWith(".test.mjs")) { + return "harness"; + } + return null; + } + if (isUnderDir(target, harness)) { + const rel = NodePath.relative(harness, target); + const parts = rel.split(NodePath.sep); + const top = parts[0] ?? ""; + if (top === "backups" || top === "projects" || top === "state") return null; + if (HARNESS_TOP_FILES.has(rel)) return "harness"; + if (HARNESS_DIRS.has(top) && parts.length > 1) return "harness"; + return null; + } + if (options?.allowTmp !== true) { + const tmpDirs = [ + canonicalRealPath(NodeOS.tmpdir(), "/", paths.homeDir), + canonicalRealPath("/tmp", "/", paths.homeDir), + canonicalRealPath("/var/tmp", "/", paths.homeDir), + ]; + if (tmpDirs.some((tmp) => target === tmp || isUnderDir(target, tmp))) return null; + } + const base = NodePath.basename(target); + if (base === "AGENTS.md" || base === "CLAUDE.md") return "harness"; + if ( + (base === "settings.json" || base === "settings.local.json") && + NodePath.basename(NodePath.dirname(target)) === ".claude" + ) { + return "harness"; + } + const segs = target.split(NodePath.sep); + for (let i = 0; i < segs.length - 1; i += 1) { + const next = segs[i + 1]; + if (segs[i] === ".claude" && next !== undefined && PROJECT_CLAUDE_DIRS.has(next)) { + if (i + 2 < segs.length) return "harness"; + } + } + return null; +} + +/** + * Authenticated caller identity derived server-side from McpInvocationContext + ProjectionStore. + * Never populated from caller-supplied tool arguments. + */ +export interface SimCallerContext { + readonly sessionId: string; + readonly alsoSessionId?: string | undefined; + /** True when the caller is in the same fork/side-chat family as an attempt's author. */ + readonly forkFamilySessionIds?: ReadonlyArray | undefined; + readonly threadId?: ThreadId | undefined; + readonly activeRunId?: RunId | undefined; + readonly providerInstanceId?: ProviderInstanceId | undefined; + readonly driver?: string | undefined; + readonly model?: string | undefined; + readonly projectId?: ProjectId | undefined; + readonly projectName?: string | undefined; + readonly workspaceRoot?: string | undefined; + readonly subagent?: boolean | undefined; +} + +export interface SimAdvisorEscalationCandidate { + readonly kind: + | "recurring_failures" + | "cross_harness_conflict" + | "new_model_generation" + | "repeated_drift"; + readonly id?: string | undefined; + readonly summary: string; +} + +export interface SimAdvisorEscalation { + readonly modelSelection: ModelSelection; + readonly candidates: ReadonlyArray; + readonly guidance: string; +} + +export type SimTelemetryEvent = + | { + readonly ts: string; + readonly kind: "unrecorded_harness_edit"; + readonly threadId: string; + readonly runId?: string | undefined; + readonly providerInstanceId?: string | undefined; + readonly model?: string | undefined; + readonly files: ReadonlyArray; + } + | { + readonly ts: string; + readonly kind: "direct_sim_record_edit"; + readonly threadId: string; + readonly runId?: string | undefined; + readonly providerInstanceId?: string | undefined; + readonly model?: string | undefined; + readonly files: ReadonlyArray; + } + | { + readonly ts: string; + readonly kind: "checkpoint_rollback"; + readonly threadId: string; + readonly runId?: string | undefined; + readonly checkpointId?: string | undefined; + readonly providerInstanceId?: string | undefined; + readonly model?: string | undefined; + } + | { + readonly ts: string; + readonly kind: "mid_thread_model_switch"; + readonly threadId: string; + readonly fromProvider?: string | undefined; + readonly fromModel?: string | undefined; + readonly toProvider?: string | undefined; + readonly toModel?: string | undefined; + } + | { + readonly ts: string; + readonly kind: "interrupted_with_steer"; + readonly threadId: string; + readonly interruptedRunId?: string | undefined; + readonly followupRunId?: string | undefined; + readonly providerInstanceId?: string | undefined; + readonly model?: string | undefined; + readonly reason?: string | undefined; + } + | { + readonly ts: string; + readonly kind: "new_model_observed"; + readonly threadId?: string | undefined; + readonly providerInstanceId: string; + readonly model: string; + } + | { + readonly ts: string; + readonly kind: "delegated_review_completed"; + readonly threadId: string; + readonly childThreadId?: string | undefined; + readonly providerInstanceId?: string | undefined; + readonly model?: string | undefined; + readonly title?: string | undefined; + readonly excerpt?: string | undefined; + }; + +export interface SimReadRequest { + readonly action: "index" | "show" | "brief_all" | "find" | "by_file" | "check" | "review"; + readonly ids?: ReadonlyArray | undefined; + readonly brief?: boolean | undefined; + readonly query?: string | undefined; + readonly file?: string | undefined; + readonly policy?: string | undefined; + readonly harness?: string | undefined; + readonly page?: number | undefined; +} + +export interface SimReadResult { + readonly text: string; + readonly failed?: boolean | undefined; + readonly advisorEscalation?: SimAdvisorEscalation | undefined; +} + +export interface SimAttemptInput { + readonly problem?: string | undefined; + readonly new?: string | undefined; + readonly action: SimAction; + readonly what: string; + readonly why: string; + readonly files?: ReadonlyArray | undefined; + readonly anchor?: string | undefined; + readonly supersedes?: ReadonlyArray | undefined; + readonly depends_on?: ReadonlyArray | undefined; + readonly predicted?: ReadonlyArray | undefined; + readonly expect?: string | undefined; + readonly policy?: string | undefined; + readonly domain?: string | undefined; + readonly harness?: string | undefined; + readonly accepted?: boolean | undefined; + readonly rejected_because?: string | undefined; + readonly unanswered?: boolean | undefined; + readonly backfilled?: boolean | undefined; + readonly round?: string | undefined; + readonly sample?: string | undefined; +} + +export interface SimObserveInput { + readonly attempt: string; + readonly target?: string | undefined; + readonly result: SimResult; + readonly evidence: string; + readonly source: SimSource; + readonly policy?: string | undefined; + readonly domain?: string | undefined; + readonly harness?: string | undefined; + readonly date?: string | undefined; + /** Set server-side when the caller shares fork/side-chat lineage with the attempt author. */ + readonly selfGradeReason?: string | undefined; +} + +export type SimWriteRequest = + | { readonly action: "attempt"; readonly input: SimAttemptInput } + | { readonly action: "observe"; readonly input: SimObserveInput } + | { + readonly action: "amend"; + readonly target: string; + readonly field: string; + readonly value: string | ReadonlyArray; + readonly reason: string; + } + | { + readonly action: "retract"; + readonly attempt: string; + readonly outcome?: number | undefined; + readonly reason: string; + readonly undo?: boolean | undefined; + } + | { readonly action: "link"; readonly a: string; readonly kind: SimLinkKind; readonly b: string } + | { readonly action: "merge"; readonly from: string; readonly into: string } + | { + readonly action: "carry"; + readonly fromPolicy?: string | undefined; + readonly toPolicy?: string | undefined; + readonly fromDomain?: string | undefined; + readonly toDomain?: string | undefined; + readonly fromHarness?: string | undefined; + readonly toHarness?: string | undefined; + readonly date?: string | undefined; + readonly note?: string | undefined; + }; + +export interface SimWriteResult { + readonly text: string; + readonly problemId?: string | undefined; + readonly attemptId?: string | undefined; + readonly settled?: boolean | undefined; + readonly unconfirmedReason?: string | undefined; +} + +export interface SimApplyHarnessChangeRequest { + readonly file: string; + readonly oldText?: string | undefined; + readonly newText?: string | undefined; + readonly content?: string | undefined; + readonly append?: boolean | undefined; + readonly dryRun?: boolean | undefined; + readonly attempt: SimAttemptInput; +} + +export interface SimApplyHarnessChangeResult { + readonly dryRun: boolean; + readonly file: string; + readonly text: string; + readonly brief?: string | undefined; + readonly predictionLine?: string | undefined; + readonly diffPreview?: string | undefined; + readonly problemId?: string | undefined; + readonly attemptId?: string | undefined; +} + +export interface SimAuditOptions { + readonly since?: string | undefined; + readonly days?: number | undefined; + readonly limit?: number | undefined; + readonly includeClaudeLogs?: boolean | undefined; +} + +export interface SimAuditReport { + readonly text: string; + readonly window: { readonly since: string; readonly source: string }; + readonly threadsScanned: number; + readonly claudeSessionsScanned: number; + readonly sim: { + readonly journalBroken: string | null; + readonly driftCount: number; + readonly uncoveredCount: number; + readonly liveRules: number; + readonly openPredictions: number; + readonly missedLiveRules: number; + }; + readonly signals: { + readonly verbalCorrections: number; + readonly unrecordedHarnessEdits: number; + readonly checkpointRollbacks: number; + readonly midThreadModelSwitches: number; + readonly interruptedWithSteer: number; + readonly delegatedReviews: number; + readonly newlyObservedModels: ReadonlyArray<{ + readonly providerInstanceId: string; + readonly model: string; + }>; + }; + readonly advisorEscalation?: SimAdvisorEscalation | undefined; +} + +export interface SimThreadInspectionResult { + readonly threadId: string; + readonly text: string; +} + +export interface SimStateSnapshot { + readonly state: SimState; + readonly broken: string | null; + readonly paths: SimResolvedPaths; +} + +export class SimService extends Context.Service< + SimService, + { + readonly read: ( + caller: SimCallerContext, + request: SimReadRequest, + ) => Effect.Effect; + readonly write: ( + caller: SimCallerContext, + request: SimWriteRequest, + ) => Effect.Effect; + readonly applyHarnessChange: ( + caller: SimCallerContext, + request: SimApplyHarnessChangeRequest, + ) => Effect.Effect; + readonly resetThreadSeenEpoch: ( + threadId: ThreadId, + extraSessionIds?: ReadonlyArray, + ) => Effect.Effect; + readonly trackProviderThread: (input: { + readonly threadId: ThreadId; + readonly providerThreadId: string; + readonly extraSessionIds?: ReadonlyArray | undefined; + }) => Effect.Effect; + readonly getThreadSeenEpoch: (threadId: ThreadId) => Effect.Effect; + readonly recordTelemetry: (event: SimTelemetryEvent) => Effect.Effect; + readonly readTelemetry: (sinceMs?: number) => Effect.Effect>; + readonly recordRecentAttemptInTurn: (input: { + readonly threadId: ThreadId; + readonly runId?: RunId | undefined; + readonly workspaceRoot?: string | undefined; + readonly files: ReadonlyArray; + }) => Effect.Effect; + readonly hasRecentAttemptForFile: (input: { + readonly threadId: ThreadId; + readonly runId?: RunId | undefined; + readonly workspaceRoot?: string | undefined; + readonly file: string; + }) => Effect.Effect; + readonly getStateSnapshot: () => Effect.Effect; + readonly getObservedModels: () => Effect.Effect>; + readonly resolvePaths: () => Effect.Effect; + readonly findAttemptAuthorSessions: (attemptId: string) => Effect.Effect>; + } +>()("t3/sim/SimContracts/SimService") {} + +export class SimAuditService extends Context.Service< + SimAuditService, + { + readonly audit: ( + caller: SimCallerContext, + options?: SimAuditOptions, + ) => Effect.Effect; + readonly inspectThread: ( + caller: SimCallerContext, + threadIdPrefix: string, + ) => Effect.Effect; + readonly markAuditDone: ( + caller: SimCallerContext, + ) => Effect.Effect< + { readonly lastAuditAt: string; readonly statePath: string; readonly text: string }, + SimServiceError + >; + } +>()("t3/sim/SimContracts/SimAuditService") {} diff --git a/apps/server/src/sim/SimInstructions.test.ts b/apps/server/src/sim/SimInstructions.test.ts new file mode 100644 index 0000000000000..f5a1809658780 --- /dev/null +++ b/apps/server/src/sim/SimInstructions.test.ts @@ -0,0 +1,418 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { assert, describe, it } from "@effect/vitest"; +import { ProjectId, ServerSettings, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES } from "../provider/CodexDeveloperInstructions.ts"; +import { + resolveSimPaths, + type SimAttempt, + type SimObservation, + type SimService, + type SimSettingsConfig, + type SimState, +} from "./SimContracts.ts"; +import { + SIM_MAX_INJECTED_SECTIONS, + SIM_SECTION_MAX_UTF8_BYTES, + buildSimThreadInstructions, + createSimInstructionCache, + resolveSimThreadInstructions, + type SimThreadInstructionsInput, +} from "./SimInstructions.ts"; + +const DEFAULT_SIM = Schema.decodeSync(ServerSettings)({}).sim; +const GUIDE_HEADING = "## Self-Improvement Memory (SIM)"; +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?> = {}) { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sim-instructions-")); + const homeDir = NodePath.join(root, "home"); + const harnessDir = NodePath.join(homeDir, ".claude"); + NodeFS.mkdirSync(NodePath.join(harnessDir, "sim"), { recursive: true }); + for (const [name, text] of Object.entries(files)) { + const path = NodePath.join(harnessDir, name); + NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true }); + NodeFS.writeFileSync(path, text); + } + const paths = resolveSimPaths({ harnessDir }, homeDir); + return { + paths, + input: ( + overrides: Partial & { + readonly sim?: Partial; + } = {}, + ): SimThreadInstructionsInput => { + const { sim, ...rest } = overrides; + return { + settings: { ...DEFAULT_SIM, ...sim }, + paths, + providerInstanceId: "codex", + driver: "codex", + model: "gpt-test", + ...rest, + }; + }, + [Symbol.dispose]: () => NodeFS.rmSync(root, { recursive: true, force: true }), + }; +} + +function observation(result: SimObservation["result"], policy: string, harness?: string) { + return { + date: "2026-11-01", + result, + evidence: "synthetic", + source: "test", + policy, + domain: "global", + sample: "s", + by: "session", + ...(harness === undefined ? {} : { harness }), + } satisfies SimObservation; +} + +function attempt(id: string, anchor: string, overrides: Partial = {}): SimAttempt { + return { + id, + round: "r1", + sample: "s", + by: "session", + accepted: true, + backfilled: false, + action: "add", + what: "synthetic rule", + why: "synthetic", + files: ["~/.claude/AGENTS.md"], + anchor, + supersedes: [], + depends_on: [], + predicted: [], + expect: null, + policy: "gpt-test", + domain: "global", + considered: [], + observations: [], + missed: [], + fixed: [], + pending: [], + passed: 0, + total: 0, + superseded_by: null, + live: true, + ...overrides, + }; +} + +function simState(attempts: ReadonlyArray): SimState { + return { + schema: 4, + next_id: 2, + next_attempt: attempts.length + 1, + events: attempts.length, + head: "genesis", + carried_from: [], + aliases: {}, + problems: [ + { + id: "P1", + name: "synthetic", + opened_round: "r1", + former_names: [], + related: [], + attempts: [...attempts], + }, + ], + }; +} + +const RULES = `# Agent rules + +## Testing +- Run the focused tests before every push to a branch. + - Name the command you ran in the report. +- Prefer table-driven cases when extending a test file. + +## Database +- Use the staging database for integration checks. + +## Formatting +- Indent shell scripts with two spaces always. +`; + +describe("buildSimThreadInstructions", () => { + it("never injects rule files into Claude Code, which loads them itself", () => { + using fixture = makeFixture({ "AGENTS.md": RULES, "sim/sim.jsonl": "" }); + for (const target of [ + { providerInstanceId: "claudeAgent", driver: "claudeAgent" }, + { providerInstanceId: "claudeAgent", driver: "custom" }, + { providerInstanceId: "work-claude", driver: "claudeAgent" }, + ]) { + assert.deepEqual( + buildSimThreadInstructions( + fixture.input({ ...target, sim: { providerOverrides: { claudeAgent: true } } }), + ), + [], + ); + } + }); + + it("injects the rules and the SIM guide into other harnesses", () => { + using fixture = makeFixture({ "AGENTS.md": RULES }); + for (const driver of ["codex", "antigravity", "opencode"]) { + const sections = buildSimThreadInstructions( + fixture.input({ providerInstanceId: driver, driver }), + ); + assert.lengthOf(sections, 2); + assert.include(sections[0], "# Harness rules from `~/.claude/AGENTS.md`"); + assert.include(sections[0], "- Use the staging database for integration checks."); + assert.include(sections[1], GUIDE_HEADING); + assert.isBelow(Buffer.byteLength(sections[1]!, "utf8"), 1_500); + } + }); + + it("follows the enable switches and provider overrides", () => { + using fixture = makeFixture({ "AGENTS.md": RULES }); + const injected = (input: Parameters[0]) => + buildSimThreadInstructions(fixture.input(input)).length > 0; + assert.isFalse(injected({ sim: { enabled: false } })); + assert.isFalse(injected({ sim: { injectRules: false } })); + assert.isFalse(injected({ sim: { providerOverrides: { codex: false } } })); + assert.isFalse( + injected({ providerInstanceId: "codex-work", sim: { providerOverrides: { codex: false } } }), + ); + assert.isTrue( + injected({ + providerInstanceId: "codex-work", + sim: { providerOverrides: { "codex-work": true, codex: false } }, + }), + ); + }); + + it("is a no-op on a machine without harness files or a SIM journal", () => { + using fixture = makeFixture(); + assert.deepEqual( + buildSimThreadInstructions(fixture.input({ sim: { ruleFiles: ["~/missing.md"] } })), + [], + ); + NodeFS.writeFileSync(fixture.paths.journalPath, ""); + const sections = buildSimThreadInstructions(fixture.input()); + assert.lengthOf(sections, 1); + assert.include(sections[0], GUIDE_HEADING); + }); + + it("reads configured rule files once, however they are spelled", () => { + using fixture = makeFixture({ + "AGENTS.md": "- Main rule from the harness file.\n", + "notes/extra.md": "- Extra rule from a configured file.\n", + }); + const sections = buildSimThreadInstructions( + fixture.input({ + sim: { + ruleFiles: ["~/.claude/notes/extra.md", "notes/extra.md", "~/.claude/AGENTS.md"], + }, + }), + ); + const text = sections.join("\n"); + assert.equal(text.split("Extra rule from a configured file.").length, 2); + assert.equal(text.split("Main rule from the harness file.").length, 2); + assert.include(text, "# Harness rules from `~/.claude/notes/extra.md`"); + }); + + it("drops rules SIM shows misfiring here, scoped elsewhere or removed, and keeps the rest", () => { + using fixture = makeFixture({ "AGENTS.md": RULES }); + const state = simState([ + attempt("A1", "Run the focused tests before every push", { + observations: [observation("misfired", "gpt-test", "codex")], + }), + attempt("A2", "Use the staging database", { domain: "billing" }), + attempt("A3", "Indent shell scripts with two spaces", { action: "remove", live: false }), + ]); + const rules = (input: Partial) => + buildSimThreadInstructions(fixture.input({ simState: state, projectName: "web", ...input })) + .slice(0, -1) + .join("\n"); + + const here = rules({}); + assert.notInclude(here, "Run the focused tests"); + assert.notInclude(here, "Name the command you ran", "a dropped rule takes its sub-bullets"); + assert.include(here, "- Prefer table-driven cases"); + assert.notInclude(here, "staging database"); + assert.notInclude(here, "## Database", "a heading without rules goes too"); + assert.notInclude(here, "Indent shell scripts"); + assert.notInclude(here, "## Formatting"); + + assert.include(rules({ model: "other-model" }), "Run the focused tests"); + assert.include( + rules({ providerInstanceId: "opencode", driver: "opencode" }), + "Run the focused tests", + ); + assert.include(rules({ projectName: "billing" }), "staging database"); + assert.include(rules({ projectName: undefined }), "staging database"); + + // A newer live attempt on the same anchor without a misfire brings the rule back. + const superseded = simState([ + ...state.problems[0]!.attempts, + attempt("A4", "Run the focused tests before every push"), + ]); + assert.include(rules({ simState: superseded }), "Run the focused tests"); + + // An accepted remove attempt stores anchor: null and identifies the dropped rule via supersedes. + const removedState = simState([ + attempt("A1", "Run the focused tests before every push", { + live: false, + superseded_by: "A2", + }), + { + ...attempt("A2", "", { + action: "remove", + live: false, + supersedes: ["A1"], + policy: "gpt-test", + depends_on: ["model"], + }), + anchor: null, + }, + ]); + assert.notInclude( + rules({ simState: removedState, model: "gpt-test" }), + "Run the focused tests", + ); + assert.include(rules({ simState: removedState, model: "gpt-other" }), "Run the focused tests"); + }); + + it("keeps every section under Codex's byte limit with multi-byte text", () => { + const bullets = Array.from( + { length: 400 }, + (_, index) => + `- Regel ${index}: Prüfe Änderungen gründlich, bevor du pushst 🚀🧪 — größer, schöner.`, + ); + const longLine = `- ${"Über🦀".repeat(800)}`; + assert.isAbove(Buffer.byteLength(longLine, "utf8"), 6_000); + using fixture = makeFixture({ + "AGENTS.md": `# Regeln\n\n${longLine}\n\n## Viele Regeln\n${bullets.join("\n")}\n`, + "notes/late.md": "- A late rule that cannot fit.\n", + }); + const sections = buildSimThreadInstructions( + fixture.input({ sim: { ruleFiles: ["~/.claude/notes/late.md"] } }), + ); + assert.lengthOf(sections, SIM_MAX_INJECTED_SECTIONS); + for (const section of sections) { + assert.isAtMost(Buffer.byteLength(section, "utf8"), SIM_SECTION_MAX_UTF8_BYTES); + assert.isAtMost(Buffer.byteLength(section, "utf8"), CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES); + assert.notMatch(section, LONE_SURROGATE); + } + assert.isTrue(sections[0]!.endsWith("… (use sim_read for full details)")); + for (const section of sections.slice(1, -1)) { + assert.include( + section, + "# Harness rules from `~/.claude/AGENTS.md` (continued)\n\n# Regeln\n\n## Viele Regeln\n- Regel", + "a continued section repeats its heading chain", + ); + } + const guide = sections.at(-1)!; + assert.include(guide, GUIDE_HEADING); + assert.include(guide, "`~/.claude/AGENTS.md`, `~/.claude/notes/late.md` for the rest"); + }); + + it("offers the advisor only when one is configured", () => { + using fixture = makeFixture({ "AGENTS.md": RULES }); + const guide = (sim: Partial) => + buildSimThreadInstructions(fixture.input({ sim })).at(-1)!; + assert.include(guide({}), 'role: "design"'); + assert.include( + guide({}), + 'target: { providerInstanceId: "claudeAgent", model: "claude-fable-5-2" }', + ); + assert.notInclude(guide({ advisorModelSelection: null }), "delegate_task` (`role"); + }); +}); + +describe("createSimInstructionCache", () => { + it("freezes a thread's sections within a context epoch and refreshes on the next", () => { + using fixture = makeFixture({ "AGENTS.md": RULES }); + const misfiring = attempt("A1", "Run the focused tests before every push"); + const state = simState([misfiring]); + const cache = createSimInstructionCache(); + const input = fixture.input({ threadId: ThreadId.make("thread-sim"), simState: state }); + + const first = cache.resolve({ ...input, contextEpoch: 1 }); + assert.include(first.join("\n"), "Run the focused tests"); + misfiring.observations.push(observation("misfired", "gpt-test")); + assert.strictEqual(cache.resolve({ ...input, contextEpoch: 1 }), first); + + assert.notInclude( + cache.resolve({ ...input, contextEpoch: 2 }).join("\n"), + "Run the focused tests", + ); + assert.deepEqual( + cache.resolve({ + ...input, + contextEpoch: 1, + settings: { ...input.settings, injectRules: false }, + }), + [], + ); + }); + + it.effect( + "resolveSimThreadInstructions skips getStateSnapshot on Claude turns and on cached Codex turns", + () => + Effect.gen(function* () { + using fixture = makeFixture({ "AGENTS.md": RULES }); + let snapshotReads = 0; + const simService = { + getThreadSeenEpoch: () => Effect.succeed(1), + getStateSnapshot: () => + Effect.sync(() => { + snapshotReads += 1; + return { state: simState([]), broken: null, paths: fixture.paths }; + }), + resolvePaths: () => Effect.succeed(fixture.paths), + } as unknown as SimService["Service"]; + const cache = createSimInstructionCache(); + const base = { + cache, + simService: Option.some(simService), + projectStore: Option.none(), + settings: DEFAULT_SIM, + threadId: ThreadId.make("thread-fast-path"), + projectId: ProjectId.make("project-1"), + }; + + // Claude turn never touches SIM state at all. + const claude = yield* resolveSimThreadInstructions({ + ...base, + providerInstanceId: "claudeAgent", + driver: "claudeAgent", + model: "claude-opus-5-5", + }); + assert.deepEqual(claude, []); + assert.strictEqual(snapshotReads, 0); + + // Codex turn 1 loads once; turn 2 hits cache and does not replay sim.jsonl. + const first = yield* resolveSimThreadInstructions({ + ...base, + providerInstanceId: "codex", + driver: "codex", + model: "gpt-test", + }); + assert.isAbove(first.length, 0); + assert.strictEqual(snapshotReads, 1); + + const second = yield* resolveSimThreadInstructions({ + ...base, + providerInstanceId: "codex", + driver: "codex", + model: "gpt-test", + }); + assert.strictEqual(second, first); + assert.strictEqual(snapshotReads, 1); + }), + ); +}); diff --git a/apps/server/src/sim/SimInstructions.ts b/apps/server/src/sim/SimInstructions.ts new file mode 100644 index 0000000000000..b9836f48bfede --- /dev/null +++ b/apps/server/src/sim/SimInstructions.ts @@ -0,0 +1,626 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import type { ProjectId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { + canonicalHarnessFile, + classifyHarnessPath, + expandHarnessFile, + expandHomeString, + type SimAttempt, + type SimResolvedPaths, + type SimService, + type SimSettingsConfig, + type SimState, +} from "./SimContracts.ts"; + +/** Margin below Codex's 4,000-byte per-entry truncation (`CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES`). */ +export const SIM_SECTION_MAX_UTF8_BYTES = 3_800; +export const SIM_MAX_INJECTED_SECTIONS = 6; +const SIM_INSTRUCTION_CACHE_MAX_ENTRIES = 512; + +// Claude Code loads ~/.claude/AGENTS.md itself; injecting it again would double every rule. +const CLAUDE_DRIVER = "claudeAgent"; +const TRUNCATION_POINTER = "… (use sim_read for full details)"; +// Shorter anchors match too many unrelated lines to drop a rule on. +const MIN_ANCHOR_LENGTH = 8; + +export interface SimInjectionTarget { + readonly settings: SimSettingsConfig; + readonly providerInstanceId: string; + readonly driver: string; +} + +export interface SimThreadInstructionsInput extends SimInjectionTarget { + readonly paths: SimResolvedPaths; + readonly threadId?: ThreadId | undefined; + readonly contextEpoch?: number | undefined; + readonly model: string; + readonly projectName?: string | undefined; + readonly simState?: SimState | null | undefined; +} + +function resolveSimInjectionEnabled(input: SimInjectionTarget): boolean { + const { settings } = input; + if (!settings.enabled || !settings.injectRules) return false; + if (input.driver === CLAUDE_DRIVER || input.providerInstanceId === CLAUDE_DRIVER) return false; + return ( + settings.providerOverrides[input.providerInstanceId] ?? + settings.providerOverrides[input.driver] ?? + true + ); +} + +const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8"); + +/** Cuts at a code point boundary, so a surrogate pair is never split. */ +function truncateUtf8(text: string, maxBytes: number): string { + if (utf8Bytes(text) <= maxBytes) return text; + const budget = maxBytes - utf8Bytes(TRUNCATION_POINTER); + let used = 0; + let head = ""; + for (const char of text) { + const size = utf8Bytes(char); + if (used + size > budget) break; + used += size; + head += char; + } + return `${head.trimEnd()}${TRUNCATION_POINTER}`; +} + +const normalizeText = (text: string) => text.replace(/\s+/g, " ").trim(); +const sameName = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase(); + +// ── Rule file parsing ──────────────────────────────────────────────── + +interface HeadingBlock { + readonly kind: "heading"; + readonly level: number; + readonly text: string; +} + +interface RuleBlock { + readonly kind: "rule"; + readonly indent: number; + readonly bullet: boolean; + readonly gapBefore: boolean; + readonly lines: Array; +} + +type Block = HeadingBlock | RuleBlock; + +const HEADING = /^(#{1,6})\s+\S/; +const BULLET = /^(\s*)(?:[-*+]|\d+[.)])\s+/; +const FENCE = /^\s*(`{3,}|~{3,})/; +const indentOf = (line: string) => line.length - line.trimStart().length; + +/** Splits markdown into headings and rules: a bullet or paragraph with its continuation lines. */ +function parseRuleFile(text: string): Array { + const blocks: Array = []; + let current: RuleBlock | undefined; + let lastBullet: RuleBlock | undefined; + let fence: string | undefined; + let gap = false; + for (const line of text.replace(/\r\n?/g, "\n").split("\n")) { + if (fence !== undefined && current !== undefined) { + current.lines.push(line); + if (line.trimStart().startsWith(fence)) fence = undefined; + continue; + } + if (line.trim() === "") { + gap = true; + current = undefined; + continue; + } + const heading = HEADING.exec(line); + if (heading) { + blocks.push({ kind: "heading", level: heading[1]!.length, text: line.trim() }); + current = undefined; + lastBullet = undefined; + gap = false; + continue; + } + const bullet = BULLET.exec(line); + const fenceOpen = FENCE.exec(line)?.[1]; + if (bullet) { + current = { + kind: "rule", + indent: bullet[1]!.length, + bullet: true, + gapBefore: gap, + lines: [line], + }; + blocks.push(current); + lastBullet = current; + } else if (current !== undefined) { + current.lines.push(line); + } else if (lastBullet !== undefined && indentOf(line) > lastBullet.indent) { + lastBullet.lines.push("", line); + current = lastBullet; + } else { + current = { kind: "rule", indent: 0, bullet: false, gapBefore: gap, lines: [line] }; + blocks.push(current); + lastBullet = undefined; + } + if (fenceOpen !== undefined) fence = fenceOpen.slice(0, 3); + gap = false; + } + return blocks; +} + +// ── SIM-driven filtering ───────────────────────────────────────────── + +interface AttemptRef { + readonly attempt: SimAttempt; + readonly order: number; + readonly anchor: string; +} + +function attemptOrder(id: string, fallback: number): number { + const parsed = Number.parseInt(id.replace(/^\D+/, ""), 10); + return Number.isFinite(parsed) ? parsed : fallback; +} + +function indexAttemptsByFile( + simState: SimState | null | undefined, + paths: SimResolvedPaths, +): Map> { + const byFile = new Map>(); + const byId = new Map< + string, + { readonly anchor: string; readonly files: ReadonlyArray } + >(); + for (const problem of simState?.problems ?? []) { + for (const attempt of problem.attempts) { + const anchor = normalizeText(attempt.anchor ?? ""); + if (anchor.length >= MIN_ANCHOR_LENGTH) { + byId.set(attempt.id, { + anchor, + files: attempt.files.map((f) => canonicalHarnessFile(f, paths)), + }); + } + } + } + let fallback = 0; + for (const problem of simState?.problems ?? []) { + for (const attempt of problem.attempts) { + fallback += 1; + const order = attemptOrder(attempt.id, fallback); + const ownAnchor = normalizeText(attempt.anchor ?? ""); + const anchors = new Set(); + const files = new Set(attempt.files.map((f) => canonicalHarnessFile(f, paths))); + if (ownAnchor.length >= MIN_ANCHOR_LENGTH) anchors.add(ownAnchor); + if (attempt.action === "remove") { + // Removal attempts store anchor: null; resolve the removed rule's anchor via supersedes. + for (const supersededId of attempt.supersedes) { + const target = byId.get(supersededId); + if (!target) continue; + anchors.add(target.anchor); + for (const file of target.files) files.add(file); + } + } + for (const anchor of anchors) { + const ref = { attempt, order, anchor }; + for (const file of files) { + const refs = byFile.get(file) ?? []; + refs.push(ref); + byFile.set(file, refs); + } + } + } + } + return byFile; +} + +interface RuleContext { + readonly providerInstanceId: string; + readonly driver: string; + readonly model: string; + readonly projectName?: string | undefined; +} + +const harnessApplies = (harness: string | undefined, context: RuleContext) => + harness === undefined || + sameName(harness, context.driver) || + sameName(harness, context.providerInstanceId); + +const domainApplies = (domain: string, context: RuleContext) => + context.projectName === undefined || + sameName(domain, "global") || + sameName(domain, "unknown") || + sameName(domain, context.projectName); + +/** The latest standing outcome under this model and harness decides; a later fix clears a misfire. */ +function misfiredHere(attempt: SimAttempt, context: RuleContext): boolean { + const latest = attempt.observations + .filter( + (obs) => + obs.retracted === undefined && + sameName(obs.policy, context.model) && + harnessApplies(obs.harness, context), + ) + .at(-1); + return latest?.result === "misfired"; +} + +function removedHere(attempt: SimAttempt, context: RuleContext): boolean { + return ( + attempt.action === "remove" && + attempt.accepted && + attempt.retracted === undefined && + harnessApplies(attempt.harness, context) && + domainApplies(attempt.domain, context) && + (!attempt.depends_on.includes("model") || sameName(attempt.policy, context.model)) + ); +} + +/** Rules without a SIM entry always stay: SIM may only narrow what the user wrote. */ +function keepRule(text: string, refs: ReadonlyArray, context: RuleContext): boolean { + const normalized = normalizeText(text); + const matches = refs.filter((ref) => normalized.includes(ref.anchor)); + if (matches.length === 0) return true; + const live = matches.filter((ref) => ref.attempt.live); + if (live.length > 0) { + const inDomain = live.filter((ref) => domainApplies(ref.attempt.domain, context)); + const newest = inDomain.reduce( + (best, ref) => (best === undefined || ref.order > best.order ? ref : best), + undefined, + ); + return newest !== undefined && !misfiredHere(newest.attempt, context); + } + return !matches.some((ref) => removedHere(ref.attempt, context)); +} + +function filterBlocks( + blocks: ReadonlyArray, + refs: ReadonlyArray, + context: RuleContext, +): Array { + const kept: Array = []; + let droppedIndent: number | undefined; + for (const block of blocks) { + if (block.kind === "heading") { + droppedIndent = undefined; + kept.push(block); + continue; + } + if (droppedIndent !== undefined && block.bullet && block.indent > droppedIndent) continue; + droppedIndent = undefined; + if (keepRule(block.lines.join("\n"), refs, context)) { + kept.push(block); + } else if (block.bullet) { + droppedIndent = block.indent; + } + } + return kept.filter((block, index) => { + if (block.kind !== "heading") return true; + for (const next of kept.slice(index + 1)) { + if (next.kind === "rule") return true; + if (next.level <= block.level) return false; + } + return false; + }); +} + +// ── Packing into Codex-sized sections ──────────────────────────────── + +interface RuleFile { + readonly label: string; + readonly blocks: ReadonlyArray; +} + +const RULES_INTRO = + "These are the user's own harness rules. T3 Code injects them because this harness does not load them itself; follow them like your own instructions."; + +function packRuleSections( + files: ReadonlyArray, + maxSections: number, +): { readonly sections: Array; readonly omitted: Array } { + const sections: Array = []; + const omitted: Array = []; + let body: Array = []; + let bytes = 0; + let full = false; + let endsWithHeading = false; + let hasRules = false; + + const flush = () => { + // A trailing heading's rules moved on; continued sections repeat it in their heading chain. + if (endsWithHeading) body.pop(); + if (hasRules) sections.push(body.join("")); + body = []; + bytes = 0; + endsWithHeading = false; + hasRules = false; + }; + const append = (text: string) => { + body.push(text); + bytes += utf8Bytes(text); + }; + const remaining = () => SIM_SECTION_MAX_UTF8_BYTES - bytes; + + for (const file of files) { + if (full) { + omitted.push(file.label); + continue; + } + const fileHeader = `# Harness rules from \`${file.label}\``; + const headings: Array = []; + const startSection = (continued: boolean) => { + flush(); + append(continued ? `${fileHeader} (continued)` : fileHeader); + if (sections.length === 0) append(`\n\n${RULES_INTRO}`); + const chain = headings.map((heading) => heading.text).join("\n\n"); + if (continued && chain && utf8Bytes(chain) < SIM_SECTION_MAX_UTF8_BYTES / 4) { + append(`\n\n${chain}`); + } + }; + if (body.length === 0 || utf8Bytes(`\n\n${fileHeader}`) + 200 > remaining()) { + if (sections.length + (body.length > 0 ? 1 : 0) >= maxSections) { + omitted.push(file.label); + full = true; + continue; + } + startSection(false); + } else { + append(`\n\n${fileHeader}`); + endsWithHeading = true; + } + for (const block of file.blocks) { + const text = block.kind === "heading" ? block.text : block.lines.join("\n"); + const separator = block.kind === "heading" || block.gapBefore ? "\n\n" : "\n"; + if (block.kind === "heading") { + while (headings.length > 0 && headings.at(-1)!.level >= block.level) headings.pop(); + } + const size = utf8Bytes(separator + text); + // A rule too long for any section is cut down where it is, not moved. + const truncatedAnyway = size > SIM_SECTION_MAX_UTF8_BYTES / 2; + if ( + size > remaining() && + (!truncatedAnyway || remaining() < SIM_SECTION_MAX_UTF8_BYTES / 4) + ) { + if (sections.length + 1 >= maxSections) { + omitted.push(file.label); + full = true; + break; + } + startSection(true); + } + append(separator + truncateUtf8(text, remaining() - utf8Bytes(separator))); + endsWithHeading = block.kind === "heading"; + if (block.kind === "heading") headings.push(block); + else hasRules = true; + } + } + flush(); + return { sections, omitted }; +} + +// ── SIM tool guide ─────────────────────────────────────────────────── + +function simGuideSection(settings: SimSettingsConfig, omitted: ReadonlyArray): string { + const advisor = settings.advisorModelSelection; + const lines = [ + "## Self-Improvement Memory (SIM)", + "", + "SIM records every change to the agent harness across providers and models. Use its T3 tools `sim_read`, `sim_write` and `sim_apply_harness_change`.", + "- Before you edit a harness file (`AGENTS.md`, `CLAUDE.md`, harness notes or hooks), call `sim_read`: `index` or `by_file` first, then `show` on the relevant P-ids, or `brief_all` before you open a new root cause.", + "- Make the edit with `sim_apply_harness_change`, which edits and records in one step (live edits require full-access/default mode; pass `dryRun: true` in narrower modes or when the user must approve first). Never edit `sim.json`, `sim.jsonl` or `sim.lock` directly.", + "- Never grade your own change `fixed` from this thread. A later session or an independent `delegate_task` grader records the outcome with `sim_write` (`observe`).", + ...(advisor === null + ? [] + : [ + `- Only for a truly tricky harness case (recurring failed attempts, a rule conflict across models or harnesses, an architectural cleanup), you may ask for a second opinion with \`delegate_task\` (\`role: "design"\`, \`target: { providerInstanceId: "${advisor.instanceId}", model: "${advisor.model}" }\`); never for routine edits.`, + ]), + ...(omitted.length === 0 + ? [] + : [ + `- Not every harness rule fit here. Read ${omitted.map((file) => `\`${file}\``).join(", ")} for the rest.`, + ]), + ]; + return truncateUtf8(lines.join("\n"), SIM_SECTION_MAX_UTF8_BYTES); +} + +// ── Entry points ───────────────────────────────────────────────────── + +function isFile(path: string): boolean { + try { + return NodeFS.statSync(path).isFile(); + } catch { + return false; + } +} + +function resolveRuleFilePaths(settings: SimSettingsConfig, paths: SimResolvedPaths): Array { + const candidates = [ + NodePath.join(paths.harnessDir, "AGENTS.md"), + ...settings.ruleFiles.map((file) => + NodePath.resolve( + paths.harnessDir, + expandHomeString(expandHarnessFile(file, paths), paths.homeDir), + ), + ), + ]; + const seen = new Set(); + const resolved: Array = []; + for (const candidate of candidates) { + if (!isFile(candidate) || classifyHarnessPath(candidate, paths) === "record") continue; + let real = candidate; + try { + real = NodeFS.realpathSync(candidate); + } catch { + // Keep the resolved path. + } + if (seen.has(real)) continue; + seen.add(real); + resolved.push(candidate); + } + return resolved; +} + +function readRuleFile(path: string): string | undefined { + try { + return NodeFS.readFileSync(path, "utf8"); + } catch { + return undefined; + } +} + +/** Every returned section stays at or under `SIM_SECTION_MAX_UTF8_BYTES` UTF-8 bytes. */ +export function buildSimThreadInstructions( + input: SimThreadInstructionsInput, +): ReadonlyArray { + if (!resolveSimInjectionEnabled(input)) return []; + const { paths, settings } = input; + const ruleFilePaths = resolveRuleFilePaths(settings, paths); + if (ruleFilePaths.length === 0 && !isFile(paths.journalPath)) return []; + + const attemptsByFile = indexAttemptsByFile(input.simState, paths); + const files: Array = []; + for (const path of ruleFilePaths) { + const text = readRuleFile(path); + if (text === undefined) continue; + const label = canonicalHarnessFile(path, paths); + const blocks = filterBlocks(parseRuleFile(text), attemptsByFile.get(label) ?? [], input); + if (blocks.length > 0) files.push({ label, blocks }); + } + const { sections, omitted } = packRuleSections(files, SIM_MAX_INJECTED_SECTIONS - 1); + return [...sections, simGuideSection(settings, omitted)]; +} + +function simInstructionCacheKey(input: { + readonly threadId?: ThreadId | undefined; + readonly contextEpoch?: number | undefined; + readonly providerInstanceId: string; + readonly driver: string; + readonly model: string; + readonly projectName?: string | undefined; +}): string { + return [ + input.threadId, + input.contextEpoch ?? 0, + input.providerInstanceId, + input.driver, + input.model, + input.projectName ?? "", + ].join(":"); +} + +export interface SimInstructionCache { + /** Same `(thread, epoch, provider, model, project)` returns the first snapshot, keeping prompt caches warm. */ + readonly resolve: (input: SimThreadInstructionsInput) => ReadonlyArray; + readonly get: (key: string) => ReadonlyArray | undefined; + readonly set: (key: string, value: ReadonlyArray) => void; +} + +export function createSimInstructionCache( + maxEntries: number = SIM_INSTRUCTION_CACHE_MAX_ENTRIES, +): SimInstructionCache { + const entries = new Map>(); + const get = (key: string): ReadonlyArray | undefined => { + const cached = entries.get(key); + if (cached !== undefined) { + entries.delete(key); + entries.set(key, cached); + } + return cached; + }; + const set = (key: string, value: ReadonlyArray): void => { + entries.delete(key); + entries.set(key, value); + if (entries.size > maxEntries) { + const oldest = entries.keys().next(); + if (!oldest.done) entries.delete(oldest.value); + } + }; + return { + get, + set, + resolve: (input) => { + // Checked outside the snapshot so turning injection off applies on the next turn. + if (!resolveSimInjectionEnabled(input)) return []; + if (input.threadId === undefined) return buildSimThreadInstructions(input); + const key = simInstructionCacheKey(input); + const cached = get(key); + if (cached !== undefined) return cached; + const built = buildSimThreadInstructions(input); + set(key, built); + return built; + }, + }; +} + +/** + * Resolve SIM thread instructions for a turn. Checks eligibility and cache before touching the + * journal so disabled threads, Claude turns, and cached turns never replay `sim.jsonl`. + */ +export const resolveSimThreadInstructions = (input: { + readonly cache: SimInstructionCache; + readonly simService: Option.Option; + readonly projectStore: Option.Option; + readonly settings: SimSettingsConfig; + readonly threadId: ThreadId; + readonly projectId: ProjectId; + readonly providerInstanceId: string; + readonly driver: string; + readonly model: string; +}): Effect.Effect> => { + if (Option.isNone(input.simService)) return Effect.succeed([]); + if ( + !resolveSimInjectionEnabled({ + settings: input.settings, + providerInstanceId: input.providerInstanceId, + driver: input.driver, + }) + ) { + return Effect.succeed([]); + } + const sim = input.simService.value; + return Effect.gen(function* () { + const epoch = yield* sim.getThreadSeenEpoch(input.threadId); + const project = Option.isNone(input.projectStore) + ? undefined + : Option.getOrUndefined( + yield* input.projectStore.value + .getShell(input.projectId) + .pipe(Effect.orElseSucceed(() => Option.none())), + ); + const projectName = project?.title; + const key = simInstructionCacheKey({ + threadId: input.threadId, + contextEpoch: epoch, + providerInstanceId: input.providerInstanceId, + driver: input.driver, + model: input.model, + projectName, + }); + const cached = input.cache.get(key); + if (cached !== undefined) return cached; + const snapshot = yield* sim.getStateSnapshot(); + const paths = snapshot?.paths ?? (yield* sim.resolvePaths()); + const built = buildSimThreadInstructions({ + settings: input.settings, + paths, + threadId: input.threadId, + contextEpoch: epoch, + providerInstanceId: input.providerInstanceId, + driver: input.driver, + model: input.model, + projectName, + simState: snapshot?.state ?? null, + }); + input.cache.set(key, built); + return built; + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to build SIM thread instructions.", { cause }).pipe( + Effect.as([] as ReadonlyArray), + ), + ), + ); +}; diff --git a/apps/server/src/sim/SimIntegration.test.ts b/apps/server/src/sim/SimIntegration.test.ts new file mode 100644 index 0000000000000..ef364274ce70a --- /dev/null +++ b/apps/server/src/sim/SimIntegration.test.ts @@ -0,0 +1,776 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, expect, it } from "@effect/vitest"; +import { + EnvironmentId, + MessageId, + NodeId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderSessionId, + ProviderThreadId, + RunAttemptId, + RunId, + ThreadId, + type OrchestrationV2ProviderThread, + type OrchestrationV2Run, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; +import { McpSchema, McpServer } from "effect/ai"; + +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts"; +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; +import * as CheckpointService from "../orchestration-v2/CheckpointService.ts"; +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ProviderEventIngestor from "../orchestration-v2/ProviderEventIngestor.ts"; +import * as RunExecutionService from "../orchestration-v2/RunExecutionService.ts"; +import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as TurnItemPositionStore from "../orchestration-v2/TurnItemPositionStore.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts"; +import { CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES } from "../provider/CodexDeveloperInstructions.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as SimAuditService from "./SimAuditService.ts"; +import { SimService } from "./SimContracts.ts"; +import * as SimServiceImpl from "./SimService.ts"; +import * as SimStore from "./SimStore.ts"; + +const environmentId = EnvironmentId.make("environment:sim-integration"); +const projectId = ProjectId.make("project:sim-integration"); + +const mcpClient = McpSchema.McpServerClient.of({ + clientId: 1, + clientCapabilities: {}, + clientInfo: { name: "sim-integration-test", version: "1.0.0" }, + protocolVersion: "2025-06-18", + initializePayload: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "sim-integration-test", version: "1.0.0" }, + }, + getClient: Effect.die("unused"), +}); + +function makeSandbox() { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sim-integration-")); + const harnessDir = NodePath.join(root, "harness"); + const simDir = NodePath.join(harnessDir, "sim"); + NodeFS.mkdirSync(simDir, { recursive: true }); + const agentsPath = NodePath.join(harnessDir, "AGENTS.md"); + NodeFS.writeFileSync( + agentsPath, + "# Harness\n\n## Rules\n- Always verify focused tests before pushing.\n", + "utf8", + ); + return { + root, + harnessDir, + simDir, + agentsPath, + [Symbol.dispose]() { + NodeFS.rmSync(root, { recursive: true, force: true }); + }, + }; +} + +function threadScope( + threadId: ThreadId, + providerInstanceId: ProviderInstanceId, + subagent = false, +): McpInvocationContext.McpInvocationScope { + return { + environmentId, + requestNamespace: `provider:${threadId}`, + thread: { + threadId, + providerSessionId: `provider-session:${threadId}`, + providerInstanceId, + subagent, + }, + client: undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 1, + }; +} + +const parseToolJson = (result: McpSchema.CallToolResult): Record => { + const first = result.content[0]; + if (first?.type !== "text") { + throw new Error(`Expected text MCP tool content, got ${JSON.stringify(result)}`); + } + return JSON.parse(first.text) as Record; +}; + +describe("SIM cross-harness end-to-end integration", () => { + it.effect( + "enforces read-before-write, atomic apply, epoch reset, and cross-thread grading through real McpServer + SimService", + () => + Effect.gen(function* () { + using sandbox = makeSandbox(); + const authorThread = ThreadId.make("thread:author-codex"); + const forkThread = ThreadId.make("thread:fork-child"); + const delegateThread = ThreadId.make("thread:delegated-grader"); + const codexProvider = ProviderInstanceId.make("codex"); + const claudeProvider = ProviderInstanceId.make("claudeAgent"); + + const shells = new Map([ + [ + authorThread, + { + ...liveThreadShell(authorThread), + providerInstanceId: codexProvider, + projectId, + modelSelection: { instanceId: codexProvider, model: "gpt-6.2-sol" }, + }, + ], + [ + forkThread, + { + ...liveThreadShell(forkThread), + providerInstanceId: codexProvider, + projectId, + modelSelection: { instanceId: codexProvider, model: "gpt-6.2-sol" }, + lineage: { + parentThreadId: authorThread, + relationshipToParent: "fork", + rootThreadId: authorThread, + }, + }, + ], + [ + delegateThread, + { + ...liveThreadShell(delegateThread), + providerInstanceId: claudeProvider, + projectId, + modelSelection: { instanceId: claudeProvider, model: "claude-opus-5-5" }, + lineage: { + parentThreadId: authorThread, + relationshipToParent: "subagent", + rootThreadId: authorThread, + }, + }, + ], + ]); + + const providerThreadRecords = new Map< + ThreadId, + ReadonlyArray + >([ + [ + authorThread, + [ + { + id: ProviderThreadId.make("pt:author"), + driver: ProviderDriverKind.make("codex"), + nativeThreadRef: null, + } as unknown as OrchestrationV2ProviderThread, + ], + ], + [ + delegateThread, + [ + { + id: ProviderThreadId.make("pt:delegate"), + driver: ProviderDriverKind.make("claudeAgent"), + nativeThreadRef: { + driver: ProviderDriverKind.make("claudeAgent"), + nativeId: "claude-native-grader-1", + strength: "strong", + }, + } as unknown as OrchestrationV2ProviderThread, + ], + ], + ]); + + const baseDeps = Layer.mergeAll( + SqlitePersistence.layerMemory, + ServerSettings.layerTest({ + sim: { + enabled: true, + simDir: sandbox.simDir, + harnessDir: sandbox.harnessDir, + injectRules: true, + }, + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(shells.get(id) ?? null), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords: (id) => + Effect.succeed({ + thread: shells.get(id)!, + runs: [ + { + id: RunId.make(`run:${id}`), + providerThreadId: + id === authorThread + ? ProviderThreadId.make("pt:author") + : id === delegateThread + ? ProviderThreadId.make("pt:delegate") + : null, + modelSelection: shells.get(id)!.modelSelection, + } as unknown as OrchestrationV2Run, + ], + providerThreads: providerThreadRecords.get(id) ?? [], + } as never), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + getShell: () => + Effect.succeedSome({ + id: projectId, + title: "t3code-fork", + workspaceRoot: sandbox.root, + } as never), + }), + NodeServices.layer, + NodeCrypto.layer, + ); + + const simLayer = SimServiceImpl.layer.pipe(Layer.provideMerge(baseDeps)); + const auditLayer = SimAuditService.layer.pipe(Layer.provideMerge(simLayer)); + const mcpLayer = McpHttpServer.layerSimToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(auditLayer), + ); + + yield* Effect.gen(function* () { + const mcp = yield* McpServer.McpServer; + const sim = yield* SimService; + + const call = ( + scope: McpInvocationContext.McpInvocationScope, + name: string, + args: Record, + ) => + mcp + .callTool({ name, arguments: args }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, mcpClient), + ); + + const author = threadScope(authorThread, codexProvider); + const fork = threadScope(forkThread, codexProvider); + const grader = threadScope(delegateThread, claudeProvider, true); + + // 1. Direct edits to SIM record files are always blocked. + const blockedRecord = yield* call(author, "sim_apply_harness_change", { + file: NodePath.join(sandbox.simDir, "sim.jsonl"), + append: true, + content: "{}\n", + attempt: { + new: "Agents skip tests before pushing code", + action: "add", + what: "Tamper journal", + why: "Should be rejected", + anchor: "Tamper journal", + depends_on: ["model"], + predicted: ["skipped-tests"], + expect: "Rejected", + }, + }); + expect(blockedRecord.isError).toBe(true); + expect(parseToolJson(blockedRecord).code).toBe("capability_denied"); + + // 2. Consulting index is required before dry-run or live apply. + const beforeText = NodeFS.readFileSync(sandbox.agentsPath, "utf8"); + const unindexed = yield* call(author, "sim_apply_harness_change", { + file: "~/.claude/AGENTS.md", + oldText: "- Always verify focused tests before pushing.", + newText: + "- Always verify focused tests before pushing.\n- Quote the exact test command output in the final report.", + dryRun: true, + attempt: { + new: "Agents report tests passed without showing command output", + action: "add", + what: "Add rule requiring exact test command output in reports", + why: "Unverified test claims hid broken assertions", + anchor: "Quote the exact test command output", + depends_on: ["model"], + predicted: ["unverified-test-claim"], + expect: "Fixed when reports include command output; missed if claimed without output", + }, + }); + expect(unindexed.isError).toBe(true); + expect(parseToolJson(unindexed).code).toBe("invalid_request"); + + const indexed = yield* call(author, "sim_read", { action: "index" }); + expect(indexed.isError).toBe(false); + + const dryRun = yield* call(author, "sim_apply_harness_change", { + file: "~/.claude/AGENTS.md", + oldText: "- Always verify focused tests before pushing.", + newText: + "- Always verify focused tests before pushing.\n- Quote the exact test command output in the final report.", + dryRun: true, + attempt: { + new: "Agents report tests passed without showing command output", + action: "add", + what: "Add rule requiring exact test command output in reports", + why: "Unverified test claims hid broken assertions", + anchor: "Quote the exact test command output", + depends_on: ["model"], + predicted: ["unverified-test-claim"], + expect: "Fixed when reports include command output; missed if claimed without output", + }, + }); + expect(dryRun.isError).toBe(false); + expect(NodeFS.readFileSync(sandbox.agentsPath, "utf8")).toBe(beforeText); + + // 3. Live apply writes file and records attempt atomically with derived model/harness. + const applied = yield* call(author, "sim_apply_harness_change", { + file: "~/.claude/AGENTS.md", + oldText: "- Always verify focused tests before pushing.", + newText: + "- Always verify focused tests before pushing.\n- Quote the exact test command output in the final report.", + attempt: { + new: "Agents report tests passed without showing command output", + action: "add", + what: "Add rule requiring exact test command output in reports", + why: "Unverified test claims hid broken assertions", + anchor: "Quote the exact test command output", + depends_on: ["model"], + predicted: ["unverified-test-claim"], + expect: "Fixed when reports include command output; missed if claimed without output", + }, + }); + expect(applied.isError).toBe(false); + const appliedData = parseToolJson(applied); + expect(appliedData.problemId).toBe("P1"); + expect(appliedData.attemptId).toBe("A1"); + expect(NodeFS.readFileSync(sandbox.agentsPath, "utf8")).toContain( + "Quote the exact test command output", + ); + + // 4. Verify envelope-only harness & no harness key inside event.data. + const journalLine = NodeFS.readFileSync( + NodePath.join(sandbox.simDir, "sim.jsonl"), + "utf8", + ).trim(); + const parsedEvent = JSON.parse(journalLine) as { + harness?: string; + data: Record; + }; + expect(parsedEvent.harness).toBe("codex"); + expect(parsedEvent.data.policy).toBe("gpt-6.2-sol"); + expect("harness" in parsedEvent.data).toBe(false); + + // 5. Add a second problem and reset context epoch; show P1 alone without index/by_file is rejected. + yield* call(author, "sim_read", { action: "brief_all" }); + yield* call(author, "sim_read", { action: "show", ids: ["P1"] }); + const second = yield* call(author, "sim_apply_harness_change", { + file: "~/.claude/AGENTS.md", + append: true, + content: "- Never force push shared branches.\n", + attempt: { + new: "Agents force push shared branches without asking first", + action: "add", + what: "Forbid force pushing shared branches", + why: "Force push overwrote teammate work", + anchor: "Never force push shared branches.", + depends_on: ["user"], + predicted: ["force-push-loss"], + expect: "No force pushes", + }, + }); + expect(second.isError).toBe(false); + + yield* sim.resetThreadSeenEpoch(authorThread); + const blockedAfterCompaction = yield* call(author, "sim_write", { + action: "attempt", + problem: "P1", + changeAction: "revise", + what: "Tighten output quoting rule", + why: "Still missed on long runs", + files: ["~/.claude/AGENTS.md"], + anchor: "Quote the exact test command output", + supersedes: ["A1"], + depends_on: ["model"], + predicted: ["unverified-test-claim"], + expect: "Fixed when every run quotes output", + }); + expect(blockedAfterCompaction.isError).toBe(true); + expect(String(parseToolJson(blockedAfterCompaction).message)).toContain("P1"); + + // Reading only show P1 without index/by_file is still rejected when P2 exists. + yield* call(author, "sim_read", { action: "show", ids: ["P1"] }); + const blockedWithoutIndex = yield* call(author, "sim_write", { + action: "attempt", + problem: "P1", + changeAction: "revise", + what: "Tighten output quoting rule", + why: "Still missed on long runs", + files: ["~/.claude/AGENTS.md"], + anchor: "Quote the exact test command output", + supersedes: ["A1"], + depends_on: ["model"], + predicted: ["unverified-test-claim"], + expect: "Fixed when every run quotes output", + }); + expect(blockedWithoutIndex.isError).toBe(true); + expect(String(parseToolJson(blockedWithoutIndex).message)).toMatch(/index.*by_file/); + + // 6. Strict no-self-grading: author thread & fork child both stay unconfirmed; + // independent delegate_task child settles the prediction! + const selfGrade = yield* call(author, "sim_write", { + action: "observe", + attempt: "A1", + target: "unverified-test-claim", + result: "fixed", + evidence: "Author claimed it worked in the same session", + source: "test", + }); + expect(selfGrade.isError).toBe(false); + expect(parseToolJson(selfGrade).settled).toBe(false); + + const forkGrade = yield* call(fork, "sim_write", { + action: "observe", + attempt: "A1", + target: "unverified-test-claim", + result: "fixed", + evidence: "Forked thread checked the same session output", + source: "test", + }); + expect(forkGrade.isError).toBe(false); + expect(parseToolJson(forkGrade).settled).toBe(false); + + const independentGrade = yield* call(grader, "sim_write", { + action: "observe", + attempt: "A1", + target: "unverified-test-claim", + result: "fixed", + evidence: "Independent delegate grader verified exact test output in fresh run", + source: "test", + }); + expect(independentGrade.isError).toBe(false); + expect(parseToolJson(independentGrade).settled).toBe(true); + }).pipe(Effect.provide(mcpLayer)); + }), + ); + + it.effect( + "delivers filtered <4KB SIM instructions to Codex via RunExecutionService without double-injecting into Claude", + () => + Effect.gen(function* () { + using sandbox = makeSandbox(); + const runTurn = (providerId: string, driver: string, model: string, threadId: ThreadId) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const runExecution = yield* RunExecutionService.RunExecutionServiceV2; + const now = DateTime.nowUnsafe(); + const providerInstanceId = ProviderInstanceId.make(providerId); + const runId = RunId.make(`run:${threadId}`); + const attemptId = RunAttemptId.make(`attempt:${threadId}`); + const rootNodeId = NodeId.make(`node:${threadId}`); + const providerThreadId = ProviderThreadId.make(`pt:${threadId}`); + + const providerSessionId = ProviderSessionId.make(`ps:${threadId}`); + yield* runExecution.startRootRun({ + commandId: `cmd:${threadId}` as never, + providerSessionId, + attemptId, + appThread: { + id: threadId, + projectId, + title: "SIM test", + defaultProvider: providerInstanceId, + runtimeMode: "full-access", + interactionMode: "default", + modelSelection: { instanceId: providerInstanceId, model }, + activeProviderThreadId: providerThreadId, + latestRunId: runId, + activeRunId: runId, + branch: null, + worktreePath: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + } as never, + run: { + id: runId, + threadId, + ordinal: 1, + providerInstanceId, + providerThreadId, + status: "running", + userMessageId: MessageId.make(`msg:${threadId}`), + modelSelection: { instanceId: providerInstanceId, model }, + requestedAt: now, + startedAt: now, + completedAt: null, + } as never, + attempt: { + id: attemptId, + threadId, + runId, + ordinal: 1, + rootNodeId, + providerInstanceId, + providerThreadId, + providerTurnId: null, + status: "running", + } as never, + rootNode: { + id: rootNodeId, + threadId, + runId, + rootNodeId, + parentNodeId: null, + kind: "root", + status: "running", + providerThreadId, + providerTurnId: null, + } as never, + checkpointScope: { + id: `scope:${threadId}` as never, + threadId, + runId, + nodeId: rootNodeId, + parentScopeId: null, + providerThreadId, + kind: "root", + cwd: sandbox.root, + ordinalWithinParent: 0, + advancesAppRunCount: true, + createdAt: now, + } as never, + providerThread: { + id: providerThreadId, + threadId, + providerInstanceId, + driver: ProviderDriverKind.make(driver), + providerSessionId: ProviderSessionId.make(`ps:${threadId}`), + status: "ready", + nativeThreadRef: null, + } as never, + providerTurnOrdinal: 1, + session: { + driver: ProviderDriverKind.make(driver), + events: Stream.never, + startTurn: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => + Deferred.succeed(started, input).pipe(Effect.asVoid), + } as never, + message: { + messageId: MessageId.make(`msg:${threadId}`), + text: "Hello", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + modelSelection: { instanceId: providerInstanceId, model }, + runtimePolicy: { + runtimeMode: "full-access", + interactionMode: "default", + cwd: sandbox.root, + }, + }); + return yield* Deferred.await(started); + }); + + const settingsLayer = ServerSettings.layerTest({ + sim: { + enabled: true, + simDir: sandbox.simDir, + harnessDir: sandbox.harnessDir, + injectRules: true, + }, + }); + const simLayer = SimServiceImpl.layer.pipe(Layer.provideMerge(settingsLayer)); + const turnPositionsLayer = Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({ + allocate: () => Effect.succeed(0), + normalize: (item) => Effect.succeed(item), + }); + const layerTest = RunExecutionService.layer.pipe( + Layer.provide( + Layer.mergeAll( + McpAppModelContext.layerEmpty, + PreviewAgentActivity.layer, + Layer.mock(CheckpointService.CheckpointServiceV2)({ + captureBaseline: () => Effect.void, + }), + turnPositionsLayer, + Layer.mock(EventSink.EventSinkV2)({ + write: () => Effect.succeed({ committed: true, storedEvents: [] } as never), + writeIfRunCurrent: () => + Effect.succeed({ committed: true, storedEvents: [] } as never), + }), + IdAllocator.layer, + ThreadCommandExecutor.layer, + Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({ + ingestNormalized: () => Effect.succeed([]), + }), + simLayer, + ), + ), + ); + + const codexTurn = yield* runTurn( + "codex", + "codex", + "gpt-6.2-sol", + ThreadId.make("thread:run-exec-codex"), + ).pipe(Effect.provide(layerTest)); + assert.isDefined(codexTurn.threadInstructions); + assert.isAbove(codexTurn.threadInstructions!.length, 0); + assert.include( + codexTurn.threadInstructions!.join("\n\n"), + "Always verify focused tests before pushing.", + ); + assert.include( + codexTurn.threadInstructions!.join("\n\n"), + "## Self-Improvement Memory (SIM)", + ); + for (const section of codexTurn.threadInstructions!) { + assert.isAtMost( + Buffer.byteLength(section, "utf8"), + CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES, + ); + } + + const claudeTurn = yield* runTurn( + "claudeAgent", + "claudeAgent", + "claude-opus-5-5", + ThreadId.make("thread:run-exec-claude"), + ).pipe(Effect.provide(layerTest)); + assert.isUndefined(claudeTurn.threadInstructions); + }), + ); + + it.effect( + "preserves format-v2 journal and schema-3 sim.json compatibility across mixed CLI and T3 writes", + () => + Effect.gen(function* () { + using sandbox = makeSandbox(); + const simLayer = SimServiceImpl.layer.pipe( + Layer.provide( + ServerSettings.layerTest({ + sim: { enabled: true, simDir: sandbox.simDir, harnessDir: sandbox.harnessDir }, + }), + ), + ); + + // Seed a synthetic format-v2 CLI journal line (without top-level harness, matching standalone sim.mjs). + const cliEvent = { + seq: 1, + ts: "2026-11-10T10:00:00.000Z", + day: "2026-11-10", + by: "cc:cli-session-1", + v: 2, + op: "attempt", + data: { + new: "Agents push changes without running focused tests first", + action: "add", + what: "Require focused test run before push", + why: "Unverified pushes broke the branch", + files: ["~/.claude/AGENTS.md"], + anchor: "verify focused tests before pushing", + depends_on: ["model"], + predicted: ["untested-push"], + expect: "Fixed when every push includes test results", + policy: "claude-opus-5-5", + domain: "global", + considered: [], + }, + prev: "genesis", + }; + NodeFS.writeFileSync( + NodePath.join(sandbox.simDir, "sim.jsonl"), + `${JSON.stringify(cliEvent)}\n`, + "utf8", + ); + + yield* Effect.gen(function* () { + const sim = yield* SimService; + const snapshot = yield* sim.getStateSnapshot(); + assert.isNotNull(snapshot); + assert.isNull(snapshot!.broken); + expect(snapshot!.state.events).toBe(1); + // Read-only snapshot never creates or rewrites sim.json. + expect(NodeFS.existsSync(NodePath.join(sandbox.simDir, "sim.json"))).toBe(false); + + // Append a cross-harness observation from Codex (envelope harness: "codex"). + const observed = yield* sim.write( + { + sessionId: "t3:compat-codex-thread", + providerInstanceId: ProviderInstanceId.make("codex"), + driver: "codex", + model: "gpt-6.2-sol", + }, + { + action: "observe", + input: { + attempt: "A1", + target: "untested-push", + result: "fixed", + evidence: "Codex thread ran focused tests before pushing", + source: "test", + policy: "gpt-6.2-sol", + domain: "global", + harness: "codex", + }, + }, + ); + expect(observed.settled).toBe(true); + + // Verify journal envelope & schema-3 sim.json (no harness key on disk). + const lines = NodeFS.readFileSync(NodePath.join(sandbox.simDir, "sim.jsonl"), "utf8") + .trim() + .split("\n"); + expect(lines).toHaveLength(2); + const secondEvent = JSON.parse(lines[1]!) as { + prev: string; + harness?: string; + data: { observation: Record }; + }; + expect(secondEvent.prev).toBe(SimStore.sha(lines[0]!)); + expect(secondEvent.harness).toBe("codex"); + expect("harness" in secondEvent.data.observation).toBe(false); + + const onDisk = JSON.parse( + NodeFS.readFileSync(NodePath.join(sandbox.simDir, "sim.json"), "utf8"), + ) as { + schema: number; + events: number; + problems: Array<{ + attempts: Array<{ + harness?: string; + fixed: Array; + observations: Array>; + }>; + }>; + }; + expect(onDisk.schema).toBe(3); + expect(onDisk.events).toBe(2); + expect(onDisk.problems[0]!.attempts[0]!.fixed).toEqual(["untested-push"]); + expect("harness" in onDisk.problems[0]!.attempts[0]!).toBe(false); + expect("harness" in onDisk.problems[0]!.attempts[0]!.observations[0]!).toBe(false); + }).pipe(Effect.provide(simLayer)); + }), + ); +}); diff --git a/apps/server/src/sim/SimObserverReactor.test.ts b/apps/server/src/sim/SimObserverReactor.test.ts new file mode 100644 index 0000000000000..cb43091794fb6 --- /dev/null +++ b/apps/server/src/sim/SimObserverReactor.test.ts @@ -0,0 +1,535 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { + ProjectId, + RunId, + ThreadId, + type OrchestrationProjectShell, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + type OrchestrationV2RunStatus, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { USER_STOP_REASON } from "../orchestration-v2/RunExecutionService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { + type SimState, + SimService, + type SimTelemetryEvent, + canonicalHarnessFile, + resolveSimPaths, +} from "./SimContracts.ts"; +import * as SimObserverReactor from "./SimObserverReactor.ts"; + +const THREAD_ID = ThreadId.make("thread-sim"); +const RUN_ID = RunId.make("run-1"); +const OCCURRED_AT = "2026-11-19T12:00:00.000Z"; +const ROOT = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "sim-observer-")); +const HARNESS_DIR = NodePath.join(ROOT, "harness"); +const SIM_DIR = NodePath.join(HARNESS_DIR, "sim"); +const KNOWN_MODEL = "codex:gpt-5"; + +const localDay = (iso: string) => + DateTime.formatIsoDate(DateTime.setZone(DateTime.makeUnsafe(iso), DateTime.zoneMakeLocal())); + +type Call = + | { readonly kind: "reset"; readonly threadId: string; readonly sessions: ReadonlyArray } + | { + readonly kind: "track"; + readonly threadId: string; + readonly providerThreadId: string; + readonly sessions: ReadonlyArray; + } + | { + readonly kind: "hasRecent"; + readonly file: string; + readonly workspaceRoot: string | undefined; + } + | { readonly kind: "telemetry"; readonly event: SimTelemetryEvent } + | { readonly kind: "read" }; + +interface SetupOptions { + readonly enabled?: boolean; + readonly runs?: ReadonlyArray; + readonly activeProviderThreadId?: string; + readonly worktreePath?: string | null; + readonly projectWorkspaceRoot?: string; + readonly hasRecentAttempt?: boolean; + readonly state?: Partial; +} + +const setup = Effect.fnUntraced(function* (options: SetupOptions = {}) { + const calls: Array = []; + const projection = { activeProviderThreadId: options.activeProviderThreadId ?? null }; + const read = (value: A) => Effect.sync(() => (calls.push({ kind: "read" }), value)); + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({}), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + findThread: () => + read({ + id: THREAD_ID, + projectId: ProjectId.make("project-sim"), + worktreePath: options.worktreePath ?? null, + activeProviderThreadId: projection.activeProviderThreadId, + } as never), + getThreadRecords: () => + read({ thread: { id: THREAD_ID }, runs: options.runs ?? [] } as never), + }), + ...(options.projectWorkspaceRoot === undefined + ? [] + : [ + Layer.mock(ProjectStoreV2)({ + getShell: () => + Effect.succeedSome({ + title: "Sim Repo", + workspaceRoot: options.projectWorkspaceRoot!, + } as OrchestrationProjectShell), + }), + ]), + Layer.mock(SimService)({ + resetThreadSeenEpoch: (threadId, sessions) => + Effect.sync(() => { + calls.push({ kind: "reset", threadId, sessions: sessions ?? [] }); + return calls.length; + }), + trackProviderThread: ({ threadId, providerThreadId, extraSessionIds }) => + Effect.sync(() => { + calls.push({ + kind: "track", + threadId, + providerThreadId, + sessions: extraSessionIds ?? [], + }); + return true; + }), + recordTelemetry: (event) => Effect.sync(() => void calls.push({ kind: "telemetry", event })), + hasRecentAttemptForFile: ({ file, workspaceRoot }) => + Effect.sync(() => { + calls.push({ kind: "hasRecent", file, workspaceRoot }); + return options.hasRecentAttempt ?? false; + }), + getStateSnapshot: () => + read( + options.state + ? ({ state: { problems: [], ...options.state }, broken: null } as never) + : null, + ), + getObservedModels: () => read(new Set([KNOWN_MODEL])), + }), + ServerSettings.layerTest({ + sim: { enabled: options.enabled ?? true, simDir: SIM_DIR, harnessDir: HARNESS_DIR }, + }), + ); + const reactor = yield* SimObserverReactor.SimObserverReactor.pipe( + Effect.provide(SimObserverReactor.layer.pipe(Layer.provide(dependencies))), + ); + const telemetry = () => calls.flatMap((call) => (call.kind === "telemetry" ? [call.event] : [])); + const resets = () => calls.filter((call) => call.kind === "reset"); + const tracks = () => calls.filter((call) => call.kind === "track"); + return { reactor, calls, telemetry, resets, tracks, projection }; +}); + +const event = (type: string, payload: object, extra: object = {}) => + ({ + id: `event-${type}`, + type, + threadId: THREAD_ID, + occurredAt: DateTime.makeUnsafe(OCCURRED_AT), + payload, + ...extra, + }) as unknown as OrchestrationV2DomainEvent; + +const turnItem = (id: string, fields: object) => + event( + "turn-item.updated", + { id, threadId: THREAD_ID, runId: RUN_ID, status: "completed", ...fields }, + { runId: RUN_ID }, + ); + +const fileChange = (id: string, fileName: string) => + turnItem(id, { type: "file_change", fileName }); +const command = (id: string, input: string) => turnItem(id, { type: "command_execution", input }); + +function makeRun( + id: string, + status: OrchestrationV2RunStatus, + options: { + readonly ordinal?: number; + readonly instanceId?: string; + readonly model?: string; + } = {}, +) { + return { + id: RunId.make(id), + threadId: THREAD_ID, + ordinal: options.ordinal ?? 1, + providerInstanceId: options.instanceId ?? "codex", + modelSelection: { instanceId: options.instanceId ?? "codex", model: options.model ?? "gpt-5" }, + requestedAt: DateTime.makeUnsafe(OCCURRED_AT), + status, + } as unknown as OrchestrationV2Run; +} + +const runEvent = (type: "run.created" | "run.updated", run: OrchestrationV2Run) => + event(type, run, { runId: run.id }); + +const selectionEvent = (instanceId: string, model: string) => + event("thread.model-selection-updated", { + id: THREAD_ID, + providerInstanceId: instanceId, + modelSelection: { instanceId, model }, + }); + +const providerThread = (id: string, nativeId: string) => + event("provider-thread.updated", { + id, + driver: "claudeAgent", + appThreadId: THREAD_ID, + nativeThreadRef: { driver: "claudeAgent", nativeId, strength: "strong" }, + status: "active", + }); + +describe("SimObserverReactor", () => { + it.effect( + "resets the seen epoch once per completed compaction, handoff, and context switch", + () => + Effect.gen(function* () { + const { reactor, resets } = yield* setup({ activeProviderThreadId: "pt-2" }); + const compaction = turnItem("item-compact", { type: "compaction", driver: "codex" }); + const handoff = event("context-handoff.updated", { id: "handoff-1", status: "ready" }); + for (const repeated of [compaction, compaction, handoff, handoff]) { + yield* reactor.handle(repeated); + } + assert.strictEqual(resets().length, 2); + + const switching = yield* setup({ activeProviderThreadId: "pt-1" }); + yield* switching.reactor.handle(providerThread("pt-1", "native-a")); + assert.deepStrictEqual(switching.tracks(), [ + { + kind: "track", + threadId: THREAD_ID, + providerThreadId: "pt-1", + sessions: ["cc:native-a"], + }, + ]); + // A native subagent's provider thread is not the thread's context. + yield* switching.reactor.handle(providerThread("pt-sub", "native-sub")); + assert.strictEqual(switching.tracks().length, 1); + }), + ); + + it.effect("tracks active provider thread changes with both Claude sessions (restart-safe)", () => + Effect.gen(function* () { + const { reactor, tracks, projection } = yield* setup({ activeProviderThreadId: "pt-1" }); + yield* reactor.handle(providerThread("pt-1", "native-a")); + projection.activeProviderThreadId = "pt-2"; + yield* reactor.handle(providerThread("pt-2", "native-b")); + yield* reactor.handle(providerThread("pt-2", "native-b")); + assert.deepStrictEqual(tracks(), [ + { + kind: "track", + threadId: THREAD_ID, + providerThreadId: "pt-1", + sessions: ["cc:native-a"], + }, + { + kind: "track", + threadId: THREAD_ID, + providerThreadId: "pt-2", + sessions: ["cc:native-a", "cc:native-b"], + }, + ]); + }), + ); + + it.effect( + "resolves relative workspace harness edits against project workspaceRoot when no worktree is set", + () => + Effect.gen(function* () { + const workspace = NodePath.join(ROOT, "project-repo"); + const { reactor, calls, telemetry } = yield* setup({ + worktreePath: null, + projectWorkspaceRoot: workspace, + }); + yield* reactor.handle(command("item-rel", "sed -i 's/old/new/' AGENTS.md")); + yield* reactor.handle(runEvent("run.updated", makeRun(RUN_ID, "completed"))); + const expectedFile = canonicalHarnessFile( + NodePath.join(workspace, "AGENTS.md"), + resolveSimPaths({ simDir: SIM_DIR, harnessDir: HARNESS_DIR }), + ); + assert.deepStrictEqual( + calls.filter((call) => call.kind === "hasRecent"), + [{ kind: "hasRecent", file: expectedFile, workspaceRoot: workspace }], + ); + assert.deepStrictEqual(telemetry(), [ + { + ts: OCCURRED_AT, + kind: "unrecorded_harness_edit", + threadId: THREAD_ID, + runId: RUN_ID, + providerInstanceId: "codex", + model: "gpt-5", + files: [expectedFile], + }, + ]); + }), + ); + + it.effect.each([ + { name: "unrecorded edit is reported", options: {}, reported: true }, + { + name: "suppressed by a recent attempt in the turn", + options: { hasRecentAttempt: true }, + reported: false, + }, + { + name: "suppressed by a same-day attempt from this thread", + options: { + state: { + problems: [ + { + attempts: [ + { + by: `t3:${THREAD_ID}`, + round: localDay(OCCURRED_AT), + files: ["~/.claude/AGENTS.md"], + }, + ], + }, + ], + } as never, + }, + reported: false, + }, + ])("harness file_change at run end: $name", ({ options, reported }) => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(options); + yield* reactor.handle(fileChange("item-edit", NodePath.join(HARNESS_DIR, "AGENTS.md"))); + yield* reactor.handle(command("item-ws", "echo hi > ./notes.txt")); + assert.deepStrictEqual(telemetry(), [], "nothing is reported before the run ends"); + yield* reactor.handle(runEvent("run.updated", makeRun(RUN_ID, "completed"))); + assert.deepStrictEqual( + telemetry(), + reported + ? [ + { + ts: OCCURRED_AT, + kind: "unrecorded_harness_edit", + threadId: THREAD_ID, + runId: RUN_ID, + providerInstanceId: "codex", + model: "gpt-5", + files: ["~/.claude/AGENTS.md"], + }, + ] + : [], + ); + }), + ); + + it.effect( + "reports direct SIM record edits immediately and ignores sim.mjs and heredoc bodies", + () => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(); + const journal = NodePath.join(SIM_DIR, "sim.jsonl"); + yield* reactor.handle(command("item-sim", `node ${SIM_DIR}/sim.mjs attempt --what x`)); + yield* reactor.handle( + command("item-heredoc", `cat > /dev/null <<'EOF'\necho x >> ${journal}\nEOF`), + ); + assert.deepStrictEqual(telemetry(), []); + + yield* reactor.handle(fileChange("item-journal", journal)); + yield* reactor.handle(command("item-bash", `echo '{}' >> "${journal}" && ls`)); + yield* reactor.handle(command("item-bash", `echo '{}' >> "${journal}"`)); + assert.deepStrictEqual( + telemetry().map((entry) => [entry.kind, "files" in entry ? entry.files : []]), + [ + ["direct_sim_record_edit", ["~/.claude/sim/sim.jsonl"]], + ["direct_sim_record_edit", ["~/.claude/sim/sim.jsonl"]], + ], + ); + }), + ); + + it.effect("reports checkpoint rollbacks", () => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(); + yield* reactor.handle(runEvent("run.created", makeRun(RUN_ID, "running"))); + yield* reactor.handle( + event( + "checkpoint.rollback-requested", + { scopeId: "scope", checkpointId: "cp-1" }, + { runId: RUN_ID }, + ), + ); + assert.deepStrictEqual(telemetry(), [ + { + ts: OCCURRED_AT, + kind: "checkpoint_rollback", + threadId: THREAD_ID, + runId: RUN_ID, + checkpointId: "cp-1", + providerInstanceId: "codex", + model: "gpt-5", + }, + ]); + }), + ); + + it.effect.each([ + { name: "before the first turn", runs: [], switched: false }, + { name: "after a turn", runs: [makeRun(RUN_ID, "completed")], switched: true }, + ])("model selection change $name", ({ runs, switched }) => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup({ runs }); + yield* reactor.handle( + event("thread.created", { + id: THREAD_ID, + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5" }, + }), + ); + yield* reactor.handle(selectionEvent("claudeAgent", "claude-opus-5-5")); + yield* reactor.handle(selectionEvent("claudeAgent", "claude-opus-5-5")); + assert.deepStrictEqual( + telemetry(), + switched + ? [ + { + ts: OCCURRED_AT, + kind: "mid_thread_model_switch", + threadId: THREAD_ID, + fromProvider: "codex", + fromModel: "gpt-5", + toProvider: "claudeAgent", + toModel: "claude-opus-5-5", + }, + ] + : [], + ); + }), + ); + + it.effect.each([ + { name: "a person's stop", reason: USER_STOP_REASON, steered: true }, + { name: "an unknown stop", reason: undefined, steered: true }, + { name: "an agent's stop", reason: "Stopped by the orchestrator", steered: false }, + ])("interrupted run followed by a new run after $name", ({ reason, steered }) => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(); + if (reason !== undefined) { + yield* reactor.handle( + turnItem("item-stop", { + type: "run_interrupt_request", + message: reason, + status: "running", + }), + ); + } + yield* reactor.handle(runEvent("run.updated", makeRun(RUN_ID, "interrupted"))); + yield* reactor.handle(runEvent("run.created", makeRun("run-2", "queued", { ordinal: 2 }))); + yield* reactor.handle(runEvent("run.created", makeRun("run-3", "queued", { ordinal: 3 }))); + assert.deepStrictEqual( + telemetry(), + steered + ? [ + { + ts: OCCURRED_AT, + kind: "interrupted_with_steer", + threadId: THREAD_ID, + interruptedRunId: RUN_ID, + followupRunId: "run-2", + providerInstanceId: "codex", + model: "gpt-5", + reason, + }, + ] + : [], + ); + }), + ); + + it.effect("reports a newly observed model once", () => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(); + const newModel = { instanceId: "antigravity", model: "gemini-4-argon" }; + yield* reactor.handle(runEvent("run.updated", makeRun(RUN_ID, "running"))); + yield* reactor.handle(runEvent("run.updated", makeRun("run-2", "running", newModel))); + yield* reactor.handle(runEvent("run.updated", makeRun("run-2", "completed", newModel))); + assert.deepStrictEqual(telemetry(), [ + { + ts: OCCURRED_AT, + kind: "new_model_observed", + threadId: THREAD_ID, + providerInstanceId: "antigravity", + model: "gemini-4-argon", + }, + ]); + }), + ); + + it.effect("reports completed review subagents with a bounded excerpt", () => + Effect.gen(function* () { + const { reactor, telemetry } = yield* setup(); + const subagent = (id: string, title: string, result: string) => + event("subagent.updated", { + id, + status: "completed", + title, + prompt: "Look at the change.", + result, + childThreadId: "child-1", + providerInstanceId: "claudeAgent", + model: "claude-fable-5-2", + }); + const verdict = `Verdict: ship it. ${"x".repeat(400)}`; + yield* reactor.handle(subagent("task-impl", "Implement the parser", "Done.")); + yield* reactor.handle(subagent("task-review", "Check the parser diff", verdict)); + yield* reactor.handle(subagent("task-review", "Check the parser diff", verdict)); + const reports = telemetry(); + assert.strictEqual(reports.length, 1); + const [review] = reports; + assert.strictEqual(review?.kind, "delegated_review_completed"); + if (review?.kind !== "delegated_review_completed") return; + assert.strictEqual(review.title, "Check the parser diff"); + assert.strictEqual(review.childThreadId, "child-1"); + assert.strictEqual(review.model, "claude-fable-5-2"); + assert.strictEqual(review.excerpt?.length, 300); + }), + ); + + it.effect("does nothing while SIM is disabled", () => + Effect.gen(function* () { + const { reactor, calls } = yield* setup({ + enabled: false, + runs: [makeRun(RUN_ID, "completed")], + activeProviderThreadId: "pt-1", + }); + for (const disabled of [ + turnItem("item-compact", { type: "compaction", driver: "codex" }), + event("context-handoff.updated", { id: "handoff-1", status: "ready" }), + providerThread("pt-1", "native-a"), + fileChange("item-journal", NodePath.join(SIM_DIR, "sim.jsonl")), + fileChange("item-edit", NodePath.join(HARNESS_DIR, "AGENTS.md")), + event("checkpoint.rollback-requested", { scopeId: "s", checkpointId: "cp" }), + selectionEvent("claudeAgent", "claude-opus-5-5"), + runEvent("run.updated", makeRun(RUN_ID, "interrupted", { model: "new-model" })), + runEvent("run.created", makeRun("run-2", "queued", { ordinal: 2 })), + ]) { + yield* reactor.handle(disabled); + } + assert.deepStrictEqual(calls, []); + }), + ); +}); diff --git a/apps/server/src/sim/SimObserverReactor.ts b/apps/server/src/sim/SimObserverReactor.ts new file mode 100644 index 0000000000000..92417a1880bc2 --- /dev/null +++ b/apps/server/src/sim/SimObserverReactor.ts @@ -0,0 +1,607 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import type { + OrchestrationV2AppThread, + OrchestrationV2DomainEvent, + OrchestrationV2Run, + OrchestrationV2TurnItem, + ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { ProjectStoreV2 } from "../orchestration-v2/ProjectStore.ts"; +import { USER_STOP_REASON } from "../orchestration-v2/RunExecutionService.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { + type SimResolvedPaths, + SimService, + type SimTelemetryEvent, + canonicalHarnessFile, + classifyHarnessPath, + expandHarnessFile, + expandHomeString, + resolveSimPaths, +} from "./SimContracts.ts"; +import * as SimStore from "./SimStore.ts"; + +/** Watches domain events for SIM context resets, unrecorded harness edits, and RSI signals. */ +export class SimObserverReactor extends Context.Service< + SimObserverReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/sim/SimObserverReactor") {} + +const MEMORY_CAP = 512; +const EXCERPT_LIMIT = 300; +const TERMINAL_RUN_STATUSES = new Set(["completed", "interrupted", "failed", "cancelled"]); +const REVIEW_PATTERN = /\b(review|audit|findings|verdict|critic|grade|grader)\b/i; +const CLAUDE_DRIVER = "claudeAgent"; + +/** Insertion-ordered map that drops its oldest entry past the cap, so a long-lived server never grows it. */ +function remember(map: Map, key: K, value: V): void { + map.delete(key); + map.set(key, value); + if (map.size > MEMORY_CAP) map.delete(map.keys().next().value as K); +} + +function firstSighting(seen: Map, key: string): boolean { + if (seen.has(key)) return false; + remember(seen, key, true); + return true; +} + +/** Calendar day in the server's zone, matching how standalone sim.mjs stamps `day` and `round`. */ +const localDay = (at: DateTime.DateTime) => + DateTime.formatIsoDate(DateTime.setZone(at, DateTime.zoneMakeLocal())); + +interface ShellWord { + readonly kind: "word"; + readonly value: string; + /** Contains an expansion this detector cannot resolve ($VAR other than $HOME, backticks). */ + readonly dynamic: boolean; +} +type ShellToken = + | ShellWord + | { readonly kind: "op"; readonly value: string } + | { readonly kind: "redir"; readonly value: string }; + +const stripHeredocBodies = (command: string) => + command.replace( + /(<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_-]*)['"]?[^\n]*\n)[\s\S]*?(?:\n[ \t]*\2(?=\n|$)|$)/g, + "$1", + ); + +function tokenizeShell(raw: string): Array { + const source = stripHeredocBodies(raw); + const tokens: Array = []; + let index = 0; + while (index < source.length) { + const ch = source[index]!; + const next = source[index + 1]; + if (ch === " " || ch === "\t" || ch === "\r") { + index += 1; + } else if (ch === "#") { + while (index < source.length && source[index] !== "\n") index += 1; + } else if ((ch === "&" && next === "&") || (ch === "|" && next === "|")) { + tokens.push({ kind: "op", value: ch + next }); + index += 2; + } else if (ch === "&" && next === ">") { + const op = source[index + 2] === ">" ? "&>>" : "&>"; + tokens.push({ kind: "redir", value: op }); + index += op.length; + } else if (ch === "\n" || ch === ";" || ch === "|" || ch === "&" || ch === "(" || ch === ")") { + tokens.push({ kind: "op", value: ch }); + index += 1; + } else if (ch === ">" || ch === "<" || (/\d/.test(ch) && (next === ">" || next === "<"))) { + let op = /\d/.test(ch) ? ch + next : ch; + index += op.length; + while (index < source.length && /[<>&|-]/.test(source[index]!) && op.length < 4) { + op += source[index]; + index += 1; + } + tokens.push({ kind: "redir", value: op }); + } else { + let value = ""; + let dynamic = false; + while (index < source.length && !/[\s;&|()<>]/.test(source[index]!)) { + const c = source[index]!; + if (c === "'") { + const end = source.indexOf("'", index + 1); + const stop = end === -1 ? source.length : end; + value += source.slice(index + 1, stop); + index = stop + 1; + } else if (c === '"') { + index += 1; + while (index < source.length && source[index] !== '"') { + if (source[index] === "\\" && index + 1 < source.length) index += 1; + if (source[index] === "`") dynamic = true; + value += source[index]; + index += 1; + } + index += 1; + } else if (c === "\\" && index + 1 < source.length) { + value += source[index + 1]; + index += 2; + } else { + if (c === "`") dynamic = true; + value += c; + index += 1; + } + } + if (/\$(?!HOME\b|\{HOME\})/.test(value)) dynamic = true; + tokens.push({ kind: "word", value, dynamic }); + } + } + return tokens; +} + +const COMMAND_WRAPPERS = new Set(["sudo", "env", "command", "builtin", "nohup", "time", "exec"]); +const ALL_ARG_WRITERS = new Set(["rm", "unlink", "truncate", "touch", "shred", "tee", "mv"]); +const LAST_ARG_WRITERS = new Set(["cp", "install", "ln", "rsync"]); +const SIM_TOOL_SCRIPT = /(?:^|\/)sim(?:-audit)?\.mjs$/; + +function commandWriteTargets(words: ReadonlyArray): Array { + let start = 0; + while ( + start < words.length && + (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[start]!.value) || + COMMAND_WRAPPERS.has(NodePath.basename(words[start]!.value))) + ) { + start += 1; + } + const name = NodePath.basename(words[start]?.value ?? ""); + const args = words.slice(start + 1); + if (args.some((word) => SIM_TOOL_SCRIPT.test(word.value))) return []; + const operands = args.filter((word) => !word.value.startsWith("-")); + if (ALL_ARG_WRITERS.has(name)) return operands; + if (LAST_ARG_WRITERS.has(name)) return operands.slice(-1); + if (name === "sed" || name === "perl") { + const inPlace = args.some( + (word) => /^-[a-zA-Z]*i/.test(word.value) || word.value.startsWith("--in-place"), + ); + if (!inPlace) return []; + const files: Array = []; + let scriptGiven = false; + for (let i = 0; i < args.length; i += 1) { + const word = args[i]!; + if (/^-[a-zA-Z]*[ef]$/.test(word.value) || word.value === "--expression") { + scriptGiven = true; + i += 1; + } else if (!word.value.startsWith("-")) { + if (scriptGiven) files.push(word); + else scriptGiven = true; + } + } + return files; + } + return []; +} + +/** Conservative list of paths a Bash command writes, removes, or renames. Unresolvable expansions are skipped. */ +export function detectShellWriteTargets(command: string): Array { + const targets: Array = []; + let words: Array = []; + const flush = () => { + targets.push(...commandWriteTargets(words)); + words = []; + }; + const tokens = tokenizeShell(command); + for (let i = 0; i < tokens.length; i += 1) { + const token = tokens[i]!; + if (token.kind === "op") { + flush(); + } else if (token.kind === "redir") { + const target = tokens[i + 1]; + if (target?.kind !== "word") continue; + i += 1; + const writes = token.value.includes(">") && !token.value.endsWith("&"); + if (writes && target.value !== "/dev/null") targets.push(target); + } else { + words.push(token); + } + } + flush(); + return [...new Set(targets.filter((word) => !word.dynamic).map((word) => word.value))]; +} + +interface Selection { + readonly providerInstanceId: string; + readonly model: string; +} + +interface InterruptedRun extends Selection { + readonly runId: string; + readonly reason: string | undefined; +} + +const runSelection = (run: OrchestrationV2Run): Selection => ({ + providerInstanceId: run.modelSelection.instanceId ?? run.providerInstanceId, + model: run.modelSelection.model, +}); + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const projectStore = yield* Effect.serviceOption(ProjectStoreV2); + const settingsService = yield* ServerSettings.ServerSettingsService; + const sim = yield* SimService; + + const handledItems = new Map(); + const activeProviderThread = new Map(); + const claudeSession = new Map(); + const threadCwd = new Map(); + const pendingHarness = new Map>(); + const threadSelection = new Map(); + const runSelectionById = new Map(); + const interruptReasons = new Map(); + const interrupted = new Map(); + let observedModels: Set | undefined; + + const pendingKey = (threadId: string, runId: string) => `${threadId}\u0000${runId}`; + + const cwdFor = Effect.fnUntraced(function* (threadId: ThreadId) { + if (threadCwd.has(threadId)) return threadCwd.get(threadId); + const thread = yield* projections.findThread(threadId); + let cwd = thread?.worktreePath ?? undefined; + if (!cwd && thread?.projectId && Option.isSome(projectStore)) { + const project = yield* projectStore.value + .getShell(thread.projectId) + .pipe(Effect.orElseSucceed(() => Option.none())); + cwd = Option.getOrUndefined(project)?.workspaceRoot; + } + remember(threadCwd, threadId, cwd); + return cwd; + }); + + const resetEpoch = Effect.fnUntraced(function* ( + threadId: ThreadId, + nativeIds: ReadonlyArray, + ) { + const known = claudeSession.get(threadId); + const sessions = [...new Set([...nativeIds, ...(known ? [known] : [])])].map( + (id) => `cc:${id}`, + ); + yield* sim.resetThreadSeenEpoch(threadId, sessions); + }); + + const classifyFiles = Effect.fnUntraced(function* ( + event: OrchestrationV2DomainEvent, + item: OrchestrationV2TurnItem, + rawPaths: ReadonlyArray, + paths: SimResolvedPaths, + ) { + const unique = [...new Set(rawPaths.filter((value) => value.trim() !== ""))]; + if (unique.length === 0) return; + const cwd = yield* cwdFor(event.threadId); + const allowTmp = SimStore.isTestSimDir(paths); + const records: Array = []; + const harness: Array = []; + for (const raw of unique) { + const expanded = raw.trim().startsWith("~/.claude/") + ? expandHarnessFile(raw, paths) + : expandHomeString(raw, paths.homeDir); + const kind = classifyHarnessPath(expanded, paths, cwd, { allowTmp }); + if (kind === null) continue; + const absolute = NodePath.resolve(cwd ?? paths.homeDir, expanded); + (kind === "record" ? records : harness).push(canonicalHarnessFile(absolute, paths)); + } + const runId = item.runId ?? event.runId; + const selection = runId ? runSelectionById.get(runId) : undefined; + if (records.length > 0) { + yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "direct_sim_record_edit", + threadId: event.threadId, + runId, + providerInstanceId: selection?.providerInstanceId ?? event.providerInstanceId, + model: selection?.model, + files: records, + }); + } + if (harness.length > 0 && runId) { + const key = pendingKey(event.threadId, runId); + const pending = pendingHarness.get(key) ?? new Set(); + for (const file of harness) pending.add(file); + remember(pendingHarness, key, pending); + } + }); + + const flushPendingHarness = Effect.fnUntraced(function* ( + event: OrchestrationV2DomainEvent, + run: OrchestrationV2Run, + ) { + const key = pendingKey(event.threadId, run.id); + const pending = pendingHarness.get(key); + if (!pending) return; + pendingHarness.delete(key); + const cwd = yield* cwdFor(event.threadId); + const snapshot = yield* sim.getStateSnapshot(); + const authors = new Set([`t3:${event.threadId}`]); + const native = claudeSession.get(event.threadId); + if (native) authors.add(`cc:${native}`); + const days = new Set([localDay(run.requestedAt), localDay(event.occurredAt)]); + const recordedToday = new Set(); + for (const problem of snapshot?.state.problems ?? []) { + for (const attempt of problem.attempts) { + const byCaller = + authors.has(attempt.by) || (attempt.also !== undefined && authors.has(attempt.also)); + if (byCaller && days.has(attempt.recorded?.day ?? attempt.round)) { + for (const file of attempt.files) recordedToday.add(file); + } + } + } + const unrecorded: Array = []; + for (const file of pending) { + if (recordedToday.has(file)) continue; + if ( + yield* sim.hasRecentAttemptForFile({ + threadId: event.threadId, + runId: run.id, + workspaceRoot: cwd, + file, + }) + ) + continue; + unrecorded.push(file); + } + if (unrecorded.length === 0) return; + const selection = runSelection(run); + yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "unrecorded_harness_edit", + threadId: event.threadId, + runId: run.id, + providerInstanceId: selection.providerInstanceId, + model: selection.model, + files: unrecorded, + }); + }); + + const observeModel = Effect.fnUntraced(function* ( + event: OrchestrationV2DomainEvent, + selection: Selection, + ) { + observedModels ??= new Set(yield* sim.getObservedModels()); + const key = `${selection.providerInstanceId}:${selection.model}`; + if (observedModels.has(key) || observedModels.has(selection.model)) return; + observedModels.add(key); + yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "new_model_observed", + threadId: event.threadId, + providerInstanceId: selection.providerInstanceId, + model: selection.model, + }); + }); + + const handleTurnItem = Effect.fnUntraced(function* ( + event: Extract, + paths: SimResolvedPaths, + ) { + const item = event.payload; + if (item.type === "run_interrupt_request" && item.runId) { + remember(interruptReasons, item.runId, item.message); + return; + } + if (item.status !== "completed") return; + if (item.type === "compaction") { + if (firstSighting(handledItems, `compaction:${item.id}`)) + yield* resetEpoch(event.threadId, []); + } else if (item.type === "file_change") { + if (!firstSighting(handledItems, `file:${item.id}`)) return; + const files = [item.fileName, ...(item.changes ?? []).map((change) => change.path)]; + yield* classifyFiles(event, item, files, paths); + } else if (item.type === "command_execution") { + if (!firstSighting(handledItems, `command:${item.id}`)) return; + yield* classifyFiles(event, item, detectShellWriteTargets(item.input), paths); + } + }); + + const handleProviderThread = Effect.fnUntraced(function* ( + event: Extract, + ) { + const providerThread = event.payload; + const threadId = providerThread.appThreadId ?? event.threadId; + const previousNative = claudeSession.get(threadId); + const nativeId = + providerThread.driver === CLAUDE_DRIVER + ? providerThread.nativeThreadRef?.nativeId + : undefined; + if (nativeId) remember(claudeSession, threadId, nativeId); + if ( + activeProviderThread.get(threadId) === providerThread.id && + (!nativeId || nativeId === previousNative) + ) { + return; + } + // Native subagents get provider threads too; only the thread's active one is its context. + const thread = yield* projections.findThread(threadId); + if (thread?.activeProviderThreadId !== providerThread.id) return; + remember(activeProviderThread, threadId, providerThread.id); + const extraSessionIds = [ + ...new Set([previousNative, nativeId].filter((id): id is string => Boolean(id))), + ].map((id) => `cc:${id}`); + yield* sim.trackProviderThread({ + threadId, + providerThreadId: providerThread.id, + extraSessionIds, + }); + }); + + const handleSelectionChange = Effect.fnUntraced(function* ( + event: OrchestrationV2DomainEvent, + thread: OrchestrationV2AppThread, + ) { + const next: Selection = { + providerInstanceId: thread.modelSelection.instanceId ?? thread.providerInstanceId, + model: thread.modelSelection.model, + }; + let previous = threadSelection.get(event.threadId); + if (previous?.providerInstanceId === next.providerInstanceId && previous.model === next.model) { + return; + } + remember(threadSelection, event.threadId, next); + const records = yield* projections.getThreadRecords(event.threadId, ["runs"]); + // Picking a model before the first turn is setup, not a switch. + if (records.runs.length === 0) return; + const latest = records.runs.toSorted((a, b) => b.ordinal - a.ordinal)[0]!; + previous ??= runSelection(latest); + if (previous.providerInstanceId === next.providerInstanceId && previous.model === next.model) { + return; + } + yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "mid_thread_model_switch", + threadId: event.threadId, + fromProvider: previous.providerInstanceId, + fromModel: previous.model, + toProvider: next.providerInstanceId, + toModel: next.model, + }); + }); + + const handleRunCreated = Effect.fnUntraced(function* ( + event: Extract, + ) { + const run = event.payload; + remember(runSelectionById, run.id, runSelection(run)); + remember(threadSelection, event.threadId, runSelection(run)); + if (run.restartContinuationOfRunId || run.usageLimitContinuationOfRunId) return; + const stopped = interrupted.get(event.threadId); + if (!stopped || stopped.runId === run.id) return; + interrupted.delete(event.threadId); + yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "interrupted_with_steer", + threadId: event.threadId, + interruptedRunId: stopped.runId, + followupRunId: run.id, + providerInstanceId: stopped.providerInstanceId, + model: stopped.model, + reason: stopped.reason, + }); + }); + + const handleRunUpdated = Effect.fnUntraced(function* ( + event: Extract, + ) { + const run = event.payload; + const selection = runSelection(run); + remember(runSelectionById, run.id, selection); + if (run.status === "running" || run.status === "completed") + yield* observeModel(event, selection); + if (run.status === "interrupted") { + const reason = interruptReasons.get(run.id); + interruptReasons.delete(run.id); + // An agent or server stop carries its own reason; only a person's stop is a correction. + if (reason === undefined || reason === USER_STOP_REASON) { + remember(interrupted, event.threadId, { ...selection, runId: run.id, reason }); + } + } + if (TERMINAL_RUN_STATUSES.has(run.status)) yield* flushPendingHarness(event, run); + }); + + const handleEvent = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) { + const settings = yield* settingsService.getSettings; + if (!settings.sim.enabled) return; + switch (event.type) { + case "turn-item.updated": + return yield* handleTurnItem(event, resolveSimPaths(settings.sim)); + case "context-handoff.updated": + if ( + event.payload.status === "ready" && + firstSighting(handledItems, `handoff:${event.payload.id}`) + ) { + yield* resetEpoch(event.threadId, []); + } + return; + case "provider-thread.updated": + return yield* handleProviderThread(event); + case "checkpoint.rollback-requested": { + const selection = threadSelection.get(event.threadId); + const telemetry: SimTelemetryEvent = { + ts: DateTime.formatIso(event.occurredAt), + kind: "checkpoint_rollback", + threadId: event.threadId, + runId: event.runId, + checkpointId: event.payload.checkpointId, + providerInstanceId: selection?.providerInstanceId ?? event.providerInstanceId, + model: selection?.model, + }; + return yield* sim.recordTelemetry(telemetry); + } + case "thread.created": + threadCwd.delete(event.threadId); + remember(threadSelection, event.threadId, { + providerInstanceId: + event.payload.modelSelection.instanceId ?? event.payload.providerInstanceId, + model: event.payload.modelSelection.model, + }); + return; + case "thread.model-selection-updated": + case "thread.provider-switched": + threadCwd.delete(event.threadId); + return yield* handleSelectionChange(event, event.payload); + case "run.created": + return yield* handleRunCreated(event); + case "run.updated": + return yield* handleRunUpdated(event); + case "subagent.updated": { + const subagent = event.payload; + if (subagent.status !== "completed") return; + const text = [subagent.title, subagent.prompt, subagent.result].filter(Boolean).join("\n"); + if (!REVIEW_PATTERN.test(text) || !firstSighting(handledItems, `subagent:${subagent.id}`)) + return; + const excerpt = (subagent.result || subagent.prompt || subagent.title || "").trim(); + return yield* sim.recordTelemetry({ + ts: DateTime.formatIso(event.occurredAt), + kind: "delegated_review_completed", + threadId: event.threadId, + childThreadId: subagent.childThreadId ?? undefined, + providerInstanceId: subagent.providerInstanceId, + model: subagent.executedModel ?? subagent.model ?? subagent.modelSelection?.model, + title: subagent.title ?? undefined, + excerpt: excerpt.slice(0, EXCERPT_LIMIT) || undefined, + }); + } + default: + return; + } + }); + + const handle: SimObserverReactor["Service"]["handle"] = (event) => + handleEvent(event).pipe( + Effect.catchCause((cause) => + Effect.logWarning("SIM observer failed to handle an event", { + threadId: event.threadId, + type: event.type, + cause, + }), + ), + ); + + const start: SimObserverReactor["Service"]["start"] = () => + forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("SIM observer event stream failed", { cause }), + ), + ), + ); + + return { start, handle } satisfies SimObserverReactor["Service"]; +}); + +export const layer = Layer.effect(SimObserverReactor, make); diff --git a/apps/server/src/sim/SimService.test.ts b/apps/server/src/sim/SimService.test.ts new file mode 100644 index 0000000000000..7d22951681a98 --- /dev/null +++ b/apps/server/src/sim/SimService.test.ts @@ -0,0 +1,348 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import { RunId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerSettings from "../serverSettings.ts"; +import { + SimService, + type SimApplyHarnessChangeRequest, + type SimCallerContext, + type SimServiceError, +} from "./SimContracts.ts"; +import * as SimServiceLive from "./SimService.ts"; + +const RULE = "Always run the build before you claim done."; + +function sandbox(enabled = true) { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sim-test-")); + const harnessDir = NodePath.join(root, "claude"); + const workspace = NodePath.join(root, "repo"); + NodeFS.mkdirSync(NodePath.join(harnessDir, "sim"), { recursive: true }); + NodeFS.mkdirSync(workspace, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(harnessDir, "AGENTS.md"), `# Rules\n- ${RULE}\n`); + const layer = SimServiceLive.layer.pipe( + Layer.provide( + ServerSettings.layerTest({ sim: { enabled, harnessDir, advisorModelSelection: null } }), + ), + ); + return { + harnessDir, + workspace, + agents: NodePath.join(harnessDir, "AGENTS.md"), + journal: NodePath.join(harnessDir, "sim", "sim.jsonl"), + layer, + [Symbol.dispose]: () => NodeFS.rmSync(root, { recursive: true, force: true }), + }; +} + +const threadId = ThreadId.make("editor"); +const runId = RunId.make("run-1"); +const editor = (workspaceRoot: string): SimCallerContext => ({ + sessionId: "t3:editor", + threadId, + activeRunId: runId, + model: "gpt-5", + driver: "codex", + projectName: "repo", + workspaceRoot, +}); + +const quoteRule = ( + extra: Partial = {}, +): SimApplyHarnessChangeRequest => ({ + file: "~/.claude/AGENTS.md", + oldText: `- ${RULE}\n`, + newText: `- ${RULE}\n- Always quote the failing build output verbatim.\n`, + attempt: { + new: "Agents paraphrase the failing build output instead of quoting it", + action: "add", + what: "Rule to quote the failing build output", + why: "Paraphrased errors hid the real cause twice", + anchor: "quote the failing build output verbatim", + depends_on: ["model"], + predicted: ["paraphrased-build-errors"], + expect: "Build errors appear verbatim in reports", + }, + ...extra, +}); + +const flipFailure = (effect: Effect.Effect) => Effect.flip(effect); + +describe("SimService.applyHarnessChange", () => { + it.effect("previews a dry run without writing, then edits and records in one step", () => { + const sb = sandbox(); + return Effect.gen(function* () { + const sim = yield* SimService; + const caller = editor(sb.workspace); + // Must consult index or by_file before applying or previewing. + expect((yield* flipFailure(sim.applyHarnessChange(caller, quoteRule()))).code).toBe( + "seen_required", + ); + yield* sim.read(caller, { action: "index" }); + + const preview = yield* sim.applyHarnessChange(caller, { ...quoteRule(), dryRun: true }); + expect(preview.dryRun).toBe(true); + expect(preview.predictionLine).toBe( + "predicted to fix: paraphrased-build-errors; expect: Build errors appear verbatim in reports", + ); + expect(preview.diffPreview).toContain("+- Always quote the failing build output verbatim."); + expect(NodeFS.readFileSync(sb.agents, "utf8")).toBe(`# Rules\n- ${RULE}\n`); + expect(NodeFS.existsSync(sb.journal)).toBe(false); + + const live = yield* sim.applyHarnessChange(caller, quoteRule()); + expect(live).toMatchObject({ + dryRun: false, + problemId: "P1", + attemptId: "A1", + file: "~/.claude/AGENTS.md", + }); + expect(NodeFS.readFileSync(sb.agents, "utf8")).toContain( + "quote the failing build output verbatim", + ); + const event = JSON.parse(NodeFS.readFileSync(sb.journal, "utf8").trim()); + expect(event).toMatchObject({ by: "t3:editor", harness: "codex", op: "attempt" }); + expect(event.data).toMatchObject({ + policy: "gpt-5", + domain: "global", + files: ["~/.claude/AGENTS.md"], + }); + + expect(yield* sim.hasRecentAttemptForFile({ threadId, runId, file: sb.agents })).toBe(true); + expect(yield* sim.hasRecentAttemptForFile({ threadId, file: "~/.claude/AGENTS.md" })).toBe( + true, + ); + expect( + yield* sim.hasRecentAttemptForFile({ + threadId, + runId: RunId.make("run-2"), + file: sb.agents, + }), + ).toBe(false); + + // Relative workspace paths resolve against workspaceRoot consistently on record and lookup. + yield* sim.recordRecentAttemptInTurn({ + threadId, + runId, + workspaceRoot: sb.workspace, + files: ["AGENTS.md"], + }); + expect( + yield* sim.hasRecentAttemptForFile({ + threadId, + runId, + workspaceRoot: sb.workspace, + file: NodePath.join(sb.workspace, "AGENTS.md"), + }), + ).toBe(true); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }); + + it.effect( + "refuses before editing when the caller has not read the index or entry, and again after compaction", + () => { + const sb = sandbox(); + return Effect.gen(function* () { + const sim = yield* SimService; + const caller = editor(sb.workspace); + yield* sim.read(caller, { action: "index" }); + yield* sim.applyHarnessChange(caller, quoteRule()); + // Add a second problem so show P1 alone does not cover the full record. + yield* sim.read(caller, { action: "brief_all" }); + yield* sim.read(caller, { action: "show", ids: ["P1"] }); + yield* sim.applyHarnessChange(caller, { + file: sb.agents, + append: true, + content: "- Never force push shared branches.\n", + attempt: { + new: "Agents force push shared branches without asking first", + action: "add", + what: "Forbid force pushing shared branches", + why: "Force push overwrote teammate work", + anchor: "Never force push shared branches.", + depends_on: ["user"], + predicted: ["force-push-loss"], + expect: "No force pushes", + }, + }); + const other = { + ...editor(sb.workspace), + sessionId: "t3:other", + threadId: ThreadId.make("other"), + }; + const revise: SimApplyHarnessChangeRequest = { + file: sb.agents, + oldText: "quote the failing build output verbatim", + newText: "quote the failing build output verbatim, with its exit code", + attempt: { + problem: "P1", + action: "revise", + supersedes: ["A1"], + what: "Also quote the exit code", + why: "Reports dropped the exit code", + anchor: "with its exit code", + depends_on: ["model"], + predicted: ["paraphrased-build-errors"], + expect: "Exit codes appear in reports", + }, + }; + const before = NodeFS.readFileSync(sb.agents, "utf8"); + const unread = yield* flipFailure(sim.applyHarnessChange(other, revise)); + expect(unread.code).toBe("seen_required"); + expect(NodeFS.readFileSync(sb.agents, "utf8")).toBe(before); + + // show P1 alone is not enough when other problems exist and index/by_file was not consulted. + yield* sim.read(other, { action: "show", ids: ["P1"] }); + expect((yield* flipFailure(sim.applyHarnessChange(other, revise))).code).toBe( + "seen_required", + ); + + yield* sim.read(other, { action: "by_file", file: sb.agents }); + yield* sim.resetThreadSeenEpoch(other.threadId); + expect(yield* sim.getThreadSeenEpoch(other.threadId)).toBe(1); + expect((yield* flipFailure(sim.applyHarnessChange(other, revise))).code).toBe( + "seen_required", + ); + + yield* sim.read(other, { action: "by_file", file: sb.agents }); + yield* sim.read(other, { action: "show", ids: ["P1"] }); + expect((yield* sim.applyHarnessChange(other, revise)).attemptId).toBe("A3"); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }, + ); + + it.effect("puts the file back when the journal append fails", () => { + const sb = sandbox(); + return Effect.gen(function* () { + const sim = yield* SimService; + const caller = editor(sb.workspace); + yield* sim.read(caller, { action: "index" }); + // A dangling link reads as an empty journal but cannot be appended to. + NodeFS.symlinkSync(NodePath.join(sb.harnessDir, "missing", "sim.jsonl"), sb.journal); + const before = NodeFS.readFileSync(sb.agents); + const error = yield* flipFailure(sim.applyHarnessChange(caller, quoteRule())); + expect(error.code).toBe("io"); + expect(NodeFS.readFileSync(sb.agents).equals(before)).toBe(true); + + const created = NodePath.join(sb.harnessDir, "notes", "new.md"); + yield* flipFailure( + sim.applyHarnessChange(caller, { + ...quoteRule(), + file: created, + oldText: undefined, + newText: undefined, + content: "- Always quote the failing build output verbatim.\n", + }), + ); + expect(NodeFS.existsSync(created)).toBe(false); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }); + + it.effect("preserves symlinks and executable permissions when applying harness edits", () => { + const sb = sandbox(); + return Effect.gen(function* () { + const sim = yield* SimService; + const caller = editor(sb.workspace); + yield* sim.read(caller, { action: "index" }); + + // Dotfiles-style symlinked AGENTS.md stays a symlink while updating its realpath target. + const dotfilesDir = NodePath.join(NodePath.dirname(sb.harnessDir), "dotfiles"); + NodeFS.mkdirSync(dotfilesDir, { recursive: true }); + const realAgents = NodePath.join(dotfilesDir, "AGENTS.md"); + NodeFS.writeFileSync(realAgents, `# Rules\n- ${RULE}\n`, { mode: 0o640 }); + NodeFS.chmodSync(realAgents, 0o640); + NodeFS.rmSync(sb.agents); + NodeFS.symlinkSync(realAgents, sb.agents); + + const applied = yield* sim.applyHarnessChange(caller, quoteRule()); + expect(applied.attemptId).toBe("A1"); + expect(NodeFS.lstatSync(sb.agents).isSymbolicLink()).toBe(true); + expect(NodeFS.readFileSync(realAgents, "utf8")).toContain( + "quote the failing build output verbatim", + ); + expect(NodeFS.statSync(realAgents).mode & 0o777).toBe(0o640); + + // Executable hook script preserves +x bit. + const hooksDir = NodePath.join(sb.harnessDir, "hooks"); + NodeFS.mkdirSync(hooksDir, { recursive: true }); + const script = NodePath.join(hooksDir, "check.sh"); + NodeFS.writeFileSync(script, "#!/bin/sh\necho ok\n", { mode: 0o755 }); + NodeFS.chmodSync(script, 0o755); + yield* sim.read(caller, { action: "brief_all" }); + yield* sim.read(caller, { action: "show", ids: ["P1"] }); + const hookResult = yield* sim.applyHarnessChange(caller, { + file: "~/.claude/hooks/check.sh", + oldText: "echo ok", + newText: "echo verified-ok", + attempt: { + new: "Shell hooks omit verification markers in stdout logs", + action: "add", + what: "Emit verified-ok marker in check.sh", + why: "Log parser could not distinguish dry-run from real pass", + anchor: "echo verified-ok", + depends_on: ["environment"], + predicted: ["ambiguous-hook-log"], + expect: "Hook stdout contains verified-ok", + }, + }); + expect(hookResult.attemptId).toBe("A2"); + expect(NodeFS.statSync(script).mode & 0o777).toBe(0o755); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }); + + it.effect( + "refuses SIM record files, non-harness files, and harness files outside harnessDir and workspace", + () => { + const sb = sandbox(); + return Effect.gen(function* () { + const sim = yield* SimService; + const outsideDir = NodePath.join(NodePath.dirname(sb.workspace), "other-repo"); + NodeFS.mkdirSync(outsideDir, { recursive: true }); + const outsideAgents = NodePath.join(outsideDir, "AGENTS.md"); + NodeFS.writeFileSync(outsideAgents, "# Other repo\n"); + NodeFS.writeFileSync(NodePath.join(sb.workspace, "README.md"), "hello\n"); + const targets = [ + "~/.claude/sim/sim.jsonl", + "~/.claude/sim/sim.json", + "~/.claude/sim/sim.lock", + "~/.claude/sim/seen/abcd.json", + "~/.claude/sim/telemetry.jsonl", + "README.md", + outsideAgents, + ].map((file) => file.replace("~/.claude", sb.harnessDir)); + for (const file of targets) { + const error = yield* flipFailure( + sim.applyHarnessChange(editor(sb.workspace), { + ...quoteRule(), + file, + oldText: undefined, + newText: undefined, + content: "x", + }), + ); + expect([file, error.code]).toEqual([file, "forbidden_path"]); + } + expect(NodeFS.existsSync(sb.journal)).toBe(false); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }, + ); + + it.effect("does nothing while SIM is turned off", () => { + const sb = sandbox(false); + return Effect.gen(function* () { + const sim = yield* SimService; + expect( + (yield* flipFailure(sim.applyHarnessChange(editor(sb.workspace), quoteRule()))).code, + ).toBe("disabled"); + expect((yield* flipFailure(sim.read(editor(sb.workspace), { action: "index" }))).code).toBe( + "disabled", + ); + expect(yield* sim.getStateSnapshot()).toBeNull(); + }).pipe(Effect.provide(sb.layer), Effect.ensuring(Effect.sync(() => sb[Symbol.dispose]()))); + }); +}); diff --git a/apps/server/src/sim/SimService.ts b/apps/server/src/sim/SimService.ts new file mode 100644 index 0000000000000..5f45073e9c8be --- /dev/null +++ b/apps/server/src/sim/SimService.ts @@ -0,0 +1,268 @@ +import type { ThreadId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +import * as ServerSettings from "../serverSettings.ts"; +import { + SimService, + SimServiceError, + classifyHarnessPath, + resolveSimPaths, + type SimResolvedPaths, + type SimSettingsConfig, +} from "./SimContracts.ts"; +import * as SimStore from "./SimStore.ts"; + +const RECENT_RUNS_LIMIT = 256; +const REVIEW_TELEMETRY_DEFAULT_WINDOW_MS = 7 * 86_400_000; + +const isSimServiceError = Schema.is(SimServiceError); + +const toSimError = (cause: unknown): SimServiceError => + isSimServiceError(cause) + ? cause + : new SimServiceError({ + code: "io", + problems: [cause instanceof Error ? cause.message : String(cause)], + }); + +const attempt = (work: () => A) => Effect.try({ try: work, catch: toSimError }); + +const recentKey = (threadId: string, runId: string | undefined) => + `${threadId}\u0000${runId ?? ""}`; +const threadCaller = (threadId: string, workspaceRoot?: string) => ({ + sessionId: `t3:${threadId}`, + ...(workspaceRoot !== undefined ? { workspaceRoot } : {}), +}); + +const make = Effect.gen(function* () { + const serverSettings = yield* ServerSettings.ServerSettingsService; + const writes = yield* Semaphore.make(1); + const recent = new Map>(); + + const simSettings: Effect.Effect = + serverSettings.getSettings.pipe( + Effect.map((settings) => settings.sim), + Effect.mapError(toSimError), + ); + const pathsOf = (sim: SimSettingsConfig) => resolveSimPaths(sim); + const enabledSettings = simSettings.pipe( + Effect.filterOrFail( + (sim) => sim.enabled, + () => new SimServiceError({ code: "disabled", problems: ["SIM is turned off in settings"] }), + ), + ); + + /** sim.lock across processes (sim.mjs, sim-gate), polled without blocking the event loop. */ + const acquireFileLock = Effect.fn("SimService.acquireFileLock")(function* ( + paths: SimResolvedPaths, + ) { + const deadline = (yield* Clock.currentTimeMillis) + SimStore.SIM_LOCK_WAIT_MS; + while (!(yield* attempt(() => SimStore.tryLock(paths)))) { + if ((yield* Clock.currentTimeMillis) > deadline) { + return yield* new SimServiceError({ + code: "io", + problems: ["another process holds the SIM lock; try again"], + }); + } + yield* Effect.sleep(SimStore.SIM_LOCK_POLL_MS); + } + }); + const locked = (paths: SimResolvedPaths, effect: Effect.Effect) => + writes.withPermits(1)( + Effect.acquireUseRelease( + acquireFileLock(paths), + () => effect, + () => Effect.sync(() => SimStore.unlock(paths)), + ), + ); + + const loadForRead = (paths: SimResolvedPaths) => attempt(() => SimStore.loadReadOnly(paths)); + + const recordRecent = ( + threadId: string, + runId: string | undefined, + files: ReadonlyArray, + ) => { + const key = recentKey(threadId, runId); + const set = recent.get(key) ?? new Set(); + recent.delete(key); + for (const file of files) set.add(file); + recent.set(key, set); + while (recent.size > RECENT_RUNS_LIMIT) { + const oldest = recent.keys().next().value; + if (oldest === undefined) break; + recent.delete(oldest); + } + }; + + return SimService.of({ + read: Effect.fn("SimService.read")(function* (caller, request) { + const sim = yield* enabledSettings; + const paths = pathsOf(sim); + const loaded = yield* loadForRead(paths); + const telemetry = + request.action === "review" + ? SimStore.readTelemetry( + paths, + SimStore.readAuditWatermarkMs(paths) ?? + (yield* Clock.currentTimeMillis) - REVIEW_TELEMETRY_DEFAULT_WINDOW_MS, + ) + : []; + return yield* attempt(() => + SimStore.runRead({ paths, loaded, caller, settings: sim, telemetry }, request), + ); + }), + + write: Effect.fn("SimService.write")(function* (caller, request) { + const paths = pathsOf(yield* enabledSettings); + return yield* locked( + paths, + attempt(() => SimStore.runWrite(paths, caller, request)), + ); + }), + + applyHarnessChange: Effect.fn("SimService.applyHarnessChange")(function* (caller, request) { + const paths = pathsOf(yield* enabledSettings); + const allowTmp = SimStore.isTestSimDir(paths); + const run = attempt(() => + SimStore.runApplyHarnessChange(paths, caller, request, { + classify: (absolute) => + classifyHarnessPath(absolute, paths, caller.workspaceRoot, { allowTmp }), + }), + ); + // A dry run writes nothing, so it needs no lock; a live apply holds it across file edit and journal append. + const outcome = yield* request.dryRun === true ? run : locked(paths, run); + if (!outcome.result.dryRun && caller.threadId) { + recordRecent(caller.threadId, caller.activeRunId, outcome.recordedFiles); + } + return outcome.result; + }), + + resetThreadSeenEpoch: Effect.fn("SimService.resetThreadSeenEpoch")( + function* (threadId: ThreadId, extraSessionIds?: ReadonlyArray) { + const paths = pathsOf(yield* simSettings); + return yield* writes.withPermits(1)( + attempt(() => SimStore.resetThreadSeenEpoch(paths, threadId, extraSessionIds)), + ); + }, + Effect.catchCause((cause) => + Effect.logWarning("SIM seen epoch reset failed", cause).pipe(Effect.as(0)), + ), + ), + + trackProviderThread: Effect.fn("SimService.trackProviderThread")( + function* ({ threadId, providerThreadId, extraSessionIds }) { + const paths = pathsOf(yield* simSettings); + return yield* writes.withPermits(1)( + attempt(() => + SimStore.trackProviderThread(paths, threadId, providerThreadId, extraSessionIds), + ), + ); + }, + Effect.catchCause((cause) => + Effect.logWarning("SIM provider thread epoch tracking failed", cause).pipe( + Effect.as(false), + ), + ), + ), + + getThreadSeenEpoch: Effect.fn("SimService.getThreadSeenEpoch")( + function* (threadId) { + const paths = pathsOf(yield* simSettings); + return SimStore.getThreadSeenEpoch(paths, threadId); + }, + Effect.orElseSucceed(() => 0), + ), + + recordTelemetry: Effect.fn("SimService.recordTelemetry")( + function* (event) { + const sim = yield* simSettings; + if (!sim.enabled) return; + yield* writes.withPermits(1)(attempt(() => SimStore.appendTelemetry(pathsOf(sim), event))); + }, + Effect.catchCause((cause) => Effect.logWarning("SIM telemetry failed", cause)), + ), + + readTelemetry: Effect.fn("SimService.readTelemetry")( + function* (sinceMs) { + const paths = pathsOf(yield* simSettings); + return SimStore.readTelemetry(paths, sinceMs); + }, + Effect.orElseSucceed(() => []), + ), + + recordRecentAttemptInTurn: Effect.fn("SimService.recordRecentAttemptInTurn")( + function* ({ threadId, runId, workspaceRoot, files }) { + const paths = pathsOf(yield* simSettings); + recordRecent( + threadId, + runId, + files.map((file) => + SimStore.resolveCallerFile(file, threadCaller(threadId, workspaceRoot), paths), + ), + ); + }, + Effect.orElseSucceed(() => undefined), + ), + + hasRecentAttemptForFile: Effect.fn("SimService.hasRecentAttemptForFile")( + function* ({ threadId, runId, workspaceRoot, file }) { + const paths = pathsOf(yield* simSettings); + const wanted = SimStore.resolveCallerFile( + file, + threadCaller(threadId, workspaceRoot), + paths, + ); + if (runId !== undefined) + return recent.get(recentKey(threadId, runId))?.has(wanted) ?? false; + for (const [key, files] of recent) { + if (key.split("\u0000")[0] === threadId && files.has(wanted)) return true; + } + return false; + }, + Effect.orElseSucceed(() => false), + ), + + getStateSnapshot: Effect.fn("SimService.getStateSnapshot")( + function* () { + const sim = yield* simSettings; + if (!sim.enabled) return null; + const paths = pathsOf(sim); + const loaded = yield* loadForRead(paths); + return { state: loaded.state, broken: loaded.journal.broken, paths }; + }, + Effect.catchCause((cause) => + Effect.logWarning("SIM snapshot failed", cause).pipe(Effect.as(null)), + ), + ), + + getObservedModels: Effect.fn("SimService.getObservedModels")( + function* () { + const loaded = yield* loadForRead(pathsOf(yield* simSettings)); + return SimStore.observedModels(loaded.state) as ReadonlySet; + }, + Effect.orElseSucceed((): ReadonlySet => new Set()), + ), + + resolvePaths: Effect.fn("SimService.resolvePaths")( + function* () { + return pathsOf(yield* simSettings); + }, + Effect.orElseSucceed(() => resolveSimPaths()), + ), + + findAttemptAuthorSessions: Effect.fn("SimService.findAttemptAuthorSessions")( + function* (attemptId) { + const loaded = yield* loadForRead(pathsOf(yield* simSettings)); + return SimStore.attemptAuthorSessions(loaded.state, attemptId) as ReadonlyArray; + }, + Effect.orElseSucceed((): ReadonlyArray => []), + ), + }); +}); + +export const layer = Layer.effect(SimService, make); diff --git a/apps/server/src/sim/SimStore.test.ts b/apps/server/src/sim/SimStore.test.ts new file mode 100644 index 0000000000000..01753008030c1 --- /dev/null +++ b/apps/server/src/sim/SimStore.test.ts @@ -0,0 +1,773 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { + classifyHarnessPath, + resolveSimPaths, + SimServiceError, + type SimCallerContext, + type SimJournalEvent, + type SimResolvedPaths, + type SimWriteRequest, +} from "./SimContracts.ts"; +import * as SimStore from "./SimStore.ts"; + +function sandbox() { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sim-test-")); + const harnessDir = NodePath.join(root, "claude"); + NodeFS.mkdirSync(NodePath.join(harnessDir, "notes"), { recursive: true }); + const paths = resolveSimPaths({ harnessDir }, root); + return { + paths, + harness: (rel: string, text: string) => { + NodeFS.mkdirSync(NodePath.dirname(NodePath.join(harnessDir, rel)), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(harnessDir, rel), text); + }, + [Symbol.dispose]: () => NodeFS.rmSync(root, { recursive: true, force: true }), + }; +} + +const caller = (name: string, extra: Partial = {}): SimCallerContext => ({ + sessionId: `t3:${name}`, + threadId: ThreadId.make(name), + model: "gpt-5", + driver: "codex", + ...extra, +}); +const author = caller("author", { alsoSessionId: "cc:author-native" }); +const reviewer = caller("reviewer", { model: "claude-opus-5-5", driver: "claudeAgent" }); + +const write = (paths: SimResolvedPaths, who: SimCallerContext, request: SimWriteRequest) => + SimStore.runWrite(paths, who, request); + +const journal = (paths: SimResolvedPaths): Array => + NodeFS.readFileSync(paths.journalPath, "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as SimJournalEvent); + +const isSimServiceError = Schema.is(SimServiceError); + +const failure = (run: () => unknown) => { + try { + run(); + } catch (error) { + if (isSimServiceError(error)) return error; + throw error; + } + throw new Error("expected a SimServiceError"); +}; + +const RULE = "Always run the build before you claim done."; + +function readIndex(paths: SimResolvedPaths, who = author) { + return SimStore.runRead( + { + paths, + loaded: SimStore.loadReadOnly(paths), + caller: who, + settings: { advisorModelSelection: null }, + telemetry: [], + }, + { action: "index" }, + ); +} + +function recordRule(paths: SimResolvedPaths, who = author) { + readIndex(paths, who); + return write(paths, who, { + action: "attempt", + input: { + new: "Agents claim done without running the build", + action: "add", + what: "Rule to run the build first", + why: "Two threads claimed done on a red build", + files: ["~/.claude/AGENTS.md"], + anchor: "run the build before you claim done", + depends_on: ["model"], + predicted: ["unverified-done"], + expect: "No done claim without build output", + }, + }); +} + +const observe = ( + paths: SimResolvedPaths, + who: SimCallerContext, + extra: Record = {}, +) => + write(paths, who, { + action: "observe", + input: { + attempt: "A1", + target: "unverified-done", + result: "fixed", + evidence: "the next thread ran the build before claiming done", + source: "log", + ...extra, + }, + }); + +describe("SimStore journal", () => { + it("keeps harness on the event envelope and replays it onto attempts and outcomes", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `# Rules\n- ${RULE}\n`); + recordRule(sb.paths); + observe(sb.paths, reviewer); + + const [attemptEvent, observeEvent] = journal(sb.paths); + expect(attemptEvent?.harness).toBe("codex"); + expect(attemptEvent?.also).toBe("cc:author-native"); + expect(attemptEvent?.data).not.toHaveProperty("harness"); + expect(observeEvent?.harness).toBe("claudeAgent"); + expect(observeEvent?.data.observation).not.toHaveProperty("harness"); + + const { state } = SimStore.load(sb.paths); + const attempt = state.problems[0]!.attempts[0]!; + expect(attempt.harness).toBe("codex"); + expect(attempt.observations[0]?.harness).toBe("claudeAgent"); + expect(attempt.fixed).toEqual(["unverified-done"]); + }); + + it("writes schema-3 sim.json without harness fields, never rewrites on read-only load, and notes hand edits on locked load", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + observe(sb.paths, reviewer); + const written = NodeFS.readFileSync(sb.paths.recordPath, "utf8"); + const parsed = JSON.parse(written) as { + schema: number; + problems: Array<{ attempts: Array> }>; + }; + expect(parsed.schema).toBe(3); + expect(parsed.problems[0]!.attempts[0]).not.toHaveProperty("harness"); + expect( + (parsed.problems[0]!.attempts[0]!.observations as Array>)[0], + ).not.toHaveProperty("harness"); + + // Read-only load replays harness in memory from sim.jsonl without rewriting sim.json on disk. + const edited = JSON.stringify({ ...parsed, problems: [] }); + NodeFS.writeFileSync(sb.paths.recordPath, edited); + const ro = SimStore.loadReadOnly(sb.paths); + expect(ro.healed).toBe(false); + expect(ro.state.problems[0]!.attempts[0]!.harness).toBe("codex"); + expect(NodeFS.readFileSync(sb.paths.recordPath, "utf8")).toBe(edited); + + // Locked load rebuilds a hand-edited schema-3 sim.json and notes it, while an older schema rebuilds silently. + expect(SimStore.load(sb.paths).healed).toBe(true); + expect(NodeFS.readFileSync(sb.paths.recordPath, "utf8")).toBe(written); + + NodeFS.writeFileSync( + sb.paths.recordPath, + JSON.stringify({ ...parsed, schema: 2, problems: [] }), + ); + expect(SimStore.load(sb.paths).healed).toBe(false); + expect(NodeFS.readFileSync(sb.paths.recordPath, "utf8")).toBe(written); + }); + + it("refuses writes after a past line was edited, and restore puts back the last written journal", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + observe(sb.paths, reviewer); + const lines = NodeFS.readFileSync(sb.paths.journalPath, "utf8").split("\n"); + NodeFS.writeFileSync( + sb.paths.journalPath, + [lines[0]!.replace("Two threads", "Ten threads"), ...lines.slice(1)].join("\n"), + ); + + expect(SimStore.load(sb.paths).journal.broken).toMatch(/does not continue the line before it/); + expect(failure(() => observe(sb.paths, reviewer)).code).toBe("journal_broken"); + + const restored = SimStore.restore(sb.paths); + expect(restored.events).toBe(2); + expect(restored.kept && NodeFS.existsSync(restored.kept)).toBe(true); + expect(SimStore.load(sb.paths).journal.broken).toBeNull(); + }); + + it("flags a journal that was cut below what sim.json and the backup hold", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + observe(sb.paths, reviewer); + const first = NodeFS.readFileSync(sb.paths.journalPath, "utf8").split("\n")[0]; + NodeFS.writeFileSync(sb.paths.journalPath, `${first}\n`); + expect(SimStore.load(sb.paths).journal.broken).toMatch(/sim\.json holds 2 events/); + NodeFS.rmSync(sb.paths.recordPath); + expect(SimStore.load(sb.paths).journal.broken).toMatch(/backup sim-.*holds 2 events/); + }); + + it("refuses the same change twice and a backfill of today's own change", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + expect(failure(() => recordRule(sb.paths)).problems.join()).toMatch( + /already in the record as A1/, + ); + const backfill = failure(() => + write(sb.paths, author, { + action: "attempt", + input: { + problem: "P1", + action: "add", + what: "Another rule", + why: "Backfilling my own change", + files: ["~/.claude/AGENTS.md"], + anchor: "run the build before you claim done", + depends_on: ["model"], + predicted: ["unverified-done"], + backfilled: true, + round: SimStore.today(), + }, + }), + ); + expect(backfill.problems.join()).toMatch(/a change made today is recorded as it is/); + }); +}); + +describe("SimStore self-grading", () => { + const cases: Array<[string, SimCallerContext, Record, string | null]> = [ + ["the same session", author, {}, "same session as the change"], + [ + "a session sharing the native cc: id", + caller("other", { alsoSessionId: "cc:author-native" }), + {}, + "same session as the change", + ], + [ + "the same id under the other kind", + { ...caller("x"), sessionId: "cc:author" }, + {}, + "same session as the change", + ], + ["a self-reported source", reviewer, { source: "self" }, "self-reported"], + [ + "an unknown session", + { sessionId: "unknown", model: "gpt-5" }, + {}, + "the reporting session is unknown", + ], + [ + "a fork of the author", + caller("fork", { forkFamilySessionIds: ["t3:author"] }), + {}, + "reported from the fork or side-chat family of the session that made the change", + ], + [ + "a server-detected self grade", + reviewer, + { selfGradeReason: "side chat of the author" }, + "side chat of the author", + ], + ["an unrelated session", reviewer, {}, null], + ]; + + it.each(cases)("a fix reported by %s", (_label, who, extra, reason) => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + const result = observe(sb.paths, who, extra); + expect(result.unconfirmedReason ?? null).toBe(reason); + expect(result.settled).toBe(reason === null); + const recorded = journal(sb.paths)[1]!.data.observation as Record; + if ( + reason !== null && + reason !== "same session as the change" && + reason !== "the reporting session is unknown" + ) { + // Coerced to "self" on disk, so sim.mjs refuses to settle it as well. + expect(recorded.source).toBe("self"); + } + expect(SimStore.load(sb.paths).state.problems[0]!.attempts[0]!.fixed).toEqual( + reason === null ? ["unverified-done"] : [], + ); + }); + + it("preserves the original source when a fork records a non-fixed observation", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + observe(sb.paths, caller("fork", { forkFamilySessionIds: ["t3:author"] }), { + result: "missed", + source: "user", + evidence: "user caught another unverified done claim in a fork", + }); + const recorded = journal(sb.paths)[1]!.data.observation as Record; + expect(recorded.result).toBe("missed"); + expect(recorded.source).toBe("user"); + }); +}); + +describe("classifyHarnessPath", () => { + it("matches sim-gate.mjs for harness directories, project .claude directories, and /var/tmp", () => { + using sb = sandbox(); + const project = NodePath.join(sb.paths.homeDir, "repo"); + const opts = { allowTmp: false }; + expect( + classifyHarnessPath( + NodePath.join(sb.paths.harnessDir, "skills/review/SKILL.md"), + sb.paths, + undefined, + opts, + ), + ).toBe("harness"); + expect( + classifyHarnessPath( + NodePath.join(sb.paths.harnessDir, "agents/critic.md"), + sb.paths, + undefined, + opts, + ), + ).toBe("harness"); + expect( + classifyHarnessPath( + NodePath.join(sb.paths.harnessDir, "commands/check.md"), + sb.paths, + undefined, + opts, + ), + ).toBe("harness"); + expect( + classifyHarnessPath( + NodePath.join(sb.paths.harnessDir, "output-styles/concise.md"), + sb.paths, + undefined, + opts, + ), + ).toBe("harness"); + expect( + classifyHarnessPath( + NodePath.join(sb.paths.harnessDir, "settings.local.json"), + sb.paths, + undefined, + opts, + ), + ).toBe("harness"); + expect( + classifyHarnessPath(NodePath.join(project, ".claude/hooks/check.mjs"), sb.paths, undefined, { + allowTmp: true, + }), + ).toBe("harness"); + expect( + classifyHarnessPath( + NodePath.join(project, ".claude/skills/foo/SKILL.md"), + sb.paths, + undefined, + { allowTmp: true }, + ), + ).toBe("harness"); + expect(classifyHarnessPath("/var/tmp/AGENTS.md", sb.paths, undefined, opts)).toBeNull(); + }); +}); + +describe("SimStore harness inspection", () => { + it("reports Scars and hooks without a record, and drift once a recorded anchor vanishes", () => { + using sb = sandbox(); + sb.harness( + "AGENTS.md", + `# Rules\n\n## Scars\n- Scar: ${RULE}\n- Scar: never push to main without asking.\n`, + ); + sb.harness("hooks/gate.mjs", "export {};\n"); + recordRule(sb.paths); + + const before = SimStore.inspectHarness(SimStore.load(sb.paths).state, sb.paths); + expect(before.drift).toEqual([]); + expect(before.uncovered.map((unit) => unit.text ?? unit.file)).toEqual([ + "- Scar: never push to main without asking.", + "~/.claude/hooks/gate.mjs", + ]); + + sb.harness("AGENTS.md", "# Rules\n\n## Scars\n- Scar: build first.\n"); + const after = SimStore.inspectHarness(SimStore.load(sb.paths).state, sb.paths); + expect(after.drift.map((item) => item.attempt.id)).toEqual(["A1"]); + }); +}); + +describe("SimStore seen tracking", () => { + const read = (paths: SimResolvedPaths, who: SimCallerContext, ids?: Array) => + SimStore.runRead( + { + paths, + loaded: SimStore.load(paths), + caller: who, + settings: { advisorModelSelection: null }, + telemetry: [], + }, + ids ? { action: "show", ids } : { action: "brief_all" }, + ); + + it("counts an entry shown in parts only once every part was shown", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + const { state } = SimStore.load(sb.paths); + const problem = state.problems[0]!; + const scope = SimStore.seenScope(sb.paths, reviewer); + SimStore.markShown(sb.paths, state, [{ problem, from: 0, to: 40, of: 100 }], "full", scope); + SimStore.markShown(sb.paths, state, [{ problem, from: 60, to: 100, of: 100 }], "full", scope); + expect(SimStore.shownTo(sb.paths, state, scope).has("P1")).toBe(false); + SimStore.markShown(sb.paths, state, [{ problem, from: 35, to: 65, of: 100 }], "full", scope); + expect(SimStore.shownTo(sb.paths, state, scope).get("P1")).toBe("full"); + }); + + it("asks a new root cause for the whole record in brief and its closest entries in full", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n- Always quote the failing build output.\n`); + recordRule(sb.paths); + const newCause = () => + write(sb.paths, reviewer, { + action: "attempt", + input: { + new: "Agents paraphrase the failing build output instead of quoting it", + action: "add", + what: "Rule to quote the failing build output", + why: "Paraphrased errors hid the real cause", + files: ["~/.claude/AGENTS.md"], + anchor: "quote the failing build output", + depends_on: ["model"], + predicted: ["paraphrased-build-errors"], + expect: "Build errors appear verbatim", + }, + }); + const unseen = failure(newCause); + expect(unseen.code).toBe("seen_required"); + expect(unseen.problems.join("\n")).toMatch(/read this entry in full first: .*P1/); + read(sb.paths, reviewer); + expect(failure(newCause).problems.join("\n")).toMatch(/shares words with your change/); + read(sb.paths, reviewer, ["P1"]); + expect(newCause().problemId).toBe("P2"); + }); + + it("voids readings from before a compaction, across reloads and for the native session too", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + const reader = caller("reader", { alsoSessionId: "cc:reader-native" }); + const continueP1 = () => + write(sb.paths, reader, { + action: "amend", + target: "A1", + field: "why", + value: "Two threads claimed done on a red build, seen twice", + reason: "more evidence", + }); + read(sb.paths, reader, ["P1"]); + const nativeLog = NodePath.join( + sb.paths.seenDir, + `${SimStore.sha("cc:reader-native").slice(0, 16)}.json`, + ); + const preCompaction = NodeFS.readFileSync(nativeLog, "utf8"); + expect(JSON.parse(preCompaction).full.P1).toBeTypeOf("string"); + + expect(SimStore.resetThreadSeenEpoch(sb.paths, "reader", ["cc:reader-native"])).toBe(1); + expect(SimStore.getThreadSeenEpoch(sb.paths, "reader")).toBe(1); + // A log from the old context put back (or written late) must not count either. + NodeFS.writeFileSync(nativeLog, preCompaction); + const scope = SimStore.seenScope(sb.paths, reader); + expect(SimStore.shownTo(sb.paths, SimStore.load(sb.paths).state, scope).size).toBe(0); + expect(failure(continueP1).code).toBe("seen_required"); + + read(sb.paths, reader, ["P1"]); + expect(JSON.parse(NodeFS.readFileSync(nativeLog, "utf8")).t3_epoch).toBe(1); + expect(continueP1().text).toBe("amended A1."); + }); + + it("requires index or by_file in the current epoch before recording an attempt, even after show P1", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n- Always quote build errors.\n- Never force push.\n`); + recordRule(sb.paths); + // Add a second problem so show P1 alone does not cover the entire record. + read(sb.paths, author); + read(sb.paths, author, ["P1"]); + write(sb.paths, author, { + action: "attempt", + input: { + new: "Agents force push shared feature branches without consent", + action: "add", + what: "Forbid force push", + why: "Lost reviewer commits", + files: ["~/.claude/AGENTS.md"], + anchor: "Never force push.", + depends_on: ["user"], + predicted: ["force-push-loss"], + expect: "No force pushes", + }, + }); + const other = caller("other-reader"); + read(sb.paths, other, ["P1"]); + const revise = () => + write(sb.paths, other, { + action: "attempt", + input: { + problem: "P1", + action: "revise", + supersedes: ["A1"], + what: "Tighten build rule", + why: "Still missed once", + files: ["~/.claude/AGENTS.md"], + anchor: "Always quote build errors.", + depends_on: ["model"], + predicted: ["unverified-done"], + expect: "Build output quoted", + }, + }); + const missingIndex = failure(revise); + expect(missingIndex.code).toBe("seen_required"); + expect(missingIndex.problems.join("\n")).toMatch(/index.*by_file/); + + SimStore.runRead( + { + paths: sb.paths, + loaded: SimStore.loadReadOnly(sb.paths), + caller: other, + settings: { advisorModelSelection: null }, + telemetry: [], + }, + { action: "by_file", file: "~/.claude/AGENTS.md" }, + ); + expect(revise().attemptId).toBe("A3"); + }); + + it("persists active providerThreadId across reloads and bumps the epoch when it switches", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n`); + recordRule(sb.paths); + const reader = caller("restart-reader", { alsoSessionId: "cc:old-native" }); + readIndex(sb.paths, reader); + read(sb.paths, reader, ["P1"]); + + expect( + SimStore.trackProviderThread(sb.paths, "restart-reader", "pt-1", ["cc:old-native"]), + ).toBe(false); + expect(SimStore.getThreadSeenEpoch(sb.paths, "restart-reader")).toBe(0); + // Same provider thread after a simulated restart does not reset. + expect( + SimStore.trackProviderThread(sb.paths, "restart-reader", "pt-1", ["cc:old-native"]), + ).toBe(false); + expect(SimStore.getThreadSeenEpoch(sb.paths, "restart-reader")).toBe(0); + + // Switching provider thread after a restart resets the epoch and clears prior readings. + expect(SimStore.trackProviderThread(sb.paths, "restart-reader", "pt-2", [])).toBe(true); + expect(SimStore.getThreadSeenEpoch(sb.paths, "restart-reader")).toBe(1); + const scope = SimStore.seenScope(sb.paths, reader); + expect(SimStore.shownTo(sb.paths, SimStore.loadReadOnly(sb.paths).state, scope).size).toBe(0); + }); +}); + +describe("SimStore review and escalation", () => { + const advisor = { + advisorModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-fable-5-2", + }, + }; + + it("reviews live rules under the newest carried model and harness, failures first", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n- Always quote the failing build output.\n`); + recordRule(sb.paths); + SimStore.runRead( + { + paths: sb.paths, + loaded: SimStore.load(sb.paths), + caller: author, + settings: advisor, + telemetry: [], + }, + { action: "show", ids: ["P1"] }, + ); + write(sb.paths, author, { + action: "attempt", + input: { + problem: "P1", + action: "add", + what: "Rule to quote the failing build output", + why: "Paraphrased errors hid the real cause", + files: ["~/.claude/AGENTS.md"], + anchor: "quote the failing build output", + depends_on: ["user"], + predicted: ["paraphrased-build-errors"], + expect: "Build errors appear verbatim", + }, + }); + write(sb.paths, author, { + action: "carry", + fromPolicy: "gpt-5", + toPolicy: "gpt-6", + fromHarness: "codex", + toHarness: "codex", + }); + write(sb.paths, caller("tester", { model: "gpt-6" }), { + action: "observe", + input: { + attempt: "A2", + target: "paraphrased-build-errors", + result: "missed", + evidence: "gpt-6 paraphrased the error again", + source: "user", + }, + }); + const review = SimStore.renderReview(SimStore.load(sb.paths).state, {}); + const rows = review.split("\n").filter((line) => /^A\d/.test(line)); + expect(review).toMatch(/under gpt-6 on codex: 2 \(1 with a failure/); + expect(rows.map((row) => row.split(" ")[0])).toEqual(["A2", "A1"]); + }); + + it("escalates recurring failures, cross-harness conflicts, unseen models and repeated drift only when an advisor is set", () => { + using sb = sandbox(); + sb.harness("AGENTS.md", `- ${RULE}\n- Always quote the failing build output.\n`); + recordRule(sb.paths); + observe(sb.paths, reviewer); + observe(sb.paths, caller("codex-user"), { + result: "missed", + evidence: "codex claimed done on a red build again", + }); + const { state } = SimStore.load(sb.paths); + const telemetry = [ + { + ts: "2026-11-10T00:00:00Z", + kind: "new_model_observed" as const, + providerInstanceId: "antigravity", + model: "gemini-4", + }, + { + ts: "2026-11-10T00:00:00Z", + kind: "new_model_observed" as const, + providerInstanceId: "codex", + model: "gpt-5", + }, + { + ts: "2026-11-10T00:00:00Z", + kind: "unrecorded_harness_edit" as const, + threadId: "t", + files: ["~/.claude/AGENTS.md"], + }, + ]; + const health = { drift: [{ attempt: state.problems[0]!.attempts[0]!, reason: "gone" }] }; + const escalation = SimStore.buildAdvisorEscalation(state, advisor, health, telemetry); + expect(escalation?.candidates.map((candidate) => candidate.kind)).toEqual([ + "cross_harness_conflict", + "new_model_generation", + "repeated_drift", + ]); + expect(escalation?.guidance).toMatch( + /delegate_task with role "design" and target \{"providerInstanceId":"claudeAgent","model":"claude-fable-5-2"\}/, + ); + expect(escalation?.guidance).not.toContain("modelSelection"); + expect( + SimStore.buildAdvisorEscalation(state, { advisorModelSelection: null }, health, telemetry), + ).toBeUndefined(); + expect( + SimStore.buildAdvisorEscalation(state, advisor, { drift: [] }, [])?.candidates.map( + (c) => c.kind, + ), + ).toEqual(["cross_harness_conflict"]); + + // index and check never attach advisorEscalation; review does. + const readCtx = { + paths: sb.paths, + loaded: SimStore.loadReadOnly(sb.paths), + caller: reviewer, + settings: advisor, + telemetry, + }; + expect(SimStore.runRead(readCtx, { action: "index" }).advisorEscalation).toBeUndefined(); + expect(SimStore.runRead(readCtx, { action: "check" }).advisorEscalation).toBeUndefined(); + expect( + SimStore.runRead(readCtx, { action: "review", policy: "gpt-5" }).advisorEscalation?.candidates + .length, + ).toBeGreaterThan(0); + + // Once a superseding live attempt fixes the problem with no failures, recurring_failures stays quiet. + readIndex(sb.paths, author); + SimStore.runRead({ ...readCtx, caller: author }, { action: "show", ids: ["P1"] }); + write(sb.paths, author, { + action: "attempt", + input: { + problem: "P1", + action: "revise", + supersedes: ["A1"], + what: "Tighten build verification rule", + why: "A1 missed under codex", + files: ["~/.claude/AGENTS.md"], + anchor: "Always quote the failing build output.", + depends_on: ["user"], + predicted: ["unverified-done"], + expect: "Verified every run", + }, + }); + observe(sb.paths, caller("codex-user"), { + attempt: "A2", + result: "missed", + evidence: "A2 missed once too before A3", + }); + expect( + SimStore.buildAdvisorEscalation( + SimStore.loadReadOnly(sb.paths).state, + advisor, + { drift: [] }, + [], + )?.candidates.map((c) => c.kind), + ).toContain("recurring_failures"); + sb.harness( + "AGENTS.md", + `- ${RULE}\n- Always quote the failing build output.\n- Paste build exit code.\n`, + ); + readIndex(sb.paths, author); + SimStore.runRead( + { ...readCtx, loaded: SimStore.loadReadOnly(sb.paths), caller: author }, + { action: "show", ids: ["P1"] }, + ); + write(sb.paths, author, { + action: "attempt", + input: { + problem: "P1", + action: "revise", + supersedes: ["A2"], + what: "Require exit code", + why: "A2 still missed", + files: ["~/.claude/AGENTS.md"], + anchor: "Paste build exit code.", + depends_on: ["user"], + predicted: ["unverified-done"], + expect: "Exit code pasted", + }, + }); + observe(sb.paths, reviewer, { + attempt: "A3", + result: "fixed", + evidence: "A3 fixed the issue cleanly", + }); + expect( + SimStore.buildAdvisorEscalation( + SimStore.loadReadOnly(sb.paths).state, + advisor, + { drift: [] }, + [], + ), + ).toBeUndefined(); + }); +}); + +describe("SimStore telemetry", () => { + it("trims the telemetry file to its newest lines once it grows past its cap", () => { + using sb = sandbox(); + const event = (index: number) => ({ + ts: "2026-11-10T00:00:00Z", + kind: "checkpoint_rollback" as const, + threadId: `thread-${index}`, + checkpointId: `checkpoint-${"x".repeat(200)}-${index}`, + }); + for (let index = 0; index < 2_100; index += 1) SimStore.appendTelemetry(sb.paths, event(index)); + const kept = SimStore.readTelemetry(sb.paths); + expect(kept.length).toBeLessThanOrEqual(2_000); + expect(kept[kept.length - 1]).toEqual(event(2_099)); + expect(SimStore.readTelemetry(sb.paths, Date.parse("2026-11-11T00:00:00Z"))).toEqual([]); + }); +}); diff --git a/apps/server/src/sim/SimStore.ts b/apps/server/src/sim/SimStore.ts new file mode 100644 index 0000000000000..2fb0cb375b949 --- /dev/null +++ b/apps/server/src/sim/SimStore.ts @@ -0,0 +1,3382 @@ +// @effect-diagnostics nodeBuiltinImport:off globalDate:off - a synchronous port of sim.mjs that shares its files and clock-based stamps. +// Port of the standalone ~/.claude/sim/sim.mjs (journal format v2). Both tools share one +// directory, so every journal line written here must replay unchanged in sim.mjs: harness +// lives on the event envelope, never in `data` of attempt/observe. Functions that write the +// journal or sim.json expect the caller to hold sim.lock (see tryLock). +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { + SIM_DEFAULT_PAGE_CHARS, + SIM_DEPENDS, + SIM_FORMAT, + SIM_FULL_BUDGET, + SIM_GENESIS, + SIM_INDEX_BUDGET, + SIM_LINK_INVERSE, + SIM_NAME_LIMIT, + SIM_RESULTS, + SIM_SCHEMA, + SIM_SOURCES, + SIM_TEXT_LIMIT, + SIM_UNKNOWN, + SIM_ACTIONS, + SimServiceError, + canonicalHarnessFile, + expandHarnessFile, + expandHomeString, + isPathWithinRoot, + type SimAdvisorEscalation, + type SimAdvisorEscalationCandidate, + type SimApplyHarnessChangeRequest, + type SimApplyHarnessChangeResult, + type SimAttempt, + type SimAttemptInput, + type SimCallerContext, + type SimCarrySide, + type SimErrorCode, + type SimJournalEvent, + type SimJournalOp, + type SimLinkKind, + type SimObservation, + type SimObserveInput, + type SimProblem, + type SimReadRequest, + type SimReadResult, + type SimResolvedPaths, + type SimSettingsConfig, + type SimState, + type SimTelemetryEvent, + type SimWriteRequest, + type SimWriteResult, +} from "./SimContracts.ts"; + +type Data = Record; + +const NEEDS_PREDICTED = ["fixed", "missed"]; +const FAILURE_RESULTS = ["missed", "regressed", "misfired"]; +const AMENDABLE = { + problem: ["name"], + always: ["what", "why", "anchor", "files", "depends_on"], + beforeOutcome: ["expect", "policy", "domain"], + backfilledBeforeOutcome: ["round", "sample", "predicted"], +}; +const RELATED_LIMIT = 3; +const RELATED_FLOOR = 0.5; +const RELATED_LENGTH = 0.5; +const SEEN_DAYS = 14; +const SITTING_MINUTES = 60; +const KEPT_BACKUPS = 14; +const FAIL_CHARS = 8000; +const BACKUP_NAME = /^sim-\d{4}-\d{2}-\d{2}\.jsonl$/; +const SLUG = /^[a-z0-9]+(-[a-z0-9]+)*$/; +const BACKED_UP_TOOLS = ["sim.mjs", "sim.test.mjs", "sim-audit.mjs"]; + +const SIM_LOCK_STALE_MS = 30_000; +export const SIM_LOCK_WAIT_MS = 15_000; +export const SIM_LOCK_POLL_MS = 40; +const TELEMETRY_MAX_LINES = 2_000; +const TELEMETRY_MAX_BYTES = 512 * 1024; +const TELEMETRY_KEEP_LINES = 1_000; + +const fail = (code: SimErrorCode, problems: string | ReadonlyArray) => + new SimServiceError({ + code, + problems: typeof problems === "string" ? [problems] : [...problems], + }); +const invalid = (problems: string | ReadonlyArray) => fail("validation", problems); + +export const sha = (text: string | Uint8Array) => + NodeCrypto.createHash("sha256").update(text).digest("hex"); +const squash = (text: unknown) => String(text).replace(/\s+/g, " ").trim(); +const isText = (value: unknown, min = 1): value is string => + typeof value === "string" && value.trim().length >= min; +const isList = (value: unknown): value is Array => + Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim().length > 0); +const idNumber = (id: string) => Number(String(id).slice(1)); +const count = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`; +const estimateTokens = (text: string) => Math.ceil(text.length / 3.5); +const asData = (value: unknown): Data => + value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Data) : {}; + +/** Root causes count as the same text when only case, spacing or a final period differ. */ +const sameName = (name: unknown) => squash(name).replace(/[.]+$/, "").toLowerCase(); + +export function today(): string { + const now = new Date(); + const pad = (n: number) => String(n).padStart(2, "0"); + return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`; +} + +function isDate(value: unknown): value is string { + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false; + const parsed = new Date(`${value}T00:00:00Z`); + return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value; +} + +/** A session id without the kind in front, so that "cc:abc" and "abc" name the same session. */ +export const bare = (id: string) => String(id).replace(/^(cc|t3):/, ""); + +const canonicalFile = (file: unknown, paths: SimResolvedPaths) => + canonicalHarnessFile(String(file), paths); + +/** A SIM dir under the OS temp dir is a test sandbox: its harness files may live there too. */ +export function isTestSimDir(paths: Pick): boolean { + const rel = NodePath.relative(NodeOS.tmpdir(), paths.simDir); + return rel !== "" && !rel.startsWith("..") && !NodePath.isAbsolute(rel); +} + +/** The harness a record was made under; Claude Code sessions recorded by sim.mjs carry none. */ +const effectiveHarness = (record: { + readonly harness?: string | undefined; + readonly by: string; +}): string | undefined => + record.harness ?? (record.by.startsWith("cc:") ? "claudeAgent" : undefined); + +function emptyState(): SimState { + return { + schema: SIM_SCHEMA, + next_id: 1, + next_attempt: 1, + events: 0, + head: SIM_GENESIS, + carried_from: [], + aliases: {}, + problems: [], + }; +} + +function resolveId(state: SimState, id: string): string { + const seen = new Set(); + let current = id; + while (state.aliases[current]) { + if (seen.has(current)) throw invalid(`alias loop at ${current}`); + seen.add(current); + current = state.aliases[current]!; + } + return current; +} + +function findProblem(state: SimState, id: unknown): SimProblem | null { + const resolved = resolveId(state, String(id).trim()); + return state.problems.find((problem) => problem.id === resolved) ?? null; +} + +export function findAttempt( + state: SimState, + attemptId: unknown, +): { problem: SimProblem; attempt: SimAttempt } | null { + const wanted = String(attemptId).trim(); + for (const problem of state.problems) { + const attempt = problem.attempts.find((item) => item.id === wanted); + if (attempt) return { problem, attempt }; + } + return null; +} + +/** The entry that has this root cause, now or under an earlier wording. */ +function problemNamed( + state: SimState, + name: unknown, + except: string | null = null, +): SimProblem | null { + const wanted = sameName(name); + return ( + state.problems.find( + (item) => + item.id !== except && + (sameName(item.name) === wanted || + item.former_names.some((old) => sameName(old) === wanted)), + ) ?? null + ); +} + +export const allAttempts = (state: SimState) => + state.problems.flatMap((problem) => problem.attempts); + +function supersededBy(state: SimState, attemptId: string): string | null { + const later = allAttempts(state).find( + (item) => item.accepted && !item.retracted && item.supersedes.includes(attemptId), + ); + return later ? later.id : null; +} + +const standing = (attempt: SimAttempt) => attempt.observations.filter((obs) => !obs.retracted); + +const FORK_FAMILY_REASON = + "reported from the fork or side-chat family of the session that made the change"; + +/** True when one of these sessions made or recorded the attempt, compared with and without `cc:`/`t3:`. */ +function sharesFamily( + attempt: Pick, + sessionIds: ReadonlyArray, +): boolean { + const authors = [attempt.by, attempt.also, attempt.sample].filter( + (id): id is string => !!id && id !== SIM_UNKNOWN, + ); + return sessionIds.some((id) => + authors.some((author) => id === author || bare(id) === bare(author)), + ); +} + +/** + * Why a reported fix cannot settle the prediction, or null when it can. Matches sim.mjs and also + * compares session ids without their `cc:`/`t3:` kind, plus the caller's fork/side-chat family. + */ +function ownReport( + attempt: Pick, + obs: Pick, + forkFamilySessionIds?: ReadonlyArray, +): string | null { + const names = (record: { readonly by: string; readonly also?: string | undefined }) => + [record.by, record.also].filter((id): id is string => !!id && id !== SIM_UNKNOWN); + const same = (a: string, b: string) => a === b || bare(a) === bare(b); + if (obs.source === "self") return "self-reported"; + if (obs.by === SIM_UNKNOWN) return "the reporting session is unknown"; + const reporters = names(obs); + if (reporters.some((id) => names(attempt).some((author) => same(id, author)))) { + return attempt.backfilled + ? "reported by the session that recorded the change" + : "same session as the change"; + } + if (attempt.sample !== SIM_UNKNOWN && reporters.some((id) => same(id, attempt.sample))) { + return "same session as the change"; + } + if (forkFamilySessionIds && sharesFamily(attempt, forkFamilySessionIds)) + return FORK_FAMILY_REASON; + if (attempt.by === SIM_UNKNOWN) return "the session that recorded the change is unknown"; + return null; +} + +const settlesFix = (attempt: SimAttempt, obs: SimObservation) => + obs.result === "fixed" && !ownReport(attempt, obs); + +const ATTEMPT_FIELDS = [ + "problem", + "new", + "action", + "what", + "why", + "files", + "anchor", + "supersedes", + "depends_on", + "predicted", + "expect", + "policy", + "domain", + "accepted", + "rejected_because", + "unanswered", + "considered", + "backfilled", + "round", + "sample", + "observations", +]; +const OBSERVE_FIELDS = ["target", "result", "evidence", "source", "policy", "domain", "date"]; +// Replay tolerates a legacy `harness` key in data; T3 itself only ever writes it on the envelope. +const LEGACY_DATA_FIELDS = ["harness"]; + +function unknownFields( + input: Data, + allowed: ReadonlyArray, + errors: Array, + label: string, +) { + const extra = Object.keys(input).filter( + (key) => !allowed.includes(key) && !LEGACY_DATA_FIELDS.includes(key), + ); + if (extra.length) { + errors.push( + `${label}: unknown field${extra.length === 1 ? "" : "s"} ${extra.join(", ")} (allowed: ${allowed.join(", ")})`, + ); + } +} + +function tooLong(value: unknown, limit: number, label: string, errors: Array) { + if (typeof value === "string" && value.trim().length > limit) { + errors.push( + `${label} has ${value.trim().length} characters; the limit is ${limit}. Say it shorter: every later session reads it`, + ); + } +} + +interface EventContext { + readonly seq: number; + readonly day: string; + readonly by: string; + readonly also: string | null; + readonly harness: string | null; +} + +function validateObservation( + attempt: SimAttempt, + raw: unknown, + errors: Array, + label: string, + day: string, + historic: boolean, +) { + const obs = asData(raw); + unknownFields(obs, historic ? [...OBSERVE_FIELDS, "sample"] : OBSERVE_FIELDS, errors, label); + if (!SIM_RESULTS.includes(obs.result as never)) { + errors.push(`${label}: result must be one of ${SIM_RESULTS.join(", ")}`); + } + if (!SIM_SOURCES.includes(obs.source as never)) { + errors.push(`${label}: source must be one of ${SIM_SOURCES.join(", ")}`); + } + if (!isText(obs.evidence, 10)) + errors.push(`${label}: evidence is required (what was seen, and where)`); + tooLong(obs.evidence, SIM_TEXT_LIMIT, `${label}: evidence`, errors); + if (!isText(obs.policy)) + errors.push(`${label}: policy is required (the model the outcome was seen under)`); + if (!isText(obs.domain)) errors.push(`${label}: domain is required (the project, or "global")`); + if (historic && obs.sample !== undefined && !isText(obs.sample)) { + errors.push(`${label}: sample must name the session that saw the outcome, or be left out`); + } + if (!isDate(obs.date)) errors.push(`${label}: date must be YYYY-MM-DD`); + else if (isDate(attempt.round) && obs.date < attempt.round) { + errors.push(`${label}: date ${obs.date} is before the change it judges (${attempt.round})`); + } else if (historic && obs.date >= day) { + errors.push( + `${label}: an outcome inside a backfilled record must lie before today; record a new one with observe`, + ); + } else if (obs.date > day) { + errors.push(`${label}: date ${obs.date} is in the future`); + } + if (obs.result === "kept") return; + if (!isText(obs.target) || !SLUG.test(obs.target)) { + errors.push(`${label}: target must be a kebab-case slug`); + } else if ( + NEEDS_PREDICTED.includes(String(obs.result)) && + !attempt.predicted.includes(obs.target) + ) { + errors.push( + `${label}: "${obs.target}" is not a predicted target of ${attempt.id} (${attempt.predicted.join(", ") || "none"}); use regressed, misfired or inconclusive for an effect that was not predicted`, + ); + } +} + +function cleanObservation( + raw: Data, + sample: string, + ctx: EventContext, + harness: string | null, +): SimObservation { + const obs: SimObservation = { + date: String(raw.date), + result: raw.result as SimObservation["result"], + evidence: String(raw.evidence).trim(), + source: raw.source as SimObservation["source"], + policy: String(raw.policy).trim(), + domain: String(raw.domain).trim(), + sample, + by: ctx.by, + }; + if (harness) obs.harness = harness; + if (ctx.also) obs.also = ctx.also; + if (raw.result !== "kept") obs.target = String(raw.target); + return obs; +} + +const legacyHarness = (data: Data) => (isText(data.harness) ? data.harness.trim() : null); + +function applyAttempt(state: SimState, data: unknown, ctx: EventContext, paths: SimResolvedPaths) { + const errors: Array = []; + const input = asData(data); + unknownFields(input, ATTEMPT_FIELDS, errors, "attempt"); + const accepted = input.accepted !== false; + const backfilled = input.backfilled === true; + const hasProblem = isText(input.problem); + const hasNew = isText(input.new); + + if (hasProblem === hasNew) { + errors.push('give exactly one of "problem" (an existing P-id) or "new" (a new root cause)'); + } + let problem: SimProblem | null = null; + if (isText(input.problem)) { + problem = findProblem(state, input.problem.trim()); + if (!problem) errors.push(`problem ${input.problem} does not exist`); + } + if (hasNew && squash(input.new).split(" ").length < 3) { + errors.push('"new" must state the root cause as a sentence, not a label'); + } + if (hasNew) tooLong(input.new, SIM_NAME_LIMIT, "the root cause", errors); + if (!SIM_ACTIONS.includes(input.action as never)) { + errors.push(`action must be one of ${SIM_ACTIONS.join(", ")}`); + } + if (!isText(input.what)) errors.push("what is required (the change itself)"); + if (!isText(input.why)) errors.push("why is required (the reason for this change)"); + for (const field of ["what", "why", "expect", "rejected_because"]) { + tooLong(input[field], SIM_TEXT_LIMIT, field, errors); + } + if (!isText(input.policy)) + errors.push("policy is required (the model the failure was seen under)"); + if (!isText(input.domain)) errors.push('domain is required (the project, or "global")'); + + if (backfilled) { + if (!isDate(input.round)) + errors.push("round must be YYYY-MM-DD (the day the old change was made)"); + else if (input.round > ctx.day) errors.push(`round ${input.round} is in the future`); + if (input.sample !== undefined && !isText(input.sample)) { + errors.push("sample must name the session that made the change, or be left out"); + } + } else { + if (input.round !== undefined || input.sample !== undefined) { + errors.push( + 'round and sample are set by the tool; only the record of an old change ("backfilled": true) names them', + ); + } + if (input.observations !== undefined) { + errors.push( + "outcomes cannot be recorded together with the change; record them later with observe", + ); + } + if (input.considered === undefined) { + errors.push( + "considered is required: the entries you read in full before this change ([] when none relates)", + ); + } + } + const considered = input.considered === undefined ? [] : input.considered; + if (!Array.isArray(considered) || considered.some((id) => !isText(id))) { + errors.push("considered must be a list of entry ids"); + } else { + for (const id of considered as Array) { + if (!findProblem(state, id.trim())) errors.push(`considered: ${id} does not exist`); + } + } + + const supersedes = input.supersedes === undefined ? [] : input.supersedes; + if (!Array.isArray(supersedes) || supersedes.some((id) => !isText(id))) { + errors.push("supersedes must be a list of attempt ids"); + } + const predicted = input.predicted === undefined ? [] : input.predicted; + if (!Array.isArray(predicted) || predicted.some((slug) => !isText(slug) || !SLUG.test(slug))) { + errors.push("predicted must be a list of kebab-case target slugs"); + } + const files = input.files === undefined ? [] : input.files; + if (!Array.isArray(files) || files.some((file) => !isText(file))) { + errors.push("files must be a list of paths"); + } + const supersedesList = Array.isArray(supersedes) ? (supersedes as Array) : []; + + const unanswered = input.unanswered === true; + if (accepted) { + if (unanswered || input.rejected_because !== undefined) { + errors.push( + 'rejected_because and unanswered belong to a proposal that was not carried out ("accepted": false)', + ); + } + if (!Array.isArray(files) || !files.length) + errors.push("files is required (where the change lives)"); + if (input.action !== "remove") { + if (!isText(input.anchor, 6)) { + errors.push("anchor is required (a phrase that identifies the rule in one of the files)"); + } + const depends = input.depends_on; + if ( + !Array.isArray(depends) || + !depends.length || + depends.some((item) => !SIM_DEPENDS.includes(item as never)) + ) { + errors.push(`depends_on must list one or more of ${SIM_DEPENDS.join(", ")}`); + } + if (Array.isArray(predicted) && !predicted.length) { + errors.push("predicted is required (the failures this change should stop)"); + } + if (!backfilled && !isText(input.expect)) { + errors.push("expect is required (what will count as fixed, and what as missed)"); + } + if (input.action === "add" && supersedesList.length) { + errors.push('an "add" supersedes nothing; use revise or replace'); + } + if ((input.action === "revise" || input.action === "replace") && !supersedesList.length) { + errors.push(`a ${input.action} must name the attempt it changes in supersedes`); + } + } + for (const id of supersedesList) { + const hit = findAttempt(state, id); + if (!hit) errors.push(`supersedes: ${id} does not exist`); + else if (!hit.attempt.accepted || hit.attempt.retracted || hit.attempt.action === "remove") { + errors.push(`supersedes: ${id} is not a mechanism`); + } else if (supersededBy(state, hit.attempt.id)) { + errors.push( + `supersedes: ${id} is no longer live (changed by ${supersededBy(state, hit.attempt.id)})`, + ); + } + } + } else if (unanswered === isText(input.rejected_because)) { + errors.push( + 'a proposal that was not carried out needs exactly one of "rejected_because" (why it was turned down) or "unanswered": true (nobody decided)', + ); + } + if (errors.length) throw invalid(errors); + + const harness = ctx.harness ?? legacyHarness(input); + const attempt = { + id: `A${state.next_attempt}`, + round: backfilled ? String(input.round) : ctx.day, + sample: backfilled ? (isText(input.sample) ? input.sample.trim() : SIM_UNKNOWN) : ctx.by, + by: ctx.by, + accepted, + backfilled, + action: input.action as SimAttempt["action"], + what: String(input.what).trim(), + why: String(input.why).trim(), + files: (files as Array).map((file) => canonicalFile(file, paths)), + anchor: accepted && input.action !== "remove" ? String(input.anchor).trim() : null, + supersedes: supersedesList.map((id) => id.trim()), + depends_on: Array.isArray(input.depends_on) + ? [...(input.depends_on as Array)] + : [], + predicted: [...(predicted as Array)], + expect: isText(input.expect) ? input.expect.trim() : null, + policy: String(input.policy).trim(), + domain: String(input.domain).trim(), + ...(harness ? { harness } : {}), + considered: (considered as Array).map((id) => id.trim()), + observations: [], + } as unknown as SimAttempt; + if (ctx.also) attempt.also = ctx.also; + if (backfilled) attempt.recorded = { by: ctx.by, day: ctx.day }; + if (!accepted && unanswered) attempt.unanswered = true; + if (!accepted && !unanswered) attempt.rejected_because = String(input.rejected_because).trim(); + + if (backfilled && input.observations !== undefined) { + if (!Array.isArray(input.observations)) throw invalid("observations must be a list"); + if (!accepted) throw invalid("a proposal that was not carried out has no outcomes"); + input.observations.forEach((raw, index) => + validateObservation(attempt, raw, errors, `observations[${index}]`, ctx.day, true), + ); + if (errors.length) throw invalid(errors); + attempt.observations = input.observations.map((raw) => { + const obs = asData(raw); + return cleanObservation( + obs, + isText(obs.sample) ? obs.sample.trim() : SIM_UNKNOWN, + ctx, + harness, + ); + }); + } + + let created = false; + if (!problem) { + problem = problemNamed(state, input.new); + if (!problem) { + problem = { + id: `P${state.next_id}`, + name: squash(input.new), + opened_round: attempt.round, + former_names: [], + related: [], + attempts: [], + }; + state.next_id += 1; + state.problems.push(problem); + created = true; + } + } + state.next_attempt += 1; + problem.attempts.push(attempt); + sortAttempts(problem); + return { problem: problem.id, attempt: attempt.id, created }; +} + +function sortAttempts(problem: SimProblem) { + problem.attempts.sort((a, b) => + a.round === b.round ? idNumber(a.id) - idNumber(b.id) : a.round < b.round ? -1 : 1, + ); + problem.opened_round = problem.attempts.reduce( + (first, item) => (item.round < first ? item.round : first), + problem.attempts[0]!.round, + ); +} + +function applyObserve(state: SimState, data: unknown, ctx: EventContext) { + const input = asData(data); + const hit = isText(input.attempt) ? findAttempt(state, input.attempt.trim()) : null; + if (!hit) throw invalid(`attempt ${String(input.attempt)} does not exist`); + if (!hit.attempt.accepted) { + throw invalid(`${hit.attempt.id} was a proposal that was not carried out; it has no outcomes`); + } + if (hit.attempt.retracted) throw invalid(`${hit.attempt.id} was retracted; it has no outcomes`); + const raw: Data = { ...asData(input.observation) }; + const errors: Array = []; + if (raw.sample !== undefined) { + errors.push("observation: sample is set by the tool (the session that reports the outcome)"); + delete raw.sample; + } + if (raw.date === undefined) raw.date = ctx.day; + validateObservation(hit.attempt, raw, errors, "observation", ctx.day, false); + if (errors.length) throw invalid(errors); + hit.attempt.observations.push( + cleanObservation(raw, ctx.by, ctx, ctx.harness ?? legacyHarness(raw)), + ); + return { problem: hit.problem.id, attempt: hit.attempt.id }; +} + +function mergeProblems(state: SimState, from: SimProblem, into: SimProblem) { + into.attempts.push(...from.attempts); + sortAttempts(into); + if (sameName(from.name) !== sameName(into.name)) into.former_names.push(from.name); + into.former_names.push(...from.former_names); + for (const link of from.related) { + if ( + resolveId(state, link.id) !== into.id && + !into.related.some((item) => item.id === link.id && item.kind === link.kind) + ) { + into.related.push(link); + } + } + into.related = into.related.filter((link) => link.id !== from.id); + state.aliases[from.id] = into.id; + state.problems = state.problems.filter((problem) => problem.id !== from.id); +} + +function applyMerge(state: SimState, data: unknown) { + const input = asData(data); + const from = isText(input.from) ? findProblem(state, input.from.trim()) : null; + const into = isText(input.into) ? findProblem(state, input.into.trim()) : null; + const errors: Array = []; + if (!from) errors.push(`problem ${String(input.from)} does not exist`); + if (!into) errors.push(`problem ${String(input.into)} does not exist`); + if (from && into && from.id === into.id) errors.push("cannot merge an entry into itself"); + if (errors.length || !from || !into) throw invalid(errors); + mergeProblems(state, from, into); + return { problem: into.id, merged: from.id }; +} + +function applyLink(state: SimState, data: unknown) { + const input = asData(data); + const a = isText(input.a) ? findProblem(state, input.a.trim()) : null; + const b = isText(input.b) ? findProblem(state, input.b.trim()) : null; + const errors: Array = []; + if (!a) errors.push(`problem ${String(input.a)} does not exist`); + if (!b) errors.push(`problem ${String(input.b)} does not exist`); + if (a && b && a.id === b.id) errors.push("cannot link an entry to itself"); + const kind = input.kind as SimLinkKind; + if (typeof input.kind !== "string" || !Object.hasOwn(SIM_LINK_INVERSE, input.kind)) { + errors.push(`kind must be one of ${Object.keys(SIM_LINK_INVERSE).join(", ")}`); + } + if (errors.length || !a || !b) throw invalid(errors); + const add = (problem: SimProblem, id: string, linkKind: SimLinkKind) => { + if (!problem.related.some((item) => item.id === id && item.kind === linkKind)) { + problem.related.push({ id, kind: linkKind }); + } + }; + add(a, b.id, kind); + add(b, a.id, SIM_LINK_INVERSE[kind]); + return { problem: a.id }; +} + +function applyCarry(state: SimState, data: unknown) { + const input = asData(data); + const errors: Array = []; + const side = (value: unknown, label: string) => { + const record = asData(value); + if (!isText(record.policy) && !isText(record.domain)) + errors.push(`${label} needs a policy or a domain`); + }; + side(input.from, "from"); + side(input.into, "into"); + if (!isDate(input.date)) errors.push("date must be YYYY-MM-DD"); + tooLong(input.note, SIM_TEXT_LIMIT, "note", errors); + if (errors.length) throw invalid(errors); + const pick = (value: unknown): SimCarrySide => { + const record = asData(value); + const out: SimCarrySide = {}; + if (isText(record.policy)) out.policy = record.policy.trim(); + if (isText(record.domain)) out.domain = record.domain.trim(); + if (isText(record.harness)) out.harness = record.harness.trim(); + return out; + }; + const entry: SimState["carried_from"][number] = { + date: String(input.date), + from: pick(input.from), + into: pick(input.into), + }; + if (isText(input.note)) entry.note = input.note.trim(); + state.carried_from.push(entry); + return {}; +} + +function applyAmend(state: SimState, data: unknown, ctx: EventContext, paths: SimResolvedPaths) { + const input = asData(data); + if (!isText(input.reason, 5)) throw invalid("reason is required (why the record is corrected)"); + if (!isText(input.target)) throw invalid("target is required (a P-id or an A-id)"); + const target = input.target.trim(); + const reason = input.reason.trim(); + if (reason.length > SIM_TEXT_LIMIT) { + throw invalid(`reason has ${reason.length} characters; the limit is ${SIM_TEXT_LIMIT}`); + } + const field = String(input.field); + const value = input.value; + if (target.startsWith("P")) { + const problem = findProblem(state, target); + if (!problem) throw invalid(`problem ${target} does not exist`); + if (!AMENDABLE.problem.includes(field)) throw invalid(`an entry's ${field} cannot be amended`); + if (!isText(value) || squash(value).split(" ").length < 3) { + throw invalid("the root cause must be a sentence, not a label"); + } + if (squash(value).length > SIM_NAME_LIMIT) { + throw invalid( + `the root cause has ${squash(value).length} characters; the limit is ${SIM_NAME_LIMIT}`, + ); + } + const twin = problemNamed(state, value, problem.id); + const former = problem.name; + if (sameName(problem.name) !== sameName(value)) problem.former_names.push(problem.name); + problem.name = squash(value); + (problem.amended ??= []).push({ seq: ctx.seq, field: "name", reason, was: former }); + if (twin) { + const [older, newer] = + idNumber(twin.id) < idNumber(problem.id) ? [twin, problem] : [problem, twin]; + mergeProblems(state, newer, older); + return { problem: older.id, merged: newer.id }; + } + return { problem: problem.id }; + } + const hit = findAttempt(state, target); + if (!hit) throw invalid(`attempt ${target} does not exist`); + const { attempt } = hit; + const judged = attempt.observations.length > 0; + const allowed = [...AMENDABLE.always]; + if (!judged) { + allowed.push( + ...AMENDABLE.beforeOutcome, + ...(attempt.backfilled ? AMENDABLE.backfilledBeforeOutcome : []), + ); + } + if (!allowed.includes(field)) { + let extra = ""; + if (field === "harness") + extra = " (it stands as recorded; retract the attempt and record it again)"; + else if (AMENDABLE.backfilledBeforeOutcome.includes(field) && !attempt.backfilled) { + extra = " after the fact (a prediction stands as it was made)"; + } else if ([...AMENDABLE.beforeOutcome, ...AMENDABLE.backfilledBeforeOutcome].includes(field)) { + extra = + " once it has had an outcome (what was predicted, and where, stands as it was judged)"; + } + throw invalid(`an attempt's ${field} cannot be amended${extra}`); + } + const errors: Array = []; + if (["what", "why", "expect", "domain", "policy", "sample"].includes(field) && !isText(value)) { + errors.push(`${field} must be text`); + } + if (["what", "why", "expect"].includes(field)) tooLong(value, SIM_TEXT_LIMIT, field, errors); + if (field === "anchor" && !isText(value, 6)) errors.push("anchor must be a phrase of the rule"); + if (field === "files" && !(isList(value) && value.length)) + errors.push("files must be a list of paths"); + if ( + field === "depends_on" && + !( + Array.isArray(value) && + value.length && + value.every((item) => SIM_DEPENDS.includes(item as never)) + ) + ) { + errors.push(`depends_on must list one or more of ${SIM_DEPENDS.join(", ")}`); + } + if (field === "round" && !(isDate(value) && value <= ctx.day)) { + errors.push("round must be YYYY-MM-DD and not in the future"); + } + if ( + field === "predicted" && + !(isList(value) && value.length && value.every((slug) => SLUG.test(slug))) + ) { + errors.push("predicted must be a list of kebab-case slugs"); + } + if (errors.length) throw invalid(errors); + const record = attempt as unknown as Data; + const was = record[field]; + if (field === "files") + attempt.files = (value as Array).map((file) => canonicalFile(file, paths)); + else if (field === "depends_on" || field === "predicted") + record[field] = [...(value as Array)]; + else record[field] = typeof value === "string" ? value.trim() : value; + (attempt.amended ??= []).push({ + seq: ctx.seq, + field, + reason, + was: Array.isArray(was) ? [...was] : was, + }); + if (field === "round") sortAttempts(hit.problem); + return { problem: hit.problem.id, attempt: attempt.id }; +} + +function applyRetract(state: SimState, data: unknown, ctx: EventContext) { + const input = asData(data); + const hit = isText(input.attempt) ? findAttempt(state, input.attempt.trim()) : null; + if (!hit) throw invalid(`attempt ${String(input.attempt)} does not exist`); + if (!isText(input.reason, 5)) throw invalid("reason is required (why the record is wrong)"); + if (input.reason.trim().length > SIM_TEXT_LIMIT) { + throw invalid( + `reason has ${input.reason.trim().length} characters; the limit is ${SIM_TEXT_LIMIT}`, + ); + } + const whole = input.outcome === undefined || input.outcome === null; + const record: SimAttempt | SimObservation | undefined = whole + ? hit.attempt + : Number.isInteger(input.outcome) + ? hit.attempt.observations[(input.outcome as number) - 1] + : undefined; + const label = whole ? hit.attempt.id : `outcome ${String(input.outcome)} of ${hit.attempt.id}`; + if (!record) throw invalid(`${hit.attempt.id} has no outcome number ${String(input.outcome)}`); + if (input.undo === true) { + if (!record.retracted) throw invalid(`${label} is not retracted`); + record.restored = { + seq: ctx.seq, + reason: input.reason.trim(), + retracted_because: record.retracted.reason, + }; + delete record.retracted; + } else { + if (record.retracted) throw invalid(`${label} is already retracted`); + record.retracted = { seq: ctx.seq, reason: input.reason.trim() }; + delete record.restored; + } + return { problem: hit.problem.id, attempt: hit.attempt.id }; +} + +export interface SimEventOutcome { + readonly problem?: string; + readonly attempt?: string; + readonly created?: boolean; + readonly merged?: string; +} + +/** Apply one journal event to a state. Throws and leaves no trace when it is invalid. */ +function applyEvent( + state: SimState, + event: Pick & { + readonly also?: string | undefined; + readonly harness?: string | undefined; + }, + paths: SimResolvedPaths, +): SimEventOutcome { + const ops: Record = { + attempt: true, + observe: true, + merge: true, + link: true, + carry: true, + amend: true, + retract: true, + }; + if (!ops[event.op]) throw invalid(`unknown operation ${String(event.op)}`); + if (event.v !== SIM_FORMAT) { + throw invalid(`event ${event.seq} has format ${event.v}; this tool reads format ${SIM_FORMAT}`); + } + if (!isDate(event.day) || !isText(event.by)) + throw invalid(`event ${event.seq} lacks its day or its session`); + const ctx: EventContext = { + seq: event.seq, + day: event.day, + by: event.by, + also: isText(event.also) ? event.also : null, + harness: isText(event.harness) ? event.harness.trim() : null, + }; + let outcome: SimEventOutcome; + switch (event.op) { + case "attempt": + outcome = applyAttempt(state, event.data, ctx, paths); + break; + case "observe": + outcome = applyObserve(state, event.data, ctx); + break; + case "merge": + outcome = applyMerge(state, event.data); + break; + case "link": + outcome = applyLink(state, event.data); + break; + case "carry": + outcome = applyCarry(state, event.data); + break; + case "amend": + outcome = applyAmend(state, event.data, ctx, paths); + break; + case "retract": + outcome = applyRetract(state, event.data, ctx); + break; + } + state.events = event.seq; + return outcome; +} + +/** Fill in what follows from the record: outcome tallies and liveness. */ +function derive(state: SimState): SimState { + for (const problem of state.problems) { + for (const attempt of problem.attempts) { + const outcomes = standing(attempt); + const missed = (target: string) => + outcomes.some((obs) => obs.target === target && obs.result === "missed"); + const fixed = (target: string) => + outcomes.some((obs) => obs.target === target && settlesFix(attempt, obs)); + attempt.missed = attempt.predicted.filter(missed); + attempt.fixed = attempt.predicted.filter((target) => fixed(target) && !missed(target)); + attempt.pending = attempt.predicted.filter((target) => !fixed(target) && !missed(target)); + attempt.passed = outcomes.filter((obs) => settlesFix(attempt, obs)).length; + attempt.total = outcomes.filter((obs) => obs.result !== "kept").length; + attempt.superseded_by = attempt.accepted ? supersededBy(state, attempt.id) : null; + attempt.live = + attempt.accepted && + !attempt.retracted && + attempt.action !== "remove" && + !attempt.superseded_by; + } + } + return state; +} + +function fold(events: ReadonlyArray, paths: SimResolvedPaths): SimState { + const state = emptyState(); + for (const event of events) applyEvent(state, event, paths); + return derive(state); +} + +const journalLines = (file: string) => + NodeFS.existsSync(file) + ? NodeFS.readFileSync(file, "utf8") + .split("\n") + .filter((line) => line.length) + : []; + +export interface SimJournal { + readonly events: Array; + readonly head: string; + broken: string | null; + readonly lines: Array; +} + +/** Read the journal and verify its order and hash chain. */ +function readJournal(file: string): SimJournal { + const lines = journalLines(file); + const events: Array = []; + let head = SIM_GENESIS; + let broken: string | null = null; + lines.forEach((line, index) => { + let event: SimJournalEvent | null = null; + try { + event = JSON.parse(line) as SimJournalEvent; + } catch { + broken ??= `line ${index + 1} is not valid JSON`; + } + if (event) { + if (event.seq !== index + 1) broken ??= `line ${index + 1} has sequence number ${event.seq}`; + if (event.prev !== head) broken ??= `line ${index + 1} does not continue the line before it`; + events.push(event); + } + head = sha(line); + }); + return { events, head, broken, lines }; +} + +/** One attempt at sim.lock, with sim.mjs's stale-holder recovery. */ +export function tryLock(paths: SimResolvedPaths): boolean { + NodeFS.mkdirSync(paths.simDir, { recursive: true }); + for (let round = 0; round < 2; round += 1) { + try { + NodeFS.writeFileSync(paths.lockPath, `${process.pid}`, { flag: "wx" }); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + try { + if (Date.now() - NodeFS.statSync(paths.lockPath).mtimeMs <= SIM_LOCK_STALE_MS) return false; + // Only one waiter wins the rename, so only one removes a dead holder's lock. + const stale = `${paths.lockPath}.${process.pid}`; + NodeFS.renameSync(paths.lockPath, stale); + NodeFS.unlinkSync(stale); + } catch { + // another waiter removed or replaced it first + } + } + } + return false; +} + +export function unlock(paths: SimResolvedPaths) { + NodeFS.rmSync(paths.lockPath, { force: true }); +} + +/** + * Serialize `sim.json` as schema 3 byte-identical to standalone `sim.mjs` (omitting in-memory + * `harness` fields that live on the `sim.jsonl` envelope so the two tools never rewrite each + * other's `sim.json`). + */ +function serializeForDisk(state: SimState): string { + const strip = (record: T): T => { + const out: Record = {}; + for (const [key, value] of Object.entries(record)) { + if (key === "harness") continue; + out[key] = value; + } + return out as T; + }; + const stripAttempt = (attempt: SimAttempt): SimAttempt => { + const out: Record = {}; + for (const [key, value] of Object.entries(attempt)) { + if (key === "harness") continue; + out[key] = + key === "observations" + ? (value as ReadonlyArray).map((obs) => strip(obs)) + : value; + } + return out as unknown as SimAttempt; + }; + const diskState: SimState = { + ...state, + schema: SIM_SCHEMA, + carried_from: state.carried_from.map((entry) => ({ + ...entry, + from: strip(entry.from), + into: strip(entry.into), + })), + problems: state.problems.map((problem) => ({ + ...problem, + attempts: problem.attempts.map(stripAttempt), + })), + }; + return `${JSON.stringify(diskState, null, 1)}\n`; +} + +function writeWhole( + file: string, + content: string | Uint8Array, + options?: { readonly mode?: number | undefined }, +) { + const temp = `${file}.${process.pid}.tmp`; + NodeFS.writeFileSync( + temp, + content, + options?.mode !== undefined ? { mode: options.mode } : undefined, + ); + if (options?.mode !== undefined) { + // Re-apply mode after creation so process umask does not strip executable bits (e.g. .sh hooks). + NodeFS.chmodSync(temp, options.mode); + } + NodeFS.renameSync(temp, file); +} + +const backupNames = (paths: SimResolvedPaths) => + NodeFS.existsSync(paths.backupsDir) + ? NodeFS.readdirSync(paths.backupsDir) + .filter((name) => BACKUP_NAME.test(name)) + .sort() + : []; + +function newestBackup(paths: SimResolvedPaths) { + const names = backupNames(paths); + const name = names[names.length - 1]; + if (!name) return null; + return { name, lines: journalLines(NodePath.join(paths.backupsDir, name)) }; +} + +function departsFromBackup( + lines: ReadonlyArray, + kept: { name: string; lines: Array } | null, +): string | null { + if (!kept || !kept.lines.length) return null; + const last = kept.lines.length - 1; + if (lines.length < kept.lines.length || lines[last] !== kept.lines[last]) { + return `the backup ${kept.name} holds ${count(kept.lines.length, "event")} that the journal does not begin with`; + } + return null; +} + +function backup(paths: SimResolvedPaths) { + NodeFS.mkdirSync(paths.backupsDir, { recursive: true }); + writeWhole( + NodePath.join(paths.backupsDir, `sim-${today()}.jsonl`), + NodeFS.readFileSync(paths.journalPath), + ); + const old = backupNames(paths); + for (const name of old.slice(0, Math.max(0, old.length - KEPT_BACKUPS))) { + NodeFS.rmSync(NodePath.join(paths.backupsDir, name)); + } + for (const name of BACKED_UP_TOOLS) { + const source = NodePath.join(paths.simDir, name); + if (!NodeFS.existsSync(source)) continue; + const content = NodeFS.readFileSync(source); + const target = NodePath.join(paths.backupsDir, name); + if (!NodeFS.existsSync(target) || !NodeFS.readFileSync(target).equals(content)) + writeWhole(target, content); + } +} + +function recordOnDisk(paths: SimResolvedPaths) { + if (!NodeFS.existsSync(paths.recordPath)) + return { text: null, events: 0, schema: null as unknown }; + const text = NodeFS.readFileSync(paths.recordPath, "utf8"); + try { + const parsed = JSON.parse(text) as { events?: unknown; schema?: unknown }; + return { + text, + events: Number.isInteger(parsed.events) ? (parsed.events as number) : 0, + schema: parsed.schema, + }; + } catch { + return { text, events: 0, schema: null as unknown }; + } +} + +interface Trusted { + readonly journal: SimJournal; + state: SimState; + readonly disk: ReturnType; +} + +function readTrusted(paths: SimResolvedPaths): Trusted { + const kept = newestBackup(paths); + const disk = recordOnDisk(paths); + const journal = readJournal(paths.journalPath); + if (!journal.broken && disk.events > journal.events.length) { + journal.broken = `sim.json holds ${count(disk.events, "event")}, the journal only ${journal.events.length}`; + } + if (!journal.broken) journal.broken = departsFromBackup(journal.lines, kept); + let state = emptyState(); + if (!journal.broken) { + try { + state = fold(journal.events, paths); + state.head = journal.head; + } catch (error) { + journal.broken = `an event no longer applies: ${error instanceof Error ? error.message : String(error)}`; + } + } + return { journal, state, disk }; +} + +const outOfDate = ({ journal, state, disk }: Trusted) => + !journal.broken && journal.events.length > 0 && disk.text !== serializeForDisk(state); + +export interface SimLoaded { + readonly journal: SimJournal; + readonly state: SimState; + readonly healed: boolean; +} + +function shownFromDisk(seen: Trusted): SimLoaded { + let shown: SimState | null = null; + try { + shown = seen.disk.text === null ? null : (JSON.parse(seen.disk.text) as SimState); + } catch { + // nothing readable is left; the caller reports the damage + } + if (!shown || !Array.isArray(shown.problems)) shown = emptyState(); + return { journal: seen.journal, state: shown, healed: false }; +} + +/** Read-only load from the journal without locking or writing sim.json. */ +export function loadReadOnly(paths: SimResolvedPaths): SimLoaded { + const seen = readTrusted(paths); + if (!seen.journal.broken) return { journal: seen.journal, state: seen.state, healed: false }; + return shownFromDisk(seen); +} + +/** Load the record; the caller holds sim.lock. The journal decides: a differing sim.json is rebuilt. */ +export function load(paths: SimResolvedPaths): SimLoaded { + const seen = readTrusted(paths); + let healed = false; + if (outOfDate(seen)) { + writeWhole(paths.recordPath, serializeForDisk(seen.state)); + const otherVersion = typeof seen.disk.schema === "number" && seen.disk.schema !== SIM_SCHEMA; + healed = seen.disk.text !== null && !otherVersion; + } + if (!seen.journal.broken) return { journal: seen.journal, state: seen.state, healed }; + return shownFromDisk(seen); +} + +const brokenHelp = (reason: string) => + `the journal sim.jsonl is damaged (${reason}): it was changed outside this tool. ` + + 'Nothing is written until it is repaired. Run "sim.mjs restore" to put back the copy from the last write.'; + +export interface SimEventStamp { + readonly by: string; + readonly also?: string | undefined; + readonly harness?: string | undefined; +} + +/** Append one event; the caller holds sim.lock. Validation runs first, so an invalid event changes nothing. */ +function append( + paths: SimResolvedPaths, + op: SimJournalOp, + data: Data, + stamp: SimEventStamp, +): { outcome: SimEventOutcome; state: SimState; event: SimJournalEvent } { + const { journal, state } = readTrusted(paths); + if (journal.broken) throw fail("journal_broken", brokenHelp(journal.broken)); + // What a later reader replays is the JSON line, so validate exactly that. + const cleanData = JSON.parse(JSON.stringify(data)) as Data; + const event: SimJournalEvent = { + seq: journal.events.length + 1, + ts: new Date().toISOString(), + day: today(), + by: stamp.by, + ...(stamp.also ? { also: stamp.also } : {}), + ...(stamp.harness ? { harness: stamp.harness } : {}), + v: SIM_FORMAT, + op, + data: cleanData, + prev: journal.head, + }; + const outcome = applyEvent(state, event, paths); + const line = JSON.stringify(event); + NodeFS.mkdirSync(paths.simDir, { recursive: true }); + NodeFS.appendFileSync(paths.journalPath, `${line}\n`); + const written = fold([...journal.events, event], paths); + written.head = sha(line); + writeWhole(paths.recordPath, serializeForDisk(written)); + backup(paths); + return { outcome, state: written, event }; +} + +/** Put back the journal as last written; the caller holds sim.lock. */ +export function restore(paths: SimResolvedPaths) { + for (const name of backupNames(paths).reverse()) { + const kept = readJournal(NodePath.join(paths.backupsDir, name)); + let state: SimState | null = null; + try { + if (!kept.broken && kept.events.length) state = fold(kept.events, paths); + } catch { + // an unusable copy; fall through + } + if (!state) { + NodeFS.renameSync( + NodePath.join(paths.backupsDir, name), + NodePath.join(paths.backupsDir, `${name}.unusable-${Date.now()}`), + ); + continue; + } + let damaged: string | null = null; + if (NodeFS.existsSync(paths.journalPath)) { + damaged = `${paths.journalPath}.damaged-${Date.now()}`; + NodeFS.renameSync(paths.journalPath, damaged); + } + NodeFS.copyFileSync(NodePath.join(paths.backupsDir, name), paths.journalPath); + state.head = kept.head; + writeWhole(paths.recordPath, serializeForDisk(state)); + return { name, events: kept.events.length, kept: damaged }; + } + throw fail("io", `no usable backup in ${paths.backupsDir}`); +} + +function readHarnessFile( + file: string, + paths: SimResolvedPaths, + overrides?: ReadonlyMap, +) { + const override = overrides?.get(file); + if (override !== undefined) return override; + const full = expandHarnessFile(file, paths); + try { + return NodeFS.statSync(full).isFile() ? NodeFS.readFileSync(full, "utf8") : null; + } catch { + return null; + } +} + +const occurrences = (text: string, phrase: string | null) => + squash(text).split(squash(phrase ?? "")).length - 1; + +function coverageUnits(paths: SimResolvedPaths) { + const units: Array<{ file: string; text: string | null }> = []; + const notes = NodePath.join(paths.harnessDir, "notes"); + const noteFiles = NodeFS.existsSync(notes) + ? NodeFS.readdirSync(notes) + .filter((item) => item.endsWith(".md")) + .sort() + .map((name) => `~/.claude/notes/${name}`) + : []; + for (const file of ["~/.claude/AGENTS.md", ...noteFiles]) { + const text = readHarnessFile(file, paths); + if (text === null) continue; + let inLessons = false; + for (const line of text.split("\n")) { + if (line.startsWith("## ")) inLessons = /^## (Scars|Wins)\b/.test(line); + else if (/^\s*- /.test(line) && (inLessons || /^\s*-\s+(Scar|Win)\b/.test(line))) { + units.push({ file, text: line }); + } + } + } + const hooks = NodePath.join(paths.harnessDir, "hooks"); + if (NodeFS.existsSync(hooks)) { + for (const name of NodeFS.readdirSync(hooks) + .filter((item) => item.endsWith(".mjs")) + .sort()) { + units.push({ file: `~/.claude/hooks/${name}`, text: null }); + } + } + return units; +} + +/** Recent Claude Code writers without a transcript here. T3 stamps `t3:` writers itself, so they are known. */ +function strangers(journal: SimJournal, paths: SimResolvedPaths) { + const roots = [NodePath.join(paths.harnessDir, "projects")]; + if (paths.harnessDir === NodePath.join(paths.homeDir, ".claude")) { + try { + for (const name of NodeFS.readdirSync(paths.homeDir)) { + if (/^\.claude-/.test(name)) roots.push(NodePath.join(paths.homeDir, name, "projects")); + } + } catch { + // an unreadable home lists no extra roots + } + } + const folders = roots + .filter((root) => NodeFS.existsSync(root)) + .flatMap((root) => NodeFS.readdirSync(root).map((name) => NodePath.join(root, name))); + const found = new Map>(); + if (!folders.length) return found; + const since = new Date(Date.now() - SEEN_DAYS * 86_400_000).toISOString().slice(0, 10); + const known = new Map(); + for (const event of journal.events) { + if (typeof event.day !== "string" || event.day < since || typeof event.by !== "string") + continue; + if (event.by.startsWith("t3:")) continue; + if (!known.has(event.by)) { + const id = event.by.startsWith("cc:") ? event.by.slice(3) : null; + known.set( + event.by, + id !== null && + folders.some((folder) => NodeFS.existsSync(NodePath.join(folder, `${id}.jsonl`))), + ); + } + if (!known.get(event.by)) found.set(event.by, [...(found.get(event.by) ?? []), event.seq]); + } + return found; +} + +export interface SimHarnessHealth { + readonly drift: ReadonlyArray<{ readonly attempt: SimAttempt; readonly reason: string }>; + readonly uncovered: ReadonlyArray<{ readonly file: string; readonly text: string | null }>; + readonly unchecked: ReadonlyArray; +} + +/** Compare the record with the harness files: drift, and agent-added rules without a record. */ +export function inspectHarness(state: SimState, paths: SimResolvedPaths): SimHarnessHealth { + const live = allAttempts(state).filter((attempt) => attempt.live); + const drift: Array<{ attempt: SimAttempt; reason: string }> = []; + const unchecked: Array = []; + for (const attempt of live) { + const first = attempt.files[0] ?? ""; + const text = readHarnessFile(first, paths); + if (text === null) { + if (first.startsWith("~/.claude/")) + drift.push({ attempt, reason: `${first} does not exist` }); + else unchecked.push(attempt); + } else if (!occurrences(text, attempt.anchor)) { + drift.push({ attempt, reason: `"${attempt.anchor}" is no longer in ${first}` }); + } + } + const uncovered = coverageUnits(paths).filter((unit) => { + const inFile = live.filter((attempt) => attempt.files.includes(unit.file)); + return unit.text === null + ? !inFile.length + : !inFile.some((attempt) => occurrences(unit.text!, attempt.anchor)); + }); + return { drift, uncovered, unchecked }; +} + +const words = (text: string) => + new Set( + squash(text) + .toLowerCase() + .split(/[^a-z0-9äöüß]+/) + .filter((word) => word.length >= 4) + .map((word) => word.replace(/(ing|ed|es|s)$/, "")) + .filter((word) => word.length >= 3), + ); + +const problemWords = (problem: SimProblem) => + words( + [ + problem.name, + ...problem.former_names, + ...problem.attempts.flatMap((attempt) => [ + attempt.what, + attempt.anchor ?? "", + ...attempt.predicted, + ]), + ].join(" "), + ); + +/** The entries closest to a text by shared words (TF-IDF with a length penalty). */ +function relatedProblems( + state: SimState, + text: string, + limit = RELATED_LIMIT, + floor = RELATED_FLOOR, +): Array { + const docs = state.problems.map((problem) => ({ id: problem.id, words: problemWords(problem) })); + const spread = new Map(); + for (const doc of docs) + for (const word of doc.words) spread.set(word, (spread.get(word) ?? 0) + 1); + const average = docs.reduce((sum, doc) => sum + doc.words.size, 0) / (docs.length || 1) || 1; + const length = (doc: { words: Set }) => + 1 - RELATED_LENGTH + (RELATED_LENGTH * doc.words.size) / average; + const query = words(text); + return docs + .map((doc) => ({ + id: doc.id, + score: + [...query] + .filter((word) => doc.words.has(word)) + .reduce((sum, word) => sum + 1 / spread.get(word)!, 0) / length(doc), + })) + .filter((item) => item.score >= floor) + .sort((a, b) => b.score - a.score || idNumber(a.id) - idNumber(b.id)) + .slice(0, limit) + .map((item) => item.id); +} + +type Need = Map; + +function mustReadInFull(state: SimState, input: Data) { + const need: Need = new Map(); + const cited = isText(input.problem) + ? findProblem(state, input.problem.trim()) + : isText(input.new) + ? problemNamed(state, input.new) + : null; + if (cited) need.set(cited.id, ["full", "you continue it"]); + for (const id of Array.isArray(input.supersedes) ? input.supersedes : []) { + const hit = isText(id) ? findAttempt(state, id) : null; + if (hit && !need.has(hit.problem.id)) + need.set(hit.problem.id, ["full", `it holds ${id}, which you change`]); + } + const opensNew = !cited && isText(input.new); + const text = opensNew + ? [input.new, input.what, input.anchor, ...(isList(input.predicted) ? input.predicted : [])] + .filter((item): item is string => isText(item)) + .join(" ") + : null; + return { need, text }; +} + +function demandShown( + state: SimState, + shown: ReadonlyMap, + need: Need, + text: string | null = null, + hint = "", +) { + if (text !== null) { + for (const id of relatedProblems(state, text)) { + if (!need.has(id)) need.set(id, ["full", "it shares words with your change"]); + } + } + const lacking = [...need].filter( + ([id, [level]]) => !(shown.get(id) === "full" || (level === "brief" && shown.has(id))), + ); + const unseen = + text === null + ? [] + : state.problems.filter((problem) => !shown.has(problem.id) && !need.has(problem.id)); + if (!lacking.length && !unseen.length) return; + const lines: Array = []; + for (const level of ["full", "brief"] as const) { + const group = lacking.filter(([, [wanted]]) => wanted === level); + if (!group.length) continue; + const ids = group.map(([id]) => id).join(" "); + const which = group.length === 1 ? "this entry" : "these entries"; + lines.push( + level === "full" + ? `read ${which} in full first: SIM read action "show" with ids ${ids}` + : `read ${which} at least in brief first: SIM read action "show" with ids ${ids} and brief: true`, + ); + lines.push(...group.map(([id, [, why]]) => `${indexLine(findProblem(state, id)!)} <- ${why}`)); + } + if (unseen.length) { + const few = unseen.length < state.problems.length; + const command = few + ? `SIM read action "show" with ids ${unseen.map((problem) => problem.id).join(" ")} and brief: true` + : 'SIM read action "brief_all"'; + lines.push( + `a new root cause needs the whole record in view first: ${command} (${few ? "" : "every page; "}${unseen.length} of ${state.problems.length} entries not shown to this session as they are now)`, + ); + } + lines.push( + `${hint}Then repeat the write: the server knows what it has shown to this session, and a reading counts until the entry changes or the context is compacted.`, + ); + throw fail("seen_required", lines); +} + +function requireReading( + state: SimState, + shown: ReadonlyMap, + input: Data, +) { + const { need, text } = mustReadInFull(state, input); + demandShown( + state, + shown, + need, + text, + 'If one of these entries is the root cause of your change, record under it ("problem"). ', + ); + return [...need.keys()]; +} + +const short = (file: string) => file.replace(/^~\/\.claude\//, ""); +const briefId = (session: string) => (session.length > 14 ? session.slice(0, 11) : session); + +type Tally = Record< + "fixed" | "unconfirmed" | "missed" | "regressed" | "misfired" | "inconclusive" | "pending", + number +>; + +function tally(attempts: ReadonlyArray): Tally { + const sum: Tally = { + fixed: 0, + unconfirmed: 0, + missed: 0, + regressed: 0, + misfired: 0, + inconclusive: 0, + pending: 0, + }; + for (const attempt of attempts.filter((item) => !item.retracted)) { + for (const obs of standing(attempt)) { + if (obs.result === "fixed") sum[settlesFix(attempt, obs) ? "fixed" : "unconfirmed"] += 1; + else if (obs.result in sum) sum[obs.result as keyof Tally] += 1; + } + if (attempt.live) sum.pending += attempt.pending.length; + } + return sum; +} + +function tallyText(sum: Tally) { + const parts = ( + ["fixed", "unconfirmed", "missed", "regressed", "misfired", "inconclusive"] as const + ) + .filter((key) => sum[key]) + .map((key) => `${key} ${sum[key]}`); + if (sum.pending) parts.push(`open ${sum.pending}`); + return parts.length ? parts.join(" ") : "no outcomes"; +} + +const INDEX_LEGEND = + "id | root cause | live rules | attempts | outcomes (fixed = seen by another session; unconfirmed = a fix only the changing session reported; open = predictions of live rules not settled yet)"; + +function indexLine(problem: SimProblem) { + const accepted = problem.attempts.filter((attempt) => attempt.accepted); + const live = accepted.filter((attempt) => attempt.live); + const proposals = problem.attempts.length - accepted.length; + const files = [...new Set(live.map((attempt) => short(attempt.files[0] ?? "")))].join(", "); + const where = live.length ? `${live.length} live: ${files}` : "no live rule"; + const tries = `${count(problem.attempts.length, "attempt")}${proposals ? ` (${proposals} not carried out)` : ""}`; + return `${problem.id} | ${problem.name} | ${where} | ${tries} | ${tallyText(tally(accepted))}`; +} + +function renderIndex(state: SimState) { + return state.problems.map(indexLine).join("\n"); +} + +function renderFile(state: SimState, file: string): Array { + const lines: Array = []; + for (const problem of state.problems) { + for (const attempt of problem.attempts) { + if (attempt.live && attempt.files.includes(file)) { + lines.push( + `${problem.id} ${attempt.id} "${attempt.anchor}"${attempt.files[0] === file ? "" : ` (in ${short(attempt.files[0] ?? "")})`}`, + ); + } + } + } + return lines; +} + +const attemptText = (attempt: SimAttempt) => + [ + attempt.what, + attempt.why, + attempt.anchor, + attempt.expect, + attempt.rejected_because, + ...attempt.predicted, + ...attempt.observations.map((obs) => `${obs.target} ${obs.evidence}`), + ] + .filter(Boolean) + .join(" "); + +function searchProblems(state: SimState, query: string): Array { + const wanted = squash(query).toLowerCase().split(" ").filter(Boolean); + return state.problems.filter((problem) => { + const text = [problem.name, ...problem.former_names, ...problem.attempts.map(attemptText)] + .join(" ") + .toLowerCase(); + return wanted.every((word) => text.includes(word)); + }); +} + +function attemptState(attempt: SimAttempt) { + if (attempt.retracted) return `RETRACTED (${attempt.retracted.reason})`; + if (!attempt.accepted) return attempt.unanswered ? "PROPOSED, no answer" : "REJECTED"; + if (attempt.live) return "LIVE"; + return attempt.action === "remove" + ? "removal" + : `no longer live (changed by ${attempt.superseded_by})`; +} + +/** `withHarness: false` reproduces sim.mjs byte for byte, so seen stamps agree between the two tools. */ +function renderAttempt(attempt: SimAttempt, withHarness: boolean) { + const head = [ + attempt.id, + attempt.round, + attempt.action, + attemptState(attempt), + attempt.policy, + attempt.domain, + ]; + if (withHarness && attempt.harness) head.push(`harness ${attempt.harness}`); + if (attempt.backfilled) { + head.push( + `backfilled by ${briefId(attempt.by)}${attempt.sample === SIM_UNKNOWN ? "" : `, made by ${briefId(attempt.sample)}`}`, + ); + } else head.push(`by ${briefId(attempt.by)}`); + const lines = [` ${head.join(" · ")}`, ` what: ${attempt.what}`, ` why: ${attempt.why}`]; + if (attempt.rejected_because) lines.push(` rejected because: ${attempt.rejected_because}`); + if (attempt.files.length) { + lines.push( + ` where: ${attempt.files.join(", ")}${attempt.anchor ? ` "${attempt.anchor}"` : ""}`, + ); + } + if (attempt.supersedes.length) { + lines.push( + ` ${attempt.accepted ? "changes" : "would change"}: ${attempt.supersedes.join(", ")}`, + ); + } + if (attempt.depends_on.length) lines.push(` depends on: ${attempt.depends_on.join(", ")}`); + if (attempt.predicted.length) { + const label = attempt.action === "remove" ? "may bring back" : "predicted to fix"; + lines.push( + // oxlint-disable-next-line t3code/no-em-dash-copy -- byte-identical to sim.mjs, whose seen stamps hash this text + ` ${label}: ${attempt.predicted.join(", ")}${attempt.expect ? ` — ${attempt.expect}` : ""}`, + ); + } + attempt.observations.forEach((obs, index) => { + const what = obs.result === "kept" ? "kept after review" : `${obs.target} ${obs.result}`; + const own = obs.result === "fixed" ? ownReport(attempt, obs) : null; + const back = obs.restored + ? `restored after a retraction (${obs.restored.retracted_because}; restored: ${obs.restored.reason}) ` + : ""; + const note = obs.retracted + ? `RETRACTED (${obs.retracted.reason}) ` + : own + ? `not confirmed (${own}): ` + : ""; + const seen = + obs.sample !== obs.by && obs.sample !== SIM_UNKNOWN + ? `, said to be seen by ${briefId(obs.sample)}` + : ""; + const harness = withHarness && obs.harness ? `, ${obs.harness}` : ""; + lines.push( + ` outcome ${index + 1}: ${back}${note}${what} (${obs.date}, ${obs.source}, ${obs.policy}${harness}, ${obs.domain}, by ${briefId(obs.by)}${seen}) ${obs.evidence}`, + ); + }); + if (attempt.accepted && !attempt.retracted && attempt.pending.length) { + lines.push(` still open: ${attempt.pending.join(", ")}`); + } + if (attempt.restored) { + lines.push( + ` restored after a retraction (${attempt.restored.retracted_because}; restored: ${attempt.restored.reason})`, + ); + } + for (const change of attempt.amended ?? []) { + const was = + change.was === undefined || change.was === null + ? "nothing" + : Array.isArray(change.was) + ? change.was.join(", ") + : `"${String(change.was)}"`; + lines.push(` amended: ${change.field}, was ${was} (${change.reason})`); + } + return lines.join("\n"); +} + +function problemHead(state: SimState, problem: SimProblem) { + // oxlint-disable-next-line t3code/no-em-dash-copy -- byte-identical to sim.mjs, whose seen stamps hash this text + const head = [`${problem.id} — ${problem.name}`, `opened ${problem.opened_round}`]; + const formerIds = Object.keys(state.aliases) + .filter((id) => resolveId(state, id) === problem.id) + .sort((a, b) => idNumber(a) - idNumber(b)); + if (formerIds.length) head.push(`merged from ${formerIds.join(", ")}`); + const links = problem.related + .map((link) => `${link.kind} ${resolveId(state, link.id)}`) + .filter((text) => !text.endsWith(` ${problem.id}`)); + if (links.length) head.push([...new Set(links)].join(", ")); + return head.join(" · "); +} + +function renderProblemWith(state: SimState, problem: SimProblem, withHarness: boolean) { + const lines = [problemHead(state, problem)]; + for (const name of problem.former_names) lines.push(` earlier wording: ${name}`); + for (const attempt of problem.attempts) lines.push(renderAttempt(attempt, withHarness)); + return lines.join("\n"); +} + +/** Every attempt of an entry in full, with the harness each was made under. */ +const renderProblem = (state: SimState, problem: SimProblem) => + renderProblemWith(state, problem, true); + +const clip = (text: string, size: number) => + text.length <= size ? text : `${text.slice(0, size - 1).trimEnd()}…`; + +function renderBrief(state: SimState, problem: SimProblem) { + const lines = [problemHead(state, problem)]; + for (const attempt of problem.attempts) { + const sum = tally([attempt]); + const harness = attempt.harness ? ` [${attempt.harness}]` : ""; + const parts = [ + `${attempt.id} ${attempt.round} ${attempt.action}${harness}, ${attemptState(attempt)}: ${clip(attempt.what, 160)}`, + ]; + if (attempt.rejected_because) parts.push(`because: ${clip(attempt.rejected_because, 160)}`); + if (attempt.accepted && !attempt.retracted) parts.push(tallyText(sum)); + lines.push(` ${parts.join(" | ")}`); + } + return lines.join("\n"); +} + +function renderCarried(state: SimState) { + const side = (value: SimCarrySide) => + [value.policy, value.domain, value.harness].filter(Boolean).join(" / "); + return state.carried_from + .map( + (item) => + `carried ${item.date}: ${side(item.from)} -> ${side(item.into)}${item.note ? ` (${item.note})` : ""}`, + ) + .join("\n"); +} + +function warnings(state: SimState, journal: SimJournal, health: SimHarnessHealth) { + const out: Array = []; + if (journal.broken) out.push(`WARNING: ${brokenHelp(journal.broken)}`); + const { drift, uncovered } = health; + if (drift.length || uncovered.length) { + const parts: Array = []; + if (drift.length) + parts.push(`${count(drift.length, "recorded rule")} changed or vanished without a record`); + if (uncovered.length) { + parts.push( + `${count(uncovered.length, "agent-added rule")} (Scar, Win, hook) without a record`, + ); + } + out.push( + `WARNING: ${parts.join("; ")}. Run the SIM "check" read and reconcile before you propose.`, + ); + } + return out; +} + +const rulesPointer = () => + 'How to read and write this record: use sim_read ("index", "by_file", "show", "check", "review", "audit"), sim_write, and sim_apply_harness_change.'; +const HEALED_NOTE = + "note: sim.json did not match the journal and was rebuilt. Change the record only through this tool."; + +interface PagePart { + readonly index: number; + readonly from: number; + readonly to: number; + readonly of: number; +} + +/** Cut units into pages; a unit longer than a page is cut at line ends and each piece knows its range. */ +function pages(units: ReadonlyArray, separator: string, size: number) { + const pieces: Array = []; + units.forEach((unit, index) => { + if (unit.length <= size) { + pieces.push({ text: unit, index, from: 0, to: unit.length, of: unit.length }); + return; + } + const parts: Array = []; + let chunk: Array = []; + let used = 0; + for (const line of unit.split("\n")) { + if (chunk.length && used + line.length + 1 > size) { + parts.push(chunk.join("\n")); + chunk = []; + used = 0; + } + chunk.push(line); + used += line.length + 1; + } + if (chunk.length) parts.push(chunk.join("\n")); + let from = 0; + for (const text of parts) { + pieces.push({ + text, + index, + from, + to: Math.min(unit.length, from + text.length + 1), + of: unit.length, + }); + from += text.length + 1; + } + }); + const out: Array<{ text: string; parts: Array }> = []; + let page: typeof pieces = []; + let used = 0; + const close = () => { + out.push({ + text: page.map((piece) => piece.text).join(separator), + parts: page.map(({ index, from, to, of }) => ({ index, from, to, of })), + }); + page = []; + used = 0; + }; + for (const piece of pieces) { + if (page.length && used + piece.text.length + separator.length > size) close(); + page.push(piece); + used += piece.text.length + separator.length; + } + if (page.length || !out.length) close(); + return out; +} + +function paged(options: { + readonly command: string; + readonly page?: number | undefined; + readonly head?: ReadonlyArray; + readonly units: ReadonlyArray; + readonly separator?: string; + readonly tail?: ReadonlyArray; + readonly size?: number; + readonly shown?: ((parts: ReadonlyArray) => void) | null; +}): string { + const head = options.head ?? []; + const tail = options.tail ?? []; + const size = options.size ?? SIM_DEFAULT_PAGE_CHARS; + const fixed = [...head, ...tail].join("\n").length + 200; + const list = pages(options.units, options.separator ?? "\n", Math.max(1000, size - fixed)); + const wanted = options.page === undefined ? 1 : Number(options.page); + if (!Number.isInteger(wanted) || wanted < 1 || wanted > list.length) { + throw invalid( + `this output has ${count(list.length, "page")}; page ${String(options.page)} does not exist`, + ); + } + const current = list[wanted - 1]!; + const out = wanted === 1 ? [...head] : []; + if (current.text) out.push(current.text); + if (list.length > 1) { + out.push( + wanted < list.length + ? `page ${wanted} of ${list.length}: nothing is left out, read on with: ${options.command} page ${wanted + 1}` + : `page ${wanted} of ${list.length}, the last one.`, + ); + } + if (wanted === list.length) out.push(...tail); + options.shown?.(current.parts); + return out.join("\n"); +} + +interface SeenLog { + session: string; + full: Record; + brief: Record; + parts: Record }>; + at: Record; + index_at?: number; + files_at?: Record; + t3_epoch?: number; +} + +interface EpochEntry { + readonly epoch: number; + readonly resetAt: number; + readonly updatedAt?: number | undefined; + readonly lastProviderThreadId?: string | undefined; + readonly lastExtraSessionIds?: ReadonlyArray | undefined; +} + +/** Which seen logs a caller reads and writes, and the context epoch its readings must belong to. */ +export interface SimSeenScope { + readonly sessions: ReadonlyArray; + readonly epoch: number; + readonly resetAt: number; +} + +const seenFile = (paths: SimResolvedPaths, session: string) => + NodePath.join(paths.seenDir, `${sha(session).slice(0, 16)}.json`); +/** An entry as sim.mjs renders it; a reading counts only while this stamp holds. */ +const stamp = (state: SimState, problem: SimProblem) => + sha(renderProblemWith(state, problem, false)).slice(0, 16); + +const freshLog = (session: string): SeenLog => ({ + session, + full: {}, + brief: {}, + parts: {}, + at: {}, +}); + +function readSeen(paths: SimResolvedPaths, session: string): SeenLog { + try { + const log = JSON.parse(NodeFS.readFileSync(seenFile(paths, session), "utf8")) as SeenLog; + if ( + log && + log.session === session && + typeof log.full === "object" && + typeof log.brief === "object" + ) { + return { ...log, parts: log.parts ?? {}, at: log.at ?? {} }; + } + } catch { + // no log yet, or an unreadable one: nothing counts as shown + } + return freshLog(session); +} + +function joinRanges(ranges: ReadonlyArray<[number, number]>) { + const out: Array<[number, number]> = []; + for (const [from, to] of [...ranges].sort((a, b) => a[0] - b[0])) { + const last = out[out.length - 1]; + if (last && from <= last[1]) last[1] = Math.max(last[1], to); + else out.push([from, to]); + } + return out; +} + +function saveSeen(paths: SimResolvedPaths, session: string, log: SeenLog) { + try { + NodeFS.mkdirSync(paths.seenDir, { recursive: true }); + writeWhole(seenFile(paths, session), JSON.stringify(log)); + } catch { + return; + } + const limit = Date.now() - SEEN_DAYS * 86_400_000; + for (const name of NodeFS.readdirSync(paths.seenDir)) { + try { + if (NodeFS.statSync(NodePath.join(paths.seenDir, name)).mtimeMs < limit) { + NodeFS.rmSync(NodePath.join(paths.seenDir, name)); + } + } catch { + // another session removed it first + } + } +} + +function readEpochs(paths: SimResolvedPaths): Record { + try { + const parsed = JSON.parse(NodeFS.readFileSync(paths.epochsPath, "utf8")) as unknown; + return parsed !== null && typeof parsed === "object" + ? (parsed as Record) + : {}; + } catch { + return {}; + } +} + +export function getThreadSeenEpoch(paths: SimResolvedPaths, threadId: string): number { + return readEpochs(paths)[threadId]?.epoch ?? 0; +} + +const threadSessionId = (threadId: string) => `t3:${threadId}`; + +function pruneAndWriteEpochs( + paths: SimResolvedPaths, + epochs: Record, + now: number, +) { + // Seen logs expire after SEEN_DAYS; an epoch older than twice that guards nothing. + for (const [id, entry] of Object.entries(epochs)) { + const refTime = entry.updatedAt ?? entry.resetAt; + if (refTime > 0 && now - refTime > 2 * SEEN_DAYS * 86_400_000) delete epochs[id]; + } + NodeFS.mkdirSync(paths.simDir, { recursive: true }); + writeWhole(paths.epochsPath, `${JSON.stringify(epochs)}\n`); +} + +/** After compaction: readings from before no longer count for this thread (or its native session). */ +export function resetThreadSeenEpoch( + paths: SimResolvedPaths, + threadId: string, + extraSessionIds: ReadonlyArray = [], +): number { + const epochs = readEpochs(paths); + const existing = epochs[threadId]; + const now = Date.now(); + const next = (existing?.epoch ?? 0) + 1; + const knownExtras = [...new Set([...(existing?.lastExtraSessionIds ?? []), ...extraSessionIds])]; + epochs[threadId] = { + epoch: next, + resetAt: now, + updatedAt: now, + ...(existing?.lastProviderThreadId + ? { lastProviderThreadId: existing.lastProviderThreadId } + : {}), + ...(knownExtras.length ? { lastExtraSessionIds: knownExtras } : {}), + }; + pruneAndWriteEpochs(paths, epochs, now); + for (const session of new Set([threadSessionId(threadId), ...knownExtras])) { + saveSeen(paths, session, { ...freshLog(session), t3_epoch: next }); + } + return next; +} + +/** + * Persist the active provider thread for `threadId` in `t3-epochs.json` so a provider-thread + * switch (/clear, fresh context, provider switch) still bumps the seen epoch after a server + * restart. Returns true when a switch triggered an epoch reset. + */ +export function trackProviderThread( + paths: SimResolvedPaths, + threadId: string, + providerThreadId: string, + extraSessionIds: ReadonlyArray = [], +): boolean { + const epochs = readEpochs(paths); + const existing = epochs[threadId]; + const now = Date.now(); + const combinedExtras = [ + ...new Set([...(existing?.lastExtraSessionIds ?? []), ...extraSessionIds]), + ]; + if (existing?.lastProviderThreadId === providerThreadId) { + if (combinedExtras.length > (existing.lastExtraSessionIds?.length ?? 0)) { + epochs[threadId] = { ...existing, updatedAt: now, lastExtraSessionIds: combinedExtras }; + pruneAndWriteEpochs(paths, epochs, now); + } + return false; + } + if (existing?.lastProviderThreadId === undefined) { + epochs[threadId] = { + epoch: existing?.epoch ?? 0, + resetAt: existing?.resetAt ?? 0, + updatedAt: now, + lastProviderThreadId: providerThreadId, + ...(combinedExtras.length ? { lastExtraSessionIds: combinedExtras } : {}), + }; + pruneAndWriteEpochs(paths, epochs, now); + return false; + } + const next = (existing.epoch ?? 0) + 1; + epochs[threadId] = { + epoch: next, + resetAt: now, + updatedAt: now, + lastProviderThreadId: providerThreadId, + ...(extraSessionIds.length ? { lastExtraSessionIds: [...new Set(extraSessionIds)] } : {}), + }; + pruneAndWriteEpochs(paths, epochs, now); + for (const session of new Set([threadSessionId(threadId), ...combinedExtras])) { + saveSeen(paths, session, { ...freshLog(session), t3_epoch: next }); + } + return true; +} + +function hasConsultedIndexOrFile( + paths: SimResolvedPaths, + scope: SimSeenScope, + files: ReadonlyArray, +): boolean { + const now = Date.now(); + const canonical = files.map((file) => canonicalFile(file, paths)); + for (const session of scope.sessions) { + const log = readSeen(paths, session); + if ((log.t3_epoch ?? 0) < scope.epoch) continue; + const fresh = (at: unknown): boolean => { + if (typeof at !== "number" || at <= 0) return false; + if (at < scope.resetAt) return false; + if (session === SIM_UNKNOWN && now - at > SITTING_MINUTES * 60_000) return false; + return true; + }; + if (fresh(log.index_at)) return true; + if (canonical.length > 0 && log.files_at) { + if (canonical.every((file) => fresh(log.files_at?.[file]))) return true; + } + } + return false; +} + +function requireIndexConsulted( + paths: SimResolvedPaths, + scope: SimSeenScope, + files: ReadonlyArray, +) { + if (hasConsultedIndexOrFile(paths, scope, files)) return; + const target = files[0]; + const hint = target + ? `call sim_read with action "index" or action "by_file" (file: "${target}") in this context first` + : 'call sim_read with action "index" in this context first'; + throw fail("seen_required", [ + `read the SIM index or this file's entries before recording or applying a harness change: ${hint}.`, + "Then repeat the call: the server tracks what it has shown to this session in the current context epoch.", + ]); +} + +export function readAuditWatermarkMs(paths: SimResolvedPaths): number | null { + try { + const parsed = JSON.parse(NodeFS.readFileSync(paths.auditStatePath, "utf8")) as { + last_audit_at?: unknown; + }; + if (typeof parsed.last_audit_at !== "string") return null; + const ms = Date.parse(parsed.last_audit_at); + return Number.isFinite(ms) ? ms : null; + } catch { + return null; + } +} + +export function seenScope(paths: SimResolvedPaths, caller: SimCallerContext): SimSeenScope { + const sessions = [caller.sessionId || SIM_UNKNOWN]; + if (caller.alsoSessionId && caller.alsoSessionId !== sessions[0]) + sessions.push(caller.alsoSessionId); + const entry = caller.threadId ? readEpochs(paths)[caller.threadId] : undefined; + return { sessions, epoch: entry?.epoch ?? 0, resetAt: entry?.resetAt ?? 0 }; +} + +/** A log as it may be extended in this epoch: one from an earlier context starts over. */ +function currentLog(paths: SimResolvedPaths, session: string, scope: SimSeenScope): SeenLog { + const log = readSeen(paths, session); + const fresh = (log.t3_epoch ?? 0) < scope.epoch ? freshLog(session) : log; + fresh.t3_epoch = scope.epoch; + return fresh; +} + +function markIndexShown(paths: SimResolvedPaths, scope: SimSeenScope, file: string | null = null) { + const now = Date.now(); + for (const session of scope.sessions) { + const log = currentLog(paths, session, scope); + if (file) log.files_at = { ...log.files_at, [file]: now }; + else log.index_at = now; + saveSeen(paths, session, log); + } +} + +export function markShown( + paths: SimResolvedPaths, + state: SimState, + items: ReadonlyArray<{ problem: SimProblem; from?: number; to?: number; of?: number }>, + level: "full" | "brief", + scope: SimSeenScope, + keepTime = false, +) { + if (!items.length) return; + for (const session of scope.sessions) { + const log = currentLog(paths, session, scope); + const now = Date.now(); + const lapsed = (at: number) => session === SIM_UNKNOWN && now - at > SITTING_MINUTES * 60_000; + for (const { problem, from = 0, to = 1, of = 1 } of items) { + const mark = stamp(state, problem); + let at = now; + if (!(from === 0 && to >= of)) { + const key = `${problem.id} ${level}`; + const noted = log.parts[key]; + const had = + noted && noted.mark === mark && Array.isArray(noted.ranges) && !lapsed(noted.at) + ? noted + : null; + const ranges = joinRanges([...(had ? had.ranges : []), [from, to]]); + at = had ? had.at : now; + const first = ranges[0]; + if (!(ranges.length === 1 && first && first[0] === 0 && first[1] >= of)) { + log.parts[key] = { mark, at, ranges }; + continue; + } + delete log.parts[key]; + } + log.brief[problem.id] = mark; + if (level === "full") log.full[problem.id] = mark; + log.at[problem.id] = keepTime && log.at[problem.id] ? log.at[problem.id]! : at; + } + if ( + !keepTime && + state.problems.length && + state.problems.every( + (problem) => + log.brief[problem.id] === stamp(state, problem) && !lapsed(log.at[problem.id] ?? 0), + ) + ) { + log.index_at = now; + } + saveSeen(paths, session, log); + } +} + +/** What the caller was shown of each entry as it is now, in this context epoch, over both session names. */ +export function shownTo( + paths: SimResolvedPaths, + state: SimState, + scope: SimSeenScope, +): Map { + const levels = new Map(); + for (const session of scope.sessions) { + const log = readSeen(paths, session); + if ((log.t3_epoch ?? 0) < scope.epoch) continue; + const lapsed = (id: string) => + session === SIM_UNKNOWN && Date.now() - (log.at[id] ?? 0) > SITTING_MINUTES * 60_000; + for (const problem of state.problems) { + if (lapsed(problem.id) || (log.at[problem.id] ?? 0) < scope.resetAt) continue; + const mark = stamp(state, problem); + if (log.full[problem.id] === mark) levels.set(problem.id, "full"); + else if (log.brief[problem.id] === mark && !levels.has(problem.id)) + levels.set(problem.id, "brief"); + } + } + return levels; +} + +function keepShown( + paths: SimResolvedPaths, + before: ReadonlyMap, + state: SimState, + scope: SimSeenScope, + created: string | null = null, +) { + for (const level of ["full", "brief"] as const) { + const kept = state.problems.filter( + (problem) => (problem.id === created ? "full" : before.get(problem.id)) === level, + ); + markShown( + paths, + state, + kept.map((problem) => ({ problem })), + level, + scope, + true, + ); + } +} + +export function appendTelemetry(paths: SimResolvedPaths, event: SimTelemetryEvent) { + NodeFS.mkdirSync(paths.simDir, { recursive: true }); + NodeFS.appendFileSync(paths.telemetryPath, `${JSON.stringify(event)}\n`); + const size = NodeFS.statSync(paths.telemetryPath).size; + if (size <= TELEMETRY_MAX_BYTES / 2) return; + const lines = NodeFS.readFileSync(paths.telemetryPath, "utf8").split("\n").filter(Boolean); + if (lines.length > TELEMETRY_MAX_LINES || size > TELEMETRY_MAX_BYTES) { + writeWhole(paths.telemetryPath, `${lines.slice(-TELEMETRY_KEEP_LINES).join("\n")}\n`); + } +} + +export function readTelemetry(paths: SimResolvedPaths, sinceMs?: number): Array { + let raw: string; + try { + raw = NodeFS.readFileSync(paths.telemetryPath, "utf8"); + } catch { + return []; + } + const out: Array = []; + for (const line of raw.split("\n")) { + if (!line) continue; + try { + const event = JSON.parse(line) as SimTelemetryEvent; + if (typeof event?.kind !== "string" || typeof event.ts !== "string") continue; + if (sinceMs !== undefined) { + const ms = Date.parse(event.ts); + if (Number.isFinite(ms) && ms < sinceMs) continue; + } + out.push(event); + } catch { + // a torn line from a crash mid-append + } + } + return out; +} + +/** Models SIM already knows: every policy an attempt, outcome or carry names, plain and per harness. */ +export function observedModels(state: SimState): Set { + const out = new Set(); + const add = (policy: string | undefined, harness: string | undefined) => { + if (!policy) return; + out.add(policy); + if (harness) out.add(`${harness}::${policy}`); + }; + for (const attempt of allAttempts(state)) { + add(attempt.policy, effectiveHarness(attempt)); + for (const obs of attempt.observations) add(obs.policy, effectiveHarness(obs)); + } + for (const carry of state.carried_from) { + add(carry.from.policy, carry.from.harness); + add(carry.into.policy, carry.into.harness); + } + return out; +} + +function unseenModels(state: SimState, telemetry: ReadonlyArray) { + const known = observedModels(state); + const out = new Map(); + for (const event of telemetry) { + if (event.kind !== "new_model_observed" || known.has(event.model)) continue; + out.set(`${event.providerInstanceId}::${event.model}`, { + providerInstanceId: event.providerInstanceId, + model: event.model, + }); + } + return [...out.values()]; +} + +/** Live rules to reassess under a model (and optionally one harness): failures first, then the most model-dependent. */ +export function renderReview( + state: SimState, + options: { + readonly policy?: string | undefined; + readonly harness?: string | undefined; + readonly page?: number | undefined; + readonly telemetry?: ReadonlyArray; + }, +): string { + const last = state.carried_from[state.carried_from.length - 1]; + const policy = options.policy ?? last?.into.policy; + const harness = + options.harness ?? (options.policy === undefined ? last?.into.harness : undefined); + if (!policy) + throw invalid('name the model to review for: SIM read action "review" with policy '); + const rows: Array<{ rank: number; failed: boolean; id: number; text: string }> = []; + for (const problem of state.problems) { + for (const attempt of problem.attempts.filter((item) => item.live)) { + const here = standing(attempt).filter( + (obs) => obs.policy === policy && (!harness || effectiveHarness(obs) === harness), + ); + if (here.some((obs) => obs.result === "kept")) continue; + const failed = here.filter((obs) => FAILURE_RESULTS.includes(obs.result)); + const confirmed = here.filter((obs) => settlesFix(attempt, obs)); + if (!failed.length && confirmed.length) continue; + const seen = here.length + ? tallyText(tally([{ ...attempt, observations: here, live: false }])) + : "no outcome"; + const rank = + (failed.length ? 0 : 10) + + (SIM_DEPENDS.findIndex((item) => attempt.depends_on.includes(item)) + 1 || 9); + const made = effectiveHarness(attempt); + const origin = + attempt.policy === policy ? "made under this model" : `made under ${attempt.policy}`; + rows.push({ + rank, + failed: failed.length > 0, + id: idNumber(attempt.id), + text: `${attempt.id} ${problem.id} [${attempt.depends_on.join(",")}] ${short(attempt.files[0] ?? "")} "${attempt.anchor}" | ${origin}${made ? ` (${made})` : ""} | under ${policy}${harness ? ` on ${harness}` : ""}: ${seen}`, + }); + } + } + rows.sort((a, b) => a.rank - b.rank || a.id - b.id); + const failures = rows.filter((row) => row.failed).length; + const where = `${policy}${harness ? ` on ${harness}` : ""}`; + const head = [ + `Live rules to reassess under ${where}: ${rows.length} (${failures} with a failure under it, ${rows.length - failures} without a confirmed outcome under it). Failures first, then the rules that depend on the model.`, + ]; + const fresh = unseenModels(state, options.telemetry ?? []); + if (fresh.length) { + head.push( + `Models seen in T3 runs but not yet in SIM (record a carry when one is a new generation): ${fresh.map((item) => `${item.model} (${item.providerInstanceId})`).join(", ")}`, + ); + } + const tail = [ + 'For each: read the entry in full, then keep it (observe with result "kept" and the reason), or revise, replace or remove it (attempt).', + "A rule without an outcome is untested: that is neither evidence for it nor against it.", + ]; + return paged({ + command: `SIM review ${where}`, + page: options.page, + head, + units: rows.map((row) => row.text), + tail, + }); +} + +/** Tricky cases worth a stronger model's second opinion; undefined when there are none or the advisor is off. */ +export function buildAdvisorEscalation( + state: SimState, + settings: Pick, + health: Pick, + telemetry: ReadonlyArray, +): SimAdvisorEscalation | undefined { + const modelSelection = settings.advisorModelSelection; + if (modelSelection === null) return undefined; + const candidates: Array = []; + for (const problem of state.problems) { + const liveAttempts = problem.attempts.filter((attempt) => attempt.live); + const hasFailingLive = liveAttempts.some((attempt) => + standing(attempt).some((obs) => FAILURE_RESULTS.includes(obs.result)), + ); + const failedAttempts = problem.attempts.filter( + (attempt) => + !attempt.retracted && standing(attempt).some((obs) => FAILURE_RESULTS.includes(obs.result)), + ); + if (failedAttempts.length >= 2 && hasFailingLive) { + candidates.push({ + kind: "recurring_failures", + id: problem.id, + summary: `${problem.id} has ${failedAttempts.length} attempts that failed (${failedAttempts.map((a) => a.id).join(", ")}): ${clip(problem.name, 120)}`, + }); + } + const conflicting = liveAttempts.filter((attempt) => { + const outcomes = standing(attempt); + const setting = (obs: SimObservation) => `${obs.policy}::${effectiveHarness(obs) ?? ""}`; + const fixedIn = new Set(outcomes.filter((obs) => obs.result === "fixed").map(setting)); + const failedIn = new Set( + outcomes.filter((obs) => FAILURE_RESULTS.includes(obs.result)).map(setting), + ); + return [...fixedIn].some((where) => [...failedIn].some((other) => other !== where)); + }); + const conflictLinks = + liveAttempts.length > 0 ? problem.related.filter((link) => link.kind === "conflicts") : []; + if (conflicting.length || conflictLinks.length) { + const parts = [ + ...(conflicting.length + ? [ + `fixed under one model or harness and failed under another (${conflicting.map((a) => a.id).join(", ")})`, + ] + : []), + ...(conflictLinks.length + ? [`conflicts with ${conflictLinks.map((link) => link.id).join(", ")}`] + : []), + ]; + candidates.push({ + kind: "cross_harness_conflict", + id: problem.id, + summary: `${problem.id}: ${parts.join("; ")}`, + }); + } + } + const hasLiveModelRules = allAttempts(state).some( + (attempt) => attempt.live && attempt.depends_on.includes("model"), + ); + if (hasLiveModelRules) { + for (const item of unseenModels(state, telemetry)) { + candidates.push({ + kind: "new_model_generation", + summary: `${item.model} (${item.providerInstanceId}) runs in T3 but has no SIM record or carry yet`, + }); + } + } + const unrecorded = telemetry.filter((event) => event.kind === "unrecorded_harness_edit").length; + if (health.drift.length + unrecorded >= 2) { + candidates.push({ + kind: "repeated_drift", + summary: `${count(health.drift.length, "drifted rule")} and ${count(unrecorded, "unrecorded harness edit")}`, + }); + } + if (!candidates.length) return undefined; + const target = { + providerInstanceId: modelSelection.instanceId, + model: modelSelection.model, + ...(modelSelection.options !== undefined ? { options: modelSelection.options } : {}), + }; + return { + modelSelection, + candidates, + guidance: + `These SIM cases are tricky enough for a second opinion. Only on demand, never for routine edits: call delegate_task with role "design" and target ${JSON.stringify(target)}, ` + + "hand it the entries named here (read them in full first), and ask for a diagnosis and a proposed attempt. Record any resulting change yourself through the SIM tools.", + }; +} + +export interface SimReadContext { + readonly paths: SimResolvedPaths; + readonly loaded: SimLoaded; + readonly caller: SimCallerContext; + readonly settings: Pick; + readonly telemetry: ReadonlyArray; +} + +export function runRead(context: SimReadContext, request: SimReadRequest): SimReadResult { + const { paths, loaded, caller } = context; + const { journal, state, healed } = loaded; + const scope = seenScope(paths, caller); + const health = inspectHarness(state, paths); + const head: Array = []; + if (healed) head.push(HEALED_NOTE); + head.push(...warnings(state, journal, health)); + const escalation = () => + buildAdvisorEscalation(state, context.settings, health, context.telemetry); + const writable = !journal.broken; + + switch (request.action) { + case "index": { + if (!state.problems.length) { + if (writable) markIndexShown(paths, scope); + return { + text: [ + ...head, + journal.broken + ? "Nothing can be shown until the journal is restored." + : "The record is empty.", + rulesPointer(), + ].join("\n"), + }; + } + head.push(`${count(state.problems.length, "root cause")}: ${INDEX_LEGEND}`); + const tail = [ + 'In full: action "show" with ids. Every entry in brief: action "brief_all". Rules of a file: action "by_file". Search: action "find".', + rulesPointer(), + ]; + const text = paged({ + command: "SIM index", + page: request.page, + head, + units: state.problems.map(indexLine), + tail, + shown: writable ? () => markIndexShown(paths, scope) : null, + }); + return { text }; + } + case "by_file": { + if (!isText(request.file)) + throw invalid('give the harness file: action "by_file" with file '); + const file = resolveCallerFile(request.file, caller, paths); + if (writable) markIndexShown(paths, scope, file); + const rules = renderFile(state, file); + return { + text: [ + ...head, + `${file}: ${count(rules.length, "recorded rule")}. Entry, attempt, and the phrase that identifies the rule:`, + ...rules, + rulesPointer(), + ].join("\n"), + }; + } + case "find": { + if (!isText(request.query)) + throw invalid('give the words to search for: action "find" with query'); + const hits = searchProblems(state, request.query); + if (!hits.length) return { text: `no entry contains: ${request.query}` }; + return { + text: paged({ + command: `SIM find ${request.query}`, + page: request.page, + units: hits.map(indexLine), + }), + }; + } + case "show": + case "brief_all": { + const all = request.action === "brief_all" || !request.ids?.length; + const brief = request.action === "brief_all" || request.brief === true; + let selected: Array = state.problems; + if (!all) { + selected = []; + const missing: Array = []; + for (const raw of request.ids ?? []) { + const id = raw.trim(); + const problem = id.startsWith("A") + ? findAttempt(state, id)?.problem + : findProblem(state, id); + if (!problem) missing.push(id); + else if (!selected.includes(problem)) selected.push(problem); + } + if (missing.length) throw fail("not_found", `not in the record: ${missing.join(", ")}`); + } + if (all && state.carried_from.length) head.push(renderCarried(state)); + const units = selected.map((problem) => + brief ? renderBrief(state, problem) : renderProblem(state, problem), + ); + const command = `SIM show ${all ? "all" : (request.ids ?? []).join(" ")}${brief ? " brief" : ""}`; + const text = paged({ + command, + page: request.page, + head, + units, + separator: "\n\n", + tail: [rulesPointer()], + shown: writable + ? (parts) => + markShown( + paths, + state, + parts.map(({ index, from, to, of }) => ({ + problem: selected[index]!, + from, + to, + of, + })), + brief ? "brief" : "full", + scope, + ) + : null, + }); + return { text }; + } + case "check": + return renderCheck(paths, loaded, health, request.page); + case "review": + return { + text: renderReview(state, { + policy: request.policy, + harness: request.harness, + page: request.page, + telemetry: context.telemetry, + }), + advisorEscalation: escalation(), + }; + } +} + +function renderCheck( + paths: SimResolvedPaths, + loaded: SimLoaded, + health: SimHarnessHealth, + page?: number, +) { + const { journal, state, healed } = loaded; + const errors: Array = []; + const notes: Array = []; + if (journal.broken) errors.push(brokenHelp(journal.broken)); + if (healed) notes.push(HEALED_NOTE); + const { drift, uncovered, unchecked } = health; + for (const item of drift) { + const hit = findAttempt(state, item.attempt.id); + errors.push(`DRIFT ${item.attempt.id} (${hit?.problem.id ?? "?"}): ${item.reason}`); + } + if (drift.length) { + notes.push( + "DRIFT: a recorded rule changed without a record. If only the wording moved, amend its anchor; else record an attempt that revises, replaces or removes it.", + ); + } + for (const unit of uncovered) { + errors.push( + `NO RECORD ${unit.file}: ${unit.text === null ? "hook" : `"${squash(unit.text).slice(0, 90)}"`}`, + ); + } + if (uncovered.length) { + notes.push( + "NO RECORD: a Scar, Win or hook has no live record. Record it as an attempt (backfilled, with the session that made it if you know it).", + ); + } + if (unchecked.length) { + notes.push( + `not checked (file not on this machine): ${unchecked.map((attempt) => attempt.id).join(", ")}`, + ); + } + for (const [session, events] of journal.broken ? [] : strangers(journal, paths)) { + const who = + session === SIM_UNKNOWN + ? "a session without an id" + : session.startsWith("cc:") + ? `${session}, a session without a transcript on this machine` + : `${session}, a session this tool cannot look up`; + notes.push( + `note: ${count(events.length, "journal event")} of the last ${SEEN_DAYS} days (${events[0]} to ${events[events.length - 1]}) came from ${who}. Session ids are taken on trust: check that these events are genuine.`, + ); + } + const index = estimateTokens(renderIndex(state)); + const full = estimateTokens( + state.problems.map((problem) => renderProblem(state, problem)).join("\n\n"), + ); + notes.push( + `size: index about ${index} tokens (budget ${SIM_INDEX_BUDGET}), everything about ${full} tokens (budget ${SIM_FULL_BUDGET})`, + ); + if (index > SIM_INDEX_BUDGET) { + notes.push( + `The index is over its budget: every harness change now reads about ${index} tokens. The budget is the user's to raise; entries are never dropped or lumped to meet it.`, + ); + } + if (full > SIM_FULL_BUDGET) { + notes.push( + "Everything in full is over its budget: at a model change, go entry by entry from review instead of reading every entry in full in a small context.", + ); + } + const live = allAttempts(state).filter((attempt) => attempt.live).length; + notes.push( + `${count(state.problems.length, "root cause")}, ${count(allAttempts(state).length, "attempt")}, ${live} live, ${count(journal.events.length, "journal event")}`, + ); + const failed = errors.length > 0; + const tail = [...notes, failed ? `${count(errors.length, "problem")} found.` : "ok"]; + return { + text: paged({ + command: "SIM check", + page, + units: errors, + tail, + size: failed ? FAIL_CHARS : SIM_DEFAULT_PAGE_CHARS, + }), + failed, + }; +} + +const eventStamp = (caller: SimCallerContext, harness?: string | undefined): SimEventStamp => ({ + by: isText(caller.sessionId) ? caller.sessionId : SIM_UNKNOWN, + ...(caller.alsoSessionId && caller.alsoSessionId !== caller.sessionId + ? { also: caller.alsoSessionId } + : {}), + ...(harness ? { harness } : {}), +}); + +const callerHarness = (caller: SimCallerContext) => caller.driver ?? caller.providerInstanceId; + +/** Fill what the server knows about the caller into an attempt the caller left open. */ +function resolveAttemptDefaults( + input: SimAttemptInput, + caller: SimCallerContext, + paths: SimResolvedPaths, +): SimAttemptInput { + const files = input.files?.map((file) => resolveCallerFile(file, caller, paths)); + const global = files?.length && files.every((file) => file.startsWith("~/.claude/")); + const policy = input.policy ?? caller.model; + const harness = input.harness ?? callerHarness(caller); + const domain = input.domain ?? (global ? "global" : (caller.projectName ?? "global")); + return { + ...input, + ...(files ? { files } : {}), + ...(policy ? { policy } : {}), + ...(harness ? { harness } : {}), + domain, + }; +} + +/** `~/.claude/` names the configured harness dir, as in the record; other `~/` paths the home dir. */ +function expandCallerPath(file: string, paths: SimResolvedPaths): string { + const trimmed = file.trim(); + return trimmed.startsWith("~/.claude/") + ? expandHarnessFile(trimmed, paths) + : expandHomeString(trimmed, paths.homeDir); +} + +/** A path as the caller wrote it, resolved against its workspace, in the record's spelling. */ +export function resolveCallerFile( + file: string, + caller: SimCallerContext, + paths: SimResolvedPaths, +): string { + const trimmed = file.trim(); + if ( + trimmed.startsWith("~/") || + NodePath.isAbsolute(trimmed) || + /^\$(?:HOME|\{HOME\})\//.test(trimmed) + ) { + return canonicalFile(trimmed, paths); + } + return canonicalFile(NodePath.resolve(caller.workspaceRoot ?? paths.homeDir, trimmed), paths); +} + +const ATTEMPT_INPUT_KEYS = [ + "problem", + "new", + "action", + "what", + "why", + "files", + "anchor", + "supersedes", + "depends_on", + "predicted", + "expect", + "policy", + "domain", + "accepted", + "rejected_because", + "unanswered", + "backfilled", + "round", + "sample", +] as const; + +/** The journal data of an attempt: never `harness`, which travels on the envelope. */ +function attemptData(input: SimAttemptInput): Data { + const data: Data = {}; + for (const key of ATTEMPT_INPUT_KEYS) { + const value = input[key]; + if (value === undefined) continue; + data[key] = Array.isArray(value) + ? value.map((item) => (typeof item === "string" ? item.trim() : item)) + : value; + } + if (isText(data.problem)) data.problem = data.problem.trim(); + return data; +} + +/** + * Anchor checks right after the edit: the anchor must identify exactly one place, and the file that + * holds it moves first. `overrides` stands in for files whose new content is not on disk yet. + */ +function checkAgainstFiles( + input: Data, + paths: SimResolvedPaths, + overrides?: ReadonlyMap, +) { + const findings: Array = []; + if ( + input.accepted !== false && + input.action !== "remove" && + isText(input.anchor) && + Array.isArray(input.files) && + input.files.every((file) => isText(file)) && + input.files.length + ) { + const anchor = input.anchor; + const files = (input.files as Array).map((file) => canonicalFile(file, paths)); + const hits = files.map((file) => { + const text = readHarnessFile(file, paths, overrides); + return text === null ? 0 : occurrences(text, anchor); + }); + const holders = files.filter((_, index) => (hits[index] ?? 0) > 0); + const first = holders[0]; + if (!first) { + findings.push( + `the anchor is in none of ${files.join(", ")}; make the change first, and quote a phrase of the rule exactly`, + ); + } else if (holders.length > 1 || (hits[files.indexOf(first)] ?? 0) > 1) { + findings.push( + `the anchor occurs more than once in ${holders.join(", ")}; quote a longer phrase that occurs once`, + ); + } else { + input.files = [first, ...files.filter((file) => file !== first)]; + } + } + if (findings.length && input.backfilled !== true) throw invalid(findings); + return findings; +} + +interface PreparedAttempt { + readonly data: Data; + readonly harness: string | undefined; + readonly findings: ReadonlyArray; + readonly target: SimProblem | null; +} + +/** Everything sim.mjs checks before it appends an attempt, in its order: fields, today, twin, files, reading. */ +function prepareAttempt( + paths: SimResolvedPaths, + loaded: SimLoaded, + caller: SimCallerContext, + rawInput: SimAttemptInput, + overrides?: ReadonlyMap, +): PreparedAttempt { + const { state, journal } = loaded; + if (journal.broken) throw fail("journal_broken", brokenHelp(journal.broken)); + const input = resolveAttemptDefaults(rawInput, caller, paths); + const data = attemptData(input); + const stampCtx = eventStamp(caller, input.harness); + applyEvent( + structuredClone(state), + { + seq: state.events + 1, + v: SIM_FORMAT, + day: today(), + by: stampCtx.by, + op: "attempt", + data: { ...data, considered: [] }, + }, + paths, + ); + const me = [caller.sessionId, caller.alsoSessionId] + .filter((id): id is string => isText(id)) + .map(bare); + if ( + data.backfilled === true && + data.round === today() && + (!isText(data.sample) || me.includes(bare(data.sample.trim()))) + ) { + throw invalid( + 'a change made today is recorded as it is, not as an old one: leave out "backfilled", "round" and "sample", and give "expect". Only when another session made it and left no record: name that session in "sample".', + ); + } + const target = isText(data.problem) + ? findProblem(state, data.problem) + : isText(data.new) + ? problemNamed(state, data.new) + : null; + const same = (a: unknown, b: unknown) => squash(a) === squash(b); + const twin = target?.attempts.find( + (item) => + !item.retracted && + item.action === data.action && + item.accepted === (data.accepted !== false) && + same(item.what, data.what) && + same(item.why, data.why), + ); + if (twin) { + const outcome = twin.live ? ` An outcome of it goes to: observe ${twin.id}.` : ""; + throw invalid( + `this change is already in the record as ${twin.id}: same entry, action, "what" and "why".${outcome} A change that is repeated on new evidence names that evidence in "why".`, + ); + } + const findings = checkAgainstFiles(data, paths, overrides); + const scope = seenScope(paths, caller); + data.considered = requireReading(state, shownTo(paths, state, scope), data); + if (data.backfilled !== true) { + requireIndexConsulted( + paths, + scope, + Array.isArray(data.files) ? (data.files as Array) : [], + ); + } + return { data, harness: input.harness, findings, target }; +} + +function appendAttempt( + paths: SimResolvedPaths, + caller: SimCallerContext, + prepared: PreparedAttempt, + state: SimState, +) { + const scope = seenScope(paths, caller); + const before = shownTo(paths, state, scope); + const done = append(paths, "attempt", prepared.data, eventStamp(caller, prepared.harness)); + keepShown( + paths, + before, + done.state, + scope, + done.outcome.created ? (done.outcome.problem ?? null) : null, + ); + return done; +} + +function attemptReply(prepared: PreparedAttempt, done: ReturnType): SimWriteResult { + const { outcome, state } = done; + const place = outcome.created ? `new entry ${outcome.problem}` : `entry ${outcome.problem}`; + const joined = + !outcome.created && prepared.data.new + ? " (an entry with this root cause existed; the attempt was added to it)" + : ""; + const out = [`recorded ${outcome.attempt} in ${place}${joined}.`]; + if (prepared.data.accepted !== false) { + out.push(`When you see how it performs: observe ${outcome.attempt}`); + const gone = (findProblem(state, outcome.problem)?.attempts ?? []).filter( + (item) => + item.id !== outcome.attempt && + !item.retracted && + (!item.accepted || item.action === "remove"), + ); + if (prepared.data.action !== "remove" && gone.length) { + out.push( + `note: this entry holds ${count(gone.length, "change")} that ${gone.length === 1 ? "was" : "were"} removed or not carried out (${gone.map((item) => item.id).join(", ")}). If yours repeats one of them, its "why" must name the new evidence; correct it with amend ${outcome.attempt} why`, + ); + } + } + for (const finding of prepared.findings) { + out.push(`note: ${finding} (fine if a later change replaced it; record that change next)`); + } + return { text: out.join("\n"), problemId: outcome.problem, attemptId: outcome.attempt }; +} + +/** A statement about entries (merge, link, amend, retract) is taken only from a session shown them. */ +function writeShown( + paths: SimResolvedPaths, + loaded: SimLoaded, + caller: SimCallerContext, + op: SimJournalOp, + data: Data, + needOf: (state: SimState) => Array<[SimProblem | null, "full" | "brief", string]>, + textOf: (state: SimState) => string | null = () => null, + check: ((state: SimState) => void) | null = null, +) { + const { state, journal } = loaded; + if (journal.broken) throw fail("journal_broken", brokenHelp(journal.broken)); + const stampCtx = eventStamp(caller); + applyEvent( + structuredClone(state), + { seq: state.events + 1, v: SIM_FORMAT, day: today(), by: stampCtx.by, op, data }, + paths, + ); + check?.(state); + const scope = seenScope(paths, caller); + const before = shownTo(paths, state, scope); + const need: Need = new Map(); + for (const [problem, level, why] of needOf(state)) + if (problem) need.set(problem.id, [level, why]); + demandShown(state, before, need, textOf(state)); + const done = append(paths, op, data, stampCtx); + keepShown(paths, before, done.state, scope); + return done; +} + +function keepsWords(name: string, wordings: ReadonlyArray) { + const now = words(name); + return wordings.every((wording) => { + const was = [...words(wording)]; + return was.length > 0 && was.filter((word) => now.has(word)).length * 2 >= was.length; + }); +} + +function wordingsOf(problem: SimProblem) { + const chain = [ + ...(problem.amended ?? []) + .filter((change) => change.field === "name") + .map((change) => String(change.was)), + problem.name, + ]; + let base = 0; + for (let i = 1; i < chain.length; i += 1) + if (!keepsWords(chain[i]!, chain.slice(base, i))) base = i; + return chain.slice(base); +} + +const entryOf = + (attemptId: string) => + (state: SimState): Array<[SimProblem | null, "full" | "brief", string]> => [ + [findAttempt(state, attemptId)?.problem ?? null, "full", "it holds the record you correct"], + ]; + +/** Run one write; the caller holds sim.lock. */ +export function runWrite( + paths: SimResolvedPaths, + caller: SimCallerContext, + request: SimWriteRequest, +): SimWriteResult { + const loaded = load(paths); + switch (request.action) { + case "attempt": { + const prepared = prepareAttempt(paths, loaded, caller, request.input); + return attemptReply(prepared, appendAttempt(paths, caller, prepared, loaded.state)); + } + case "observe": + return observe(paths, loaded, caller, request.input); + case "merge": { + const { from, into } = request; + const { outcome } = writeShown(paths, loaded, caller, "merge", { from, into }, (state) => [ + [findProblem(state, from), "full", "you merge it away"], + [findProblem(state, into), "full", "you merge into it"], + ]); + return { + text: `merged ${outcome.merged} into ${outcome.problem}; all attempts are kept, and ${outcome.merged} still resolves.`, + problemId: outcome.problem, + }; + } + case "link": { + const { a, b, kind } = request; + writeShown(paths, loaded, caller, "link", { a, b, kind }, (state) => + [a, b].map((id) => [findProblem(state, id), "brief", "you link it"]), + ); + return { text: `linked: ${a} ${kind} ${b}.` }; + } + case "carry": { + if (loaded.journal.broken) throw fail("journal_broken", brokenHelp(loaded.journal.broken)); + const side = (policy?: string, domain?: string, harness?: string) => ({ + ...(policy ? { policy } : {}), + ...(domain ? { domain } : {}), + ...(harness ? { harness } : {}), + }); + append( + paths, + "carry", + { + date: request.date ?? today(), + from: side(request.fromPolicy, request.fromDomain, request.fromHarness), + into: side(request.toPolicy, request.toDomain, request.toHarness), + ...(request.note ? { note: request.note } : {}), + }, + eventStamp(caller), + ); + return { + text: 'recorded the change of setting. List what to reassess with the SIM "review" read.', + }; + } + case "retract": { + const { attempt, outcome, reason, undo } = request; + writeShown( + paths, + loaded, + caller, + "retract", + { + attempt, + ...(outcome === undefined ? {} : { outcome }), + reason, + ...(undo ? { undo } : {}), + }, + entryOf(attempt), + ); + const what = outcome === undefined ? attempt : `outcome ${outcome} of ${attempt}`; + return { + text: undo + ? `${what} counts again.` + : `retracted ${what}; it stays in the record and no longer counts.`, + attemptId: attempt, + }; + } + case "amend": { + const { target, field, reason } = request; + const value: unknown = Array.isArray(request.value) ? [...request.value] : request.value; + const data: Data = { target, field, value, reason }; + const check = (state: SimState) => { + const hit = field === "anchor" || field === "files" ? findAttempt(state, target) : null; + if (!hit?.attempt.live) return; + const files = + field === "files" && Array.isArray(value) + ? value.map((file) => resolveCallerFile(String(file), caller, paths)) + : hit.attempt.files; + const probe: Data = { + action: hit.attempt.action, + anchor: field === "anchor" ? value : hit.attempt.anchor, + files, + }; + checkAgainstFiles(probe, paths); + if (field === "files") data.value = probe.files; + }; + const renames = isText(target) && target.startsWith("P"); + const twinOf = (state: SimState) => + problemNamed(state, value, findProblem(state, target)?.id ?? null); + const needOf = renames + ? (state: SimState): Array<[SimProblem | null, "full" | "brief", string]> => [ + [findProblem(state, target), "full", "you rename it"], + ...(twinOf(state) + ? [ + [twinOf(state), "full", "it has this root cause already"] as [ + SimProblem | null, + "full", + string, + ], + ] + : []), + ] + : entryOf(target); + const textOf = (state: SimState) => { + const problem = findProblem(state, target); + return !renames || + !problem || + twinOf(state) || + keepsWords(String(value), wordingsOf(problem)) + ? null + : String(value); + }; + const { outcome } = writeShown(paths, loaded, caller, "amend", data, needOf, textOf, check); + return { + text: outcome.merged + ? `amended; ${outcome.merged} now has the same root cause as ${outcome.problem} and was merged into it.` + : `amended ${target}.`, + ...(outcome.problem ? { problemId: outcome.problem } : {}), + }; + } + } +} + +function observe( + paths: SimResolvedPaths, + loaded: SimLoaded, + caller: SimCallerContext, + input: SimObserveInput, +): SimWriteResult { + const { state, journal } = loaded; + if (journal.broken) throw fail("journal_broken", brokenHelp(journal.broken)); + const attemptId = input.attempt.trim(); + const hit = findAttempt(state, attemptId); + // A fork-family "fixed" report is coerced to "self" so that sim.mjs, which knows nothing of forks, refuses it too. + const selfGradeReason = + input.result === "fixed" + ? (input.selfGradeReason ?? + (hit && sharesFamily(hit.attempt, caller.forkFamilySessionIds ?? []) + ? FORK_FAMILY_REASON + : undefined)) + : undefined; + const harness = input.harness ?? callerHarness(caller); + const policy = input.policy ?? caller.model; + const domain = input.domain ?? hit?.attempt.domain; + const observation: Data = { + ...(input.target !== undefined ? { target: input.target } : {}), + result: input.result, + evidence: input.evidence, + source: selfGradeReason ? "self" : input.source, + ...(policy !== undefined ? { policy } : {}), + ...(domain !== undefined ? { domain } : {}), + ...(input.date !== undefined ? { date: input.date } : {}), + }; + const scope = seenScope(paths, caller); + const before = shownTo(paths, state, scope); + const done = append( + paths, + "observe", + { attempt: attemptId, observation }, + eventStamp(caller, harness), + ); + keepShown(paths, before, done.state, scope); + const record = findAttempt(done.state, done.outcome.attempt)!.attempt; + const last = record.observations[record.observations.length - 1]!; + const own = last.result === "fixed" ? (selfGradeReason ?? ownReport(record, last)) : null; + const note = own + ? `\nnote: this report does not settle the prediction (${own}). A change is not judged by the session that made or recorded it, nor by its forks; an outcome from another session settles it.` + : ""; + return { + text: `recorded for ${done.outcome.attempt} in ${done.outcome.problem}: fixed ${record.fixed.length}, missed ${record.missed.length}, open ${record.pending.length}.${note}`, + ...(done.outcome.problem ? { problemId: done.outcome.problem } : {}), + attemptId: done.outcome.attempt, + settled: last.result === "fixed" && !own, + ...(own ? { unconfirmedReason: own } : {}), + }; +} + +function diffPreview(before: string, after: string): string { + const a = before.split("\n"); + const b = after.split("\n"); + let start = 0; + while (start < a.length && start < b.length && a[start] === b[start]) start += 1; + let endA = a.length; + let endB = b.length; + while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) { + endA -= 1; + endB -= 1; + } + return clip( + [ + `@@ line ${start + 1} @@`, + ...a.slice(start, endA).map((line) => `-${line}`), + ...b.slice(start, endB).map((line) => `+${line}`), + ].join("\n"), + 4000, + ); +} + +function proposedContent(request: SimApplyHarnessChangeRequest, current: string | null): string { + if (request.oldText !== undefined || request.newText !== undefined) { + if (request.oldText === undefined || request.newText === undefined) { + throw invalid("give both oldText and newText for a replacement"); + } + if (current === null) throw invalid("the file does not exist; create it with content instead"); + if (!request.oldText) throw invalid("oldText must not be empty"); + const hits = current.split(request.oldText).length - 1; + if (hits !== 1) { + throw invalid(`oldText occurs ${hits} times in the file; it must occur exactly once`); + } + return current.replace(request.oldText, () => request.newText!); + } + if (request.content === undefined) + throw invalid("give oldText and newText, or content (with append: true to add)"); + if (request.append === true) { + const base = current ?? ""; + return base && !base.endsWith("\n") + ? `${base}\n${request.content}` + : `${base}${request.content}`; + } + return request.content; +} + +export interface SimHarnessChangeOutcome { + readonly result: SimApplyHarnessChangeResult; + /** Files of the recorded attempt, in the record's spelling; empty for a dry run. */ + readonly recordedFiles: ReadonlyArray; +} + +/** Edit a harness file and record the attempt as one step; the caller holds sim.lock for a live apply. */ +export function runApplyHarnessChange( + paths: SimResolvedPaths, + caller: SimCallerContext, + request: SimApplyHarnessChangeRequest, + options: { readonly classify: (absolute: string) => "record" | "harness" | null }, +): SimHarnessChangeOutcome { + const absolute = NodePath.resolve( + caller.workspaceRoot ?? paths.homeDir, + expandCallerPath(request.file, paths), + ); + const kind = options.classify(absolute); + if (kind === "record") { + throw fail( + "forbidden_path", + `${request.file} is part of the SIM record; it changes only through the SIM tools`, + ); + } + if (kind !== "harness") { + throw fail( + "forbidden_path", + `${request.file} is not an agent harness file; edit it with your normal tools`, + ); + } + const inHarnessDir = + isPathWithinRoot(absolute, paths.harnessDir, undefined, paths.homeDir) || + (NodeFS.existsSync(absolute) && + isPathWithinRoot(NodePath.dirname(absolute), paths.harnessDir, undefined, paths.homeDir)); + const inWorkspace = + isText(caller.workspaceRoot) && + isPathWithinRoot(absolute, caller.workspaceRoot, undefined, paths.homeDir); + if (!inHarnessDir && !inWorkspace) { + throw fail( + "forbidden_path", + `${request.file} lies outside the configured harness directory and this thread's workspace`, + ); + } + const file = canonicalFile(absolute, paths); + const loaded = request.dryRun === true ? loadReadOnly(paths) : load(paths); + if (loaded.journal.broken) throw fail("journal_broken", brokenHelp(loaded.journal.broken)); + if (request.attempt.backfilled === true) { + throw invalid("a change made now is recorded as it is: leave out backfilled, round and sample"); + } + const health = inspectHarness(loaded.state, paths); + const supersedes = new Set((request.attempt.supersedes ?? []).map((id) => id.trim())); + const drifted = health.drift.filter( + (item) => item.attempt.files[0] === file && !supersedes.has(item.attempt.id), + ); + if (drifted.length) { + throw fail("drift", [ + ...drifted.map((item) => `DRIFT ${item.attempt.id}: ${item.reason}`), + "Reconcile first: amend the anchor if only the wording moved, or name the drifted attempt in supersedes.", + ]); + } + const attemptFiles = (request.attempt.files ?? []).map((item) => + resolveCallerFile(item, caller, paths), + ); + const files = [file, ...attemptFiles.filter((item) => item !== file)]; + let writeTarget = absolute; + let originalMode: number | undefined; + let current: string | null = null; + let existed = false; + try { + writeTarget = NodeFS.realpathSync(absolute); + const stat = NodeFS.statSync(writeTarget); + originalMode = stat.mode & 0o7777; + current = NodeFS.readFileSync(writeTarget, "utf8"); + existed = true; + } catch { + writeTarget = absolute; + current = null; + } + const next = proposedContent(request, current); + if (next === current) throw invalid("the change leaves the file as it is"); + const overrides = new Map([[file, next]]); + const prepared = prepareAttempt(paths, loaded, caller, { ...request.attempt, files }, overrides); + const target = prepared.target; + const predicted = Array.isArray(prepared.data.predicted) + ? (prepared.data.predicted as Array) + : []; + const predictionLine = `predicted to fix: ${predicted.join(", ") || "nothing"}${isText(prepared.data.expect) ? `; expect: ${prepared.data.expect}` : ""}`; + const preview = diffPreview(current ?? "", next); + if (request.dryRun === true) { + return { + result: { + dryRun: true, + file, + ...(target ? { brief: renderBrief(loaded.state, target), problemId: target.id } : {}), + predictionLine, + diffPreview: preview, + text: [ + `dry run: nothing written. ${file} would change and the attempt would be recorded${target ? ` under ${target.id}` : " as a new entry"}.`, + predictionLine, + preview, + ].join("\n"), + }, + recordedFiles: [], + }; + } + const original = existed ? NodeFS.readFileSync(writeTarget) : null; + NodeFS.mkdirSync(NodePath.dirname(writeTarget), { recursive: true }); + writeWhole(writeTarget, next, { mode: originalMode }); + let done: ReturnType; + try { + // On disk now: the anchor must hold there, not only in the proposal. + checkAgainstFiles(prepared.data, paths); + done = appendAttempt(paths, caller, prepared, loaded.state); + } catch (error) { + // Once the journal holds the attempt, the edit is recorded: keep it even if a later step (sim.json, backup) failed. + if (readJournal(paths.journalPath).events.length <= loaded.journal.events.length) { + if (original !== null) writeWhole(writeTarget, original, { mode: originalMode }); + else NodeFS.rmSync(writeTarget, { force: true }); + } + throw error; + } + const reply = attemptReply(prepared, done); + return { + result: { + dryRun: false, + file, + text: `${file} changed.\n${reply.text}`, + predictionLine, + diffPreview: preview, + ...(reply.problemId ? { problemId: reply.problemId } : {}), + ...(reply.attemptId ? { attemptId: reply.attemptId } : {}), + }, + recordedFiles: Array.isArray(prepared.data.files) + ? (prepared.data.files as Array) + : [file], + }; +} + +/** Sessions that made or recorded an attempt, as the record names them. */ +export function attemptAuthorSessions(state: SimState, attemptId: string): Array { + const hit = findAttempt(state, attemptId); + if (!hit) return []; + return [...new Set([hit.attempt.by, hit.attempt.also, hit.attempt.sample])].filter( + (id): id is string => !!id && id !== SIM_UNKNOWN, + ); +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 669346f4bfb33..22d6b08cb7b2a 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1493,6 +1493,43 @@ export const ServerSettings = Schema.Struct({ orchestratorThreadWorkerEfforts: Schema.Array(OrchestratorThreadWorkerEffort).pipe( Schema.withDecodingDefault(Effect.succeed([])), ), + /** Self-improvement memory (SIM) cross-harness configuration (fork feature). */ + sim: Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + simDir: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + harnessDir: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + injectRules: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + ruleFiles: Schema.Array(TrimmedNonEmptyString).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), + providerOverrides: Schema.Record(TrimmedNonEmptyString, Schema.Boolean).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + /** Optional on-demand advisor model for tricky SIM escalations; null disables advisor hints. */ + advisorModelSelection: Schema.NullOr(ModelSelection).pipe( + Schema.withDecodingDefault( + Effect.succeed({ + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-fable-5-2", + }), + ), + ), + }).pipe( + Schema.withDecodingDefault( + Effect.succeed({ + enabled: true, + simDir: "", + harnessDir: "", + injectRules: true, + ruleFiles: [], + providerOverrides: {}, + advisorModelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-fable-5-2", + }, + }), + ), + ), snoozePresets: SnoozePresetSettings.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_PRESETS)), ), @@ -1951,6 +1988,17 @@ export const ServerSettingsPatch = Schema.Struct({ orchestratorEffort: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)), orchestratorWorkerEffort: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)), orchestratorThreadWorkerEfforts: Schema.optionalKey(Schema.Array(OrchestratorThreadWorkerEffort)), + sim: Schema.optionalKey( + Schema.Struct({ + enabled: Schema.optionalKey(Schema.Boolean), + simDir: Schema.optionalKey(TrimmedString), + harnessDir: Schema.optionalKey(TrimmedString), + injectRules: Schema.optionalKey(Schema.Boolean), + ruleFiles: Schema.optionalKey(Schema.Array(TrimmedNonEmptyString)), + providerOverrides: Schema.optionalKey(Schema.Record(TrimmedNonEmptyString, Schema.Boolean)), + advisorModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)), + }), + ), snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozePresets: Schema.optionalKey(SnoozePresetSettings), hiddenThreadTags: Schema.optionalKey(Schema.Array(Schema.String)), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 33bc49ff8927a..6ddf7c5f73b7d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8550,10 +8550,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( sessionId: string, ) { const mcpSession = yield* mcpSessions.read(turnInput.threadId); + const threadInstructions = (turnInput.threadInstructions ?? []) + .filter((section) => section.trim().length > 0) + .join("\n\n"); const instructionState = { interactionMode: turnInput.runtimePolicy.interactionMode, hasT3Mcp: mcpSession !== undefined, hasDeviceTools: mcpSession?.capabilities?.has("device") === true, + ...(threadInstructions ? { threadInstructions } : {}), } satisfies T3AcpInstructionState; const userText = flavor.rewriteUserText === undefined diff --git a/packages/provider-core/src/server/orchestrationInstructions.test.ts b/packages/provider-core/src/server/orchestrationInstructions.test.ts index c8dd21cc02634..b9b33787e3aae 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.test.ts @@ -83,3 +83,75 @@ describe("T3 device instructions", () => { assert.notInclude(t3AcpPromptWithInstructions({ prompt: "Hi.", state }), "## T3 Code devices"); }); }); + +describe("ACP thread instructions", () => { + const base = { interactionMode: "default", hasT3Mcp: true, hasDeviceTools: false } as const; + const rules = "## Thread rules\n\nAlways run the focused tests."; + + it("add nothing to the ACP prompt when a thread has no instructions", () => { + const plain = t3AcpPromptWithInstructions({ prompt: "Hi.", state: base }); + assert.match( + plain, + /"clientRequestId":"\.\.\."\}'`\.\n<\/t3_code_instructions>\n\n\nHi\.\n<\/user_request>$/, + ); + assert.notInclude(plain, "T3 thread instructions"); + for (const threadInstructions of [undefined, ""]) { + assert.equal( + t3AcpPromptWithInstructions({ prompt: "Hi.", state: { ...base, threadInstructions } }), + plain, + ); + assert.equal( + t3AcpPromptWithInstructions({ + prompt: "Hi.", + state: { ...base, threadInstructions }, + previousState: base, + }), + "Hi.", + ); + } + }); + + it("deliver once, then again only when they change or are removed", () => { + const state = { ...base, threadInstructions: rules }; + const first = t3AcpPromptWithInstructions({ prompt: "Go.", state }); + assert.include(first, `\n\n${rules}\n`); + assert.notInclude(first, "replace earlier"); + + assert.equal( + t3AcpPromptWithInstructions({ prompt: "Again.", state, previousState: state }), + "Again.", + ); + + const changed = t3AcpPromptWithInstructions({ + prompt: "Next.", + state: { ...base, threadInstructions: "## Thread rules\n\nNew rule." }, + previousState: state, + }); + assert.include( + changed, + "The following T3 thread instructions replace earlier T3 thread instructions:\n## Thread rules\n\nNew rule.\n", + ); + + const removed = t3AcpPromptWithInstructions({ + prompt: "Done.", + state: base, + previousState: state, + }); + assert.include( + removed, + "Earlier T3 thread instructions no longer apply.\n", + ); + assert.notInclude(removed, rules); + }); + + it("resend unchanged thread instructions without a replacement notice when the mode changes", () => { + const state = { ...base, threadInstructions: rules }; + const planned = t3AcpPromptWithInstructions({ + prompt: "Plan.", + state: { ...state, interactionMode: "plan" }, + previousState: state, + }); + assert.include(planned, rules); + assert.notInclude(planned, "replace earlier"); + }); +}); diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 85aeb06dd09ae..6f432e698604e 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -82,6 +82,23 @@ export interface T3AcpInstructionState { readonly interactionMode: ProviderInteractionMode; readonly hasT3Mcp: boolean; readonly hasDeviceTools: boolean; + /** The thread's instruction sections joined by blank lines; omitted when there are none. */ + readonly threadInstructions?: string | undefined; +} + +const T3_ACP_THREAD_INSTRUCTIONS_REPLACED = + "The following T3 thread instructions replace earlier T3 thread instructions:"; +const T3_ACP_THREAD_INSTRUCTIONS_REMOVED = "Earlier T3 thread instructions no longer apply."; + +// The ACP transcript is append-only, so a change or removal must say what it replaces. +function t3AcpThreadInstructions( + current: string | undefined, + previous: string | undefined, +): ReadonlyArray { + if (!current) return previous ? [T3_ACP_THREAD_INSTRUCTIONS_REMOVED] : []; + return previous && previous !== current + ? [`${T3_ACP_THREAD_INSTRUCTIONS_REPLACED}\n${current}`] + : [current]; } /** ACP lacks system/developer fields; inject context on first prompt and tool/mode changes. */ @@ -95,7 +112,9 @@ export function t3AcpPromptWithInstructions(input: { if ( input.previousState?.interactionMode === input.state.interactionMode && input.previousState.hasT3Mcp === input.state.hasT3Mcp && - input.previousState.hasDeviceTools === input.state.hasDeviceTools + input.previousState.hasDeviceTools === input.state.hasDeviceTools && + (input.previousState.threadInstructions || undefined) === + (input.state.threadInstructions || undefined) ) { return input.prompt; } @@ -111,6 +130,10 @@ export function t3AcpPromptWithInstructions(input: { T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS, ] : []), + ...t3AcpThreadInstructions( + input.state.threadInstructions, + input.previousState?.threadInstructions, + ), ]; return `\n${instructions.join("\n\n")}\n\n\n\n${input.prompt}\n`; } diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 0072f9d1897b7..58f4423137bc9 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4338,6 +4338,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr mcpAvailable ? "To wait for a background shell you started (tests, a build), call `t3_background_wait` with its shell ID before you end your turn. Do not mark work you leave running, or PRs." : undefined, + ...(turnInput.threadInstructions ?? []), ] .filter((part) => part !== undefined && part.length > 0) .join("\n\n"); diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 023c6eb74333e..019c06cf3a434 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -409,6 +409,7 @@ export function applyServerSettingsPatch( usageModelAliases: usageModelAliasesPatch, // Entry replacement: deepMerge would keep keys the client meant to clear. projectSettingsOverrides: projectSettingsOverridesPatch, + sim: simPatch, projectAgentBrowserAccessOverrides: _legacyBrowserAccess, projectAutoPullOverrides: _legacyAutoPull, projectScriptOverrides: _legacyScripts, @@ -612,6 +613,24 @@ export function applyServerSettingsPatch( ...(patch.defaultProjectScripts !== undefined ? { defaultProjectScripts: patch.defaultProjectScripts } : {}), + ...(simPatch !== undefined + ? { + sim: { + ...current.sim, + ...(simPatch.enabled !== undefined ? { enabled: simPatch.enabled } : {}), + ...(simPatch.simDir !== undefined ? { simDir: simPatch.simDir } : {}), + ...(simPatch.harnessDir !== undefined ? { harnessDir: simPatch.harnessDir } : {}), + ...(simPatch.injectRules !== undefined ? { injectRules: simPatch.injectRules } : {}), + ...(simPatch.ruleFiles !== undefined ? { ruleFiles: simPatch.ruleFiles } : {}), + ...(simPatch.providerOverrides !== undefined + ? { providerOverrides: simPatch.providerOverrides } + : {}), + ...(simPatch.advisorModelSelection !== undefined + ? { advisorModelSelection: simPatch.advisorModelSelection } + : {}), + }, + } + : {}), ...(usageLimitSourcesPatch !== undefined ? { usageLimitSources: mergeSettingsEntries(