Separate how an environment starts from how a client reaches it
+
Choose a route. This is a reading aid, not a live connection test: it performs no network action and has no automatic transitions.
+
+
+
+
+
{initial.label}. {initial.target}.
+
+
+
{initial.target}{initial.label}
+
+
Launch transport
{initial.launch}
+
Access transport
{initial.access}
+
Trust boundary
{initial.boundary}
+
Registration fact
{initial.registration}
+
+
+
+
+
All four routes at a glance
+
+ {Object.values(routes).map((route) => (
+
+
{route.label}
+
{route.target}
+
Launch: {route.launch}
+
Access: {route.access}
+
Boundary: {route.boundary}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
diff --git a/src/components/AcpForkLab.astro b/src/components/AcpForkLab.astro
new file mode 100644
index 0000000..3bd394d
--- /dev/null
+++ b/src/components/AcpForkLab.astro
@@ -0,0 +1,42 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("AcpForkLab requires a stable kebab-case id.");
+}
+const labId = `acp-fork-${id}`;
+
+const rows = [
+ { label: "Model & mode", cursor: "Sets a base model, then resolves a mode through returned configuration/mode aliases.", grok: "Uses the setup result’s current model and calls session/set_model only if the requested model differs.", boundary: "Both call into ACP, but their selection policies are adapter code—not a generic negotiated product feature." },
+ { label: "Question", cursor: "cursor/ask_question parks a Deferred and maps answers to canonical user-input events.", grok: "x.ai/ask_user_question (including an underscore variant) has its own response and cancellation mapping.", boundary: "Deferred callback waits are in-process. Durable requests exist only after later runtime ingestion." },
+ { label: "Interrupt race", cursor: "Cancels ACP and resolves pending waits; prompt-in-flight counting prevents a superseded prompt from settling too early.", grok: "Marks target id before a thread lock and suppresses late notifications for interrupted turns.", boundary: "A cancel notification crosses a process boundary; neither path is a durable stop proof." },
+ { label: "Rollback", cursor: "Truncates the adapter’s local read snapshot; no Cursor native revert call appears in this method.", grok: "Returns an explicit unsupported provider request error.", boundary: "Neither row is an orchestration-event rollback or a transaction with provider history." },
+];
+const payload = JSON.stringify(rows).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive semantic fork
One shared ACP rail, four distinct product decisions
Select a concern to compare concrete adapter behavior and the boundary it does not cross.
+
+
{rows.map((row, index) => )}
+
Selected {rows[0].label}
+
{rows[0].label}
Cursor
{rows[0].cursor}
Grok
{rows[0].grok}
Boundary
{rows[0].boundary}
+
+ All comparisons{rows.map((row) =>
{row.label}
Cursor: {row.cursor}
Grok: {row.grok}
Boundary: {row.boundary}
)}
+
+
+
+
diff --git a/src/components/AdapterContractLab.astro b/src/components/AdapterContractLab.astro
new file mode 100644
index 0000000..0916078
--- /dev/null
+++ b/src/components/AdapterContractLab.astro
@@ -0,0 +1,266 @@
+---
+import { getSourceReference, sourceReferenceHref, sourceReferenceLabel } from "../lib/sources";
+
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("AdapterContractLab requires a stable kebab-case id.");
+}
+
+const stages = [
+ { label: "Durable intent", short: "intent", owner: "Orchestration", boundary: "The product command has committed. No native call is part of that SQL transaction." },
+ { label: "Resolve route", short: "route", owner: "ProviderService", boundary: "The persisted binding selects one configured instance and its current live adapter." },
+ { label: "Invoke SPI", short: "call", owner: "ProviderAdapter", boundary: "A typed method crosses into provider-owned behavior." },
+ { label: "Native runtime", short: "native", owner: "Harness", boundary: "Process, SDK query, RPC request, and native session state remain outside SQLite." },
+ { label: "Canonical event", short: "event", owner: "Hot stream", boundary: "The adapter translates selected observations into ProviderRuntimeEvent values." },
+ { label: "Domain update", short: "commit", owner: "Runtime ingestion", boundary: "A selected canonical event becomes durable only after an internal command commits." },
+] as const;
+
+const scenarios = {
+ start: {
+ label: "Start an absent session",
+ state: "No live adapter session",
+ method: "startSession(input)",
+ immediate: "Returns ProviderSession after native start/resume setup; this is not assistant output.",
+ native: "Create or adopt the provider-native session and begin its event consumer.",
+ event: "session.started / thread.started may follow on the hot stream.",
+ durable: "ProviderService can upsert the thread → instance binding and opaque cursor separately.",
+ caveat: "A process crash can still lose native state or an event between hot boundaries.",
+ tone: "success",
+ sourceIds: ["provider-adapter-contract", "provider-service-start-session", "provider-runtime-event-union"],
+ },
+ send: {
+ label: "Send on a ready session",
+ state: "Live session, no active turn",
+ method: "sendTurn(input)",
+ immediate: "Returns ProviderTurnStartResult with threadId, turnId, and optional cursor—not generated text.",
+ native: "Submit a prompt/turn through the adapter's native transport.",
+ event: "turn.started, content/item activity, requests, and turn completion can arrive later.",
+ durable: "Runtime ingestion dispatches separate internal commands for selected events.",
+ caveat: "The original sequence acknowledgement proves durable intent, not native acceptance or completion.",
+ tone: "success",
+ sourceIds: ["provider-adapter-contract", "provider-turn-reactor", "provider-runtime-ingestion"],
+ },
+ running: {
+ label: "Send while a turn is running",
+ state: "Live session with active turn",
+ method: "sendTurn(input) again",
+ immediate: "The generic SPI still exposes sendTurn; it has no steer return type or steer capability.",
+ native: "Concrete adapters may steer, queue, start another native turn, or reject according to their implementation.",
+ event: "Any accepted behavior must still be expressed through canonical runtime events.",
+ durable: "The durable product command does not make the provider-specific concurrency rule universal.",
+ caveat: "OpenCode has tested steering behavior; the ProviderAdapter contract alone does not promise it.",
+ tone: "warning",
+ sourceIds: ["provider-adapter-contract", "opencode-steer-behavior"],
+ },
+ approve: {
+ label: "Resolve an approval",
+ state: "Pending native request",
+ method: "respondToRequest(threadId, requestId, decision)",
+ immediate: "Returns void when the adapter accepts the response operation.",
+ native: "Resolve the provider-native pending request or deferred handler.",
+ event: "request.resolved can describe the observed resolution.",
+ durable: "The pending/resolved product activity is durable only through ingestion commands.",
+ caveat: "Not every provider originates the same approval shapes or policies.",
+ tone: "neutral",
+ sourceIds: ["provider-adapter-interactions", "provider-command-control-forwarding", "provider-runtime-event-union"],
+ },
+ input: {
+ label: "Answer structured input",
+ state: "Pending native input request",
+ method: "respondToUserInput(threadId, requestId, answers)",
+ immediate: "Returns void when the adapter accepts the answers.",
+ native: "Resolve an SDK deferred, ACP elicitation/extension, or native question as implemented.",
+ event: "user-input.resolved can describe the observed resolution.",
+ durable: "Request state enters the domain through separate ingestion dispatches.",
+ caveat: "A method in the shared interface is not proof that every native runtime can originate the request.",
+ tone: "neutral",
+ sourceIds: ["provider-adapter-interactions", "provider-runtime-event-union"],
+ },
+ interrupt: {
+ label: "Interrupt an active turn",
+ state: "Live session with active turn",
+ method: "interruptTurn(threadId, turnId?)",
+ immediate: "Returns void after the adapter's interruption request path succeeds.",
+ native: "Send cancellation/interrupt through the provider-specific transport.",
+ event: "turn.aborted, turn.completed, warning, or error explains later observed state.",
+ durable: "The domain settles only when the corresponding runtime observation is ingested.",
+ caveat: "A successful interrupt call is not proof that no late native event can race it.",
+ tone: "warning",
+ sourceIds: ["provider-adapter-contract", "provider-command-control-forwarding", "provider-runtime-ingestion"],
+ },
+ rollback: {
+ label: "Roll back provider history",
+ state: "Routable session or recoverable binding",
+ method: "rollbackThread(threadId, numTurns)",
+ immediate: "Returns a provider-thread snapshot when implemented successfully.",
+ native: "Apply the adapter's own rollback/revert semantics.",
+ event: "No universal canonical rollback event is guaranteed by this method.",
+ durable: "T3's checkpoint/revert workflow remains a separate cross-store saga.",
+ caveat: "Grok explicitly rejects provider rollback; Cursor and other adapters differ in what is actually reverted.",
+ tone: "failure",
+ sourceIds: ["provider-adapter-contract", "grok-rollback-unsupported", "checkpoint-revert-saga"],
+ },
+} as const;
+
+const resolved = Object.fromEntries(Object.entries(scenarios).map(([key, scenario]) => [key, {
+ ...scenario,
+ sources: scenario.sourceIds.map((sourceId) => {
+ const source = getSourceReference(sourceId);
+ return { href: sourceReferenceHref(source), label: sourceReferenceLabel(source) };
+ }),
+}]));
+const initial = resolved.start;
+const labId = `adapter-contract-${id}`;
+const payload = JSON.stringify({ stages, scenarios: resolved }).replaceAll("<", "\\u003c");
+---
+
+
+
+ Interactive contract tracer
+
What does one adapter call actually prove?
+
Choose a call, then move from durable intent to native work and back. The return boundary and the event boundary stay visibly separate.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {stages.map((stage, index) =>
{index + 1}{stage.short}
)}
+
+
+
+ {initial.label}; boundary 1 of {stages.length}: {stages[0].label}.
+
+
+
+
+
+
+
+
+
diff --git a/src/components/ArtifactFactoryLab.astro b/src/components/ArtifactFactoryLab.astro
new file mode 100644
index 0000000..5adf0df
--- /dev/null
+++ b/src/components/ArtifactFactoryLab.astro
@@ -0,0 +1,167 @@
+---
+interface Props { id?: string; }
+const { id = "artifact-factory" } = Astro.props;
+const labId = `artifact-factory-${id}`;
+const routes = {
+ npm: {
+ label: "npm CLI",
+ artifact: "t3 package",
+ boundary: "The published package contains dist only; publishing first proves the exact server version clients will invoke.",
+ steps: [
+ ["Build server", "The server bundle emits dist/bin.mjs and the service launcher.", "Bundled code is not yet a complete product surface."],
+ ["Embed renderer", "The CLI build copies apps/web/dist into dist/client when it is present.", "A missing web build logs a warning during build, but publication later requires client/index.html."],
+ ["Assert publish inputs", "The publish command requires the executable, launcher, and bundled client entry.", "The temporary npm manifest resolves workspace/catalog dependencies before npm sees it."],
+ ["Publish exact version", "Release CI publishes the CLI before it is allowed to create the GitHub Release.", "The release is held if npm publication fails."],
+ ],
+ },
+ desktop: {
+ label: "Desktop release",
+ artifact: "DMG · AppImage · NSIS",
+ boundary: "The build script describes broad platform targets, but release.yml decides which jobs actually run and ship.",
+ steps: [
+ ["Build inputs", "Desktop, server, web, and branded client assets must exist before staging begins.", "The artifact builder validates emitted bundles rather than trusting configuration alone."],
+ ["Stage closure", "Electron output, server dist, resources, production dependencies, native sidecars, and platform assets form a temporary app tree.", "Windows splits the server tree into a server.asar sidecar; macOS/Linux keep one merged tree."],
+ ["Package per matrix", "electron-builder creates platform-specific payloads and updater metadata.", "Builder code can target more combinations than CI has elected to ship."],
+ ["Release four lanes", "Current CI runs macOS arm64 DMG, macOS x64 DMG, Linux x64 AppImage, and Windows x64 NSIS.", "Windows arm64 is commented out in the release matrix: capability is not a published artifact."],
+ ],
+ },
+ hosted: {
+ label: "Hosted + mobile",
+ artifact: "Channel deploy · store build · OTA",
+ boundary: "Web channels are release-controlled aliases; mobile JavaScript can move only to native binaries with a matching fingerprint.",
+ steps: [
+ ["Select channel", "Stable and nightly releases derive separate versions, tags, and hosted channel names.", "Vercel Git-triggered deploys are disabled so an arbitrary commit does not become a product channel."],
+ ["Deploy web", "Release CI builds, deploys, and aliases one immutable deployment to latest or nightly.", "The public router uses a cookie to select a channel, then rewrites the app route."],
+ ["Reconcile stores", "Mobile CI compares the declared app version with finished production builds and creates/submits builds when needed.", "Store approval remains an external store process, not an OTA operation."],
+ ["Gate OTA", "An EAS production update is published only where a completed production build matches the current native fingerprint.", "Native drift skips OTA instead of shipping JavaScript into an incompatible binary."],
+ ],
+ },
+ aur: {
+ label: "AUR bridge",
+ artifact: "Arch package metadata",
+ boundary: "AUR repackages a published Linux AppImage; it does not build an independent desktop artifact from the source tree.",
+ steps: [
+ ["Accept a release tag", "The release script accepts only stable semver tags or the nightly tag shape.", "Other tag shapes exit before an AUR package is changed."],
+ ["Choose package lane", "Stable tags select t3code-bin; nightly tags select t3code-nightly-bin.", "The package names preserve channel separation for Arch users."],
+ ["Pin upstream", "The script reads the named GitHub Release asset digest and the LICENSE at that tag.", "A missing or malformed SHA-256 stops packaging."],
+ ["Validate then publish", "namcap and makepkg validate the updated PKGBUILD before an optional authenticated AUR push.", "Without the AUR SSH key, validation completes but publication is skipped."],
+ ],
+ },
+};
+const initialRoute = "npm";
+---
+
+
+
+ Interactive artifact factory · Chapter 37
+
Choose a delivery lane, then inspect its gates
+
Each lane has a different output and failure boundary. Advance manually; no state progresses on its own.
+
+
+
+
+
+
+
diff --git a/src/components/BookCover.astro b/src/components/BookCover.astro
new file mode 100644
index 0000000..70c2e1e
--- /dev/null
+++ b/src/components/BookCover.astro
@@ -0,0 +1,28 @@
+---
+import { Image } from "astro:assets";
+import cover from "../../cover.png";
+import lock from "../../sources/t3code.lock.json";
+const base = import.meta.env.BASE_URL.endsWith("/") ? import.meta.env.BASE_URL : `${import.meta.env.BASE_URL}/`;
+---
+
+
+
+
+
+
+
+ Source-level field guide
+
Follow the control plane all the way down.
+
From a tap on a phone to a provider subprocess, persisted event, hidden Git checkpoint, and streamed UI update—every layer is explained against one pinned source revision.
+ pingdotgg/t3code · commit {lock.shortCommit}
+ Local/hosted web · Electron · iOS/Android
+ Codex · Claude · Cursor · Grok · OpenCode
+
+
+
+
diff --git a/src/components/Callout.astro b/src/components/Callout.astro
new file mode 100644
index 0000000..0405a3e
--- /dev/null
+++ b/src/components/Callout.astro
@@ -0,0 +1,13 @@
+---
+interface Props {
+ title: string;
+ tone?: "info" | "warning" | "success";
+}
+const { title, tone = "info" } = Astro.props;
+---
+
+
+
diff --git a/src/components/CheckpointGraphLab.astro b/src/components/CheckpointGraphLab.astro
new file mode 100644
index 0000000..24cf096
--- /dev/null
+++ b/src/components/CheckpointGraphLab.astro
@@ -0,0 +1,135 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("CheckpointGraphLab requires a stable kebab-case id.");
+}
+const labId = `checkpoint-graph-${id}`;
+const states = [
+ {
+ id: "before",
+ label: "Before turn",
+ eyebrow: "Baseline · turn 0",
+ detail: "The current workspace is captured as the baseline hidden ref. The branch still points at its ordinary commit; the checkpoint is a separate content snapshot.",
+ ref: "refs/t3/checkpoints//turn/0",
+ files: ["README.md · unchanged", "src/app.ts · unchanged"],
+ consequence: "A later turn diff can compare this baseline to the next checkpoint.",
+ },
+ {
+ id: "after",
+ label: "After turn",
+ eyebrow: "Checkpoint · turn 1",
+ detail: "After the turn, T3 builds a tree with an isolated Git index, stores it under a hidden ref, then derives a changed-file summary before it records checkpoint metadata.",
+ ref: "refs/t3/checkpoints//turn/1",
+ files: ["README.md · 3 additions, 1 deletion", "src/app.ts · 12 additions"],
+ consequence: "The visible summary is derived from the checkpoint diff; it is not an independent file watcher.",
+ },
+ {
+ id: "diff",
+ label: "Inspect a diff",
+ eyebrow: "Read-only comparison",
+ detail: "A turn view compares checkpoint 0 → 1. A full-thread view compares the baseline → a selected checkpoint. Working-tree and branch views are separate live Git comparisons.",
+ ref: "turn 0 → turn 1",
+ files: ["- const title = \"old\";", "+ const title = \"new\";", "+ export const ready = true;"],
+ consequence: "Inspecting a patch does not restore files or alter the provider conversation.",
+ },
+ {
+ id: "revert",
+ label: "Revert to turn 0",
+ eyebrow: "Ordered destructive saga",
+ detail: "The reactor restores worktree and index content, cleans untracked paths, refreshes workspace entries, asks the bound provider to roll back counted turns, attempts best-effort deletion of newer hidden refs, then records a completed revert.",
+ ref: "restore turn 0; prune turn 1",
+ files: ["README.md · baseline restored", "src/app.ts · baseline restored", "turn 1 hidden ref · delete attempted"],
+ consequence: "This is a content restore plus a provider-history operation, not a Git branch reset or an undo of a remote push.",
+ },
+ {
+ id: "failure",
+ label: "Provider rollback fails",
+ eyebrow: "Partial failure boundary",
+ detail: "Filesystem restore happens before provider rollback. If the live provider cannot roll back, the reactor appends a failure activity and does not dispatch thread.reverted; the working tree may already be restored while durable history and stale refs remain.",
+ ref: "filesystem restored; completion withheld",
+ files: ["README.md · baseline restored", "provider conversation · not rolled back", "turn 1 ref · still present"],
+ consequence: "The user must treat this as a mismatched partial state, not as a completed revert.",
+ },
+] as const;
+const payload = JSON.stringify(states).replaceAll("<", "\\u003c");
+---
+
+
+
+ Interactive checkpoint graph
+
Walk one turn through capture, review, and a partial rollback failure
+
Each button is a discrete state. Nothing plays by itself, and the full ledger stays available without JavaScript.
+
+
+ {states.map((state, index) => )}
+
+
State: {states[0].label}. {states[0].detail}
+
+
+
ordinary branch
+
+
AHEAD
+
Δworkspace after turn
+
+
0hidden baseline
+
1hidden checkpoint
+
● circles are illustrative content snapshots; a checkpoint ref is not shown as a normal branch tip.
+
+
+ {states[0].eyebrow}
+
{states[0].label}
+
{states[0].detail}
+
+
Reference / operation
{states[0].ref}
+
Observed files
{states[0].files.map((file) =>
{file}
)}
+
Boundary
{states[0].consequence}
+
+
+
+
+ Complete state ledger
+
+ {states.map((state) =>
{state.label}
{state.detail}
Boundary: {state.consequence}
)}
+
+
+
+
+
+
+
+
+
diff --git a/src/components/ClaudeSdkStreamLab.astro b/src/components/ClaudeSdkStreamLab.astro
new file mode 100644
index 0000000..530171c
--- /dev/null
+++ b/src/components/ClaudeSdkStreamLab.astro
@@ -0,0 +1,47 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("ClaudeSdkStreamLab requires a stable kebab-case id.");
+}
+const labId = `claude-sdk-${id}`;
+
+const messages = [
+ { label: "Query configured", native: "The SDK query receives cwd, model, effort, permission mode, and optional resume metadata.", product: "A ProviderSession records a live Claude binding and a resumable cursor shape.", caveat: "The SDK session and query stream are provider-owned runtime state; a stored cursor is not a replay of every transient message." },
+ { label: "Assistant + tool", native: "Assistant text and tool-use/result messages stream from the Agent SDK.", product: "Content and item lifecycle events are normalized for thread projections.", caveat: "The canonical item taxonomy is T3’s contract; it is not an assertion that all SDK message fields persist." },
+ { label: "Permission / question", native: "A tool request or structured input pauses on an SDK-side deferred response.", product: "request.opened or user-input.requested gives clients a canonical action.", caveat: "The deferred is volatile. The durable record appears only after runtime ingestion’s internal command commits." },
+ { label: "Todo / task", native: "TodoWrite and agent/task-shaped SDK messages provide planning and work signals.", product: "turn.plan.updated and task/activity events drive product work views.", caveat: "These are adapter normalizations, not a cross-provider task scheduler or durable execution queue." },
+ { label: "Result / error", native: "A terminal SDK result carries success, cancellation, error, and sometimes usage fields.", product: "turn completion plus optional thread token usage or runtime error reaches T3.", caveat: "Live context telemetry is not transcript accounting, and an SDK result still crosses a hot delivery bridge before durable projection." },
+];
+const payload = JSON.stringify(messages).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive stream classifier
Classify one Claude SDK observation
Choose an event family to see the native message, its product projection, and the point where durable truth begins.
Advance one race at a time. The first render is a still, authoritative snapshot at sequence 10.
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Snapshot at sequence 10 is loaded. No page request is in flight.
+
+
+
+
Session
+
Live cursor
+
History epoch
+
Older page
+
+
+
+
Snapshotauthoritative window: turns 8–10
+
+
+
+ Static race reference
+
+
A snapshot replaces loaded history and establishes its cursor.
+
An event at or below that cursor is ignored as overlap or a duplicate.
+
An invalid or oversized resume gap receives a new snapshot, not a partial replay.
+
A new session refreshes authority before reusing a cursor.
+
A revert increments history epoch, so a pre-revert older page is discarded.
+
An older page ahead of live cursor waits for its watermark; a stale page does not merge.
+
+
+
+
+
+
+
+
diff --git a/src/components/CodexRpcBoundaryLab.astro b/src/components/CodexRpcBoundaryLab.astro
new file mode 100644
index 0000000..84035f9
--- /dev/null
+++ b/src/components/CodexRpcBoundaryLab.astro
@@ -0,0 +1,63 @@
+---
+interface Props { id: string; }
+interface Step { label: string; native: string; canonical: string; durable: string; }
+
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("CodexRpcBoundaryLab requires a stable kebab-case id.");
+}
+const labId = `codex-rpc-${id}`;
+
+const steps: Step[] = [
+ { label: "Start / resume", native: "Spawn codex app-server, initialize it, then start or resume a provider thread.", canonical: "session.started and thread.started identify a live adapter session.", durable: "Only the orchestration binding and any saved resume cursor can survive; the child process and event consumer are live state." },
+ { label: "Turn request", native: "turn/start carries the prompt plus selected model, reasoning effort, and service tier.", canonical: "turn.started and item/content events describe the product-visible turn.", durable: "The earlier turn-start command is durable intent. Native request completion is not a SQL commit." },
+ { label: "Server asks", native: "The app-server sends an incoming approval or user-input JSON-RPC request.", canonical: "request.opened or user-input.requested becomes a pending product request.", durable: "The pending native handler waits in process; its durable counterpart arrives only after runtime ingestion dispatches an internal command." },
+ { label: "Notifications", native: "Items, plan deltas, token usage, reroutes, and errors arrive as app-server notifications.", canonical: "The adapter maps selected shapes into ProviderRuntimeEvent values.", durable: "The adapter queue and hot provider stream are volatile until ingestion commits a derived internal command." },
+ { label: "Stop / failure", native: "Close the runtime or observe child stdio/process/protocol failure.", canonical: "session.exited, runtime.warning, or runtime.error explains the observed outcome.", durable: "Stopping a process does not retroactively prove a provider result was projected; a prior accepted intent may outlive delivery." },
+];
+const payload = JSON.stringify(steps).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive transport ledger
Move one Codex observation across the boundary
The labels deliberately separate upstream JSON-RPC from T3’s stable runtime vocabulary and from durable orchestration state.
+
+
+
+
+
+
+
Position 1 of {steps.length}: {steps[0].label}
+
{steps[0].label}
Native app-server
{steps[0].native}
Canonical T3 event
{steps[0].canonical}
Durability boundary
{steps[0].durable}
+
+ All boundary positions{steps.map((step) =>
{step.label}
Native: {step.native}
Canonical: {step.canonical}
Durable: {step.durable}
)}
+
+
+
+
+
+
+
diff --git a/src/components/CommandBoundaryLab.astro b/src/components/CommandBoundaryLab.astro
new file mode 100644
index 0000000..87ff9f7
--- /dev/null
+++ b/src/components/CommandBoundaryLab.astro
@@ -0,0 +1,664 @@
+---
+import { getSourceReference, sourceReferenceHref, sourceReferenceLabel } from "../lib/sources";
+
+interface Props {
+ id: string;
+}
+
+interface BoundaryStage {
+ label: string;
+ shortLabel: string;
+ position: string;
+ durable: string;
+ external: string;
+ client: string;
+ retry: string;
+ provider: string;
+ guarantee: string;
+ tone: "neutral" | "warning" | "failure" | "success";
+ sourceIds: string[];
+}
+
+interface BoundaryPath {
+ label: string;
+ description: string;
+ stages: BoundaryStage[];
+}
+
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("CommandBoundaryLab requires a stable kebab-case id.");
+}
+
+const paths: Record<"existing" | "bootstrap", BoundaryPath> = {
+ existing: {
+ label: "Turn on an existing thread",
+ description:
+ "One normalized command is decided, then its two-to-four-event batch, projections, and accepted receipt share one SQL transaction.",
+ stages: [
+ {
+ label: "Before normalization",
+ shortLabel: "wire",
+ position: "The client command has crossed schema and authorization checks, but normalization has not produced the dispatchable command.",
+ durable: "No orchestration event or command receipt exists.",
+ external: "No attachment staging or provider work has begun.",
+ client: "The request can fail without a durable orchestration result.",
+ retry: "The same command id enters the normal path again because there is no receipt to find.",
+ provider: "No provider intent exists.",
+ guarantee: "No durable intent",
+ tone: "neutral",
+ sourceIds: ["command-union-boundary", "normalizer-staging-boundary"],
+ },
+ {
+ label: "After normalization and staging",
+ shortLabel: "stage",
+ position: "The server has supplied timestamps and workspace context and may have created attachment directories or written attachment bytes.",
+ durable: "The event store and receipt table are still unchanged.",
+ external: "Filesystem staging can already exist outside the later SQL transaction.",
+ client: "A later failure returns an error even though staged files may remain.",
+ retry: "The command is normalized and staged again; receipt deduplication has not started yet.",
+ provider: "No provider intent exists.",
+ guarantee: "External work, no receipt",
+ tone: "warning",
+ sourceIds: ["normalizer-staging-boundary", "turn-normalizer"],
+ },
+ {
+ label: "Invariant rejection",
+ shortLabel: "reject",
+ position: "The serialized decider has read the authoritative in-memory model and refuses the command before opening the SQL transaction.",
+ durable: "No event is appended. A rejected receipt is attempted afterward on a best-effort path.",
+ external: "Any earlier normalization-time staging is outside that rejection bookkeeping.",
+ client: "The caller receives an invariant error.",
+ retry: "After client normalization runs again, a saved rejected receipt keeps the same id rejected without re-evaluation; if that receipt was not saved, the command can be decided again.",
+ provider: "No provider intent is published.",
+ guarantee: "Best-effort sticky rejection",
+ tone: "failure",
+ sourceIds: ["existing-turn-decider", "engine-rejected-receipt"],
+ },
+ {
+ label: "SQL transaction failure",
+ shortLabel: "rollback",
+ position: "Decision has already allocated event data, but an event append, projection, or receipt write fails inside the transaction.",
+ durable: "Events, transactional projections, and the accepted receipt roll back together.",
+ external: "Pre-transaction staged files are not part of the SQL rollback.",
+ client: "The caller receives a persistence failure; no sequence is acknowledged.",
+ retry: "With no accepted receipt, the same id is normalized and decided again; clock and UUID-derived values may differ.",
+ provider: "No committed event reaches the hot event bus.",
+ guarantee: "SQL all-or-none",
+ tone: "failure",
+ sourceIds: ["decider-effect-dependencies", "engine-commit-publication"],
+ },
+ {
+ label: "Hard crash after commit",
+ shortLabel: "gap",
+ position: "The SQL transaction committed, but the process dies before the in-memory fold and PubSub loop can publish the batch.",
+ durable: "The complete event batch, projections, and accepted receipt are durable.",
+ external: "The hot reactor saw none of this batch in the failed process.",
+ client: "No acknowledgement reaches the caller.",
+ retry: "After any client normalization work, a same-id retry returns the stored last sequence and does not republish the missing hot events.",
+ provider: "Durable turn intent can exist without the provider reactor receiving its trigger.",
+ guarantee: "Durable but not delivered",
+ tone: "failure",
+ sourceIds: ["engine-commit-publication", "command-receipt-handling", "engine-failure-reconciliation", "hot-reactor-no-replay"],
+ },
+ {
+ label: "Sequence acknowledged",
+ shortLabel: "ack",
+ position: "The engine committed the batch, updated its in-memory model, and offered every committed event to the hot PubSub before returning.",
+ durable: "Two to four events, their synchronous projections, and one accepted receipt are committed.",
+ external: "Publication wakes asynchronous reactors; provider execution is outside this transaction.",
+ client: "The RPC result contains the last committed event sequence.",
+ retry: "The same id and aggregate return that stored sequence without deciding or appending again.",
+ provider: "The acknowledgement proves durable intent, not that a harness accepted, ran, or completed the turn.",
+ guarantee: "Durable intent acknowledged",
+ tone: "success",
+ sourceIds: ["turn-atomic-batch", "command-commit-acknowledgement", "provider-turn-reactor"],
+ },
+ ],
+ },
+ bootstrap: {
+ label: "Full first-turn WebSocket bootstrap",
+ description:
+ "The full WebSocket path creates a thread, prepares a worktree, launches setup, and starts the turn through separate durability boundaries.",
+ stages: [
+ {
+ label: "After normalization, before the saga",
+ shortLabel: "stage",
+ position: "The WebSocket turn-start command still carries its bootstrap payload after normalization; the ordinary command engine has not received a subcommand.",
+ durable: "No bootstrap step has committed.",
+ external: "Attachment staging may already exist, but no worktree or setup process has been requested.",
+ client: "The WebSocket request can still fail without creating the thread.",
+ retry: "The same outer id has no saga-level receipt that can replay the whole result.",
+ provider: "No provider intent exists.",
+ guarantee: "No saga-level idempotency",
+ tone: "neutral",
+ sourceIds: ["command-union-boundary", "bootstrap-saga-full"],
+ },
+ {
+ label: "Thread creation committed",
+ shortLabel: "thread",
+ position: "A server-generated id dispatched thread.create through the ordinary engine as the first saga step.",
+ durable: "The thread event and that subcommand's receipt are committed independently of the final turn.",
+ external: "No worktree is guaranteed yet.",
+ client: "The outer request is still pending.",
+ retry: "Repeating the outer request tries the creation path again; it does not retrieve one receipt for the whole saga.",
+ provider: "The thread exists, but no turn-start request has been committed.",
+ guarantee: "First independent commit",
+ tone: "warning",
+ sourceIds: ["bootstrap-saga-full", "bootstrap-command-path"],
+ },
+ {
+ label: "Worktree prepared and metadata committed",
+ shortLabel: "Git + meta",
+ position: "Git remote/worktree operations run outside SQLite, then thread.meta.update commits with another server-generated id.",
+ durable: "Thread metadata can point at the newly prepared worktree in a separate event and receipt.",
+ external: "A branch and worktree now exist outside the event-store transaction.",
+ client: "The outer request remains pending and can still fail later.",
+ retry: "An identical outer retry can collide with already-created thread, branch, or worktree state.",
+ provider: "No final turn intent is guaranteed yet.",
+ guarantee: "Mixed durable and Git state",
+ tone: "warning",
+ sourceIds: ["bootstrap-saga-full"],
+ },
+ {
+ label: "Setup launch fails",
+ shortLabel: "setup",
+ position: "The setup runner rejects the launch. The handler attempts to append failure activity, logs a warning, and continues the saga.",
+ durable: "Failure activity is best effort; the earlier thread and metadata commits remain.",
+ external: "No setup process started, but the prepared worktree remains.",
+ client: "Setup-launch failure alone does not fail the outer turn-start request.",
+ retry: "The saga continues to the final turn; this is not a rollback boundary.",
+ provider: "The eventual provider turn may run against a worktree whose setup did not launch.",
+ guarantee: "Recorded warning, saga continues",
+ tone: "warning",
+ sourceIds: ["bootstrap-saga-full"],
+ },
+ {
+ label: "Final turn fails; compensate",
+ shortLabel: "delete",
+ position: "A non-interruption failure reaches compensation after the thread was created, so thread.delete is dispatched uninterruptibly.",
+ durable: "Successful compensation tombstones the thread in another independent commit; prior history is not erased.",
+ external: "The Git worktree and branch are not removed by this compensation.",
+ client: "The caller receives the original dispatch failure, annotated as deleted only when cleanup succeeds.",
+ retry: "Retrying the outer request is a new saga attempt, not a replay of an atomic transaction.",
+ provider: "No successful final turn acknowledgement exists.",
+ guarantee: "Domain compensation only",
+ tone: "failure",
+ sourceIds: ["bootstrap-saga-full", "bootstrap-command-path"],
+ },
+ {
+ label: "Final turn acknowledged",
+ shortLabel: "ack",
+ position: "The last saga step strips bootstrap data and dispatches the normalized turn-start through the ordinary engine.",
+ durable: "Earlier saga commits plus the final two-to-four-event turn transaction are durable, each with its own receipt boundary.",
+ external: "Git/setup effects remain outside SQL and provider work begins asynchronously from hot events.",
+ client: "The WebSocket RPC returns the final turn transaction's last sequence.",
+ retry: "The outer bootstrap is not end-to-end idempotent even though each dispatched subcommand has receipt semantics.",
+ provider: "The acknowledgement proves durable turn intent only.",
+ guarantee: "Successful saga, not one transaction",
+ tone: "success",
+ sourceIds: ["bootstrap-saga-full", "turn-atomic-batch", "provider-turn-reactor"],
+ },
+ ],
+ },
+};
+
+const resolvedPaths = Object.fromEntries(
+ Object.entries(paths).map(([key, path]) => [
+ key,
+ {
+ ...path,
+ stages: path.stages.map(({ sourceIds, ...stage }) => ({
+ ...stage,
+ sources: sourceIds.map((sourceId) => {
+ const source = getSourceReference(sourceId);
+ return {
+ label: sourceReferenceLabel(source),
+ href: sourceReferenceHref(source),
+ };
+ }),
+ })),
+ },
+ ]),
+);
+const initial = resolvedPaths.existing.stages[0];
+const payload = JSON.stringify(resolvedPaths).replaceAll("<", "\\u003c");
+const labId = `command-boundary-${id}`;
+---
+
+
+
+ Interactive boundary explorer
+
Where can a command fail?
+
Switch paths and move the failure position. Watch which state is durable, which state is external, and what an identical retry can actually recover.
Launch the connection, then move the work on a different path
+
Choose a manual step. The lab distinguishes the short setup exchange from the HTTP and WebSocket traffic that follows it.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Control plane · account and endpoint authorization
+
Clerk session reaches the relay
+
A signed-in client presents its Clerk credential to list or link environments. This authorizes relay control-plane work; it is not an environment WebSocket credential.
+
+
Sender → receiver
Client → relay
+
Proof in use
Clerk bearer credential
+
What becomes possible
Discovery, link challenge, or relay DPoP token exchange
Select a teaching event. The ledger identifies authority, durable records, and the narrow recovery claim; it never simulates a model or invents a provider prompt.
+
+
+
+
+
+
+
+
+
+
+
+
+
Event 1 of 5 · live provider work begins
+
A provider receives a turn in its own native session
+
T3 constructs the visible current-turn payload. The provider-native session owns the accumulated conversation context and private compaction state.
+
+
+
+
+
Record
Authoritative owner
This event
After server restart
+
+
Accumulated native context
provider-native session
T3's explicit request enters provider-owned history
provider-specific resume only
+
T3 thread history
T3 orchestration
message/activity projection may commit
durable product record reloads
+
Resume cursor
provider shape; T3 persists binding
adapter may return/update it
same adapter receives opaque cursor
+
Context telemetry
provider emits; T3 latest-selects
only if a usable event arrives
latest retained activity may render
+
Client cache/draft/outbox
client surface
surface-specific local state
not a provider prompt or server authority
+
+
+
+
+
+ Boundary statement
+
T3 constructs and records the visible request around a turn. It does not own or serialize the provider's accumulated hidden conversation context.
T3 constructs the visible current-turn request; the selected provider's native session owns accumulated conversation context and hidden provider state.
+
What does T3 persist to attempt continuation?
A provider/instance-bound runtime record with an opaque resume cursor, runtime/session metadata, plus separate thread projections.
+
What does compaction add to T3?
A normalized context-compaction activity when an adapter reports a compacted provider thread; no generic T3 summary/prompt replacement is established.
+
What is the context meter?
The newest valid provider-reported context-window activity available in the bounded thread snapshot, not a prompt archive, aggregate usage total, or cost ledger.
+
Is there universal long-term memory?
No such cross-provider T3 subsystem is established by the inspected generic contracts/service paths. This is an audited inference, not a claim about native provider features.
+
What about local drafts/outbox/cache?
Client-owned resilience/presentation state. It is deliberately deferred to Chapter 33 and cannot replace provider-session recovery.
+
diff --git a/src/components/DecisionLedgerLab.astro b/src/components/DecisionLedgerLab.astro
new file mode 100644
index 0000000..d5d88a9
--- /dev/null
+++ b/src/components/DecisionLedgerLab.astro
@@ -0,0 +1,352 @@
+---
+interface Props {
+ id?: string;
+}
+
+const { id = "architecture-decision-ledger" } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("DecisionLedgerLab requires a stable kebab-case id.");
+}
+
+const decisions = [
+ {
+ category: "domain",
+ classification: "Shipped",
+ title: "Server authority",
+ pressure: "Remote clients must control one workspace without becoming competing owners of provider processes, Git, terminals, or files.",
+ choice: "One environment server owns product authority; clients use authenticated RPC and projections.",
+ benefit: "Authorization, orchestration, workspace effects, and durable product history meet at one address.",
+ cost: "Availability and recovery depend on that environment; clients reconcile rather than write authoritatively.",
+ alternative: "Client-owned or peer-to-peer workspaces with a separate conflict and credential model.",
+ trigger: "Concurrent offline editing or multi-writer workspace authority becomes a core requirement.",
+ },
+ {
+ category: "domain",
+ classification: "Shipped",
+ title: "Transactional event core",
+ pressure: "A command needs a durable acceptance boundary and a retry answer before external work completes.",
+ choice: "Decide, append events, fold projections, and write a receipt in one SQLite transaction.",
+ benefit: "Accepted intent and its receipt survive together; failed transactions leave no acceptance result.",
+ cost: "Files, provider calls, and later delivery remain outside the transaction; projections require maintenance.",
+ alternative: "Direct CRUD where replayable history and independently shaped read models are not valuable.",
+ trigger: "Immutable command history and projection diversity stop paying for their operational complexity.",
+ },
+ {
+ category: "delivery",
+ classification: "Shipped",
+ title: "Hot post-commit reactors",
+ pressure: "Do not call a harness while the domain transaction could still roll back.",
+ choice: "Publish committed events to scoped, hot reactor workers; keep failures isolated from acceptance.",
+ benefit: "Rollback cannot have caused provider work, and one consumer failure does not undo durable history.",
+ cost: "A crash after commit can lose pending observation; sends and runtime ingestion are not a durable outbox.",
+ alternative: "Durable outbox with attempts, idempotency keys, and a policy for ambiguous external acceptance.",
+ trigger: "An accepted turn must eventually imply an attempted provider send across process loss.",
+ },
+ {
+ category: "delivery",
+ classification: "Shipped",
+ title: "Snapshot + cursor",
+ pressure: "Clients need rebuildable read state and bounded resume without calling every page one global snapshot.",
+ choice: "Each projection advances its own cursor; composed snapshots use a safe watermark and subscriptions repair gaps.",
+ benefit: "Read models evolve independently and can rebuild from committed events.",
+ cost: "Several watermarks, order-sensitive projectors, replay limits, and client race guards must remain intelligible.",
+ alternative: "One authoritative document per thread with fewer projections and less independent fan-out.",
+ trigger: "Projection lag, cross-view joins, or replay operations exceed the current cursor model's operating envelope.",
+ },
+ {
+ category: "integration",
+ classification: "Shipped",
+ title: "Provider adapters",
+ pressure: "Harnesses disagree about sessions, approvals, streams, context, and process ownership.",
+ choice: "A narrow adapter contract emits canonical runtime facts while ProviderService owns product policy and routing.",
+ benefit: "One product model preserves native provenance without inventing false provider parity.",
+ cost: "Adapter maintenance and capability differences remain explicit; no universal conformance proof exists.",
+ alternative: "A stricter generic protocol that may discard native features or push product policy into every driver.",
+ trigger: "Important native lifecycles require pervasive escape hatches that the canonical contract cannot express.",
+ },
+ {
+ category: "connectivity",
+ classification: "Shipped",
+ title: "One reconnect owner",
+ pressure: "Several views and devices can observe an environment without independent retry loops or merged authorities.",
+ choice: "An environment-scoped supervisor owns generations and one active lease; caches synchronize separately.",
+ benefit: "Transport lifecycle has one owner while shell and thread views keep precise refresh boundaries.",
+ cost: "Leases, generations, and surface-specific reconciliation add client-runtime complexity.",
+ alternative: "A global connection manager that would need another way to preserve environment ownership.",
+ trigger: "The product adds a real cross-environment write model, not just combined presentation.",
+ },
+ {
+ category: "connectivity",
+ classification: "Shipped",
+ title: "Durable mobile intent outbox",
+ pressure: "A user can send while the phone loses connectivity or foreground time.",
+ choice: "Optimistically enqueue, persist durably, then confirm and deliver through a serialized mobile outbox.",
+ benefit: "User intent can survive locally before the environment can accept it.",
+ cost: "Backoff, existence guards, confirmation, and delivery choices become a separate lifecycle.",
+ alternative: "Always-online direct send, sacrificing the local recovery contract.",
+ trigger: "Intent becomes multi-device collaborative work needing server-issued identities or all clients need the same queue.",
+ },
+ {
+ category: "operations",
+ classification: "Shipped",
+ title: "Exact-version updates",
+ pressure: "A visible client must not request a server runtime that is unavailable or incompatible.",
+ choice: "Publish the exact CLI first; stage and preflight the exact server runtime before launcher activation.",
+ benefit: "An update target is reproducible and the managed-server trial has a defined rollback boundary.",
+ cost: "Release order, launcher compatibility, and platform-specific update state machines remain necessary.",
+ alternative: "Floating channel updates paired with a stronger compatibility negotiation protocol.",
+ trigger: "Compatibility proof becomes sufficient without requiring equal client and server versions.",
+ },
+ {
+ category: "connectivity",
+ classification: "Shipped",
+ title: "Scope-driven background work",
+ pressure: "Mobile should remain useful in the background without keeping every environment permanently active.",
+ choice: "Reference-counted scopes retain declared per-environment background demand.",
+ benefit: "Continuation has an owner and can end when that owner releases its interest.",
+ cost: "Scope cleanup and platform scheduling constraints remain part of correctness; it is not a durable job queue.",
+ alternative: "An always-on global worker with higher resource use and leak risk.",
+ trigger: "The product needs OS-managed durable jobs with explicit completion receipts.",
+ },
+];
+
+const payload = JSON.stringify(decisions).replaceAll("<", "\\u003c");
+const first = decisions[0];
+---
+
+
+
+ Interactive decision ledger
+
Trace the trade-off, then test its reversal trigger
+
Filter the ledger, select a decision, and move through its six-step path. No animation advances on its own.
+
+
+
+
+ Category
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
{first.classification}·{first.category}
+
{first.title}
+
+
+
1Pressure
{first.pressure}
+
2Choice
{first.choice}
+
3Benefit
{first.benefit}
+
4Cost
{first.cost}
+
5Alternative
{first.alternative}
+
6Reversal trigger
{first.trigger}
+
+
+
+
1 of 6 · Pressure
+
+
+
+
+
+ Server authority selected. Step 1 of 6: Pressure.
+
+
+
+
+ Complete static ledger
+
+
+
Decision
Pressure
Choice
Benefit
Cost
Alternative
Reversal trigger
+
+ {decisions.map((decision) => (
+
+
{decision.classification}{decision.title}
+
{decision.pressure}
+
{decision.choice}
+
{decision.benefit}
+
{decision.cost}
+
{decision.alternative}
+
{decision.trigger}
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/components/DeliveryGapLab.astro b/src/components/DeliveryGapLab.astro
new file mode 100644
index 0000000..d18bcfb
--- /dev/null
+++ b/src/components/DeliveryGapLab.astro
@@ -0,0 +1,357 @@
+---
+import {
+ getSourceReference,
+ sourceReferenceHref,
+ sourceReferenceLabel,
+} from "../lib/sources";
+
+interface Props {
+ id?: string;
+}
+
+const { id = "post-commit-delivery-gap" } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("DeliveryGapLab requires a stable kebab-case id.");
+}
+
+const phases = [
+ {
+ label: "Before commit",
+ boundary: "The SQL transaction has not committed.",
+ durable: "No accepted intent is durable yet.",
+ volatile: "Only the command worker and transaction-local writes exist.",
+ external: "No provider work has started.",
+ retry: "After restart, the client can retry and the command can execute normally.",
+ sourceId: "engine-receipt-publication-boundary",
+ },
+ {
+ label: "Transaction open",
+ boundary: "Events, projections, and the accepted receipt have been written inside one SQL transaction.",
+ durable: "A process crash rolls the uncommitted transaction back as a unit.",
+ volatile: "The proposed in-memory command model has not replaced the live model.",
+ external: "The event has not reached the hot bus.",
+ retry: "No accepted receipt survives, so the retry can decide and commit again.",
+ sourceId: "engine-receipt-publication-boundary",
+ },
+ {
+ label: "Commit returned",
+ boundary: "The event, SQL projections, and accepted receipt are durable; publication has not happened yet.",
+ durable: "Intent and its command sequence survive restart.",
+ volatile: "No durable outbox row or per-reactor cursor records pending delivery.",
+ external: "The provider has not seen the intent.",
+ retry: "The same command id returns the stored sequence and does not republish, so that retry leaves this delivery gap unrepaired.",
+ sourceId: "engine-receipt-publication-boundary",
+ },
+ {
+ label: "Hot publish",
+ boundary: "The committed event is offered to current PubSub subscribers.",
+ durable: "The domain event remains durable in SQLite.",
+ volatile: "Subscriber queues live only in this process; publication is not a recoverable job record.",
+ external: "A reactor may or may not have dequeued the event.",
+ retry: "A receipt hit still returns success without replaying reactor work.",
+ sourceId: "provider-reactor-hot-subscription",
+ },
+ {
+ label: "Turn-start observed",
+ boundary: "For a turn-start event, the provider reactor handles the event and marks its derived turn key in a volatile dedupe cache.",
+ durable: "The original intent is durable, but reactor progress is not.",
+ volatile: "The dedupe mark is made before the provider effect and disappears on restart.",
+ external: "The adapter call has not necessarily begun.",
+ retry: "Within the same process a duplicate can be suppressed even after a later failure; after restart the hot event itself is gone.",
+ sourceId: "provider-reactor-forked-send",
+ },
+ {
+ label: "Send forked",
+ boundary: "The serialized handler forks providerService.sendTurn and can return to its queue.",
+ durable: "There is still no durable side-effect attempt record.",
+ volatile: "The child fiber is outside the worker's outstanding counter.",
+ external: "Two provider sends can overlap even though handler bodies were dequeued serially.",
+ retry: "Closing the scope may interrupt the child; the worker drain does not prove that the send completed.",
+ sourceId: "provider-reactor-forked-send",
+ },
+ {
+ label: "Provider accepted",
+ boundary: "The external harness may have accepted the turn before local binding/state persistence finishes.",
+ durable: "The original intent survives, but acceptance by the harness is outside SQLite's transaction.",
+ volatile: "Local knowledge of the provider result may still be only in a running fiber.",
+ external: "The turn can continue in the harness after the server loses its exact completion point.",
+ retry: "Recovery is ambiguous: blindly repeating can duplicate work, while doing nothing can strand it.",
+ sourceId: "provider-send-binding-order",
+ },
+ {
+ label: "Runtime publish",
+ boundary: "ProviderService logs a canonical runtime event and then publishes it to another hot PubSub.",
+ durable: "The diagnostic log is best-effort and is not the orchestration recovery ledger.",
+ volatile: "Runtime ingestion has not necessarily consumed the event.",
+ external: "The harness action has occurred; its canonical result is in transit inside the process.",
+ retry: "A crash before ingestion loses this delivery; no durable runtime-event cursor replays it.",
+ sourceId: "provider-runtime-publish",
+ },
+ {
+ label: "Buffer released",
+ boundary: "Runtime ingestion invalidates a buffered entry before dispatching its internal command.",
+ durable: "No new orchestration result is durable until that internal command commits.",
+ volatile: "Dispatch interruption or failure can lose the released batch; the removed value is not restored on this path.",
+ external: "The provider result already exists outside the domain model.",
+ retry: "Re-delivery is not generally idempotent: internal command ids include a random UUID suffix.",
+ sourceId: "runtime-ingestion-buffer-dispatch",
+ },
+ {
+ label: "Result committed",
+ boundary: "The internal command re-enters the same engine and commits the provider result as domain events.",
+ durable: "The projected result and its receipt now survive restart.",
+ volatile: "Any new downstream reactor work again crosses the same commit-before-publish seam.",
+ external: "The durable model has caught up with the observed harness result.",
+ retry: "The internal command receipt protects only that generated command id; it does not repair an earlier missed hot event.",
+ sourceId: "engine-receipt-publication-boundary",
+ },
+];
+
+const resolved = phases.map(({ sourceId, ...phase }) => {
+ const source = getSourceReference(sourceId);
+ return {
+ ...phase,
+ source: {
+ label: sourceReferenceLabel(source),
+ href: sourceReferenceHref(source),
+ },
+ };
+});
+const payload = JSON.stringify(resolved).replaceAll("<", "\\u003c");
+const first = resolved[0];
+---
+
+
+
+ Crash-timing lab
+
Move the crash across the delivery seam
+
Each position means “the process disappears immediately after this boundary.”
+
+
+
+
+
+
+
+
+
+
+ Use the arrow keys to move the simulated crash through the ordered phases.
+
+
+
+
+ {resolved.map((phase, index) => (
+
+
+
+ ))}
+
+
+
+
+ Position 1 of {resolved.length}: {first.label}
+
+ ))}
+
+
+
+
+
+
+
+
diff --git a/src/components/DesktopProcessLab.astro b/src/components/DesktopProcessLab.astro
new file mode 100644
index 0000000..3c7a51d
--- /dev/null
+++ b/src/components/DesktopProcessLab.astro
@@ -0,0 +1,104 @@
+---
+interface Props { id?: string; }
+const { id = "desktop-process" } = Astro.props;
+const labId = `desktop-process-${id}`;
+const modes = {
+ local: { label: "Host-local primary", process: "Electron main → primary local server child on macOS, Linux, or Windows → renderer window", transport: "fd3 bootstrap; fd4 host telemetry; fd5 diagnostics-demand control; HTTP / WebSocket", authority: "Electron main selects the child configuration and owns native APIs; renderer receives only curated IPC.", boot: "Main resolves the primary configuration, starts the host-local child, and probes its HTTP endpoint.", ready: "The ready callback gives the primary URL to the window service; the renderer is then served from the desktop target.", shutdown: "The pool stops the primary with SIGTERM and grace; an unexpected exit may instead enter the instance restart loop." },
+ wsl: { label: "Windows + WSL", process: "Electron main → either a WSL-only primary, or a Windows primary plus optional WSL secondary → renderer connections", transport: "A Windows host-local primary uses fd3/fd4/fd5. WSL receives bootstrap on stdin because wsl.exe drops forwarded extra descriptors.", authority: "The pool owns these local child instances. WSL is a distinct Linux environment, not a replacement for the SSH gateway.", boot: "WSL-only resolves the primary as WSL. Dual mode starts Windows primary first, then forks reconciliation for a distro-specific secondary on a distinct port.", ready: "A WSL-only primary opens the window after its probe. In dual mode, Windows primary opens it while the WSL secondary reaches readiness independently.", shutdown: "Unregistering a WSL secondary closes its child scope; application finalization stops every registered instance concurrently." },
+ ssh: { label: "SSH gateway", process: "Electron main → SSH environment manager → remote t3 process / tunnel → renderer connection", transport: "Curated renderer IPC asks main to discover, ensure, bootstrap, or disconnect an SSH environment; the remote endpoint is reached through the SSH path.", authority: "SSH is a remote environment gateway owned by the desktop SSH service. It is not an entry in the local backend-process pool.", boot: "The renderer requests a target; main delegates to the SSH environment manager, which can launch or connect to the remote environment.", ready: "A remote descriptor, bearer bootstrap, and WebSocket token establish a normal environment connection; primary-child readiness is unrelated.", shutdown: "Disconnecting the SSH environment tears down the gateway path. It is distinct from stopping local pool children during app shutdown." },
+} as const;
+type ModeKey = keyof typeof modes;
+const stages = ["boot", "ready", "shutdown"] as const;
+type StageKey = typeof stages[number];
+const initialMode: ModeKey = "local";
+const initialStage: StageKey = "boot";
+---
+
+
+ Interactive process lab · Chapter 32
Choose a delivery path, then advance its lifecycle
The same renderer can observe different transports; native and process authority stays in Electron main.
+ Zoom with the controls, +/−, or Ctrl/⌘ + trackpad scroll. Enable Pan to drag, use two-finger scrolling, or use the arrow keys. 0 fits the diagram; Esc leaves Pan or expanded view.
+
Protect intent before crossing a lifecycle boundary
+
Switch tracks and failure cases, then step through the exact guard that keeps an offline command or downloaded update from outrunning its durable state.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Outbox · offline creation
+
The local queue becomes visible before its file write settles
+
The immediate queued row is optimistic. Delivery cannot begin until the serialized mutation queue confirms that the atomic file write survived.
+
+
+
+
+
+
Guard in forceConfirm the exact queued object after its durable write
+
Authority after this stepmobile outbox file; server has received nothing
+
+
+
+
Offline command outbox. Step 1 of 7.
+
+
+
+
+ Static mobile continuity ledger
+
+
+
Boundary
Durable prerequisite
Safety decision
Recovery
+
+
Offline turn dispatch
Exact queued message confirmed after atomic-file write
Wait for a connected environment; creations also wait for a live shell
Transient/interrupted failures back off while the file remains
+
Creation replay
Live shell establishes whether the deterministic thread id already exists
If it exists, remove the queued creation without sending it again
A failed cleanup can be retried without duplicating the thread
+
Automatic OTA restart
Composer drafts and outbox writes flush
Restart only while truly backgrounded and no foreground handoff is active
Failed flush or unsafe handoff keeps the runtime alive and rearms the next background
+
+
+
+
+
+
+
+
+
diff --git a/src/components/OpenCodeRecoveryLab.astro b/src/components/OpenCodeRecoveryLab.astro
new file mode 100644
index 0000000..9230521
--- /dev/null
+++ b/src/components/OpenCodeRecoveryLab.astro
@@ -0,0 +1,41 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("OpenCodeRecoveryLab requires a stable kebab-case id.");
+}
+const labId = `opencode-recovery-${id}`;
+
+const branches = [
+ { label: "No valid cursor", result: "Create", detail: "An absent, malformed, or wrong-version cursor supplies no recognized native session id, so the adapter creates a new OpenCode session without a session.get probe.", durable: "The resulting id is returned as a current-version resume cursor for the outer provider-binding persistence path." },
+ { label: "Confirmed missing", result: "Create", detail: "session.get reports a structured 404 / NotFoundError, so the stored native session is gone and a fresh session is permitted.", durable: "This is a native-context loss that is explicitly recognized, not a successful replay of old hot events." },
+ { label: "Transient probe error", result: "Fail", detail: "Authentication, transport, server, or non-404 failures propagate instead of silently creating an empty conversation.", durable: "No new cursor is minted; the existing durable binding remains the recovery clue for a later retry." },
+ { label: "Same directory", result: "Adopt", detail: "The existing session is reused after lexical/real-path comparison and its permission rules are reasserted for the current runtime mode.", durable: "The existing session id remains the cursor; upstream history remains provider-owned." },
+ { label: "Different directory", result: "Fork", detail: "The adapter asks OpenCode to fork the adopted session into the requested cwd, preserving upstream conversation history, then updates permissions.", durable: "The new fork id replaces the returned resume cursor; T3 is not copying native history into its own event log." },
+];
+const payload = JSON.stringify(branches).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive recovery decision
What does an OpenCode resume cursor actually do?
Choose an observed condition; the outcome distinguishes provider-native recovery from durable product binding.
2Runtime ingestioncanonical request activity; pauses the active assistant segment
+
3Client commandthread.approval.respond records response intent
+
4Reactor and serviceresolve the bound session and call the adapter
+
5Provider replynative resolution later returns as activity
+
+
+
+ Static provider × mode matrix
Provider
{modes.map((mode) =>
{mode}
)}
{Object.values(providers).map((provider) =>
{provider.label}
{modes.map((mode) =>
{provider.modes[mode]}
)}
)}
+
+
+
+
+
+
+
diff --git a/src/components/ProjectDiscoveryLab.astro b/src/components/ProjectDiscoveryLab.astro
new file mode 100644
index 0000000..55b3d37
--- /dev/null
+++ b/src/components/ProjectDiscoveryLab.astro
@@ -0,0 +1,66 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("ProjectDiscoveryLab requires a stable kebab-case id.");
+}
+const labId = `project-discovery-${id}`;
+const cases = [
+ { label: "Existing directory, valid t3.json", root: "Normalize the supplied path and verify it is a directory.", project: "A project.create command can claim this normalized root if no active project already uses it.", config: "Decode t3.json at that root; its defaultThreadEnvMode can participate only after a project-level override is absent.", identity: "If Git has a fetch remote, resolve a canonical repository identity for projection and cross-environment grouping." },
+ { label: "Missing directory, creation not requested", root: "Normalization reports that the workspace root does not exist.", project: "No project is created because the command cannot pass root validation.", config: "There is no root at which to load t3.json.", identity: "No repository identity is derived." },
+ { label: "Missing directory, creation requested", root: "The root service creates the directory recursively, verifies it, then returns the normalized path.", project: "The create command still must satisfy the one-active-project-per-normalized-root invariant.", config: "A missing t3.json is an ordinary absence, not an error.", identity: "A newly created empty directory has no Git-remote identity until it becomes a qualifying repository." },
+ { label: "Existing regular file", root: "Normalization rejects it: a workspace root must be a directory.", project: "No project projection changes.", config: "t3.json is never consulted as project configuration for this invalid root.", identity: "No identity is derived." },
+ { label: "Directory with invalid t3.json", root: "The workspace root itself remains valid.", project: "The durable project record can still exist at the root.", config: "The best-effort loader logs the read/decode problem and presents no usable file configuration, so defaults fall through.", identity: "Repository identity is independent of t3.json validity." },
+];
+const payload = JSON.stringify(cases).replaceAll("<", "\\u003c");
+---
+
+
+ Filesystem decision explainer
What becomes a T3 project?
Choose one observed filesystem state. The four answers keep root validation, durable projection, checked-in configuration, and Git identity separate.
+ Step through three durable events. Every registered projector is considered in
+ order, including no-ops; the safe snapshot watermark is the slowest required
+ cursor, not the event-store head.
+
+
+
+
+
+
+
+
+
+
+
+ No sample event has been folded. All projector cursors are at 0.
+
+
+
+
Event-store head
+
Safe snapshot sequence
+
Current event
+
+
+
+ Normal command control flow
+ outer SQL begins → append → projector SQL + cursor → optional filesystem cleanup → accepted receipt → outer commit
+ Cleanup runs before commit but is not enlisted in SQL rollback.
+
+ Start with the cursor, not a promise of eventual consistency.
+
On a normal command, all nine folds run sequentially before the command transaction commits.
+
+
+
+ Projector catch-up stops at sequence 1,000
+
+ The event store is at 1,001, but bootstrap calls its reader with the default
+ total limit of 1,000. The stream completes with every projector cursor one
+ event behind; this path has no second catch-up call in the same bootstrap.
+
+
+
+
+
Static reference: the normal third event leaves every required cursor at 3, so the safe snapshot sequence is 3.
+
1,001-event bootstrap case: the default total read limit stops every lane at 1,000 while the event-store head is 1,001.
+
+
Order
Projector
Read side
Watermark role
At sequence 3
+
+ {lanes.map((lane, index) =>
{index + 1}
{lane.label}
{lane.table}
{lane.required ? "required" : "auxiliary"}
3
)}
+
+
+
+
+
+
+
+
+
+
diff --git a/src/components/ProviderRoutingLab.astro b/src/components/ProviderRoutingLab.astro
new file mode 100644
index 0000000..02c4a88
--- /dev/null
+++ b/src/components/ProviderRoutingLab.astro
@@ -0,0 +1,216 @@
+---
+import { getSourceReference, sourceReferenceHref, sourceReferenceLabel } from "../lib/sources";
+
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("ProviderRoutingLab requires a stable kebab-case id.");
+}
+
+const stages = [
+ { label: "Settings", short: "settings", question: "What was authored?" },
+ { label: "Hydration", short: "merge", question: "Does explicit or legacy config win?" },
+ { label: "Construction", short: "scope", question: "Can the driver decode and create it?" },
+ { label: "Discovery", short: "view", question: "Is it live or only a shadow snapshot?" },
+ { label: "Binding", short: "route", question: "Which exact instance does the thread name?" },
+ { label: "Operation", short: "recover", question: "Can the current adapter adopt or resume?" },
+] as const;
+
+const scenarios = {
+ legacy: {
+ label: "Legacy Codex default",
+ authored: "providers.codex exists; providerInstances.codex is absent.",
+ hydration: "Synthesize the default instance id `codex` from the legacy typed blob.",
+ construction: "Registered Codex driver decodes config and creates one scoped live instance.",
+ discovery: "UI snapshot and routable adapter both use instanceId `codex`.",
+ binding: "Thread binding names `codex`; driver kind verifies `codex`.",
+ operation: "Exact adapter lookup succeeds; an active session routes immediately.",
+ outcome: "Routable default instance",
+ secret: "Only marked sensitive environment values are split/redacted.",
+ tone: "success",
+ sourceIds: ["provider-instance-hydration", "provider-driver-instance-spi", "provider-adapter-registry-live"],
+ },
+ explicit: {
+ label: "Explicit work account",
+ authored: "providerInstances.codex_work uses driver `codex`; a legacy default may coexist.",
+ hydration: "Keep `codex_work` exactly as authored. It does not overwrite the default `codex` key.",
+ construction: "The same driver factory creates independent adapter, snapshot, and text-generation closures.",
+ discovery: "Both instances can expose different health, model, and auth observations.",
+ binding: "A work thread persists `providerInstanceId: codex_work`.",
+ operation: "Lookup cannot fall back to `codex`; it routes the work instance only.",
+ outcome: "Two same-driver instances stay isolated",
+ secret: "Sensitive per-instance environment can point each process at different homes or credentials.",
+ tone: "success",
+ sourceIds: ["provider-instance-identity-contract", "provider-instance-registry-tests", "provider-service-start-session"],
+ },
+ override: {
+ label: "Explicit default overrides legacy",
+ authored: "Both providers.codex and providerInstances.codex are present.",
+ hydration: "The explicit `providerInstances.codex` envelope wins; no legacy copy is synthesized for that id.",
+ construction: "Decode the explicit opaque config and compute enabled state; nested false dominates.",
+ discovery: "Exactly one default-id snapshot is produced from the explicit entry.",
+ binding: "Existing default bindings still name `codex`, now resolving the replacement configuration.",
+ operation: "If the object changed, the old scope closes first; later work may need cursor recovery.",
+ outcome: "Explicit configuration wins, without live-session handoff",
+ secret: "A redacted sensitive patch preserves the prior secret rather than writing an empty value.",
+ tone: "warning",
+ sourceIds: ["provider-instance-hydration", "provider-instance-enabled-precedence", "provider-instance-registry-reconcile"],
+ },
+ shadow: {
+ label: "Unknown fork driver",
+ authored: "providerInstances.research names valid slug `forkAgent`, absent from this build.",
+ hydration: "The open driver slug parses successfully and remains in the effective map.",
+ construction: "No registered driver exists, so construction yields an unavailable shadow.",
+ discovery: "The UI sees disabled/error/unavailable with its exact reason.",
+ binding: "A persisted binding can still name `research`, but no live adapter is listed.",
+ operation: "getByInstance fails; the service does not silently choose another account or driver.",
+ outcome: "Visible configuration, intentionally unroutable",
+ secret: "Unknown opaque config is preserved; the contracts layer does not attempt driver-specific decoding.",
+ tone: "failure",
+ sourceIds: ["provider-instance-identity-contract", "provider-instance-build-shadow", "provider-unavailable-shadow"],
+ },
+ rebuilt: {
+ label: "Changed instance with cursor",
+ authored: "codex_work config changes while a thread binding and resume cursor remain persisted.",
+ hydration: "The same instance id now carries a different entry.",
+ construction: "Close the old child scope before creating the replacement instance and stream.",
+ discovery: "Registries re-pull the replacement object after the change tick.",
+ binding: "SQLite still maps the thread to codex_work and retains opaque resume data.",
+ operation: "No active replacement session: an eligible operation calls startSession with saved cursor/mode/cwd/model.",
+ outcome: "Lazy resume attempt; not zero-downtime migration",
+ secret: "Changed sensitive values are materialized before the new driver scope is created.",
+ tone: "warning",
+ sourceIds: ["provider-instance-registry-reconcile", "provider-registry-live-sync", "provider-service-session-recovery"],
+ },
+ stranded: {
+ label: "Removed instance binding",
+ authored: "The thread still names codex_work, but settings removed that instance.",
+ hydration: "codex_work disappears from the effective map.",
+ construction: "The old child scope closes and no replacement is created.",
+ discovery: "The snapshot is pruned and live adapter lookup excludes the id.",
+ binding: "The durable thread binding is not automatically reassigned or deleted.",
+ operation: "Exact route lookup fails; another Codex instance cannot claim the thread implicitly.",
+ outcome: "Durable binding stranded until explicit repair/configuration",
+ secret: "Removing a sensitive environment entry also removes its named secret through settings logic.",
+ tone: "failure",
+ sourceIds: ["provider-instance-registry-reconcile", "provider-adapter-registry-live", "provider-service-session-recovery"],
+ },
+ nocursor: {
+ label: "Live instance, no resume state",
+ authored: "The configured instance is healthy; the thread binding exists after its live session was lost.",
+ hydration: "No settings change is required.",
+ construction: "The current instance and adapter are live.",
+ discovery: "Health does not imply ownership of this thread's native session.",
+ binding: "The route is exact but its resume cursor is null/absent.",
+ operation: "Recovery-capable operations return validation failure instead of starting an unrelated fresh conversation.",
+ outcome: "Routable instance, unrecoverable conversation",
+ secret: "Credentials may be healthy and still cannot reconstruct missing provider continuation state.",
+ tone: "failure",
+ sourceIds: ["provider-service-session-recovery", "provider-session-directory"],
+ },
+ opencode: {
+ label: "External OpenCode password",
+ authored: "An external serverUrl and serverPassword live in the OpenCode config blob.",
+ hydration: "The explicit config is decoded by the OpenCode driver.",
+ construction: "No local server scope is owned for an external URL; the client uses supplied Basic auth.",
+ discovery: "Connection/auth health belongs to this instance snapshot.",
+ binding: "Threads still route by instance id, never by server URL or password.",
+ operation: "The adapter calls the external server for that configured instance.",
+ outcome: "Routable external instance with a plaintext-settings exception",
+ secret: "serverPassword is documented and tested as plaintext in settings; password UI styling is not encryption.",
+ tone: "warning",
+ sourceIds: ["opencode-password-settings", "opencode-password-persistence-test", "opencode-external-basic-auth"],
+ },
+} as const;
+
+const resolved = Object.fromEntries(Object.entries(scenarios).map(([key, scenario]) => [key, {
+ ...scenario,
+ sources: scenario.sourceIds.map((sourceId) => { const source = getSourceReference(sourceId); return { href: sourceReferenceHref(source), label: sourceReferenceLabel(source) }; }),
+}]));
+const initial = resolved.legacy;
+const labId = `provider-routing-${id}`;
+const payload = JSON.stringify({ stages, scenarios: resolved }).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive fleet router
Which configured runtime receives the thread?
Walk from authored settings to one exact route. Discovery visibility, live behavior, and resume eligibility are different checks.
+
+
+
+
+
+
+
+
+
{stages.map((stage, index) =>
{index + 1}{stage.short}
)}
+
{initial.label}; stage 1 of {stages.length}: {stages[0].label}. {initial.outcome}.
Configure the durable receipt and the original delivery window, then replay the id. The result separates SQL deduplication from hot delivery and provider execution.
+
+
+
+
+
+
+
+
+
+
The delivery window describes the accepted attempt whose receipt is being replayed.
+
+
+
+
1Accepted SQLcomplete
+
2Hot publishcomplete
+
3RPC responsereceived
+
4Providernot proven
+
+
+
+ Accepted receipt, same aggregate, same intent: return the stored sequence without new events. Provider execution is not proven.
+
+
+
+
+
Engine decision
Replay the accepted sequence
+ deduplicated
+
+
The engine finds the accepted row before the decider and returns its stored resultSequence.
+
+
Durable record
The original event batch, projections, and accepted receipt remain committed.
+
Events and delivery
The retry appends zero events and republishes zero events.
+
Client result
The retry receives the stored last sequence.
+
Payload binding
The receipt checks aggregate kind and id, not command type or a payload fingerprint.
+
Provider meaning
The sequence acknowledges durable intent only; provider acceptance or completion is outside the receipt.
One release, three replacement boundaries, four signal lanes
+
Choose a lens, select a teaching case, and move the marker yourself. The model shows the point at which each owner may proceed—and the boundary that keeps it from doing so.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Release graph · stable exact-version path
+
Publishing the CLI unblocks every client that can request a server update
+
The graph does not update a machine. It only makes a matching, exact runtime available before a client can advertise itself.
+
+
+
+
Guard
publish `t3@V` before a client at V is exposed
+
Owner now
release workflow
+
Failure boundary
a client cannot target a package that has not published
+
+
+
+
Release graph. Step 1.
+
+
+
+
+ Static operations ledger
+
+
+
Flow
Proceed only after
Owner
If it cannot proceed
+
+
Exact server update
`t3@<version>` publishes before client release
release workflow, then service launcher
client version cannot be offered before the matching runtime exists
+
Desktop application
user chooses download and then install; pooled backends stop
desktop updater
state records an error or remains downloaded for a later install
Select a complete trace, then advance deliberately. The marker crosses the owner that acts next; its final boundary says what does—and does not—converge.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step 1 of 6
+
+
+
+
+
+
Trace 1 · Local first turn
+
Client sends one existing-thread command
+
The user action enters the environment through an authorized RPC method; no provider work has happened yet.
Choose an illustrative control for the current teaching state. A step flashes once, then rests; this is neither a live provider simulator nor the server's complete legality matrix.
+
+
+
+
+
Current state
+
Resting
+
No active provider turn is projected. A new user message can create durable start intent.
+
+
+
+
Restingno active turn
+
Startingintent awaits runtime
+
Runningcorrelated live turn
+
Approvalwaiting on a decision
+
Inputwaiting on answers
+
Interruptedstop intent recorded
+
Readyturn ended
+
Errornew intent required
+
+
+
+
Durable record
Nothing new is being committed for this simulated turn.
correlated runtime facts can update session/messages
provider liveness remains hot
+
Approval / input
Respond; interrupt
pending request is visible; the turn can remain running
provider waits for a response
+
Interrupted
Start a new intent
a matching projected turn can be marked interrupted
native abortion or session-state facts may still arrive later
+
Completed / ready
Start a new intent
completion may settle session; checkpoint is separate
native session may still exist or later exit
+
+
+
+
* “Steer” is provider-specific. The generic adapter contract has no steer method; this lab models its guarded superseding-turn case. The table is intentionally selective: the start decider itself does not enforce a “must be ready” state guard.
Move through the historical lane. The live context sample stays visible as a deliberately excluded operational signal.
+
+
+
+ Live lane, not an input: thread T-9 currently reports 88,000 / 200,000 context tokens. It changes the composer meter only; it contributes 0 tokens and $0 to the historical total below.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Stage 1 of 6 · parse records
+
Four candidate records arrive from three files
+
The scanner streams provider JSONL. These are candidate usage records, not yet a total.
historical total = Σ kept, in-range records after source-fingerprint ownership
+
reasoning ⊆ output; do not add it a second time
+
+
+
+ Static walkthrough and no-JavaScript reference
+
+
Parse. Candidate rows total 538 tokens: three 160-token Claude copies and one 58-token Codex record.
+
Normalize. Claude's usage maps to 100 uncached + 30 cached + 10 creation + 20 output = 160. Codex's input includes cache, so it maps to 40 uncached + 10 cached + 0 creation + 8 output = 58.
+
Within-file dedupe. Keep C-1a; drop C-1b, which repeats the same Claude message/request key in a.jsonl.
+
Cross-file dedupe. Keep the first surviving Claude key; drop C-1c from the copied/resumed file. Codex has no global key here: its parser-local delta/fork suppression has already accepted distinct record X-1. The subtotal is 218 tokens.
+
Bucket and price. Place the two retained records in their day/provider/model buckets. The displayed formula applies model rates only when no finite provider-reported cost exists; price provenance remains part of the result.
+
Merge environments. Environment A owns the Claude source fingerprint. Environment B reports the identical fingerprint and is a shadow copy, so its Claude bucket is excluded. Environment C owns a different Codex fingerprint. The merged historical total remains 218 tokens.
+
+
Still excluded: the live 88,000 / 200,000 thread context snapshot. It answers a capacity question, not this historical file-accounting question.
+
+
+
+
+
+
diff --git a/src/components/WorkLogLab.astro b/src/components/WorkLogLab.astro
new file mode 100644
index 0000000..b328024
--- /dev/null
+++ b/src/components/WorkLogLab.astro
@@ -0,0 +1,68 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) throw new Error("WorkLogLab requires a stable kebab-case id.");
+const views = {
+ web: { label: "Web · chat work log", lead: "Illustrative projection, not live data: a quiet parent narrative collapses agent lifecycle into a spawn-batch call to action.", rows: [["Parent", "thread.message-sent", "durable thread narrative"], ["Spawn batch", "direct agents", "grouped by spawn turn"], ["Spawn batch", "workflow members", "grouped under the coordinator; CTA opens Agents"]], note: "Web's separate Agents surface carries detailed per-agent state. Progress and usage use stable latest-state streams, but the parent log is not one row per task." },
+ agents: { label: "Web · Agents panel", lead: "Illustrative projection, not live data: a derived roster updates retained agent state in place.", rows: [["Agent", "task.progress", "working state when the payload identifies an agent"], ["Agent", "task.updated", "idle is resumable when reported"], ["Workflow", "task progress", "provider-derived members when present"]], note: "Token, tool, and duration fields are task-local rollups only when typed usage supplies them. They are not Chapter 20 totals." },
+ mobile: { label: "Mobile · thread work log", lead: "Illustrative projection, not live data: compact rows keep a terminal signal because this path has no matching Agents roster.", rows: [["Work log", "task.completed", "terminal agent signal"], ["Work log", "terminal task.updated", "Codex child terminal signal"], ["Work log", "retained activity", "only source-backed activity is shown"]], note: "A mobile work log derives from the same activities; it does not create a mobile-only task store." },
+} as const;
+const initial = views.web;
+const labId = `work-log-${id}`;
+const payload = JSON.stringify({ views }).replaceAll("<", "\\u003c");
+---
+
+
+ Interactive work-log projector
One thread, three surface projections
Switch views to see what a surface may derive from durable thread activity without inventing a scheduler record.
“Desktop uses the web renderer path” does not erase Electron-only authority: preview’s actual webview and automation host are desktop-owned. “No matching route” records this source audit; it is not a product roadmap claim.
+
+
+
+
+
+
+
+
diff --git a/src/components/WorktreeTopologyLab.astro b/src/components/WorktreeTopologyLab.astro
new file mode 100644
index 0000000..bc42757
--- /dev/null
+++ b/src/components/WorktreeTopologyLab.astro
@@ -0,0 +1,58 @@
+---
+interface Props { id: string; }
+const { id } = Astro.props;
+if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id)) {
+ throw new Error("WorktreeTopologyLab requires a stable kebab-case id.");
+}
+const labId = `worktree-topology-${id}`;
+const modes = [
+ { label: "Local request: no new worktree", nodes: ["No Git worktree creation", "Stored thread path, if present", "Otherwise project root", "Thread runs there"], detail: "This mode creates no linked worktree. A newly local thread commonly runs at the project root, but a local request can retain an already-selected workspace path; runtime resolution uses that stored thread path before the project root.", recovery: "If the path is not a Git repository, this is the only effective thread workspace mode. “Local” describes creation, not a ban on an existing workspace path." },
+ { label: "New worktree from local base", nodes: ["Project root", "Chosen local base", "New branch + linked worktree", "Thread runs in linked tree"], detail: "The bootstrap asks Git to create a new branch at the selected base and checks it out in a separate path. The thread is then updated with that branch and worktree path.", recovery: "A Git creation failure aborts the bootstrap; the server cleans up a thread it created during that bootstrap, but does not promise to remove every filesystem side effect Git may already have made." },
+ { label: "New worktree from origin", nodes: ["Project root", "Fetch origin", "Resolve origin base commit", "New branch + linked worktree", "Thread runs in linked tree"], detail: "When the option is enabled and origin exists, T3 fetches origin and resolves the requested base to a remote-tracking commit before creating the local branch/worktree.", recovery: "If origin is absent, the bootstrap falls back to the local selected base instead of failing solely because origin is unavailable." },
+ { label: "Delete thread + optional orphan cleanup", nodes: ["Durably delete thread", "Stop provider + close terminal history", "Offer worktree cleanup when orphaned", "Forced Git removal only if confirmed"], detail: "Thread deletion is not a worktree deletion. The server stops the provider session and closes terminal history; the web client may then offer to force-remove a worktree only when this was its sole linked thread and a local API is available.", recovery: "If the optional Git removal or refresh fails, the thread remains deleted and the worktree can remain. The web client surfaces that partial failure for inspection or later cleanup." },
+ { label: "Remove linked worktree", nodes: ["Project root", "Target linked path", "git worktree remove", "Path no longer present"], detail: "Removal calls Git with the selected linked path. The optional force flag is forwarded only when requested.", recovery: "Git remains the authority: a dirty or otherwise protected worktree can make removal fail, so inspect its state before retrying or forcing cleanup." },
+];
+const payload = JSON.stringify(modes).replaceAll("<", "\\u003c");
+---
+
+
+ Animated topology lab
Choose where a thread will run
Each activation advances only once. There is no autonomous playback: you control the topology and the motion.
+
+ {modes.map((mode, index) => )}
+
+
Selected topology: {modes[0].label}
+ {modes[0].nodes.map((node, index) =>
{node}
)}
+
{modes[0].label}
{modes[0].detail}
Recovery boundary:{modes[0].recovery}
+ All topology outcomes{modes.map((mode) =>
{mode.label}
{mode.detail}
Recovery boundary: {mode.recovery}
)}
+
+
+
+
+
+
+
diff --git a/src/content.config.ts b/src/content.config.ts
new file mode 100644
index 0000000..8d3e0ad
--- /dev/null
+++ b/src/content.config.ts
@@ -0,0 +1,27 @@
+import { defineCollection } from "astro:content";
+import { glob } from "astro/loaders";
+import { z } from "astro/zod";
+
+const book = defineCollection({
+ loader: glob({ pattern: "**/*.{md,mdx}", base: "./src/content/book" }),
+ schema: z.object({
+ slug: z.string(),
+ order: z.number().int().nonnegative(),
+ number: z.string().optional(),
+ kind: z.enum(["front", "chapter", "appendix"]),
+ part: z.string(),
+ partOrder: z.number().int().nonnegative(),
+ title: z.string(),
+ shortTitle: z.string().optional(),
+ summary: z.string(),
+ status: z.enum(["draft", "source-checked", "verified"]),
+ gates: z.array(z.enum(["sources", "links", "interaction", "editorial"])).default([]),
+ objectives: z.array(z.string()).default([]),
+ keywords: z.array(z.string()).default([]),
+ sourceAreas: z.array(z.string()).default([]),
+ visuals: z.array(z.string()).default([]),
+ updatedAt: z.coerce.date(),
+ }),
+});
+
+export const collections = { book };
diff --git a/src/generated/excerpts.json b/src/generated/excerpts.json
new file mode 100644
index 0000000..f3625fc
--- /dev/null
+++ b/src/generated/excerpts.json
@@ -0,0 +1,1842 @@
+{
+ "architecture-boundary": {
+ "id": "architecture-boundary",
+ "path": "docs/internals/overview.md",
+ "start": 5,
+ "end": 28,
+ "language": "markdown",
+ "label": "The execution boundary",
+ "code": "T3 Code is a server runtime that owns agent sessions, workspaces, and version control, plus clients\n(web, desktop, mobile) that talk to it over one authenticated Effect RPC WebSocket. The server is the\nexecution boundary: every provider process, terminal, git operation, and filesystem read happens\nthere, never in the client.\n\n```\n┌────────────────────────────────────────────────┐\n│ Clients: apps/web, apps/desktop, apps/mobile │\n│ shared runtime: packages/client-runtime │\n│ connection supervisor, RPC session, Atom state│\n└──────────────────┬─────────────────────────────┘\n │ Effect RPC over WebSocket (/ws)\n │ contract: packages/contracts\n┌──────────────────▼─────────────────────────────┐\n│ apps/server │\n│ orchestration engine (event-sourced) │\n│ provider driver registry (5 built-in drivers) │\n│ checkpointing, VCS, terminals, filesystem │\n└──────────────────┬─────────────────────────────┘\n │ per-driver transport\n┌──────────────────▼─────────────────────────────┐\n│ Agent CLIs: Codex, Claude, Cursor, Grok, │\n│ OpenCode │\n└────────────────────────────────────────────────┘",
+ "checksum": "fd6effc6bfb1e04275e59190badc87399e6298b077fe3d05e7eb0f8544afd698"
+ },
+ "orchestration-rpc-methods": {
+ "id": "orchestration-rpc-methods",
+ "path": "packages/contracts/src/orchestration.ts",
+ "start": 27,
+ "end": 36,
+ "language": "typescript",
+ "label": "Orchestration RPC surface",
+ "code": "export const ORCHESTRATION_WS_METHODS = {\n dispatchCommand: \"orchestration.dispatchCommand\",\n getWorkflowScript: \"orchestration.getWorkflowScript\",\n getTurnDiff: \"orchestration.getTurnDiff\",\n getFullThreadDiff: \"orchestration.getFullThreadDiff\",\n searchThreads: \"orchestration.searchThreads\",\n getArchivedShellSnapshot: \"orchestration.getArchivedShellSnapshot\",\n subscribeShell: \"orchestration.subscribeShell\",\n subscribeThread: \"orchestration.subscribeThread\",\n} as const;",
+ "checksum": "654f6e0acadb65856a7b1267a314ba5d501fdb7bb2b44847ec54d2a77e034e7c"
+ },
+ "turn-start-command": {
+ "id": "turn-start-command",
+ "path": "packages/contracts/src/orchestration.ts",
+ "start": 847,
+ "end": 864,
+ "language": "typescript",
+ "label": "Client turn-start command",
+ "code": "const ClientThreadTurnStartCommand = Schema.Struct({\n type: Schema.Literal(\"thread.turn.start\"),\n commandId: CommandId,\n threadId: ThreadId,\n message: Schema.Struct({\n messageId: MessageId,\n role: Schema.Literal(\"user\"),\n text: Schema.String,\n attachments: Schema.Array(UploadChatAttachment),\n }),\n modelSelection: Schema.optional(ModelSelection),\n titleSeed: Schema.optional(TrimmedNonEmptyString),\n runtimeMode: RuntimeMode,\n interactionMode: ProviderInteractionMode,\n bootstrap: Schema.optional(ThreadTurnStartBootstrap),\n sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n createdAt: IsoDateTime,\n});",
+ "checksum": "2a356b9b8badac1a1eda578900fc6847c5095057aaa4bc34c9ab057b352c64ec"
+ },
+ "provider-adapter-core": {
+ "id": "provider-adapter-core",
+ "path": "apps/server/src/provider/Services/ProviderAdapter.ts",
+ "start": 47,
+ "end": 71,
+ "language": "typescript",
+ "label": "Provider adapter lifecycle contract",
+ "code": "export interface ProviderAdapterShape {\n /**\n * Provider kind implemented by this adapter.\n */\n readonly provider: ProviderDriverKind;\n readonly capabilities: ProviderAdapterCapabilities;\n\n /**\n * Start a provider-backed session.\n */\n readonly startSession: (\n input: ProviderSessionStartInput,\n ) => Effect.Effect;\n\n /**\n * Send a turn to an active provider session.\n */\n readonly sendTurn: (\n input: ProviderSendTurnInput,\n ) => Effect.Effect;\n\n /**\n * Interrupt an active turn.\n */\n readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect;",
+ "checksum": "a75847d120df17015de3fdcd97ab0f5a3b5d3f7c8b19f950e0c0d484441e17cf"
+ },
+ "provider-adapter-interactions": {
+ "id": "provider-adapter-interactions",
+ "path": "apps/server/src/provider/Services/ProviderAdapter.ts",
+ "start": 73,
+ "end": 94,
+ "language": "typescript",
+ "label": "Provider approval and input contract",
+ "code": " /**\n * Respond to an interactive approval request.\n */\n readonly respondToRequest: (\n threadId: ThreadId,\n requestId: ApprovalRequestId,\n decision: ProviderApprovalDecision,\n ) => Effect.Effect;\n\n /**\n * Respond to a structured user-input request.\n */\n readonly respondToUserInput: (\n threadId: ThreadId,\n requestId: ApprovalRequestId,\n answers: ProviderUserInputAnswers,\n ) => Effect.Effect;\n\n /**\n * Stop one provider session.\n */\n readonly stopSession: (threadId: ThreadId) => Effect.Effect;",
+ "checksum": "67b4610571f49faa99826588c7af37dafaf379bc25f4e9d012a429cc31f5858d"
+ },
+ "provider-adapter-stream": {
+ "id": "provider-adapter-stream",
+ "path": "apps/server/src/provider/Services/ProviderAdapter.ts",
+ "start": 126,
+ "end": 134,
+ "language": "typescript",
+ "label": "Canonical provider event stream",
+ "code": " /**\n * Stop all sessions owned by this adapter.\n */\n readonly stopAll: () => Effect.Effect;\n\n /**\n * Canonical runtime event stream emitted by this adapter.\n */\n readonly streamEvents: Stream.Stream;",
+ "checksum": "4a95ebce476cfbf3fd22ef7f508d1ef5b55ac49db91548ed4b3ab8fdd482d443"
+ },
+ "orchestration-transaction": {
+ "id": "orchestration-transaction",
+ "path": "apps/server/src/orchestration/Layers/OrchestrationEngine.ts",
+ "start": 197,
+ "end": 259,
+ "language": "typescript",
+ "label": "Atomic command commit",
+ "code": " const committedCommand = yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const committedEvents: OrchestrationEvent[] = [];\n let nextCommandReadModel = commandReadModel;\n\n for (const nextEvent of eventBases) {\n const savedEvent = yield* eventStore.append(nextEvent);\n nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);\n yield* projectionPipeline.projectEvent(savedEvent);\n committedEvents.push(savedEvent);\n }\n\n const lastSavedEvent = committedEvents.at(-1) ?? null;\n if (lastSavedEvent === null) {\n return yield* new OrchestrationCommandInvariantError({\n commandType: envelope.command.type,\n detail: \"Command produced no events.\",\n });\n }\n\n yield* commandReceiptRepository.upsert({\n commandId: envelope.command.commandId,\n aggregateKind: lastSavedEvent.aggregateKind,\n aggregateId: lastSavedEvent.aggregateId,\n acceptedAt: lastSavedEvent.occurredAt,\n resultSequence: lastSavedEvent.sequence,\n status: \"accepted\",\n error: null,\n });\n\n return {\n committedEvents,\n lastSequence: lastSavedEvent.sequence,\n nextCommandReadModel,\n } as const;\n }),\n )\n .pipe(\n Effect.catchTag(\"SqlError\", (sqlError) =>\n Effect.fail(\n toPersistenceSqlError(\"OrchestrationEngine.processEnvelope:transaction\")(sqlError),\n ),\n ),\n );\n\n commandReadModel = committedCommand.nextCommandReadModel;\n for (const [index, event] of committedCommand.committedEvents.entries()) {\n yield* PubSub.publish(eventPubSub, event);\n if (index === 0) {\n yield* Metric.update(\n Metric.withAttributes(\n orchestrationCommandAckDuration,\n metricAttributes({\n ...baseMetricAttributes,\n ackEventType: event.type,\n }),\n ),\n Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),\n );\n }\n }\n return { sequence: committedCommand.lastSequence };",
+ "checksum": "24e00da0c432e501172e3847817fde311d8656b07e3b8261c657ecf6b4c35d4c"
+ },
+ "orchestration-dispatch": {
+ "id": "orchestration-dispatch",
+ "path": "apps/server/src/orchestration/Layers/OrchestrationEngine.ts",
+ "start": 331,
+ "end": 368,
+ "language": "typescript",
+ "label": "Serialized command dispatch and event fan-out",
+ "code": " yield* projectionPipeline.bootstrap;\n commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();\n\n const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));\n yield* Effect.forkScoped(worker);\n yield* Effect.logDebug(\"orchestration engine started\").pipe(\n Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),\n );\n\n const readEvents: OrchestrationEngineShape[\"readEvents\"] = (fromSequenceExclusive, limit) =>\n eventStore.readFromSequence(fromSequenceExclusive, limit);\n\n const dispatch: OrchestrationEngineShape[\"dispatch\"] = (command, options) =>\n Effect.gen(function* () {\n const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();\n yield* Queue.offer(commandQueue, {\n command,\n origin: options?.origin,\n result,\n startedAtMs: yield* Clock.currentTimeMillis,\n });\n return yield* Deferred.await(result);\n });\n\n return {\n readEvents,\n dispatch,\n // Each access creates a fresh PubSub subscription so that multiple\n // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)\n // each independently receive all domain events.\n get streamDomainEvents(): OrchestrationEngineShape[\"streamDomainEvents\"] {\n return Stream.fromPubSub(eventPubSub);\n },\n // The command read model's snapshotSequence tracks the latest committed\n // event sequence (updated on the worker fiber). A plain property read is a\n // consistent, committed value — reassignment of `commandReadModel` is\n // atomic on the single-threaded event loop.\n latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),",
+ "checksum": "85e20350d344ef6e865480addc97f37638fb833acbee999092d2a1b537019bfa"
+ },
+ "server-runtime-core": {
+ "id": "server-runtime-core",
+ "path": "apps/server/src/server.ts",
+ "start": 353,
+ "end": 416,
+ "language": "typescript",
+ "label": "Authentication, remote endpoint, provider, and server dependency assembly",
+ "code": "const AuthLayerLive = EnvironmentAuth.layer.pipe(\n Layer.provideMerge(PersistenceLayerLive),\n Layer.provide(ServerSecretStore.layer),\n);\n\nconst CloudManagedEndpointRuntimeLive = Layer.mergeAll(\n RelayClientLive,\n CloudManagedEndpointRuntime.layer.pipe(\n Layer.provide(ServerSecretStore.layer),\n Layer.provide(RelayClientLive),\n ),\n);\n\nconst ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(\n Layer.provideMerge(ProviderLayerLive),\n Layer.provideMerge(OrchestrationLayerLive),\n);\n\nconst RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(\n // Core Services\n Layer.provideMerge(ServerSettingsLayerLive),\n Layer.provideMerge(CheckpointingLayerLive),\n Layer.provideMerge(SourceControlProviderRegistryLayerLive),\n Layer.provideMerge(GitLayerLive),\n Layer.provideMerge(VcsLayerLive),\n Layer.provideMerge(ProviderRuntimeLayerLive),\n Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),\n Layer.provideMerge(PersistenceLayerLive),\n Layer.provideMerge(Keybindings.layer),\n Layer.provideMerge(ProviderRegistryLive),\n // The instance registry is the new routing keystone — text generation,\n // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`\n // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;\n // `providerInstances` hydration merges `settings.providers.`\n // with explicit `providerInstances` entries on boot.\n Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n // Shared native/canonical NDJSON writers used by both the per-instance\n // drivers (native stream, written from inside each `Adapter`) and\n // `ProviderService` (canonical stream, written after event normalization).\n // Provided once at the runtime level so every consumer sees the same\n // logger instances.\n Layer.provideMerge(ProviderEventLoggers.layer),\n // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old\n // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but\n // the rewritten registry reads snapshots off the instance registry and\n // no longer transitively provides it. Exposing it at the runtime level\n // keeps a single Live for all opencode consumers.\n Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),\n Layer.provideMerge(WorkspaceLayerLive),\n Layer.provideMerge(ProjectFaviconResolverLayerLive),\n Layer.provideMerge(RepositoryIdentityResolver.layer),\n Layer.provideMerge(ServerEnvironment.layer),\n Layer.provideMerge(AuthLayerLive),\n Layer.provideMerge(ServerSecretStore.layer),\n Layer.provideMerge(\n Layer.mergeAll(\n CloudCliTokenManager.layer.pipe(\n Layer.provide(ServerSecretStore.layer),\n Layer.provide(ExternalLauncher.layer),\n ),\n CloudManagedEndpointRuntimeLive,\n ),\n ),\n);",
+ "checksum": "11cc88459d4db7e4b29b6b738dcdaba486d8385f6cec6e7dde0d7851c7ada9c5"
+ },
+ "dispatch-result": {
+ "id": "dispatch-result",
+ "path": "packages/contracts/src/orchestration.ts",
+ "start": 1580,
+ "end": 1583,
+ "language": "typescript",
+ "label": "Successful client dispatch result",
+ "code": "export const DispatchResult = Schema.Struct({\n sequence: NonNegativeInt,\n});\nexport type DispatchResult = typeof DispatchResult.Type;",
+ "checksum": "151b83cdd47b9a449a38bb64d9f7b37ccd31ab6f109753cb6535214e12bf98de"
+ },
+ "rejected-receipt-best-effort": {
+ "id": "rejected-receipt-best-effort",
+ "path": "apps/server/src/orchestration/Layers/OrchestrationEngine.ts",
+ "start": 287,
+ "end": 325,
+ "language": "typescript",
+ "label": "Best-effort invariant-rejection receipt",
+ "code": " if (Exit.isSuccess(exit)) {\n yield* Deferred.succeed(envelope.result, exit.value);\n return;\n }\n\n const error = Cause.squash(exit.cause) as OrchestrationDispatchError;\n if (\n !isOrchestrationCommandPreviouslyRejectedError(error) &&\n !isOrchestrationCommandIdConflictError(error)\n ) {\n yield* reconcileReadModelAfterDispatchFailure.pipe(\n Effect.catch(() =>\n Effect.logWarning(\n \"failed to reconcile orchestration read model after dispatch failure\",\n ).pipe(\n Effect.annotateLogs({\n commandId: envelope.command.commandId,\n snapshotSequence: commandReadModel.snapshotSequence,\n }),\n ),\n ),\n );\n\n if (isOrchestrationCommandInvariantError(error)) {\n yield* commandReceiptRepository\n .upsert({\n commandId: envelope.command.commandId,\n aggregateKind: aggregateRef.aggregateKind,\n aggregateId: aggregateRef.aggregateId,\n acceptedAt: yield* nowIso,\n resultSequence: commandReadModel.snapshotSequence,\n status: \"rejected\",\n error: error.message,\n })\n .pipe(Effect.catch(() => Effect.void));\n }\n }\n\n yield* Deferred.fail(envelope.result, error);",
+ "checksum": "baa86ecd4a4a583386c539189ea6d26d3b4c6377201a660a9d22b2eb52a7645b"
+ },
+ "hot-reactor-no-replay": {
+ "id": "hot-reactor-no-replay",
+ "path": "apps/server/src/orchestration/Layers/ProviderCommandReactor.ts",
+ "start": 1405,
+ "end": 1409,
+ "language": "typescript",
+ "label": "Hot post-commit stream has no pending-work replay",
+ "code": " yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent));\n\n // The domain event stream is hot, so work pending before this reactor\n // starts cannot be resumed. Correlated completions only clear the request\n // captured here, leaving any newer request untouched.",
+ "checksum": "fe4e62df9690c497361768207b76ed48bb65364abc5ef5b123321deb6c0277ee"
+ },
+ "cli-entry-command": {
+ "id": "cli-entry-command",
+ "path": "apps/server/src/bin.ts",
+ "start": 23,
+ "end": 71,
+ "language": "typescript",
+ "label": "Root CLI and subcommand dispatch",
+ "code": "const connectPublicConfigMissingMessage =\n \"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.\";\n\nclass ConnectPublicConfigMissingError extends CliError.UserError {\n override get message() {\n return connectPublicConfigMissingMessage;\n }\n}\n\nconst connectUnavailableCommand = Command.make(\"connect\", {\n command: Argument.string(\"command\").pipe(Argument.variadic),\n}).pipe(\n Command.withDescription(\"T3 Connect is unavailable in builds without public configuration.\"),\n Command.withHidden,\n Command.withHandler(() =>\n Effect.fail(\n new CliError.ShowHelp({\n commandPath: [\"t3\", \"connect\"],\n errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],\n }),\n ),\n ),\n);\n\nexport const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>\n Command.make(\"t3\", { ...sharedServerCommandFlags }).pipe(\n Command.withDescription(\"Run the T3 Code server.\"),\n Command.withHandler((flags) => runServerCommand(flags)),\n Command.withSubcommands([\n startCommand,\n serveCommand,\n pairCommand,\n authCommand,\n projectCommand,\n serviceCommand,\n servicePreflightCommand,\n triageCommand,\n cloudEnabled ? connectCommand : connectUnavailableCommand,\n ]),\n );\n\nexport const cli = makeCli();\n\nif (import.meta.main) {\n Command.run(cli, { version: packageJson.version }).pipe(\n Effect.scoped,\n Effect.provide(CliRuntimeLayer),\n NodeRuntime.runMain,\n );",
+ "checksum": "4cbb1e2584966a2f8399dbdf57f860033d79e1da2aba843e49a008d4a4cdc2ab"
+ },
+ "cli-config-precedence": {
+ "id": "cli-config-precedence",
+ "path": "apps/server/src/cli/config.ts",
+ "start": 244,
+ "end": 280,
+ "language": "typescript",
+ "label": "Mode, port, and base-directory precedence",
+ "code": " const mode: ServerConfig.RuntimeMode = Option.getOrElse(\n resolveOptionPrecedence(\n normalizedFlags.mode,\n Option.fromUndefinedOr(env.mode),\n Option.fromUndefinedOr(bootstrap?.mode),\n ),\n () => \"web\",\n );\n\n const port = yield* Option.match(\n resolveOptionPrecedence(\n normalizedFlags.port,\n Option.fromUndefinedOr(env.port),\n Option.fromUndefinedOr(bootstrap?.port),\n ),\n {\n onSome: (value) => Effect.succeed(value),\n onNone: () => {\n if (mode === \"desktop\") {\n return Effect.succeed(ServerConfig.DEFAULT_PORT);\n }\n return findAvailablePort(ServerConfig.DEFAULT_PORT);\n },\n },\n );\n const devUrl = Option.getOrElse(\n resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),\n () => undefined,\n );\n const explicitBaseDir = resolveOptionPrecedence(\n normalizedFlags.baseDir,\n Option.fromUndefinedOr(env.t3Home),\n ).pipe(Option.filter((value) => value.trim().length > 0));\n const baseDir = yield* resolveBaseDir(\n Option.getOrUndefined(\n resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),\n ),",
+ "checksum": "f772af33c3c09ffd6b1641fe1391724758215ae054421feba0e93fc83f736d87"
+ },
+ "cli-serve-semantics": {
+ "id": "cli-serve-semantics",
+ "path": "apps/server/src/cli/server.ts",
+ "start": 21,
+ "end": 35,
+ "language": "typescript",
+ "label": "Start and headless serve semantics",
+ "code": "export const startCommand = Command.make(\"start\", { ...sharedServerCommandFlags }).pipe(\n Command.withDescription(\"Run the T3 Code server.\"),\n Command.withHandler((flags) => runServerCommand(flags)),\n);\n\nexport const serveCommand = Command.make(\"serve\", { ...sharedServerCommandFlags }).pipe(\n Command.withDescription(\n \"Run the T3 Code server without opening a browser and print headless pairing details.\",\n ),\n Command.withHandler((flags) =>\n runServerCommand(flags, {\n startupPresentation: \"headless\",\n forceAutoBootstrapProjectFromCwd: false,\n }),\n ),",
+ "checksum": "114413115c5143f5873145eb904d38d5ad2b7316516f397de0514fa0b41d8bf8"
+ },
+ "startup-readiness-order": {
+ "id": "startup-readiness-order",
+ "path": "apps/server/src/serverRuntimeStartup.ts",
+ "start": 514,
+ "end": 548,
+ "language": "typescript",
+ "label": "Prepared, activated, command-ready, and ready order",
+ "code": " yield* Effect.logDebug(\"startup phase: waiting for http listener\");\n yield* runStartupPhase(\"http.wait\", Deferred.await(httpListening));\n yield* runStartupPhase(\n \"auxiliary-roots.parked\",\n options?.awaitAuxiliaryParked ?? Effect.void,\n );\n\n // This is the prepared boundary. Every dependency has been acquired and\n // every runtime root has confirmed that it is parked before this request.\n const updateOutcome = yield* launcher.prepareTrial;\n yield* runStartupPhase(\n \"welcome.publish\",\n lifecycleEvents.publish({\n version: 1,\n type: \"welcome\",\n payload: { environment, ...welcomeBase },\n }),\n );\n yield* options?.activate ?? Effect.void;\n\n yield* Effect.logDebug(\"Accepting commands\");\n yield* commandGate.signalCommandReady;\n yield* runStartupPhase(\n \"ready.publish\",\n lifecycleEvents.publish({\n version: 1,\n type: \"ready\",\n payload: {\n at: DateTime.formatIso(yield* DateTime.now),\n environment,\n ...(updateOutcome === undefined ? {} : { updateOutcome }),\n },\n }),\n );\n yield* Effect.logDebug(\"startup phase: complete\");",
+ "checksum": "8ed6988b351036573a062e87716f4a1154d4d3e69710d8041f6b849965ced364"
+ },
+ "command-readiness-middleware": {
+ "id": "command-readiness-middleware",
+ "path": "apps/server/src/server.ts",
+ "start": 431,
+ "end": 437,
+ "language": "typescript",
+ "label": "Global route-execution readiness barrier",
+ "code": "const commandReadinessLayer = HttpRouter.middleware(\n (httpEffect) =>\n Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>\n startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),\n ),\n { global: true },\n);",
+ "checksum": "656843f40a4ec8a4e2b1a5dca6671d9264c33edd92731693262a960972ff770f"
+ },
+ "rpc-stream-contracts": {
+ "id": "rpc-stream-contracts",
+ "path": "packages/contracts/src/rpc.ts",
+ "start": 933,
+ "end": 948,
+ "language": "typescript",
+ "label": "Typed shell and thread streaming RPC contracts",
+ "code": "export const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {\n payload: OrchestrationRpcSchemas.subscribeShell.input,\n success: OrchestrationRpcSchemas.subscribeShell.output,\n error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n stream: true,\n});\n\nexport const WsOrchestrationSubscribeThreadRpc = Rpc.make(\n ORCHESTRATION_WS_METHODS.subscribeThread,\n {\n payload: OrchestrationRpcSchemas.subscribeThread.input,\n success: OrchestrationRpcSchemas.subscribeThread.output,\n error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n stream: true,\n },\n);",
+ "checksum": "efb34f4d793fed351ef25bd2e61b7c448bea8748c2edede590ba9a0f72336b0b"
+ },
+ "thread-resume-race": {
+ "id": "thread-resume-race",
+ "path": "apps/server/src/ws.ts",
+ "start": 1394,
+ "end": 1521,
+ "language": "typescript",
+ "label": "Attach-before-read and bounded thread replay",
+ "code": " [ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>\n observeRpcStreamEffect(\n ORCHESTRATION_WS_METHODS.subscribeThread,\n Effect.gen(function* () {\n const isThisThreadDetailEvent = (event: OrchestrationEvent) =>\n event.aggregateKind === \"thread\" &&\n event.aggregateId === input.threadId &&\n isThreadDetailEvent(event);\n\n const liveStream = orchestrationEngine.streamDomainEvents.pipe(\n Stream.filter(isThisThreadDetailEvent),\n Stream.map((event) => ({\n kind: \"event\" as const,\n event: projectActivityEvent(event),\n })),\n );\n\n // Attach live delivery before reading either replay or snapshot state.\n // Otherwise an event published while the snapshot is loading is lost.\n const liveBuffer = yield* Queue.unbounded();\n yield* Effect.forkScoped(\n liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),\n );\n const bufferedLiveStream = Stream.fromQueue(liveBuffer);\n\n // When the client already loaded the snapshot over HTTP it passes\n // that snapshot's sequence, and we resume the live subscription by\n // replaying persisted events after it instead of re-sending the\n // (potentially multi-KB) snapshot frame over the socket.\n //\n // The live PubSub subscription must be attached *before* draining\n // the catch-up replay, otherwise events published during the replay\n // window are dropped (they are past the persisted tail the replay\n // read, but the live stream is not yet subscribed). So fork the\n // live stream into a buffer bound to this stream's scope, then emit\n // catch-up followed by the buffered/ongoing live events. Overlapping\n // events are deduped by sequence on the client.\n //\n // The replay is bounded to the projection head captured below. The\n // catch-up range is normally tiny (a fresh HTTP snapshot sequence),\n // but a stale cached cursor can sit hundreds of thousands of global\n // events behind — replaying that decodes every intervening event\n // (including every other thread's tool payloads) only to discard\n // almost all of them, which has OOM-killed servers on large\n // databases. A truncated replay would silently drop this thread's\n // events, so past the gap cap we reset the client with a fresh\n // thread snapshot instead, exactly like subscribeShell above.\n if (input.afterSequence !== undefined) {\n const afterSequence = input.afterSequence;\n const headSequence = yield* orchestrationEngine.latestSequence;\n const replayGap = headSequence - afterSequence;\n if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) {\n const catchUpStream = orchestrationEngine\n .readEvents(afterSequence, replayGap)\n .pipe(\n Stream.filter(isThisThreadDetailEvent),\n Stream.map((event) => ({\n kind: \"event\" as const,\n event: projectActivityEvent(event),\n })),\n Stream.mapError(\n (cause) =>\n new OrchestrationGetSnapshotError({\n message: `Failed to replay thread ${input.threadId} events`,\n cause,\n }),\n ),\n );\n const afterCatchUp =\n input.requestCompletionMarker === true\n ? Stream.concat(\n Stream.fromEffect(\n Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n ).pipe(Stream.drain),\n bufferedLiveStream,\n )\n : bufferedLiveStream;\n return Stream.concat(catchUpStream, afterCatchUp);\n }\n // Gap too large (or cursor ahead of authoritative state): fall\n // through to the snapshot path so the client converges from a\n // fresh thread detail instead of an unbounded replay.\n }\n\n const snapshot = yield* projectionSnapshotQuery\n .getThreadDetailSnapshot(\n input.threadId,\n // Windowing the fallback snapshot is opt-in per subscription:\n // clients that don't send turnLimit (including all\n // pre-pagination clients) get the full thread, since they\n // have no way to load older pages.\n input.turnLimit === undefined ? undefined : { turnLimit: input.turnLimit },\n )\n .pipe(\n Effect.mapError(\n (cause) =>\n new OrchestrationGetSnapshotError({\n message: `Failed to load thread ${input.threadId}`,\n cause,\n }),\n ),\n );\n\n if (Option.isNone(snapshot)) {\n return yield* new OrchestrationGetSnapshotError({\n message: `Thread ${input.threadId} was not found`,\n cause: input.threadId,\n });\n }\n\n const afterSnapshot =\n input.requestCompletionMarker === true\n ? Stream.concat(\n Stream.fromEffect(\n Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n ).pipe(Stream.drain),\n bufferedLiveStream,\n )\n : bufferedLiveStream;\n return Stream.concat(\n Stream.make({\n kind: \"snapshot\" as const,\n snapshot: projectThreadDetailSnapshot(snapshot.value),\n }),\n afterSnapshot,\n );\n }),\n { \"rpc.aggregate\": \"orchestration\" },",
+ "checksum": "0f57dcc6b6815e4cd36c8eca74f696252ba35e6d8446a41d66f413eb214f54f3"
+ },
+ "auth-credential-precedence": {
+ "id": "auth-credential-precedence",
+ "path": "apps/server/src/auth/EnvironmentAuth.ts",
+ "start": 592,
+ "end": 632,
+ "language": "typescript",
+ "label": "Cookie, Bearer, and DPoP authentication precedence",
+ "code": " const authenticateRequest = (\n request: HttpServerRequest.HttpServerRequest,\n ): Effect.Effect => {\n const cookieToken = request.cookies[sessions.cookieName];\n const bearerToken = parseBearerToken(request);\n const dpopToken = parseDpopToken(request);\n const credential = cookieToken ?? bearerToken ?? dpopToken;\n if (!credential) {\n return Effect.fail(new ServerAuthMissingCredentialError({}));\n }\n return authenticateToken(credential).pipe(\n Effect.flatMap((session) => {\n if (session.proofKeyThumbprint) {\n if (!dpopToken || dpopToken !== credential) {\n return Effect.fail(\n new ServerAuthInvalidCredentialError({\n diagnostic: \"DPoP-bound access token requires DPoP authorization.\",\n }),\n );\n }\n return verifyRequestDpopProof({\n request,\n expectedThumbprint: session.proofKeyThumbprint,\n expectedAccessToken: dpopToken,\n }).pipe(\n Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),\n Effect.provideService(Crypto.Crypto, crypto),\n Effect.as(session),\n );\n }\n if (dpopToken) {\n return Effect.fail(\n new ServerAuthInvalidCredentialError({\n diagnostic: \"DPoP authorization requires a proof-bound access token.\",\n }),\n );\n }\n return Effect.succeed(session);\n }),\n );\n };",
+ "checksum": "d18c91b8d4ceaa79bc875630b87a342328ced1fc8a43556643ea32431af3232d"
+ },
+ "websocket-ticket-verification": {
+ "id": "websocket-ticket-verification",
+ "path": "apps/server/src/auth/SessionStore.ts",
+ "start": 785,
+ "end": 851,
+ "language": "typescript",
+ "label": "WebSocket ticket verification reloads session state",
+ "code": " const verifyWebSocketToken: SessionStore[\"Service\"][\"verifyWebSocketToken\"] = Effect.fn(\n \"SessionStore.verifyWebSocketToken\",\n )(function* (token) {\n const [encodedPayload, signature] = token.split(\".\");\n if (!encodedPayload || !signature) {\n return yield* new MalformedWebSocketTokenError({});\n }\n\n const expectedSignature = signPayload(encodedPayload, signingSecret);\n if (!timingSafeEqualBase64Url(signature, expectedSignature)) {\n return yield* new InvalidWebSocketTokenSignatureError({});\n }\n\n const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(\n Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),\n );\n\n const observedAt = yield* DateTime.now;\n const expiresAt = DateTime.make(claims.exp);\n if (Option.isNone(expiresAt)) {\n return yield* new InvalidSessionExpirationClaimError({\n sessionId: claims.sid,\n expirationClaim: claims.exp,\n });\n }\n if (claims.exp <= observedAt.epochMilliseconds) {\n return yield* new WebSocketTokenExpiredError({\n sessionId: claims.sid,\n expiresAt: expiresAt.value,\n observedAt,\n });\n }\n\n const row = yield* authSessions\n .getById({ sessionId: claims.sid })\n .pipe(\n Effect.mapError(\n (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),\n ),\n );\n if (Option.isNone(row)) {\n return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });\n }\n if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {\n return yield* new WebSocketSessionExpiredError({\n sessionId: claims.sid,\n expiresAt: row.value.expiresAt,\n observedAt,\n });\n }\n if (row.value.revokedAt !== null) {\n return yield* new WebSocketSessionRevokedError({\n sessionId: claims.sid,\n revokedAt: row.value.revokedAt,\n });\n }\n\n return {\n sessionId: row.value.sessionId,\n token,\n method: row.value.method,\n client: toClientMetadata(row.value.client),\n expiresAt: row.value.expiresAt,\n subject: row.value.subject,\n scopes: row.value.scopes,\n } satisfies VerifiedSession;\n });",
+ "checksum": "dcb5b1a1fbdbcb3efae560e941aeed24343450e553fb345e55b71c1707bd0f9f"
+ },
+ "command-union-boundary": {
+ "id": "command-union-boundary",
+ "path": "packages/contracts/src/orchestration.ts",
+ "start": 913,
+ "end": 1057,
+ "language": "typescript",
+ "label": "Client-dispatchable, normalized, and trusted internal command unions",
+ "code": "const DispatchableClientOrchestrationCommand = Schema.Union([\n ProjectCreateCommand,\n ProjectMetaUpdateCommand,\n ProjectDeleteCommand,\n ThreadCreateCommand,\n ThreadDeleteCommand,\n ThreadArchiveCommand,\n ThreadUnarchiveCommand,\n ThreadSettleCommand,\n ThreadUnsettleCommand,\n ThreadSnoozeCommand,\n ThreadUnsnoozeCommand,\n ThreadPinCommand,\n ThreadUnpinCommand,\n ThreadPinReorderCommand,\n ThreadMetaUpdateCommand,\n ThreadRuntimeModeSetCommand,\n ThreadInteractionModeSetCommand,\n ThreadTurnStartCommand,\n ThreadTurnInterruptCommand,\n ThreadApprovalRespondCommand,\n ThreadUserInputRespondCommand,\n ThreadCheckpointRevertCommand,\n ThreadSessionStopCommand,\n]);\nexport type DispatchableClientOrchestrationCommand =\n typeof DispatchableClientOrchestrationCommand.Type;\n\nexport const ClientOrchestrationCommand = Schema.Union([\n ProjectCreateCommand,\n ProjectMetaUpdateCommand,\n ProjectDeleteCommand,\n ThreadCreateCommand,\n ThreadDeleteCommand,\n ThreadArchiveCommand,\n ThreadUnarchiveCommand,\n ThreadSettleCommand,\n ThreadUnsettleCommand,\n ThreadSnoozeCommand,\n ThreadUnsnoozeCommand,\n ThreadPinCommand,\n ThreadUnpinCommand,\n ThreadPinReorderCommand,\n ThreadMetaUpdateCommand,\n ThreadRuntimeModeSetCommand,\n ThreadInteractionModeSetCommand,\n ClientThreadTurnStartCommand,\n ThreadTurnInterruptCommand,\n ThreadApprovalRespondCommand,\n ThreadUserInputRespondCommand,\n ThreadCheckpointRevertCommand,\n ThreadSessionStopCommand,\n]);\nexport type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;\n\nconst ThreadSessionSetCommand = Schema.Struct({\n type: Schema.Literal(\"thread.session.set\"),\n commandId: CommandId,\n threadId: ThreadId,\n session: OrchestrationSession,\n createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantDeltaCommand = Schema.Struct({\n type: Schema.Literal(\"thread.message.assistant.delta\"),\n commandId: CommandId,\n threadId: ThreadId,\n messageId: MessageId,\n delta: Schema.String,\n turnId: Schema.optional(TurnId),\n createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantCompleteCommand = Schema.Struct({\n type: Schema.Literal(\"thread.message.assistant.complete\"),\n commandId: CommandId,\n threadId: ThreadId,\n messageId: MessageId,\n turnId: Schema.optional(TurnId),\n createdAt: IsoDateTime,\n});\n\nconst ThreadProposedPlanUpsertCommand = Schema.Struct({\n type: Schema.Literal(\"thread.proposed-plan.upsert\"),\n commandId: CommandId,\n threadId: ThreadId,\n proposedPlan: OrchestrationProposedPlan,\n createdAt: IsoDateTime,\n});\n\nconst ThreadTurnDiffCompleteCommand = Schema.Struct({\n type: Schema.Literal(\"thread.turn.diff.complete\"),\n commandId: CommandId,\n threadId: ThreadId,\n turnId: TurnId,\n completedAt: IsoDateTime,\n checkpointRef: CheckpointRef,\n status: OrchestrationCheckpointStatus,\n files: Schema.Array(OrchestrationCheckpointFile),\n assistantMessageId: Schema.optional(MessageId),\n checkpointTurnCount: NonNegativeInt,\n createdAt: IsoDateTime,\n});\n\nconst ThreadActivityAppendCommand = Schema.Struct({\n type: Schema.Literal(\"thread.activity.append\"),\n commandId: CommandId,\n threadId: ThreadId,\n activity: OrchestrationThreadActivity,\n createdAt: IsoDateTime,\n});\n\nconst ThreadRevertCompleteCommand = Schema.Struct({\n type: Schema.Literal(\"thread.revert.complete\"),\n commandId: CommandId,\n threadId: ThreadId,\n turnCount: NonNegativeInt,\n createdAt: IsoDateTime,\n});\n\nconst ThreadTitleRegenerationCompleteCommand = Schema.Struct({\n type: Schema.Literal(\"thread.title.regeneration.complete\"),\n commandId: CommandId,\n threadId: ThreadId,\n requestId: CommandId,\n title: Schema.optional(TrimmedNonEmptyString),\n});\n\nconst InternalOrchestrationCommand = Schema.Union([\n ThreadSessionSetCommand,\n ThreadMessageAssistantDeltaCommand,\n ThreadMessageAssistantCompleteCommand,\n ThreadProposedPlanUpsertCommand,\n ThreadTurnDiffCompleteCommand,\n ThreadActivityAppendCommand,\n ThreadRevertCompleteCommand,\n ThreadTitleRegenerationCompleteCommand,\n]);\nexport type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;\n\nexport const OrchestrationCommand = Schema.Union([\n DispatchableClientOrchestrationCommand,\n InternalOrchestrationCommand,\n]);\nexport type OrchestrationCommand = typeof OrchestrationCommand.Type;",
+ "checksum": "318896f2aa24bd67ad6b1e40f4fd3b7ac6b7f29240f9290046af5135c8048721"
+ },
+ "normalizer-staging-boundary": {
+ "id": "normalizer-staging-boundary",
+ "path": "apps/server/src/orchestration/Normalizer.ts",
+ "start": 18,
+ "end": 179,
+ "language": "typescript",
+ "label": "Pre-transaction timestamp, workspace, and attachment staging",
+ "code": "export const canonicalizeClientCommandTimestamps = (\n command: ClientOrchestrationCommand,\n receivedAt: IsoDateTime,\n): ClientOrchestrationCommand => {\n const canonicalCommand =\n \"createdAt\" in command\n ? {\n ...command,\n createdAt: receivedAt,\n }\n : command;\n\n if (canonicalCommand.type !== \"thread.turn.start\" || !canonicalCommand.bootstrap?.createThread) {\n return canonicalCommand;\n }\n\n return {\n ...canonicalCommand,\n bootstrap: {\n ...canonicalCommand.bootstrap,\n createThread: {\n ...canonicalCommand.bootstrap.createThread,\n createdAt: receivedAt,\n },\n },\n };\n};\n\nexport const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>\n Effect.gen(function* () {\n const receivedAt = DateTime.formatIso(yield* DateTime.now);\n const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const serverConfig = yield* ServerConfig;\n const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n\n const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>\n workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(\n Effect.mapError(\n (cause) =>\n new OrchestrationDispatchCommandError({\n message: cause.message,\n }),\n ),\n );\n\n const normalizeProjectWorkspaceRootForCreate = (\n workspaceRoot: string,\n createIfMissing: boolean | undefined,\n ) =>\n workspacePaths\n .normalizeWorkspaceRoot(workspaceRoot, {\n createIfMissing: createIfMissing === true,\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new OrchestrationDispatchCommandError({\n message: cause.message,\n }),\n ),\n );\n\n if (canonicalCommand.type === \"project.create\") {\n return {\n ...canonicalCommand,\n workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(\n canonicalCommand.workspaceRoot,\n canonicalCommand.createWorkspaceRootIfMissing,\n ),\n createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,\n } satisfies OrchestrationCommand;\n }\n\n if (\n canonicalCommand.type === \"project.meta.update\" &&\n canonicalCommand.workspaceRoot !== undefined\n ) {\n return {\n ...canonicalCommand,\n workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),\n } satisfies OrchestrationCommand;\n }\n\n if (canonicalCommand.type !== \"thread.turn.start\") {\n return canonicalCommand as OrchestrationCommand;\n }\n\n const normalizedAttachments = yield* Effect.forEach(\n canonicalCommand.message.attachments,\n (attachment) =>\n Effect.gen(function* () {\n const parsed = parseBase64DataUrl(attachment.dataUrl);\n if (!parsed || !parsed.mimeType.startsWith(\"image/\")) {\n return yield* new OrchestrationDispatchCommandError({\n message: `Invalid image attachment payload for '${attachment.name}'.`,\n });\n }\n\n const bytes = Buffer.from(parsed.base64, \"base64\");\n if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {\n return yield* new OrchestrationDispatchCommandError({\n message: `Image attachment '${attachment.name}' is empty or too large.`,\n });\n }\n\n const attachmentId = createAttachmentId(canonicalCommand.threadId);\n if (!attachmentId) {\n return yield* new OrchestrationDispatchCommandError({\n message: \"Failed to create a safe attachment id.\",\n });\n }\n\n const persistedAttachment = {\n type: \"image\" as const,\n id: attachmentId,\n name: attachment.name,\n mimeType: parsed.mimeType.toLowerCase(),\n sizeBytes: bytes.byteLength,\n };\n\n const attachmentPath = resolveAttachmentPath({\n attachmentsDir: serverConfig.attachmentsDir,\n attachment: persistedAttachment,\n });\n if (!attachmentPath) {\n return yield* new OrchestrationDispatchCommandError({\n message: `Failed to resolve persisted path for '${attachment.name}'.`,\n });\n }\n\n yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(\n Effect.mapError(\n () =>\n new OrchestrationDispatchCommandError({\n message: `Failed to create attachment directory for '${attachment.name}'.`,\n }),\n ),\n );\n yield* fileSystem.writeFile(attachmentPath, bytes).pipe(\n Effect.mapError(\n () =>\n new OrchestrationDispatchCommandError({\n message: `Failed to persist attachment '${attachment.name}'.`,\n }),\n ),\n );\n\n return persistedAttachment;\n }),\n { concurrency: 1 },\n );\n\n return {\n ...canonicalCommand,\n message: {\n ...canonicalCommand.message,\n attachments: normalizedAttachments,\n },\n } satisfies OrchestrationCommand;\n });",
+ "checksum": "a6b4f3d074784de7397eed20ee1bfb7fa2de4eca5f62c5443b1962f1cdb5d6db"
+ },
+ "turn-atomic-batch": {
+ "id": "turn-atomic-batch",
+ "path": "apps/server/src/orchestration/decider.ts",
+ "start": 926,
+ "end": 1036,
+ "language": "typescript",
+ "label": "Existing-thread turn plans a two-to-four-event batch",
+ "code": " case \"thread.turn.start\": {\n const targetThread = yield* requireThread({\n readModel,\n command,\n threadId: command.threadId,\n });\n const sourceProposedPlan = command.sourceProposedPlan;\n const sourceThread = sourceProposedPlan\n ? yield* requireThread({\n readModel,\n command,\n threadId: sourceProposedPlan.threadId,\n })\n : null;\n const sourcePlan =\n sourceProposedPlan && sourceThread\n ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)\n : null;\n if (sourceProposedPlan && !sourcePlan) {\n return yield* new OrchestrationCommandInvariantError({\n commandType: command.type,\n detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,\n });\n }\n if (sourceThread && sourceThread.projectId !== targetThread.projectId) {\n return yield* new OrchestrationCommandInvariantError({\n commandType: command.type,\n detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,\n });\n }\n const userMessageEvent: Omit = {\n ...(yield* withEventBase({\n aggregateKind: \"thread\",\n aggregateId: command.threadId,\n occurredAt: command.createdAt,\n commandId: command.commandId,\n })),\n type: \"thread.message-sent\",\n payload: {\n threadId: command.threadId,\n messageId: command.message.messageId,\n role: \"user\",\n text: command.message.text,\n attachments: command.message.attachments,\n turnId: null,\n streaming: false,\n createdAt: command.createdAt,\n updatedAt: command.createdAt,\n },\n };\n const turnStartRequestedEvent: Omit = {\n ...(yield* withEventBase({\n aggregateKind: \"thread\",\n aggregateId: command.threadId,\n occurredAt: command.createdAt,\n commandId: command.commandId,\n })),\n causationEventId: userMessageEvent.eventId,\n type: \"thread.turn-start-requested\",\n payload: {\n threadId: command.threadId,\n messageId: command.message.messageId,\n ...(command.modelSelection !== undefined\n ? { modelSelection: command.modelSelection }\n : {}),\n ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),\n runtimeMode: targetThread.runtimeMode,\n interactionMode: targetThread.interactionMode,\n ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),\n createdAt: command.createdAt,\n },\n };\n // Real activity resets ANY override: it wakes an explicitly settled\n // thread, and it clears a keep-active pin back to neutral so the\n // thread can auto-settle again after this burst of work goes stale.\n // A snooze clears the same way — sending a message to a snoozed\n // thread is the user re-engaging, so the return ticket is spent.\n const lifecycleResetEvents: Array> = [];\n if (targetThread.settledOverride !== null) {\n lifecycleResetEvents.push({\n ...(yield* withEventBase({\n aggregateKind: \"thread\",\n aggregateId: command.threadId,\n occurredAt: command.createdAt,\n commandId: command.commandId,\n })),\n type: \"thread.unsettled\",\n payload: {\n threadId: command.threadId,\n reason: \"activity\",\n updatedAt: command.createdAt,\n },\n });\n }\n if (targetThread.snoozedUntil != null) {\n lifecycleResetEvents.push({\n ...(yield* withEventBase({\n aggregateKind: \"thread\",\n aggregateId: command.threadId,\n occurredAt: command.createdAt,\n commandId: command.commandId,\n })),\n type: \"thread.unsnoozed\",\n payload: {\n threadId: command.threadId,\n reason: \"activity\",\n updatedAt: command.createdAt,\n },\n });\n }\n return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];",
+ "checksum": "0d0fe115f9ae7b07e903de3cca6dfd815044b54aa8a56b75417acb4a17410c4d"
+ },
+ "engine-commit-publication": {
+ "id": "engine-commit-publication",
+ "path": "apps/server/src/orchestration/Layers/OrchestrationEngine.ts",
+ "start": 197,
+ "end": 259,
+ "language": "typescript",
+ "label": "SQL commit followed by in-memory fold and hot publication",
+ "code": " const committedCommand = yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const committedEvents: OrchestrationEvent[] = [];\n let nextCommandReadModel = commandReadModel;\n\n for (const nextEvent of eventBases) {\n const savedEvent = yield* eventStore.append(nextEvent);\n nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);\n yield* projectionPipeline.projectEvent(savedEvent);\n committedEvents.push(savedEvent);\n }\n\n const lastSavedEvent = committedEvents.at(-1) ?? null;\n if (lastSavedEvent === null) {\n return yield* new OrchestrationCommandInvariantError({\n commandType: envelope.command.type,\n detail: \"Command produced no events.\",\n });\n }\n\n yield* commandReceiptRepository.upsert({\n commandId: envelope.command.commandId,\n aggregateKind: lastSavedEvent.aggregateKind,\n aggregateId: lastSavedEvent.aggregateId,\n acceptedAt: lastSavedEvent.occurredAt,\n resultSequence: lastSavedEvent.sequence,\n status: \"accepted\",\n error: null,\n });\n\n return {\n committedEvents,\n lastSequence: lastSavedEvent.sequence,\n nextCommandReadModel,\n } as const;\n }),\n )\n .pipe(\n Effect.catchTag(\"SqlError\", (sqlError) =>\n Effect.fail(\n toPersistenceSqlError(\"OrchestrationEngine.processEnvelope:transaction\")(sqlError),\n ),\n ),\n );\n\n commandReadModel = committedCommand.nextCommandReadModel;\n for (const [index, event] of committedCommand.committedEvents.entries()) {\n yield* PubSub.publish(eventPubSub, event);\n if (index === 0) {\n yield* Metric.update(\n Metric.withAttributes(\n orchestrationCommandAckDuration,\n metricAttributes({\n ...baseMetricAttributes,\n ackEventType: event.type,\n }),\n ),\n Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),\n );\n }\n }\n return { sequence: committedCommand.lastSequence };",
+ "checksum": "24e00da0c432e501172e3847817fde311d8656b07e3b8261c657ecf6b4c35d4c"
+ },
+ "command-receipt-schema": {
+ "id": "command-receipt-schema",
+ "path": "apps/server/src/persistence/Services/OrchestrationCommandReceipts.ts",
+ "start": 25,
+ "end": 33,
+ "language": "typescript",
+ "label": "Durable command receipt fields",
+ "code": "export const OrchestrationCommandReceipt = Schema.Struct({\n commandId: CommandId,\n aggregateKind: OrchestrationAggregateKind,\n aggregateId: Schema.Union([ProjectId, ThreadId]),\n acceptedAt: IsoDateTime,\n resultSequence: NonNegativeInt,\n status: OrchestrationCommandReceiptStatus,\n error: Schema.NullOr(Schema.String),\n});",
+ "checksum": "264f74e9b17b136921f154402d8dc87dd27cb86328043769f9293f1d8a8b451b"
+ },
+ "projection-transaction-cursor": {
+ "id": "projection-transaction-cursor",
+ "path": "apps/server/src/orchestration/Layers/ProjectionPipeline.ts",
+ "start": 1609,
+ "end": 1678,
+ "language": "typescript",
+ "label": "Ordered projectors, transactional cursor updates, and attachment side effects",
+ "code": " const projectors: ReadonlyArray = [\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.projects,\n apply: applyProjectsProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n apply: applyThreadMessagesProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n apply: applyThreadProposedPlansProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n apply: applyThreadActivitiesProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n apply: applyThreadSessionsProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,\n apply: applyThreadTurnsProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n apply: applyCheckpointsProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,\n apply: applyPendingApprovalsProjection,\n },\n {\n name: ORCHESTRATION_PROJECTOR_NAMES.threads,\n apply: applyThreadsProjection,\n },\n ];\n\n const runProjectorForEvent = Effect.fn(\"runProjectorForEvent\")(function* (\n projector: ProjectorDefinition,\n event: OrchestrationEvent,\n ) {\n const attachmentSideEffects: AttachmentSideEffects = {\n deletedThreadIds: new Set(),\n prunedThreadRelativePaths: new Map>(),\n };\n\n yield* sql.withTransaction(\n projector.apply(event, attachmentSideEffects).pipe(\n Effect.flatMap(() =>\n projectionStateRepository.upsert({\n projector: projector.name,\n lastAppliedSequence: event.sequence,\n updatedAt: event.occurredAt,\n }),\n ),\n ),\n );\n\n yield* runAttachmentSideEffects(attachmentSideEffects).pipe(\n Effect.catch((cause) =>\n Effect.logWarning(\"failed to apply projected attachment side-effects\", {\n projector: projector.name,\n sequence: event.sequence,\n eventType: event.type,\n cause,\n }),\n ),\n );",
+ "checksum": "ec226c4bd720884378ba5cb08e9527043641bfaac002455052b75f36ee02daa0"
+ },
+ "snapshot-safe-watermark": {
+ "id": "snapshot-safe-watermark",
+ "path": "apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts",
+ "start": 195,
+ "end": 258,
+ "language": "typescript",
+ "label": "Snapshot watermark is the minimum required projector cursor",
+ "code": "const REQUIRED_SNAPSHOT_PROJECTORS = [\n ORCHESTRATION_PROJECTOR_NAMES.projects,\n ORCHESTRATION_PROJECTOR_NAMES.threads,\n ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n] as const;\n\nfunction maxIso(left: string | null, right: string): string {\n if (left === null) {\n return right;\n }\n return left > right ? left : right;\n}\n\nfunction escapeLikePattern(value: string): string {\n return value.replaceAll(\"!\", \"!!\").replaceAll(\"%\", \"!%\").replaceAll(\"_\", \"!_\");\n}\n\nfunction foldAsciiCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\nfunction buildSearchSnippet(text: string, query: string): string {\n const normalizedText = text.replace(/\\s+/g, \" \").trim();\n if (normalizedText.length <= 240) {\n return normalizedText;\n }\n\n const normalizedQuery = foldAsciiCase(query.replace(/\\s+/g, \" \").trim());\n const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);\n const bodyLength = 236;\n const idealStart = Math.max(0, matchIndex - 72);\n const start = Math.min(idealStart, normalizedText.length - bodyLength);\n const end = Math.min(normalizedText.length, start + bodyLength);\n return `${start > 0 ? \"…\" : \"\"}${normalizedText.slice(start, end)}${\n end < normalizedText.length ? \"…\" : \"\"\n }`;\n}\n\nfunction computeSnapshotSequence(\n stateRows: ReadonlyArray>,\n): number {\n if (stateRows.length === 0) {\n return 0;\n }\n const sequenceByProjector = new Map(\n stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const),\n );\n\n let minSequence = Number.POSITIVE_INFINITY;\n for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) {\n const sequence = sequenceByProjector.get(projector);\n if (sequence === undefined) {\n return 0;\n }\n if (sequence < minSequence) {\n minSequence = sequence;\n }\n }\n\n return Number.isFinite(minSequence) ? minSequence : 0;",
+ "checksum": "1e59d916d6fd2d68ce72a50afe86973454487d7b5b81d8215e632767ef82f3a4"
+ },
+ "provider-reactor-forked-send": {
+ "id": "provider-reactor-forked-send",
+ "path": "apps/server/src/orchestration/Layers/ProviderCommandReactor.ts",
+ "start": 1060,
+ "end": 1174,
+ "language": "typescript",
+ "label": "Volatile turn dedupe and forked provider send",
+ "code": " const processTurnStartRequested = Effect.fn(\"processTurnStartRequested\")(function* (\n event: Extract,\n ) {\n const key = turnStartKeyForEvent(event);\n if (yield* hasHandledTurnStartRecently(key)) {\n return;\n }\n\n const thread = yield* resolveThread(event.payload.threadId);\n if (!thread) {\n return;\n }\n\n const message = thread.messages.find((entry) => entry.id === event.payload.messageId);\n if (!message || message.role !== \"user\") {\n yield* appendProviderFailureActivity({\n threadId: event.payload.threadId,\n kind: \"provider.turn.start.failed\",\n summary: \"Provider turn start failed\",\n detail: `User message '${event.payload.messageId}' was not found for turn start request.`,\n turnId: null,\n createdAt: event.payload.createdAt,\n });\n return;\n }\n\n const isFirstUserMessageTurn =\n thread.messages.filter((entry) => entry.role === \"user\").length === 1;\n if (isFirstUserMessageTurn) {\n const project = yield* resolveProject(thread.projectId);\n const generationCwd =\n resolveThreadWorkspaceCwd({\n thread,\n projects: project ? [project] : [],\n }) ?? process.cwd();\n const generationInput = {\n messageText: message.text,\n ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),\n };\n\n yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({\n threadId: event.payload.threadId,\n branch: thread.branch,\n worktreePath: thread.worktreePath,\n ...generationInput,\n }).pipe(Effect.forkScoped);\n\n if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {\n yield* maybeGenerateThreadTitleForFirstTurn({\n threadId: event.payload.threadId,\n cwd: generationCwd,\n ...generationInput,\n }).pipe(Effect.forkScoped);\n }\n }\n\n const handleTurnStartFailure = (cause: Cause.Cause) => {\n if (Cause.hasInterruptsOnly(cause)) {\n return Effect.void;\n }\n const detail = formatFailureDetail(cause);\n return setThreadSessionErrorOnTurnStartFailure({\n threadId: event.payload.threadId,\n detail,\n createdAt: event.payload.createdAt,\n }).pipe(\n Effect.flatMap(() =>\n appendProviderFailureActivity({\n threadId: event.payload.threadId,\n kind: \"provider.turn.start.failed\",\n summary: \"Provider turn start failed\",\n detail,\n turnId: null,\n createdAt: event.payload.createdAt,\n }),\n ),\n Effect.asVoid,\n );\n };\n\n const recoverTurnStartFailure = (cause: Cause.Cause) =>\n handleTurnStartFailure(cause).pipe(\n Effect.catchCause((recoveryCause) =>\n Effect.logWarning(\"provider command reactor failed to recover turn start failure\", {\n eventType: event.type,\n threadId: event.payload.threadId,\n cause: Cause.pretty(recoveryCause),\n originalCause: Cause.pretty(cause),\n }),\n ),\n );\n\n const sendTurnRequest = yield* buildSendTurnRequestForThread({\n threadId: event.payload.threadId,\n messageText: message.text,\n ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n ...(event.payload.modelSelection !== undefined\n ? { modelSelection: event.payload.modelSelection }\n : {}),\n interactionMode: event.payload.interactionMode,\n createdAt: event.payload.createdAt,\n }).pipe(\n Effect.map(Option.some),\n Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),\n );\n\n if (Option.isNone(sendTurnRequest)) {\n return;\n }\n\n yield* providerService\n .sendTurn(sendTurnRequest.value)\n .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);\n });",
+ "checksum": "e612e2a0295ab2afbf9d9b7a9d4c7da0578c4adf5b052b24892d929ec9995f00"
+ },
+ "sqlite-runtime-pragmas": {
+ "id": "sqlite-runtime-pragmas",
+ "path": "apps/server/src/persistence/Layers/Sqlite.ts",
+ "start": 24,
+ "end": 66,
+ "language": "typescript",
+ "label": "SQLite runtime selection, pragmas, migrations, and scoped layers",
+ "code": "const makeRuntimeSqliteLayer = Effect.fn(\"makeRuntimeSqliteLayer\")(function* (\n config: RuntimeSqliteLayerConfig,\n) {\n const runtime = process.versions.bun !== undefined ? \"bun\" : \"node\";\n const loader = defaultSqliteClientLoaders[runtime];\n const clientModule = yield* Effect.promise(loader);\n return clientModule.layer(config);\n}, Layer.unwrap);\n\nconst setup = Layer.effectDiscard(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n // CLI and server write from separate processes; wait rather than fail with SQLITE_BUSY.\n yield* sql`PRAGMA busy_timeout = 5000;`;\n yield* sql`PRAGMA foreign_keys = ON;`;\n yield* sql`PRAGMA journal_mode = WAL;`;\n yield* runMigrations();\n }),\n);\n\nexport const makeSqlitePersistenceLive = Effect.fn(\"makeSqlitePersistenceLive\")(function* (\n dbPath: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });\n\n return Layer.provideMerge(\n setup,\n makeRuntimeSqliteLayer({\n filename: dbPath,\n spanAttributes: {\n \"db.name\": path.basename(dbPath),\n \"service.name\": \"t3-server\",\n },\n }),\n );\n}, Layer.unwrap);\n\nexport const SqlitePersistenceMemory = Layer.provideMerge(\n setup,\n makeRuntimeSqliteLayer({ filename: \":memory:\" }),\n);",
+ "checksum": "82fedbba97c179c80bcbcc9e8ae8dc674681b57716267f1b03717e76fcaa5ee3"
+ },
+ "provider-instance-identity-contract": {
+ "id": "provider-instance-identity-contract",
+ "path": "packages/contracts/src/providerInstance.ts",
+ "start": 4,
+ "end": 32,
+ "language": "typescript",
+ "label": "Driver kind and configured instance identity",
+ "code": " * Splits the historical \"provider kind\" concept into two:\n *\n * - `ProviderDriverKind` is the implementation kind selector (e.g. codex,\n * claudeAgent, a fork's `ollama`, …). It picks which driver package\n * handles the protocol, the probe, the adapter, and text generation.\n *\n * - `ProviderInstanceId` is the routing key (a user-defined slug).\n * Threads, sessions, runtime events, and persisted bindings reference\n * instance ids — never driver kinds — so a user can configure multiple\n * instances of the same driver (e.g. `codex_personal` + `codex_work`),\n * each with independent driver-specific configuration.\n *\n * Forward/backward compatibility invariant\n * ----------------------------------------\n * `ProviderDriverKind` is intentionally an **open** branded slug, not a closed\n * literal union. The server hosts forks, ships in PRs that add drivers, and\n * users frequently roll between branches and forks. Any of those paths can\n * leave `ServerSettings`, persisted thread state, or session bindings\n * referencing a driver that the currently-running build does not know about.\n *\n * The rule: parsing any of those payloads must always succeed, and the\n * runtime is responsible for marking the unknown driver/instance as\n * \"unavailable\" rather than crashing. Built-in drivers shipped by the core\n * product happens to register in a given build is not part of the contract\n * layer. Driver availability is discovered through the runtime registry.\n *\n * Driver-specific configuration is similarly opaque at the contracts layer:\n * drivers live in (or will be extracted to) their own packages and own their\n * config schemas. The contracts package only knows the envelope.",
+ "checksum": "c407854da6ce483f2fa76dd285ed7e16f5708176e172140e34c28cc8248e9176"
+ },
+ "provider-driver-instance-spi": {
+ "id": "provider-driver-instance-spi",
+ "path": "apps/server/src/provider/ProviderDriver.ts",
+ "start": 55,
+ "end": 117,
+ "language": "typescript",
+ "label": "Scoped provider driver and instance records",
+ "code": "/**\n * One materialized provider instance. Held by the registry, looked up by\n * `instanceId`, torn down by closing the scope it was created in.\n *\n * The three \"shape\" fields are captured closures owned by this instance —\n * stopping one instance cannot affect another, and starting a second\n * instance of the same driver does not reach into the first instance's\n * state.\n */\nexport interface ProviderInstance {\n readonly instanceId: ProviderInstanceId;\n readonly driverKind: ProviderDriverKind;\n readonly continuationIdentity: ProviderContinuationIdentity;\n readonly displayName: string | undefined;\n readonly accentColor?: string | undefined;\n readonly enabled: boolean;\n readonly snapshot: ServerProviderShape;\n readonly adapter: ProviderAdapterShape;\n readonly textGeneration: TextGeneration.TextGeneration[\"Service\"];\n}\n\nexport interface ProviderContinuationIdentity {\n readonly driverKind: ProviderDriverKind;\n readonly continuationKey: string;\n}\n\nexport function defaultProviderContinuationIdentity(input: {\n readonly driverKind: ProviderDriverKind;\n readonly instanceId: ProviderInstanceId;\n}): ProviderContinuationIdentity {\n return {\n driverKind: input.driverKind,\n continuationKey: `${input.driverKind}:instance:${input.instanceId}`,\n };\n}\n\n/**\n * Inputs the registry passes to a driver's `create` function.\n *\n * `config` is the typed payload — already decoded by the registry through\n * `driver.configSchema`. Drivers never decode their own raw envelope.\n */\nexport interface ProviderDriverCreateInput {\n readonly instanceId: ProviderInstanceId;\n readonly displayName: string | undefined;\n readonly accentColor?: string | undefined;\n readonly environment: ProviderInstanceEnvironment;\n readonly enabled: boolean;\n readonly config: Config;\n}\n\n/**\n * Driver SPI — registered as a plain value, not a Layer.\n *\n * `Config` is whatever the driver decoded from\n * `ProviderInstanceConfig.config`. `R` is the union of infrastructure\n * services the driver depends on; the registry layer aggregates `R` across\n * all registered drivers and the runtime supplies them.\n *\n * `create` is responsible for *all* per-instance state — process handles,\n * pubsub topics, refs, file watchers — and must release them when its\n * scope closes. Two calls to `create` with different `instanceId` /\n * `config` MUST yield instances with no shared mutable state.",
+ "checksum": "d6fe18a1ab845da33fc05cb2ef822ef1057706345468a8b485daa76abaa9fce6"
+ },
+ "provider-driver-instance-records": {
+ "id": "provider-driver-instance-records",
+ "path": "apps/server/src/provider/ProviderDriver.ts",
+ "start": 4,
+ "end": 20,
+ "language": "typescript",
+ "label": "Plain provider driver and instance record contracts",
+ "code": " * `ProviderDriver` is a record, not a Context.Service. The thing it produces\n * (`ProviderInstance`) is also a record — three captured closures\n * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There\n * are intentionally no per-driver Context tags because tags are\n * singleton-per-runtime and we need many instances of the same driver.\n *\n * The only Effect service involved is `ProviderInstanceRegistry`, which\n * owns the live `Map` and is itself a\n * singleton.\n *\n * Driver factories are functions of `(typed config, env)` where:\n * - `typed config` is decoded once by the registry via `configSchema`,\n * so drivers never deal with raw `unknown`.\n * - `env` flows through Effect's R channel. Each driver declares the\n * subset of infrastructure services it needs (FileSystem,\n * ChildProcessSpawner, …) on its `create` return type; the registry\n * layer's R is the union of those, and the runtime layer satisfies it.",
+ "checksum": "930d8e1e57ebe1e79b5e332f52c8b90908310361e4c752ca17ed828f405b7d22"
+ },
+ "codex-app-server-client-typed-stdio": {
+ "id": "codex-app-server-client-typed-stdio",
+ "path": "packages/effect-codex-app-server/src/client.ts",
+ "start": 140,
+ "end": 211,
+ "language": "typescript",
+ "label": "Typed Codex notifications, requests, and transport calls",
+ "code": " const dispatchNotification = (\n notification: CodexProtocol.CodexAppServerIncomingNotification,\n ): Effect.Effect => {\n const schema =\n notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS\n ? CodexRpc.SERVER_NOTIFICATION_PARAMS[\n notification.method as CodexRpc.ServerNotificationMethod\n ]\n : undefined;\n const handlers = notificationHandlers.get(notification.method) ?? [];\n\n if (schema) {\n return decodeNotificationPayload(notification.method, schema, notification.params).pipe(\n Effect.flatMap((decoded) =>\n Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),\n ),\n Effect.catch(() => Effect.void),\n );\n }\n\n return unknownNotificationHandler\n ? unknownNotificationHandler(notification.method, notification.params).pipe(\n Effect.catch(() => Effect.void),\n )\n : Effect.void;\n };\n\n const dispatchRequest = (\n request: CodexProtocol.CodexAppServerIncomingRequest,\n ): Effect.Effect => {\n if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {\n const method = request.method as CodexRpc.ServerRequestMethod;\n const payloadSchema = getServerRequestParamSchema(method);\n const responseSchema = getServerRequestResponseSchema(method);\n const handler = requestHandlers.get(method);\n\n return decodeOptionalPayload(method, payloadSchema, request.params).pipe(\n Effect.flatMap((decoded) => runHandler(handler, decoded, method)),\n Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),\n );\n }\n\n return unknownRequestHandler\n ? unknownRequestHandler(request.method, request.params)\n : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));\n };\n\n const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({\n stdio,\n ...(terminationError ? { terminationError } : {}),\n ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),\n ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),\n ...(options.logger ? { logger: options.logger } : {}),\n onNotification: dispatchNotification,\n onRequest: dispatchRequest,\n });\n\n const request = (\n method: M,\n payload: CodexRpc.ClientRequestParamsByMethod[M],\n ): Effect.Effect =>\n encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(\n Effect.flatMap((encoded) => transport.request(method, encoded)),\n Effect.flatMap(\n (\n raw,\n ): Effect.Effect<\n CodexRpc.ClientRequestResponsesByMethod[M],\n CodexError.CodexAppServerError\n > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),\n ),\n );",
+ "checksum": "296b35c49fcafff9f8d6d65ab7403039c19f08f7c8e6f0a9350e22dfc01a1cf1"
+ },
+ "codex-adapter-session-runtime": {
+ "id": "codex-adapter-session-runtime",
+ "path": "apps/server/src/provider/Layers/CodexAdapter.ts",
+ "start": 1642,
+ "end": 1693,
+ "language": "typescript",
+ "label": "Codex session replacement and runtime configuration",
+ "code": " const startSession: CodexAdapterShape[\"startSession\"] = (input) =>\n Effect.scoped(\n Effect.gen(function* () {\n if (input.provider !== undefined && input.provider !== PROVIDER) {\n return yield* new ProviderAdapterValidationError({\n provider: PROVIDER,\n operation: \"startSession\",\n issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n });\n }\n\n const existing = sessions.get(input.threadId);\n if (existing && !existing.stopped) {\n yield* Effect.suspend(() => stopSessionInternal(existing));\n }\n\n const serviceTier =\n input.modelSelection?.instanceId === boundInstanceId\n ? getCodexServiceTierOptionValue(input.modelSelection)\n : undefined;\n const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n const runtimeInput: CodexSessionRuntimeOptions = {\n threadId: input.threadId,\n providerInstanceId: boundInstanceId,\n cwd: input.cwd ?? process.cwd(),\n binaryPath: codexConfig.binaryPath,\n launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),\n ...(options?.environment ? { environment: options.environment } : {}),\n ...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),\n ...(isCodexResumeCursorSchema(input.resumeCursor)\n ? { resumeCursor: input.resumeCursor }\n : {}),\n runtimeMode: input.runtimeMode,\n ...(input.modelSelection?.instanceId === boundInstanceId\n ? { model: input.modelSelection.model }\n : {}),\n ...(serviceTier ? { serviceTier } : {}),\n ...(mcpSession\n ? {\n environment: {\n ...(options?.environment ?? process.env),\n T3_MCP_BEARER_TOKEN: mcpSession.authorizationHeader.replace(/^Bearer\\s+/, \"\"),\n },\n appServerArgs: [\n \"-c\",\n `mcp_servers.t3-code.url=${mcpSession.endpoint}`,\n \"-c\",\n 'mcp_servers.t3-code.bearer_token_env_var=\"T3_MCP_BEARER_TOKEN\"',\n ],\n }\n : {}),\n };",
+ "checksum": "6dd08ac4e760401826162f8d3a0d739b58ed890361c817cb7b726329818dee33"
+ },
+ "codex-adapter-runtime-events": {
+ "id": "codex-adapter-runtime-events",
+ "path": "apps/server/src/provider/Layers/CodexAdapter.ts",
+ "start": 1000,
+ "end": 1084,
+ "language": "typescript",
+ "label": "Codex usage, turn, and plan event normalization",
+ "code": " if (event.method === \"thread/tokenUsage/updated\") {\n const payload = readPayload(\n EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,\n event.payload,\n );\n const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;\n if (!normalizedUsage) {\n return [];\n }\n return [\n {\n type: \"thread.token-usage.updated\",\n ...runtimeEventBase(event, canonicalThreadId),\n payload: {\n usage: normalizedUsage,\n },\n },\n ];\n }\n\n if (event.method === \"turn/started\") {\n const turnId = event.turnId;\n if (!turnId) {\n return [];\n }\n return [\n {\n ...runtimeEventBase(event, canonicalThreadId),\n turnId,\n type: \"turn.started\",\n payload: {},\n },\n ];\n }\n\n if (event.method === \"turn/completed\") {\n const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, event.payload);\n if (!payload) {\n return [];\n }\n const errorMessage = trimText(payload.turn.error?.message);\n return [\n {\n ...runtimeEventBase(event, canonicalThreadId),\n type: \"turn.completed\",\n payload: {\n state: toTurnStatus(payload.turn.status),\n ...(errorMessage ? { errorMessage } : {}),\n },\n },\n ];\n }\n\n if (event.method === \"turn/aborted\") {\n return [\n {\n ...runtimeEventBase(event, canonicalThreadId),\n type: \"turn.aborted\",\n payload: {\n reason: event.message ?? \"Turn aborted\",\n },\n },\n ];\n }\n\n if (event.method === \"turn/plan/updated\") {\n const payload = readPayload(EffectCodexSchema.V2TurnPlanUpdatedNotification, event.payload);\n if (!payload) {\n return [];\n }\n return [\n {\n ...runtimeEventBase(event, canonicalThreadId),\n type: \"turn.plan.updated\",\n payload: {\n ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}),\n plan: payload.plan.map((step) => ({\n step: trimText(step.step) ?? \"step\",\n status:\n step.status === \"completed\" || step.status === \"inProgress\" ? step.status : \"pending\",\n })),\n },\n },\n ];\n }",
+ "checksum": "4b82fdd81df8d8a061c9f7f0b036c32d5f5bf061f9511189548f386a038f4d9f"
+ },
+ "claude-adapter-query-config": {
+ "id": "claude-adapter-query-config",
+ "path": "apps/server/src/provider/Layers/ClaudeAdapter.ts",
+ "start": 4138,
+ "end": 4196,
+ "language": "typescript",
+ "label": "Claude permission mapping and query option assembly",
+ "code": " const runtimeModeToPermission: Record = {\n \"auto-accept-edits\": \"acceptEdits\",\n auto: \"auto\",\n \"full-access\": \"bypassPermissions\",\n };\n const permissionMode = runtimeModeToPermission[input.runtimeMode];\n const settings = {\n ...(typeof thinking === \"boolean\" ? { alwaysThinkingEnabled: thinking } : {}),\n ...(fastMode ? { fastMode: true } : {}),\n ...(ultracode ? { ultracode: true } : {}),\n };\n const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n // The attachments dir grant lets the agent Read/copy pasted images at\n // the paths ProviderService injects into the turn text, without an\n // approval prompt. It is a leaf directory holding only attachment\n // files; siblings like secrets/ and state.sqlite stay ungranted.\n const additionalDirectories = [\n ...(input.cwd ? [input.cwd] : []),\n serverConfig.attachmentsDir,\n ];\n const queryOptions: ClaudeQueryOptions = {\n ...(input.cwd ? { cwd: input.cwd } : {}),\n ...(apiModelId ? { model: apiModelId } : {}),\n pathToClaudeCodeExecutable: claudeBinaryPath,\n systemPrompt: { type: \"preset\", preset: \"claude_code\" },\n settingSources: [...CLAUDE_SETTING_SOURCES],\n // `ultracode` is a Claude Code setting, not an API effort level. It is\n // normalized to `xhigh` above and paired with `settings.ultracode`.\n ...(effectiveEffort\n ? {\n effort: effectiveEffort as unknown as NonNullable,\n }\n : {}),\n ...(permissionMode ? { permissionMode } : {}),\n ...(permissionMode === \"bypassPermissions\"\n ? { allowDangerouslySkipPermissions: true }\n : {}),\n ...(Object.keys(settings).length > 0 ? { settings } : {}),\n ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),\n ...(newSessionId ? { sessionId: newSessionId } : {}),\n includePartialMessages: true,\n canUseTool,\n env: claudeEnvironment,\n additionalDirectories,\n ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),\n ...(mcpSession\n ? {\n mcpServers: {\n \"t3-code\": {\n type: \"http\",\n url: mcpSession.endpoint,\n headers: {\n Authorization: mcpSession.authorizationHeader,\n },\n },\n },\n }\n : {}),\n };",
+ "checksum": "0b8c0d482fc624fb131e748d735394497afa9d437867ad9c1bee9f2f2119de08"
+ },
+ "claude-query-invocation": {
+ "id": "claude-query-invocation",
+ "path": "apps/server/src/provider/Layers/ClaudeAdapter.ts",
+ "start": 4223,
+ "end": 4235,
+ "language": "typescript",
+ "label": "Claude SDK query invocation",
+ "code": " const queryRuntime = yield* Effect.try({\n try: () =>\n createQuery({\n prompt,\n options: queryOptions,\n }),\n catch: (cause) =>\n new ProviderAdapterProcessError({\n provider: PROVIDER,\n threadId,\n detail: \"Failed to start Claude runtime session.\",\n cause,\n }),",
+ "checksum": "293fa0c20180cf51eb8c621ce2d48809cb91db55d182270896f857d245b8a7a1"
+ },
+ "claude-adapter-interaction-handlers": {
+ "id": "claude-adapter-interaction-handlers",
+ "path": "apps/server/src/provider/Layers/ClaudeAdapter.ts",
+ "start": 4497,
+ "end": 4529,
+ "language": "typescript",
+ "label": "Claude approval and structured-input deferreds",
+ "code": " const respondToRequest: ClaudeAdapterShape[\"respondToRequest\"] = Effect.fn(\"respondToRequest\")(\n function* (threadId, requestId, decision) {\n const context = yield* requireSession(threadId);\n const pending = context.pendingApprovals.get(requestId);\n if (!pending) {\n return yield* new ProviderAdapterRequestError({\n provider: PROVIDER,\n method: \"item/requestApproval/decision\",\n detail: `Unknown pending approval request: ${requestId}`,\n });\n }\n\n context.pendingApprovals.delete(requestId);\n yield* Deferred.succeed(pending.decision, decision);\n },\n );\n\n const respondToUserInput: ClaudeAdapterShape[\"respondToUserInput\"] = Effect.fn(\n \"respondToUserInput\",\n )(function* (threadId, requestId, answers) {\n const context = yield* requireSession(threadId);\n const pending = context.pendingUserInputs.get(requestId);\n if (!pending) {\n return yield* new ProviderAdapterRequestError({\n provider: PROVIDER,\n method: \"item/tool/respondToUserInput\",\n detail: `Unknown pending user-input request: ${requestId}`,\n });\n }\n\n context.pendingUserInputs.delete(requestId);\n yield* Deferred.succeed(pending.answers, answers);\n });",
+ "checksum": "e41de225714771b18fce1f2bcaff53bc79bfff542df321078c5ab4d1ff8086d2"
+ },
+ "acp-client-typed-surface": {
+ "id": "acp-client-typed-surface",
+ "path": "packages/effect-acp/src/client.ts",
+ "start": 40,
+ "end": 134,
+ "language": "typescript",
+ "label": "Typed ACP session command surface",
+ "code": " {\n readonly raw: AcpClientRaw;\n readonly agent: {\n /**\n * Initializes the ACP session and negotiates capabilities.\n * @see https://agentclientprotocol.com/protocol/schema#initialize\n */\n readonly initialize: (\n payload: AcpSchema.InitializeRequest,\n ) => Effect.Effect;\n /**\n * Performs ACP authentication when the agent requires it.\n * @see https://agentclientprotocol.com/protocol/schema#authenticate\n */\n readonly authenticate: (\n payload: AcpSchema.AuthenticateRequest,\n ) => Effect.Effect;\n /**\n * Logs out the current ACP identity.\n * @see https://agentclientprotocol.com/protocol/schema#logout\n */\n readonly logout: (\n payload: AcpSchema.LogoutRequest,\n ) => Effect.Effect;\n /**\n * Starts a new ACP session.\n * @see https://agentclientprotocol.com/protocol/schema#session/new\n */\n readonly createSession: (\n payload: AcpSchema.NewSessionRequest,\n ) => Effect.Effect;\n /**\n * Loads a previously saved ACP session.\n * @see https://agentclientprotocol.com/protocol/schema#session/load\n */\n readonly loadSession: (\n payload: AcpSchema.LoadSessionRequest,\n ) => Effect.Effect;\n /**\n * Lists available ACP sessions.\n * @see https://agentclientprotocol.com/protocol/schema#session/list\n */\n readonly listSessions: (\n payload: AcpSchema.ListSessionsRequest,\n ) => Effect.Effect;\n /**\n * Forks an ACP session.\n * @see https://agentclientprotocol.com/protocol/schema#session/fork\n */\n readonly forkSession: (\n payload: AcpSchema.ForkSessionRequest,\n ) => Effect.Effect;\n /**\n * Resumes an ACP session.\n * @see https://agentclientprotocol.com/protocol/schema#session/resume\n */\n readonly resumeSession: (\n payload: AcpSchema.ResumeSessionRequest,\n ) => Effect.Effect;\n /**\n * Closes an ACP session.\n * @see https://agentclientprotocol.com/protocol/schema#session/close\n */\n readonly closeSession: (\n payload: AcpSchema.CloseSessionRequest,\n ) => Effect.Effect;\n /**\n * Selects the active model for a session.\n * @see https://agentclientprotocol.com/protocol/schema#session/set_model\n */\n readonly setSessionModel: (\n payload: AcpSchema.SetSessionModelRequest,\n ) => Effect.Effect;\n /**\n * Updates a session configuration option.\n * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n */\n readonly setSessionConfigOption: (\n payload: AcpSchema.SetSessionConfigOptionRequest,\n ) => Effect.Effect;\n /**\n * Sends a prompt turn to the agent.\n * @see https://agentclientprotocol.com/protocol/schema#session/prompt\n */\n readonly prompt: (\n payload: AcpSchema.PromptRequest,\n ) => Effect.Effect;\n /**\n * Sends a real ACP `session/cancel` notification.\n * @see https://agentclientprotocol.com/protocol/schema#session/cancel\n */\n readonly cancel: (\n payload: AcpSchema.CancelNotification,\n ) => Effect.Effect;\n };",
+ "checksum": "7df29bfbf9bbea09d570a845e6123253b3cee19ee9af1f4837fbf6d050040856"
+ },
+ "cursor-session-mode-selection": {
+ "id": "cursor-session-mode-selection",
+ "path": "apps/server/src/provider/Layers/CursorAdapter.ts",
+ "start": 217,
+ "end": 294,
+ "language": "typescript",
+ "label": "Cursor negotiated mode and model selection",
+ "code": "function resolveRequestedModeId(input: {\n readonly interactionMode: ProviderInteractionMode | undefined;\n readonly runtimeMode: RuntimeMode;\n readonly modeState: AcpSessionModeState | undefined;\n}): string | undefined {\n const modeState = input.modeState;\n if (!modeState) {\n return undefined;\n }\n\n if (input.interactionMode === \"plan\") {\n return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;\n }\n\n if (input.runtimeMode === \"approval-required\") {\n return (\n findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??\n findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??\n modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??\n modeState.currentModeId\n );\n }\n\n return (\n findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??\n findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??\n modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??\n modeState.currentModeId\n );\n}\n\nfunction applyRequestedSessionConfiguration(input: {\n readonly runtime: AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n readonly runtimeMode: RuntimeMode;\n readonly interactionMode: ProviderInteractionMode | undefined;\n readonly modelSelection:\n | {\n readonly model: string;\n readonly options?: ReadonlyArray | null | undefined;\n }\n | undefined;\n readonly mapError: (context: {\n readonly cause: import(\"effect-acp/errors\").AcpError;\n readonly method: \"session/set_config_option\" | \"session/set_mode\";\n }) => E;\n}): Effect.Effect {\n return Effect.gen(function* () {\n if (input.modelSelection) {\n yield* applyCursorAcpModelSelection({\n runtime: input.runtime,\n model: input.modelSelection.model,\n selections: input.modelSelection.options,\n mapError: ({ cause }) =>\n input.mapError({\n cause,\n method: \"session/set_config_option\",\n }),\n });\n }\n\n const requestedModeId = resolveRequestedModeId({\n interactionMode: input.interactionMode,\n runtimeMode: input.runtimeMode,\n modeState: yield* input.runtime.getModeState,\n });\n if (!requestedModeId) {\n return;\n }\n\n yield* input.runtime.setMode(requestedModeId).pipe(\n Effect.mapError((cause) =>\n input.mapError({\n cause,\n method: \"session/set_mode\",\n }),\n ),\n );\n });",
+ "checksum": "496d6f291b2b479eb2836b32aeafe501dcc9f66a5d207cb94adf592c9f4a6a78"
+ },
+ "grok-acp-runtime-support": {
+ "id": "grok-acp-runtime-support",
+ "path": "apps/server/src/provider/acp/GrokAcpSupport.ts",
+ "start": 31,
+ "end": 108,
+ "language": "typescript",
+ "label": "Grok ACP launch, authentication, and model selection",
+ "code": "\nexport function buildGrokAcpSpawnInput(\n grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,\n cwd: string,\n environment?: NodeJS.ProcessEnv,\n): AcpSessionRuntime.AcpSpawnInput {\n return {\n command: grokSettings?.binaryPath || \"grok\",\n args: [\"agent\", \"stdio\"],\n cwd,\n env: {\n ...environment,\n [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,\n },\n };\n}\n\nfunction resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {\n return environment?.[GROK_API_KEY_ENV]?.trim()\n ? GROK_AUTH_METHOD_API_KEY\n : GROK_AUTH_METHOD_CACHED_TOKEN;\n}\n\nexport const makeGrokAcpRuntime = (\n input: GrokAcpRuntimeInput,\n): Effect.Effect<\n AcpSessionRuntime.AcpSessionRuntime[\"Service\"],\n EffectAcpErrors.AcpError,\n Crypto.Crypto | Scope.Scope\n> =>\n Effect.gen(function* () {\n const acpContext = yield* Layer.build(\n AcpSessionRuntime.layer({\n ...input,\n spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),\n authMethodId: resolveGrokAuthMethodId(input.environment),\n }).pipe(\n Layer.provide(\n Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),\n ),\n ),\n );\n const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(\n Effect.provide(acpContext),\n );\n return yield* makeXAiPromptCompletionRuntime(runtime);\n });\n\nexport function resolveGrokAcpBaseModelId(model: string | null | undefined): string {\n const trimmed = model?.trim();\n const base = trimmed && trimmed.length > 0 ? trimmed : \"grok-build\";\n return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? \"grok-build\";\n}\n\nexport function currentGrokModelIdFromSessionSetup(\n sessionSetupResult:\n | EffectAcpSchema.LoadSessionResponse\n | EffectAcpSchema.NewSessionResponse\n | EffectAcpSchema.ResumeSessionResponse,\n): string | undefined {\n return sessionSetupResult.models?.currentModelId?.trim() || undefined;\n}\n\nexport function applyGrokAcpModelSelection(input: {\n readonly runtime: Pick;\n readonly currentModelId: string | undefined;\n readonly requestedModelId: string | undefined;\n readonly mapError: (cause: EffectAcpErrors.AcpError) => E;\n}): Effect.Effect {\n const shouldSwitchModel =\n input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;\n if (!shouldSwitchModel) {\n return Effect.succeed(input.currentModelId);\n }\n return input.runtime\n .setSessionModel(input.requestedModelId)\n .pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));\n}",
+ "checksum": "d76d1518eb9e2c11e37e359f1d1324099034f92d77f9e6f5af7a3d167bcd168a"
+ },
+ "opencode-runtime-ownership": {
+ "id": "opencode-runtime-ownership",
+ "path": "apps/server/src/provider/opencodeRuntime.ts",
+ "start": 140,
+ "end": 177,
+ "language": "typescript",
+ "label": "Local and external OpenCode server ownership",
+ "code": "export interface OpenCodeRuntimeShape {\n /**\n * Spawns a local OpenCode server process. Its lifetime is bound to the caller's\n * `Scope.Scope` — the child is killed automatically when that scope closes.\n * Consumers that want a long-lived server must create and hold a scope explicitly\n * (see {@link Scope.make}) and close it when done.\n */\n readonly startOpenCodeServerProcess: (input: {\n readonly binaryPath: string;\n readonly environment?: NodeJS.ProcessEnv;\n readonly port?: number;\n readonly hostname?: string;\n readonly timeoutMs?: number;\n }) => Effect.Effect;\n /**\n * Returns a handle to either an externally-managed OpenCode server (when\n * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a\n * freshly spawned local server whose lifetime is bound to the caller's scope.\n */\n readonly connectToOpenCodeServer: (input: {\n readonly binaryPath: string;\n readonly serverUrl?: string | null;\n readonly environment?: NodeJS.ProcessEnv;\n readonly port?: number;\n readonly hostname?: string;\n readonly timeoutMs?: number;\n }) => Effect.Effect;\n readonly runOpenCodeCommand: (input: {\n readonly binaryPath: string;\n readonly args: ReadonlyArray;\n readonly environment?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n }) => Effect.Effect;\n readonly createOpenCodeSdkClient: (input: {\n readonly baseUrl: string;\n readonly directory: string;\n readonly serverPassword?: string;\n }) => OpencodeClient;",
+ "checksum": "846dada188ac95cfa4616580a5fa9aacefea446eb2542ea69ed44236f20b6dea"
+ },
+ "opencode-turn-and-revert": {
+ "id": "opencode-turn-and-revert",
+ "path": "apps/server/src/provider/Layers/OpenCodeAdapter.ts",
+ "start": 1430,
+ "end": 1509,
+ "language": "typescript",
+ "label": "OpenCode prompt and steering path",
+ "code": " const sendTurn: OpenCodeAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n const context = yield* ensureSessionContext(sessions, input.threadId);\n // A sendTurn while a turn is active is a steer: OpenCode queues the\n // prompt into the busy session and the work continues as one turn, so\n // the active turn id is reused instead of opening a new turn.\n const steeringTurnId = context.activeTurnId;\n const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);\n const modelSelection =\n input.modelSelection ??\n (context.session.model\n ? { instanceId: boundInstanceId, model: context.session.model }\n : undefined);\n if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) {\n return yield* new ProviderAdapterValidationError({\n provider: PROVIDER,\n operation: \"sendTurn\",\n issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,\n });\n }\n const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);\n if (!parsedModel) {\n return yield* new ProviderAdapterValidationError({\n provider: PROVIDER,\n operation: \"sendTurn\",\n issue: \"OpenCode model selection must use the 'provider/model' format.\",\n });\n }\n\n const text = input.input?.trim();\n const fileParts = toOpenCodeFileParts({\n attachments: input.attachments,\n resolveAttachmentPath: (attachment) =>\n resolveAttachmentPath({\n attachmentsDir: serverConfig.attachmentsDir,\n attachment,\n }),\n });\n if ((!text || text.length === 0) && fileParts.length === 0) {\n return yield* new ProviderAdapterValidationError({\n provider: PROVIDER,\n operation: \"sendTurn\",\n issue: \"OpenCode turns require text input or at least one attachment.\",\n });\n }\n\n const agent = getModelSelectionStringOptionValue(modelSelection, \"agent\");\n const variant = getModelSelectionStringOptionValue(modelSelection, \"variant\");\n\n context.activeTurnId = turnId;\n context.activeAgent = agent ?? (input.interactionMode === \"plan\" ? \"plan\" : undefined);\n context.activeVariant = variant;\n yield* updateProviderSession(\n context,\n {\n status: \"running\",\n activeTurnId: turnId,\n model: modelSelection?.model ?? context.session.model,\n },\n { clearLastError: true },\n );\n\n if (steeringTurnId === undefined) {\n yield* emit({\n ...(yield* buildEventBase({ threadId: input.threadId, turnId })),\n type: \"turn.started\",\n payload: {\n model: modelSelection?.model ?? context.session.model,\n ...(variant ? { effort: variant } : {}),\n },\n });\n }\n\n yield* runOpenCodeSdk(\"session.promptAsync\", () =>\n context.client.session.promptAsync({\n sessionID: context.openCodeSessionId,\n model: parsedModel,\n ...(context.activeAgent ? { agent: context.activeAgent } : {}),\n ...(context.activeVariant ? { variant: context.activeVariant } : {}),\n parts: [...(text ? [{ type: \"text\" as const, text }] : []), ...fileParts],\n }),",
+ "checksum": "bd23ad46a4ad8ad0613a82192a06a3329c10808cfda57391fd77f2ba14fcccf9"
+ },
+ "usage-live-contract": {
+ "id": "usage-live-contract",
+ "path": "packages/contracts/src/providerRuntime.ts",
+ "start": 309,
+ "end": 331,
+ "language": "typescript",
+ "label": "Live thread token-usage snapshot contract",
+ "code": "export const ThreadTokenUsageSnapshot = Schema.Struct({\n usedTokens: NonNegativeInt,\n totalProcessedTokens: Schema.optional(NonNegativeInt),\n maxTokens: Schema.optional(PositiveInt),\n inputTokens: Schema.optional(NonNegativeInt),\n cachedInputTokens: Schema.optional(NonNegativeInt),\n outputTokens: Schema.optional(NonNegativeInt),\n reasoningOutputTokens: Schema.optional(NonNegativeInt),\n lastUsedTokens: Schema.optional(NonNegativeInt),\n lastInputTokens: Schema.optional(NonNegativeInt),\n lastCachedInputTokens: Schema.optional(NonNegativeInt),\n lastOutputTokens: Schema.optional(NonNegativeInt),\n lastReasoningOutputTokens: Schema.optional(NonNegativeInt),\n toolUses: Schema.optional(NonNegativeInt),\n durationMs: Schema.optional(NonNegativeInt),\n compactsAutomatically: Schema.optional(Schema.Boolean),\n});\nexport type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;\n\nconst ThreadTokenUsageUpdatedPayload = Schema.Struct({\n usage: ThreadTokenUsageSnapshot,\n});\nexport type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;",
+ "checksum": "d63a433efcb36c6017efca4dfa4c29f8e8186b060316152534c0befba263d700"
+ },
+ "usage-codex-normalization": {
+ "id": "usage-codex-normalization",
+ "path": "apps/server/src/provider/Layers/CodexAdapter.ts",
+ "start": 159,
+ "end": 190,
+ "language": "typescript",
+ "label": "Codex live token-usage normalization",
+ "code": "function normalizeCodexTokenUsage(\n usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification[\"tokenUsage\"],\n): ThreadTokenUsageSnapshot | undefined {\n const totalProcessedTokens = usage.total.totalTokens;\n const usedTokens = usage.last.totalTokens;\n if (usedTokens === undefined || usedTokens <= 0) {\n return undefined;\n }\n\n const maxTokens = usage.modelContextWindow ?? undefined;\n const inputTokens = usage.last.inputTokens;\n const cachedInputTokens = usage.last.cachedInputTokens;\n const outputTokens = usage.last.outputTokens;\n const reasoningOutputTokens = usage.last.reasoningOutputTokens;\n\n return {\n usedTokens,\n ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens\n ? { totalProcessedTokens }\n : {}),\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),\n ...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),\n ...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),\n ...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),\n ...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),\n ...(reasoningOutputTokens !== undefined\n ? { lastReasoningOutputTokens: reasoningOutputTokens }\n : {}),",
+ "checksum": "fec887f108f8d86e020a989334ff325a8b42f40bb30b26f61e69fe87041df522"
+ },
+ "usage-codex-emission": {
+ "id": "usage-codex-emission",
+ "path": "apps/server/src/provider/Layers/CodexAdapter.ts",
+ "start": 1000,
+ "end": 1018,
+ "language": "typescript",
+ "label": "Codex live usage event emission",
+ "code": " if (event.method === \"thread/tokenUsage/updated\") {\n const payload = readPayload(\n EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,\n event.payload,\n );\n const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;\n if (!normalizedUsage) {\n return [];\n }\n return [\n {\n type: \"thread.token-usage.updated\",\n ...runtimeEventBase(event, canonicalThreadId),\n payload: {\n usage: normalizedUsage,\n },\n },\n ];\n }",
+ "checksum": "b5443e4a9d8358ced1bc548a51227ab8796667482f262f5ebc6513cda5220cf1"
+ },
+ "usage-claude-emission": {
+ "id": "usage-claude-emission",
+ "path": "apps/server/src/provider/Layers/ClaudeAdapter.ts",
+ "start": 2051,
+ "end": 2088,
+ "language": "typescript",
+ "label": "Claude live usage event emission",
+ "code": " const emitThreadTokenUsage = Effect.fn(\"emitThreadTokenUsage\")(function* (\n context: ClaudeSessionContext,\n usage: ThreadTokenUsageSnapshot | undefined,\n options?: {\n readonly rawMethod?: string;\n readonly rawPayload?: unknown;\n },\n ) {\n if (!usage) {\n return;\n }\n\n context.lastKnownTokenUsage = usage;\n context.lastKnownTotalProcessedTokens =\n usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;\n\n const turnState = context.turnState;\n const stamp = yield* makeEventStamp();\n yield* offerRuntimeEvent({\n type: \"thread.token-usage.updated\",\n eventId: stamp.eventId,\n provider: PROVIDER,\n createdAt: stamp.createdAt,\n threadId: context.session.threadId,\n ...(turnState ? { turnId: turnState.turnId } : {}),\n payload: {\n usage,\n },\n providerRefs: nativeProviderRefs(context),\n ...(options?.rawMethod || options?.rawPayload\n ? {\n raw: {\n source: \"claude.sdk.message\" as const,\n ...(options.rawMethod ? { method: options.rawMethod } : {}),\n payload: options.rawPayload,\n },\n }\n : {}),",
+ "checksum": "1358344a9ecfbb8fb89639a941e39879abdeb0f8da803ccfa6e9b66cb69478f1"
+ },
+ "usage-live-activity": {
+ "id": "usage-live-activity",
+ "path": "apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts",
+ "start": 766,
+ "end": 784,
+ "language": "typescript",
+ "label": "Live usage becomes context-window activity",
+ "code": " case \"thread.token-usage.updated\": {\n const payload = buildContextWindowActivityPayload(event);\n if (!payload) {\n return [];\n }\n\n return [\n {\n id: event.eventId,\n createdAt: event.createdAt,\n tone: \"info\",\n kind: \"context-window.updated\",\n summary: \"Context window updated\",\n payload,\n turnId: toTurnId(event.turnId) ?? null,\n ...maybeSequence,\n },\n ];\n }",
+ "checksum": "32de8fdc5bf965dcd67f6e3ebef7b896b6605e8c2a5d2d0a5544a915dccf9c1e"
+ },
+ "usage-web-context-meter": {
+ "id": "usage-web-context-meter",
+ "path": "apps/web/src/lib/contextWindow.ts",
+ "start": 50,
+ "end": 96,
+ "language": "typescript",
+ "label": "Latest valid context-window snapshot derivation",
+ "code": "export function deriveLatestContextWindowSnapshot(\n activities: ReadonlyArray,\n): ContextWindowSnapshot | null {\n for (let index = activities.length - 1; index >= 0; index -= 1) {\n const activity = activities[index];\n if (!activity || activity.kind !== \"context-window.updated\") {\n continue;\n }\n\n const payload = asRecord(activity.payload);\n const usedTokens = asFiniteNumber(payload?.usedTokens);\n if (usedTokens === null || usedTokens < 0) {\n continue;\n }\n\n const maxTokens = asFiniteNumber(payload?.maxTokens);\n const usedPercentage =\n maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null;\n const remainingTokens =\n maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;\n const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;\n\n return {\n usedTokens,\n totalProcessedTokens: asFiniteNumber(payload?.totalProcessedTokens),\n maxTokens,\n remainingTokens,\n usedPercentage,\n remainingPercentage,\n inputTokens: asFiniteNumber(payload?.inputTokens),\n cachedInputTokens: asFiniteNumber(payload?.cachedInputTokens),\n outputTokens: asFiniteNumber(payload?.outputTokens),\n reasoningOutputTokens: asFiniteNumber(payload?.reasoningOutputTokens),\n lastUsedTokens: asFiniteNumber(payload?.lastUsedTokens),\n lastInputTokens: asFiniteNumber(payload?.lastInputTokens),\n lastCachedInputTokens: asFiniteNumber(payload?.lastCachedInputTokens),\n lastOutputTokens: asFiniteNumber(payload?.lastOutputTokens),\n lastReasoningOutputTokens: asFiniteNumber(payload?.lastReasoningOutputTokens),\n toolUses: asFiniteNumber(payload?.toolUses),\n durationMs: asFiniteNumber(payload?.durationMs),\n compactsAutomatically: asBoolean(payload?.compactsAutomatically) ?? false,\n updatedAt: activity.createdAt,\n };\n }\n\n return null;\n}",
+ "checksum": "f414738aaad3b6f8526e5760a436944757fefe35662bb9ce36fe9375f1c0c35b"
+ },
+ "usage-summary-contract": {
+ "id": "usage-summary-contract",
+ "path": "packages/contracts/src/usage.ts",
+ "start": 1,
+ "end": 101,
+ "language": "typescript",
+ "label": "Historical usage version, providers, tokens, and cost buckets",
+ "code": "/**\n * Usage reporting contract.\n *\n * Each environment scans the provider CLIs' own on-disk session transcripts\n * (`~/.claude/projects/**\\/*.jsonl`, `~/.codex/sessions/**\\/*.jsonl`) rather than\n * relying on T3 Code's own orchestration projections, so usage stays complete\n * even for turns that were never driven through T3 Code. This mirrors the\n * approach `ccusage` takes.\n *\n * Environments return pre-aggregated `(day, hourStart?, provider, model)`\n * buckets. Raw transcript records never cross the wire.\n *\n * @module usage\n */\nimport * as Schema from \"effect/Schema\";\n\nimport { NonNegativeInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Bumped whenever the shape of {@link UsageSummary} changes incompatibly. The\n * client renders partial coverage when an environment reports an older version\n * rather than failing the whole page.\n */\nexport const USAGE_CONTRACT_VERSION = 4 as const;\n\nexport const UsageProviderKind = Schema.Literals([\"claude\", \"codex\"]);\nexport type UsageProviderKind = typeof UsageProviderKind.Type;\n\n/**\n * A calendar day in the reporting time zone, formatted `YYYY-MM-DD`.\n *\n * Days are bucketed server-side so that a turn always lands on the day the user\n * experienced it, not the UTC day.\n */\nconst USAGE_DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nexport const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(\n Schema.brand(\"UsageDay\"),\n);\nexport type UsageDay = typeof UsageDay.Type;\n\nexport const UsageResolution = Schema.Literals([\"day\", \"hour\"]);\nexport type UsageResolution = typeof UsageResolution.Type;\n\n/**\n * Why a bucket's cost is what it is.\n *\n * - `providerReported` - the transcript carried an explicit cost figure.\n * - `modelPriced` - we matched the model against the LiteLLM rate table.\n * - `unpriced` - tokens are known, rates are not. Counted in totals, excluded\n * from cost.\n */\nexport const UsageCostSource = Schema.Literals([\"providerReported\", \"modelPriced\", \"unpriced\"]);\nexport type UsageCostSource = typeof UsageCostSource.Type;\n\n/**\n * Token counts for a bucket.\n *\n * `cachedInputTokens` and `cacheCreationTokens` are disjoint from\n * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`\n * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic\n * folds thinking into output), so it must never be added on top.\n */\nexport const UsageTokenTotals = Schema.Struct({\n uncachedInputTokens: NonNegativeInt,\n cachedInputTokens: NonNegativeInt,\n cacheCreationTokens: NonNegativeInt,\n outputTokens: NonNegativeInt,\n reasoningTokens: NonNegativeInt,\n});\nexport type UsageTokenTotals = typeof UsageTokenTotals.Type;\n\n/**\n * One `(day, hourStart?, provider, model)` cell. `hourStart` is the UTC start\n * instant of a rolling bucket and is present only for hourly requests.\n *\n * `costUsd` is the raw API-equivalent cost of these tokens. It is not money\n * spent: subscription plans bill separately. `unpricedRecords` counts records\n * whose tokens are included in the token totals but which contributed nothing\n * to `costUsd`.\n */\nexport const UsageBucket = Schema.Struct({\n day: UsageDay,\n hourStart: Schema.optional(TrimmedNonEmptyString),\n provider: UsageProviderKind,\n model: TrimmedNonEmptyString,\n totals: UsageTokenTotals,\n costUsd: Schema.Number,\n /**\n * What the cached input would have cost at full input rates minus what it\n * actually cost. Requires the rate table, so it is computed alongside cost\n * rather than derived on the client.\n */\n cacheSavingsUsd: Schema.Number,\n costSource: UsageCostSource,\n /** Distinct assistant responses, after de-duplication. */\n records: NonNegativeInt,\n unpricedRecords: NonNegativeInt,\n /** Distinct transcript sessions that contributed to this cell. */\n sessions: NonNegativeInt,\n});",
+ "checksum": "f93dd8ada5db38b9c283d950acc7da22def26fa5c8ae2352aca8ab2aa31b3040"
+ },
+ "usage-home-discovery": {
+ "id": "usage-home-discovery",
+ "path": "apps/server/src/usage/UsageService.ts",
+ "start": 187,
+ "end": 225,
+ "language": "typescript",
+ "label": "Claude and Codex transcript home resolution",
+ "code": " /**\n * Claude's config dir is the home itself when overridden, but a default\n * install nests transcripts under `~/.claude/projects`. Probe both.\n */\n const resolveClaudeTranscriptDir = (homePath: string) =>\n Effect.gen(function* () {\n const nested = path.join(homePath, \".claude\", \"projects\");\n const nestedExists = yield* fileSystem\n .exists(nested)\n .pipe(Effect.catchCause(() => Effect.succeed(false)));\n return nestedExists ? nested : path.join(homePath, \"projects\");\n });\n\n /** Resolves the transcript directory for each provider. */\n const resolveTranscriptDirs = Effect.fn(\"UsageService.resolveTranscriptDirs\")(function* () {\n // A settings failure must surface as an error: swallowing it here would\n // present \"zero usage from every provider\" as a valid answer.\n const settings = yield* settingsService.getSettings.pipe(\n Effect.catchCause(\n (cause) =>\n new UsageReadError({\n reason: \"scanFailed\",\n // Bounded description; the squashed failure travels as the cause.\n // Squashed, not the Cause tree: a full tree in a Defect field is\n // the unbounded wire payload the bounded detail exists to avoid.\n detail: \"Server settings could not be read.\",\n cause: Cause.squash(cause),\n }),\n ),\n );\n\n const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);\n const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);\n const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);\n\n return [\n { provider: \"claude\" as const, dir: claudeDir },\n { provider: \"codex\" as const, dir: path.join(codexLayout.sharedHomePath, \"sessions\") },\n ];",
+ "checksum": "d6526ea3f89bb7c8877e0d60c06a6f36809be5b51834b133045a40debecabafd"
+ },
+ "usage-transcript-parsers": {
+ "id": "usage-transcript-parsers",
+ "path": "apps/server/src/usage/usageTranscripts.ts",
+ "start": 78,
+ "end": 137,
+ "language": "typescript",
+ "label": "Claude transcript usage normalization",
+ "code": "/**\n * Parses one line of a Claude Code transcript.\n *\n * T3 Code writes one record per assistant *content block*, and every one of\n * those records repeats the same complete `usage` object for the parent\n * message. Summing them overcounts by roughly 2.4x on a real workload, so the\n * caller must drop repeats by `dedupeKey` and keep the first.\n */\nexport function parseClaudeLine(line: string): UsageRecord | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n\n const record = parsed as Record;\n if (record[\"type\"] !== \"assistant\") return null;\n\n const message = record[\"message\"];\n if (typeof message !== \"object\" || message === null) return null;\n const messageRecord = message as Record;\n\n const usage = messageRecord[\"usage\"];\n if (typeof usage !== \"object\" || usage === null) return null;\n const usageRecord = usage as Record;\n\n const timestampMs = parseTimestampMs(record[\"timestamp\"]);\n if (timestampMs === null) return null;\n\n const model = typeof messageRecord[\"model\"] === \"string\" ? messageRecord[\"model\"] : \"\";\n if (model.length === 0) return null;\n\n const messageId = typeof messageRecord[\"id\"] === \"string\" ? messageRecord[\"id\"] : null;\n const requestId = typeof record[\"requestId\"] === \"string\" ? record[\"requestId\"] : null;\n // Matches ccusage: prefer the message/request pair, fall back to whichever\n // half exists. Records with neither cannot be de-duplicated.\n const dedupeKey =\n messageId === null && requestId === null ? null : `${messageId ?? \"\"}:${requestId ?? \"\"}`;\n\n const cost = record[\"costUSD\"];\n\n return {\n provider: \"claude\",\n timestampMs,\n model,\n sessionId: typeof record[\"sessionId\"] === \"string\" ? record[\"sessionId\"] : \"\",\n totals: {\n uncachedInputTokens: int(usageRecord[\"input_tokens\"]),\n cachedInputTokens: int(usageRecord[\"cache_read_input_tokens\"]),\n cacheCreationTokens: int(usageRecord[\"cache_creation_input_tokens\"]),\n outputTokens: int(usageRecord[\"output_tokens\"]),\n // Anthropic folds thinking tokens into output and does not break them out.\n reasoningTokens: 0,\n },\n reportedCostUsd: typeof cost === \"number\" && Number.isFinite(cost) ? cost : null,\n dedupeKey,\n };\n}",
+ "checksum": "98addede4c92886630a8f69b8ec46e776ac775bbb00896814ba7a17e244c4531"
+ },
+ "usage-dedup-buckets": {
+ "id": "usage-dedup-buckets",
+ "path": "apps/server/src/usage/usageAggregation.ts",
+ "start": 109,
+ "end": 178,
+ "language": "typescript",
+ "label": "Global deduplication, bounds, bucketing, and pricing fold",
+ "code": " /**\n * Folds one record in. Returns whether it actually contributed, so callers\n * can derive per-window facts (distinct sessions, for one) from the records\n * that landed rather than everything the mtime prefilter happened to admit.\n */\n add(record: UsageRecord): boolean {\n if (record.dedupeKey !== null) {\n if (this.#seen.has(record.dedupeKey)) {\n this.#duplicatesDropped += 1;\n return false;\n }\n this.#seen.add(record.dedupeKey);\n }\n\n if (\n this.#hourlyWindow !== null &&\n (record.timestampMs < this.#hourlyWindow.sinceTimeMs ||\n record.timestampMs >= this.#hourlyWindow.untilTimeMs)\n ) {\n this.#outOfWindow += 1;\n return false;\n }\n\n const day = this.#toDay(record.timestampMs);\n if (\n this.#hourlyWindow === null &&\n (day < this.#options.sinceDay || day > this.#options.untilDay)\n ) {\n this.#outOfWindow += 1;\n return false;\n }\n\n const hourStart =\n this.#hourlyWindow === null\n ? \"\"\n : new Date(\n this.#hourlyWindow.sinceTimeMs +\n Math.floor((record.timestampMs - this.#hourlyWindow.sinceTimeMs) / HOUR_MS) * HOUR_MS,\n ).toISOString();\n const key = `${day}\\u0000${hourStart}\\u0000${record.provider}\\u0000${record.model}`;\n let bucket = this.#buckets.get(key);\n if (bucket === undefined) {\n bucket = {\n totals: EMPTY_TOTALS,\n costUsd: 0,\n cacheSavingsUsd: 0,\n records: 0,\n unpricedRecords: 0,\n providerReportedRecords: 0,\n sessions: new Set(),\n };\n this.#buckets.set(key, bucket);\n }\n\n const priced = priceUsage(\n this.#options.rates,\n record.model,\n record.totals,\n record.reportedCostUsd,\n );\n\n bucket.totals = addTotals(bucket.totals, record.totals);\n bucket.costUsd += priced.costUsd;\n bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals);\n bucket.records += 1;\n if (priced.costSource === \"unpriced\") bucket.unpricedRecords += 1;\n if (priced.costSource === \"providerReported\") bucket.providerReportedRecords += 1;\n if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);\n return true;\n }",
+ "checksum": "ca4bb237d353ca5cbf384f3e91c0d802c24e1764b19871add182ac894cc19677"
+ },
+ "usage-pricing-cache": {
+ "id": "usage-pricing-cache",
+ "path": "apps/server/src/usage/usagePricing.ts",
+ "start": 85,
+ "end": 148,
+ "language": "typescript",
+ "label": "Historical usage rate lookup and pricing arithmetic",
+ "code": "/**\n * Models we never price, regardless of the table.\n *\n * `` marks locally generated messages that were never billed. Bare\n * family names (\"opus\", \"sonnet\") are genuinely ambiguous across generations,\n * so we report them as unpriced instead of guessing a generation.\n */\nconst UNPRICEABLE_MODELS = new Set([\n \"\",\n \"synthetic\",\n \"opus\",\n \"sonnet\",\n \"haiku\",\n \"fable\",\n]);\n\nexport function lookupRate(table: RateTable, model: string): ModelRate | null {\n const normalized = normalizeModelName(model);\n if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;\n return table.get(normalized) ?? null;\n}\n\nexport interface PricedUsage {\n readonly costUsd: number;\n readonly costSource: UsageCostSource;\n}\n\n/**\n * Prices a bucket's tokens.\n *\n * `reasoningTokens` is intentionally not charged separately: it is already\n * counted inside `outputTokens`.\n */\nexport function priceUsage(\n table: RateTable,\n model: string,\n totals: UsageTokenTotals,\n reportedCostUsd: number | null,\n): PricedUsage {\n if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {\n return { costUsd: reportedCostUsd, costSource: \"providerReported\" };\n }\n\n const rate = lookupRate(table, model);\n if (rate === null) return { costUsd: 0, costSource: \"unpriced\" };\n\n const costUsd =\n totals.uncachedInputTokens * rate.inputCostPerToken +\n totals.cachedInputTokens * rate.cacheReadCostPerToken +\n totals.cacheCreationTokens * rate.cacheCreationCostPerToken +\n totals.outputTokens * rate.outputCostPerToken;\n\n return { costUsd, costSource: \"modelPriced\" };\n}\n\n/**\n * What the cached input would have cost at full input rates, minus what it\n * actually cost. Drives the \"cache savings\" figure.\n */\nexport function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {\n const rate = lookupRate(table, model);\n if (rate === null) return 0;\n return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);\n}",
+ "checksum": "c1d6f1e6a20765222fbbd5c94a90766711a846430088f37c1242011fd9ec1518"
+ },
+ "usage-rpc-contract": {
+ "id": "usage-rpc-contract",
+ "path": "packages/contracts/src/rpc.ts",
+ "start": 260,
+ "end": 284,
+ "language": "typescript",
+ "label": "Typed usage summary RPC",
+ "code": " previewAutomationFocusHost: \"previewAutomation.focusHost\",\n\n // Server meta\n serverProbe: \"server.probe\",\n serverGetConfig: \"server.getConfig\",\n serverRefreshProviders: \"server.refreshProviders\",\n serverUpdateProvider: \"server.updateProvider\",\n serverUpdateServer: \"server.updateServer\",\n serverUpdateServerWithProgress: \"server.updateServerWithProgress\",\n serverUpsertKeybinding: \"server.upsertKeybinding\",\n serverRemoveKeybinding: \"server.removeKeybinding\",\n serverGetSettings: \"server.getSettings\",\n serverUpdateSettings: \"server.updateSettings\",\n serverDiscoverSourceControl: \"server.discoverSourceControl\",\n serverGetTraceDiagnostics: \"server.getTraceDiagnostics\",\n serverGetProcessDiagnostics: \"server.getProcessDiagnostics\",\n serverGetProcessResourceHistory: \"server.getProcessResourceHistory\",\n serverGetResourceTelemetryHistory: \"server.getResourceTelemetryHistory\",\n serverRetryResourceTelemetry: \"server.retryResourceTelemetry\",\n serverSignalProcess: \"server.signalProcess\",\n serverReportClientActivity: \"server.reportClientActivity\",\n serverReportHostPowerState: \"server.reportHostPowerState\",\n serverGetBackgroundPolicy: \"server.getBackgroundPolicy\",\n serverGetUsageSummary: \"server.getUsageSummary\",\n",
+ "checksum": "a9bdb475c42adc730d43788b4336aa36b6c0de90e60fc9dcd2139b1f929e9ea6"
+ },
+ "usage-environment-merge": {
+ "id": "usage-environment-merge",
+ "path": "packages/shared/src/usageMerge.ts",
+ "start": 102,
+ "end": 163,
+ "language": "typescript",
+ "label": "Deterministic physical-source ownership across environments",
+ "code": "/**\n * Decides which environment owns each physical transcript directory.\n *\n * Several environments on one machine (worktree servers, for instance) resolve\n * the same provider home and would otherwise double count every token. The\n * first environment in a stable order claims a fingerprint; the rest have that\n * provider's buckets dropped. Environments are sorted by id so the winner does\n * not change between renders.\n */\nfunction claimSources(environments: readonly EnvironmentUsage[]): {\n readonly ownerByFingerprint: ReadonlyMap;\n readonly duplicates: readonly string[];\n} {\n const ownerByFingerprint = new Map();\n const duplicates: string[] = [];\n\n const ordered = [...environments].sort((a, b) => a.environmentId.localeCompare(b.environmentId));\n\n for (const environment of ordered) {\n for (const source of environment.summary.sources) {\n if (source.status === \"missing\") continue;\n const key = fingerprintKey(source.fingerprint);\n if (ownerByFingerprint.has(key)) {\n duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);\n continue;\n }\n ownerByFingerprint.set(key, environment.environmentId);\n }\n }\n\n return { ownerByFingerprint, duplicates };\n}\n\n/** Sources this environment owns after fingerprint claims, plus their buckets. */\nfunction ownedContribution(\n environment: EnvironmentUsage,\n ownerByFingerprint: ReadonlyMap,\n): {\n readonly buckets: readonly UsageBucket[];\n readonly sessionsByProvider: ReadonlyMap;\n} {\n const ownedProviders = new Set();\n const sessionsByProvider = new Map();\n for (const source of environment.summary.sources) {\n if (source.status === \"missing\") continue;\n const key = fingerprintKey(source.fingerprint);\n if (ownerByFingerprint.get(key) === environment.environmentId) {\n const provider = source.fingerprint.provider;\n ownedProviders.add(provider);\n // Distinct within a directory. Summing per-bucket session counts instead\n // would count a session once per day and model it spans.\n sessionsByProvider.set(\n provider,\n (sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,\n );\n }\n }\n return {\n buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),\n sessionsByProvider,\n };\n}",
+ "checksum": "2ef3c27f0875e553cc334289b2ffa24682b812e8a15f401be76eb06240ccfb98"
+ },
+ "usage-reader-failure-policy": {
+ "id": "usage-reader-failure-policy",
+ "path": "apps/server/src/usage/usageTranscriptReader.ts",
+ "start": 92,
+ "end": 140,
+ "language": "typescript",
+ "label": "Streaming transcript read and null-on-read-failure policy",
+ "code": "/**\n * Streams one transcript and returns the usage records it contains, or `null`\n * when the file could not be read.\n *\n * The distinction matters to the caller's cache: a genuinely empty transcript\n * is a stable fact worth memoising, while a transient read failure memoised\n * under the same `(size, mtime)` key would silently drop that file's usage\n * until the file next changes.\n *\n * Codex carries the active model on `turn_context` lines that hold no usage of\n * their own, so those still have to pass through the reducer to keep model\n * attribution correct.\n */\nexport async function readTranscriptRecords(\n filePath: string,\n provider: UsageProviderKind,\n): Promise {\n const records: UsageRecord[] = [];\n const codexState = initialCodexScanState();\n\n try {\n const lines = NodeReadline.createInterface({\n input: NodeFS.createReadStream(filePath, { encoding: \"utf8\" }),\n crlfDelay: Infinity,\n });\n\n for await (const line of lines) {\n if (provider === \"codex\") {\n if (\n !mightCarryUsage(line, provider) &&\n !line.includes('\"turn_context\"') &&\n !line.includes('\"session_meta\"')\n ) {\n continue;\n }\n const record = parseCodexLine(line, codexState);\n if (record !== null) records.push(record);\n continue;\n }\n\n if (!mightCarryUsage(line, provider)) continue;\n const record = parseClaudeLine(line);\n if (record !== null) records.push(record);\n }\n } catch {\n return null;\n }\n\n return records;",
+ "checksum": "a4603871e61cae2e5575a2df75f84ff9f5684262b1cb59e638f3009e66fdfa58"
+ },
+ "usage-source-status": {
+ "id": "usage-source-status",
+ "path": "apps/server/src/usage/UsageService.ts",
+ "start": 352,
+ "end": 408,
+ "language": "typescript",
+ "label": "Current historical source status and session accounting",
+ "code": " const sources: UsageSource[] = [];\n const livePaths = new Set();\n const walkedRoots: string[] = [];\n\n for (const { provider, dir } of dirs) {\n const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));\n const exists = yield* fileSystem\n .exists(dir)\n .pipe(Effect.catchCause(() => Effect.succeed(false)));\n\n if (!exists) {\n sources.push({\n fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },\n status: \"missing\",\n scannedFiles: 0,\n skippedFiles: 0,\n malformedRecords: 0,\n distinctSessions: 0,\n message: \"No transcript directory on this environment.\",\n });\n continue;\n }\n\n walkedRoots.push(dir);\n const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));\n let scannedFiles = 0;\n let skippedFiles = 0;\n // Distinct per directory. Buckets carry per-cell session counts, but a\n // session spans days and models, so clients total this figure instead.\n const sessionIds = new Set();\n\n for (const file of files) {\n livePaths.add(file.path);\n const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);\n if (records.length === 0) {\n skippedFiles += 1;\n continue;\n }\n scannedFiles += 1;\n for (const record of records) {\n // Only sessions that contributed in-window count: the mtime slack\n // admits boundary files whose records fall outside the range.\n if (aggregator.add(record) && record.sessionId.length > 0) {\n sessionIds.add(record.sessionId);\n }\n }\n }\n\n sources.push({\n fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },\n status: \"ok\",\n scannedFiles,\n skippedFiles,\n malformedRecords: 0,\n distinctSessions: sessionIds.size,\n message: null,\n });",
+ "checksum": "619a5fb4c66a09b2bf6abed238f22779341b997262bc48736bd927aa19f042f1"
+ },
+ "project-root-normalization": {
+ "id": "project-root-normalization",
+ "path": "apps/server/src/workspace/WorkspacePaths.ts",
+ "start": 161,
+ "end": 200,
+ "language": "typescript",
+ "label": "Workspace-root resolution, validation, and opt-in creation",
+ "code": " const normalizeWorkspaceRoot: WorkspacePaths[\"Service\"][\"normalizeWorkspaceRoot\"] = Effect.fn(\n \"WorkspacePaths.normalizeWorkspaceRoot\",\n )(function* (workspaceRoot, options) {\n const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));\n let workspaceStat = yield* statWorkspaceRoot(\n workspaceRoot,\n normalizedWorkspaceRoot,\n \"validate-existing\",\n );\n if (!workspaceStat && options?.createIfMissing) {\n yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(\n Effect.mapError(\n (cause) =>\n new WorkspaceRootCreateFailedError({\n workspaceRoot,\n normalizedWorkspaceRoot,\n cause,\n }),\n ),\n );\n workspaceStat = yield* statWorkspaceRoot(\n workspaceRoot,\n normalizedWorkspaceRoot,\n \"verify-created\",\n );\n }\n if (!workspaceStat) {\n return yield* new WorkspaceRootNotExistsError({\n workspaceRoot,\n normalizedWorkspaceRoot,\n });\n }\n if (workspaceStat.type !== \"Directory\") {\n return yield* new WorkspaceRootNotDirectoryError({\n workspaceRoot,\n normalizedWorkspaceRoot,\n });\n }\n return normalizedWorkspaceRoot;\n });",
+ "checksum": "dc1befa9f427fd48c5c9988360c52a9532a82d89a2e243b0dee2c25f2794fc12"
+ },
+ "project-create-normalization": {
+ "id": "project-create-normalization",
+ "path": "apps/server/src/orchestration/Normalizer.ts",
+ "start": 55,
+ "end": 90,
+ "language": "typescript",
+ "label": "Project creation normalization before dispatch",
+ "code": " const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>\n workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(\n Effect.mapError(\n (cause) =>\n new OrchestrationDispatchCommandError({\n message: cause.message,\n }),\n ),\n );\n\n const normalizeProjectWorkspaceRootForCreate = (\n workspaceRoot: string,\n createIfMissing: boolean | undefined,\n ) =>\n workspacePaths\n .normalizeWorkspaceRoot(workspaceRoot, {\n createIfMissing: createIfMissing === true,\n })\n .pipe(\n Effect.mapError(\n (cause) =>\n new OrchestrationDispatchCommandError({\n message: cause.message,\n }),\n ),\n );\n\n if (canonicalCommand.type === \"project.create\") {\n return {\n ...canonicalCommand,\n workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(\n canonicalCommand.workspaceRoot,\n canonicalCommand.createWorkspaceRootIfMissing,\n ),\n createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,\n } satisfies OrchestrationCommand;",
+ "checksum": "6b0a20d1e9548a92779defd07120ed3e684de23de08d6de2f159a36edf6b1f57"
+ },
+ "project-root-uniqueness": {
+ "id": "project-root-uniqueness",
+ "path": "apps/server/src/orchestration/commandInvariants.ts",
+ "start": 75,
+ "end": 97,
+ "language": "typescript",
+ "label": "Active project workspace-root uniqueness invariant",
+ "code": "export function requireActiveProjectWorkspaceRootAbsent(input: {\n readonly readModel: OrchestrationReadModel;\n readonly command: OrchestrationCommand;\n readonly workspaceRoot: string;\n readonly exceptProjectId?: ProjectId;\n}): Effect.Effect {\n const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);\n const existingProject = input.readModel.projects.find(\n (project) =>\n project.deletedAt === null &&\n normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&\n project.id !== input.exceptProjectId,\n );\n if (existingProject === undefined) {\n return Effect.void;\n }\n return Effect.fail(\n invariantError(\n input.command.type,\n `Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,\n ),\n );\n}",
+ "checksum": "deb6be62e500f8c6488c70dc0a2563c7f313722d5a4dc04e4c5e9aab21b4c134"
+ },
+ "project-t3-file-schema": {
+ "id": "project-t3-file-schema",
+ "path": "packages/contracts/src/t3ProjectFile.ts",
+ "start": 7,
+ "end": 94,
+ "language": "typescript",
+ "label": "Checked-in t3.json project configuration contract",
+ "code": "/** File name of the checked-in T3 project file, resolved at the workspace root. */\nexport const T3_PROJECT_FILE_NAME = \"t3.json\";\n\n/** Public URL of the published JSON Schema for {@link T3ProjectFile}. */\nexport const T3_PROJECT_FILE_SCHEMA_URL = \"https://t3.codes/schema/t3.json\";\n\nconst T3_PROJECT_FILE_PATH_MAX_LENGTH = 512;\nconst T3_PROJECT_FILE_MAX_SCRIPTS = 50;\n\n// Annotations go on the encoded (string) side so they survive into the\n// published JSON Schema; decoding still trims and re-validates non-emptiness.\nconst trimmedNonEmpty = (annotations: { readonly description: string }, maxLength?: number) => {\n const annotated = Schema.String.annotate(annotations);\n const encoded =\n maxLength === undefined\n ? annotated.check(Schema.isNonEmpty())\n : annotated.check(Schema.isNonEmpty(), Schema.isMaxLength(maxLength));\n return encoded.pipe(Schema.decodeTo(encoded, SchemaTransformation.trim()));\n};\n\nexport const T3ProjectFileScript = Schema.Struct({\n name: trimmedNonEmpty({\n description: \"Display name for the script, shown in the T3 Code scripts menu.\",\n }),\n command: trimmedNonEmpty({\n description: \"Shell command executed in a T3 Code terminal at the project root.\",\n }),\n icon: Schema.optionalKey(\n ProjectScriptIcon.annotate({\n description: 'Icon shown next to the script in the scripts menu. Defaults to \"play\".',\n }),\n ),\n runOnWorktreeCreate: Schema.optionalKey(\n Schema.Boolean.annotate({\n description:\n \"When true, the script runs automatically after a worktree is created for a new thread.\",\n }),\n ),\n previewUrl: Schema.optionalKey(\n trimmedNonEmpty({\n description:\n \"URL opened in the in-app browser preview when this script runs. Only honored on the desktop build.\",\n }),\n ),\n autoOpenPreview: Schema.optionalKey(\n Schema.Boolean.annotate({\n description:\n \"When true, automatically open the preview panel at `previewUrl` the moment the script starts.\",\n }),\n ),\n}).annotate({\n description: \"A project script that team members can import into T3 Code.\",\n});\nexport type T3ProjectFileScript = typeof T3ProjectFileScript.Type;\n\nexport const T3ProjectFile = Schema.Struct({\n $schema: Schema.optionalKey(\n Schema.String.annotate({\n description: `URL of the JSON Schema for this file, typically \"${T3_PROJECT_FILE_SCHEMA_URL}\".`,\n }),\n ),\n iconPath: Schema.optionalKey(\n trimmedNonEmpty(\n {\n description:\n 'Workspace-relative path to the project icon (e.g. \"assets/logo.svg\"). Checked before T3 Code\\'s built-in icon locations.',\n },\n T3_PROJECT_FILE_PATH_MAX_LENGTH,\n ),\n ),\n defaultThreadEnvMode: Schema.optionalKey(\n ThreadEnvMode.annotate({\n description:\n 'Where new threads start for this repository: \"worktree\" for a fresh git worktree, \"local\" for the current checkout. A per-project setting in T3 Code overrides this; when neither is set, the global default applies.',\n }),\n ),\n scripts: Schema.optionalKey(\n Schema.Array(T3ProjectFileScript)\n .annotate({\n description: \"Project scripts shared with everyone who opens this repository in T3 Code.\",\n })\n .check(Schema.isMaxLength(T3_PROJECT_FILE_MAX_SCRIPTS)),\n ),\n}).annotate({\n title: \"T3 project file\",\n description:\n \"Checked-in project configuration for T3 Code (t3.json at the repository root). See https://t3.codes for documentation.\",\n});",
+ "checksum": "9b60c876a679d515b8a414916f3f37d5b8e502a68d55df9d21ee476d8cb4e379"
+ },
+ "project-t3-file-loader": {
+ "id": "project-t3-file-loader",
+ "path": "apps/server/src/project/T3ProjectFileLoader.ts",
+ "start": 42,
+ "end": 105,
+ "language": "typescript",
+ "label": "Best-effort t3.json loading and validation",
+ "code": " /**\n * Load and decode `t3.json` at the workspace root.\n *\n * Never fails: missing, unreadable, or invalid files resolve to\n * `Option.none` (invalid files are logged as warnings).\n */\n readonly load: (workspaceRoot: string) => Effect.Effect>;\n }\n>()(\"t3/project/T3ProjectFileLoader\") {}\n\nconst logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) =>\n Effect.logWarning(error).pipe(\n Effect.annotateLogs({\n operation: error.operation,\n workspaceRoot: error.workspaceRoot,\n filePath: error.filePath,\n errorTag: error._tag,\n }),\n );\n\nexport const make = Effect.gen(function* () {\n const fileSystem = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n\n const load: T3ProjectFileLoader[\"Service\"][\"load\"] = Effect.fn(\"T3ProjectFileLoader.load\")(\n function* (workspaceRoot) {\n const filePath = path.join(workspaceRoot, T3_PROJECT_FILE_NAME);\n const raw = yield* fileSystem.readFileString(filePath).pipe(\n Effect.map(Option.some),\n Effect.catchTags({\n PlatformError: (error) =>\n error.reason._tag === \"NotFound\"\n ? Effect.succeed(Option.none())\n : logT3ProjectFileLoadError(\n new T3ProjectFileLoadError({\n operation: \"read\",\n workspaceRoot,\n filePath,\n cause: error,\n }),\n ).pipe(Effect.as(Option.none())),\n }),\n );\n if (Option.isNone(raw)) {\n return Option.none();\n }\n return yield* decodeT3ProjectFileJson(raw.value).pipe(\n Effect.map(Option.some),\n Effect.catchTags({\n SchemaError: (error) =>\n logT3ProjectFileLoadError(\n new T3ProjectFileLoadError({\n operation: \"decode\",\n workspaceRoot,\n filePath,\n cause: error,\n }),\n ).pipe(Effect.as(Option.none())),\n }),\n );\n },\n );\n\n return T3ProjectFileLoader.of({ load });",
+ "checksum": "1a2c82901fba9d86213563abdee2569b7f48283533b7c7cc23b5bfd46b7df753"
+ },
+ "project-t3-file-loader-tests": {
+ "id": "project-t3-file-loader-tests",
+ "path": "apps/server/src/project/T3ProjectFileLoader.test.ts",
+ "start": 29,
+ "end": 88,
+ "language": "typescript",
+ "label": "t3.json JSONC, missing-file, and invalid-input tests",
+ "code": "it.layer(TestLayer)(\"T3ProjectFileLoader\", (it) => {\n describe(\"load\", () => {\n it.effect(\"loads and decodes a valid t3.json\", () =>\n Effect.gen(function* () {\n const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n const cwd = yield* makeTempDir;\n yield* writeProjectFile(\n cwd,\n `{\n // JSONC is tolerated\n \"iconPath\": \"assets/logo.svg\",\n \"scripts\": [{ \"name\": \"Dev\", \"command\": \"pnpm dev\" }],\n }`,\n );\n\n const loaded = yield* loader.load(cwd);\n\n expect(Option.isSome(loaded)).toBe(true);\n if (Option.isSome(loaded)) {\n expect(loaded.value.iconPath).toBe(\"assets/logo.svg\");\n expect(loaded.value.scripts).toEqual([{ name: \"Dev\", command: \"pnpm dev\" }]);\n }\n }),\n );\n\n it.effect(\"returns none when t3.json is missing\", () =>\n Effect.gen(function* () {\n const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n const cwd = yield* makeTempDir;\n\n const loaded = yield* loader.load(cwd);\n\n expect(Option.isNone(loaded)).toBe(true);\n }),\n );\n\n it.effect(\"returns none for malformed JSON without failing\", () =>\n Effect.gen(function* () {\n const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n const cwd = yield* makeTempDir;\n yield* writeProjectFile(cwd, \"{ not json\");\n\n const loaded = yield* loader.load(cwd);\n\n expect(Option.isNone(loaded)).toBe(true);\n }),\n );\n\n it.effect(\"returns none for schema-invalid files without failing\", () =>\n Effect.gen(function* () {\n const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n const cwd = yield* makeTempDir;\n yield* writeProjectFile(cwd, '{ \"scripts\": [{ \"name\": \"Dev\" }] }');\n\n const loaded = yield* loader.load(cwd);\n\n expect(Option.isNone(loaded)).toBe(true);\n }),\n );\n });",
+ "checksum": "e86ba3069d84308153516d912b05407d54ea3630b7ad2b1a21efb1fe37fb344f"
+ },
+ "project-thread-env-precedence": {
+ "id": "project-thread-env-precedence",
+ "path": "packages/shared/src/threadEnvMode.ts",
+ "start": 3,
+ "end": 35,
+ "language": "typescript",
+ "label": "Project, t3.json, and global thread-environment precedence",
+ "code": "/**\n * Canonical priority order for a project's default thread env mode:\n * per-project setting > checked-in t3.json > global server setting.\n *\n * An explicit composer pick outranks all of these; callers apply it before\n * consulting the defaults. Web resolves the sources imperatively at draft\n * creation, mobile reactively — both must route through this function so the\n * platforms cannot disagree on the order.\n */\nexport function resolveDefaultThreadEnvMode(sources: {\n readonly projectSetting: ThreadEnvMode | null | undefined;\n readonly projectFile: ThreadEnvMode | null | undefined;\n readonly globalDefault: ThreadEnvMode;\n}): ThreadEnvMode {\n return sources.projectSetting ?? sources.projectFile ?? sources.globalDefault;\n}\n\n/**\n * True once the resolved default can no longer change: an explicit pick or a\n * source that outranks t3.json decided, or the file read settled. While\n * false, nothing may persist the provisional default (for example into a\n * draft's workspace selection) — it could differ from the final value.\n */\nexport function isDefaultThreadEnvModeSettled(sources: {\n readonly explicitMode: ThreadEnvMode | undefined;\n readonly projectSetting: ThreadEnvMode | null | undefined;\n readonly projectFilePending: boolean;\n}): boolean {\n return (\n sources.explicitMode !== undefined ||\n sources.projectSetting != null ||\n !sources.projectFilePending\n );",
+ "checksum": "f92aec71fc3a12aa186ad667b7a2e1adb8ac4e560f6f6376511e4b0765ee7851"
+ },
+ "project-settings-inherited-default": {
+ "id": "project-settings-inherited-default",
+ "path": "apps/web/src/components/settings/ProjectSettingsPanel.tsx",
+ "start": 475,
+ "end": 482,
+ "language": "tsx",
+ "label": "Inherited project environment default in web settings",
+ "code": " const t3File = useT3ProjectFileState(\n selectedCheckout.environmentId,\n selectedCheckout.workspaceRoot,\n );\n // What the \"Default\" option resolves to while no override is set: the\n // repo's t3.json value when present, otherwise the global setting.\n const inheritedEnvMode = t3File.file?.defaultThreadEnvMode ?? settings.defaultThreadEnvMode;\n const inheritedEnvModeSource = t3File.file?.defaultThreadEnvMode != null ? \"t3.json\" : \"global\";",
+ "checksum": "7ab6370096f28cd8e0175e8d2a40f3e7e4e29a087f725975228b5ffdff9f68a2"
+ },
+ "project-settings-project-override": {
+ "id": "project-settings-project-override",
+ "path": "apps/web/src/components/settings/ProjectSettingsPanel.tsx",
+ "start": 866,
+ "end": 905,
+ "language": "tsx",
+ "label": "Project environment override controls",
+ "code": " setDefaultThreadEnvMode(null)}\n />\n ) : null\n }\n control={\n