Skip to content

Conductor & coding agent ​

Path: services/conductor
Role: Everything between a workspace id and a running build session: container, Pi Durable coding agent (OpenCode until #546), preview, LLM proxies, deploy, metering.

Shape (ADR: build-plane-runtime) ​

  • One WorkspaceDO per workspace (name = workspace id = container identity). Extends Cloudflare DurableObject (native path) or, on staging/prod until cutover, the legacy @cloudflare/sandbox Sandbox base.
  • Pi Durable behind the Agents SDK PiHarness, hosted in the DO isolate (coding-agent/pi/), not as a long-lived process in the container. Replaced OpenCode v2 in #546; see Coding agent: Pi Durable.
  • Container: real shell, vite, bun run build, LSP. /workspace is plain disk (a disposable replica), not a FUSE mount.
    • Native (scheduling_policy: "durable_object", landed #239): NativeContainerHost drives ctx.container (ensureStarted on digest-pinned images.agent, monitor() rehydrate, idle stop). I/O is native-io.ts over ctx.container.exec (scripts on stdin). Image entrypoint is tini -- sleep infinity — no root /sandbox HTTP server. Builder commands run under setpriv (clear all caps + NoNewPrivs); confinement probe fails closed.
    • Legacy (Sandbox SDK): entrypoint /sandbox; still what staging and prod run until cutover.
  • Workspace sync (landed #115): one-way, DO-authoritative. The DO Workspace SQLite store is the only authority for source files. Plan/contracts: docs/plans/workspace-sync-b.md. On native, sync I/O uses createNativeIo (must bypass WorkspaceDO’s own exec/fs overrides).
  • Template + node_modules baked in the agent image under /opt; node_modules and other derived paths never sync.

Coding agent: Pi Durable (PiHarness) (#546, merged) ​

Merged #546 (yoni-monday, 2026-10-07 14:00 IDT, merge 716c8706; +19,650/−30,882 across 303 files). OpenCode is gone. The only coding-agent loop in the WorkspaceDO is now Pi Durable (@earendil-works/pi-durable 1.0.4) behind the Agents SDK's PiHarness ([email protected], agents/harness/pi), running on a Lifecycle bound to the WorkspaceDO. There is no flag, no second runtime, and no /oc route left. @opencode-ai/* is removed from the conductor, the studio and packages/rpc. Design, parity table and risks: docs/plans/piharness-experiment.md; traps: gotchas/piharness.md.

Why: measured in workerd (V8) on the same scripted workload, Pi vs OpenCode: V8 heap after 31 turns 30.9 vs 79.7 MiB, boot CPU 27 vs 201 ms, steady-turn CPU 23 vs 61 ms, worker bundle 7.8 vs 17.4 MB. Durability is Pi's own (transcript, inbox, tool calls and recovery live in Pi's tables), so about 2,000 lines of form, inbox and repair code were deleted.

PieceNow (after #546)
WireStudio, the MCP conversation, e2e scripts and evals speak a thin Brilliant wire, /w/:ws/agent/* (packages/rpc): Pi's own AgentEvents byte for byte plus Brilliant frames (session, forms, tasks, revert, prompt). GET events is SSE opening with a session frame then Pi's snapshot. Pi has no replay cursor, so a reconnect starts from a fresh snapshot; the server ends streams cleanly on the proof lifetime and the client reconnects
Request pathroutes/agent.ts (token, guard, signed builder proof) → WorkspaceDO /__agent/* → do/agent-dispatch.ts (tombstone, builder proof, actor reservation, prompt pin) → coding-agent/pi/wire.ts → AgentRuntime (pi/runtime.ts)
AlarmThe Lifecycle and the 30 s heartbeat both want "the" alarm. do/alarm-mux.ts gives each a persisted slot and the physical alarm is the earliest; do/workspace-alarm.ts runs both. The DO uses new Lifecycle(host), not Lifecycle.install(this), because installHandlers skips the DO's own fetch/alarm
ToolsPi's read (returns images too) / write / edit / bash over a container ExecutionEnv, plus Brilliant glob / grep / question and all Brilliant tools from tools/*.ts. GPT models get apply_patch instead of edit/write. Skills via activate_skill / read_skill_resource. Long bash output (over 2,000 lines or 50 KB) is saved to /workspace/.brilliant/tmp/bash-*.log (DO only, read it with read, newest 10 kept)
StopReturns at once and bash is killed. Other tool bodies (typecheck, run_script, install_package, integrations) keep running detached, and the workspace stays reserved until they settle (bounded at 10 min). A third-party write the user stopped still completes
RecoveryPi owns it: replay-safe tools (read-only tools, write, question, update_tasks, suggest_next) re-run after an eviction; every other tool gets Pi's interrupted result and the model is told to look before repeating. run_script is never re-run. The question tool keys its form by Pi tool call, so a rerun finds the same form; orphaned approval forms of non-replay tools are cancelled at boot
IdentityA prompt is pinned to its verified caller by (session, request id) before Pi sees it; a tool call resolves its run's first input → pi_submissions.request_id → pin. Same admission and actor-reservation contracts as before, now read from Pi's tables
BillingEach terminal model response goes to the same usage outbox from the afterResponse hook; reconcile rebuilds from pi.assistant entries. Compaction is not billed, as before. Fixed by #653 (merged 2026-10-08, 8b0cd880, fixes #638): the stored generation context always has model: "" (the model isn't known at beforeRequest), and before the fix the reconciler billed from it, so every rebuilt step was refused by ingest (400 model is required) and never billed. #653 takes the model from the committed pi.assistant entry (step.model || context.model || "unknown", same as the live hook) and skips zero-token steps like pi/billing.ts does. Never bill from the stored context's model alone
UndoGit checkpoint per prompt (each prompt carries changedFiles and endCheckpoint); commit forks the Pi session before the prompt. Granularity is now per prompt, not per step
ModelsEvery model call goes through Brilliant's in-isolate LLM proxy as one pi-ai provider (pi/models.ts). gpt-6.1-sol uses openai-responses, other OpenAI/xAI models openai-completions; Gemini uses pi-ai's google-vertex adapter inside a request-scoped fetch (pi/llm-fetch-scope.ts), with a targeted MALFORMED_FUNCTION_CALL retry
CompactionPi's LLM summary compaction (verified live); the studio shows a divider
OtherLangSmith chat spans carry the full request; memprobe samples each tool; a stuck model request fails before the alarm's 15-minute cut

Verified: bun run verify green, 1,930 conductor tests, test/pi/workerd/check.ts inside workerd. Live on side env pi: scripts/e2e/piharness-live-check.ts on Claude Opus 5.5, GPT-6.1 Sol and Gemini 3.8 Flash; bun scripts/e2e-smoke.ts --env pi all green; compaction check; image attachment; a question card survived a real conductor deploy (scripts/e2e/piharness-question-deploy-check.ts).

Fixed since: #573 (MCP get_turn read a Stop before the first token as an error on later reads) was fixed by #578 (merged 2026-10-07), which adds Pi's per-prompt outcome to AgentPromptMeta, see MCP. Still open: live runs of the other OpenAI/xAI and Workers AI models. Pi Durable is "experimental" and PiHarness is beta; the branch depends on Pi internals (JSON-encoded request_ids in pi_submissions), and test/pi/pi-tables.test.ts fails loudly if a Pi bump renames them. The ADRs build-plane-runtime.md and coding-agent-harness.md still describe OpenCode.

Reading the older sections below: anything that names OpenCode, /oc, oc-dispatch.ts, durable-forms.ts / form-recovery.ts, or the billing plugin describes the pre-#546 runtime. The guarantees mostly carried over (see the plan's parity table), but the code paths did not.

Workspace sync ​

Replaces computerd/FUSE and two-way DOFS sync (option (a): keep computer's Workspace as the DO store, no backends).

DirectionBehaviour
DO → containerEvery DO mutation (tool write, /fs PUT, git checkout for undo) goes through one ordered FIFO; pushFs() resolves after those mutations are on disk.
Container → DOAfter every exec, a manifest diff pulls container changes before the exec returns. Between execs, an inotify watcher (via syncd / inotify-tools; native: ctx.container.exec watcher) pulls targeted writes (e.g. routeTree.gen.ts). Watch pulls wait while an exec runs.
ConflictsA pull never overwrites a path whose DO seq moved past the exec start; the DO version wins and is pushed back. Deletes are tombstones until no older exec is running.
HydrateFresh container: seed / unpack / reattach, then syncd reconcile for declared packages. A hydration marker on container disk guards reads so a replaced container is never pulled. Exec starts the container before the hydration check (#267 / issue #267); mid-hydrate replacement refuses “hydrated” and only writes the marker where the claim file survives.
Agent I/OLegacy: pooled Sandbox SDK sessions (one-op-per-session), separate from sync I/O. Native: ctx.container.exec via native-io.ts.

Synced vs derived: never sync node_modules, .git (push-only from DO), dist, .vite, .tanstack, .wrangler, .output, or most of .brilliant/** (except .brilliant/installed.json). The push filter is IGNORED_BRILLIANT in services/conductor/src/workspace/sync/paths.ts (shared with infra/agent-image/syncd.mjs). Exception (#406): root .brilliant/skills is push-only like .git — hydrate and DO writes push it; it is never pulled (isSyncedPath / syncd still reject it). A deps.fs write under any other .brilliant/ path still never reaches the container via pushFs().

Live check: bun scripts/e2e/sync-live-check.ts --env <side-env> (verified 20/20 on sync-b).

run_script writes inside the exec (#402, merged; fixes #399) ​

Builds seed sample data with the coding-agent tool run_script (services/conductor/src/coding-agent/tools/run-script-tool.ts). Scripts live under /workspace/.brilliant/scripts/<ts>.ts, which the push filter does not send to the container.

PieceBehaviour
Bug (pre-#402)Tool wrote via deps.fs then pushFs(); filter dropped the file → every run_script failed with Module not found "/workspace/.brilliant/scripts/<ts>.ts" and boards stayed half-filled
FixThe exec command itself writes the script: mkdir -p then printf '%s' '<base64>' | base64 -d > <path>, then bun <path> — same pattern as hydrate-steps.ts
Why base64Keeps UTF-8 intact and is shell-safe inside single quotes; native exec sends the command on stdin, so a 32 KB script stays clear of argv limits
Still calledpushFs() runs first so earlier-in-turn collection edits still reach the container; .brilliant/ stays unsynced and the DO no longer collects one dead script file per call
CleanupEXIT trap rm -f removes the script on normal exit; a timeout kill can leave one file behind
Skills (later)read / glob on /workspace/.brilliant/skills/... was open as #403 (split from #399); addressed in #406 — see Skills push-only

Tests: run-script-tool.test.ts runs the generated command in real bash (paths → tmp dir, bun → cat) and asserts the on-disk bytes match buildScriptSource(code) including é, ☕, ', $HOME, backticks. Not verified live (side-env image reuse still blocked by #277 / #319).

See Troubleshooting — Workspace sync and Common stalls for the transcript symptom.

Skills push-only (#406, merged; addresses #403) ​

Native containers have no FUSE mount: a file reaches the container only by sync push. Skills are seeded into the DO store under /workspace/.brilliant/skills (skills-seed.ts from @brilliant/harness).

PieceBehaviour
Push eligibilityRoot .brilliant/skills is push-only (isSkillsPath / isPushEligiblePath), like .git
Never pullisSyncedPath and syncd’s ignore list still reject the tree — a container edit cannot overwrite the DO copy
Fresh storeA store holding only skills is still a fresh workspace: hydrate seeds the template; skills are written into the DO before the first command
Reattach repairHydrate compares sha1sum of the container’s skills tree with the DO’s and repairs when unhydrated DO writes never reached a reattached container
Fail closedRepair fails the hydrate when .brilliant or .brilliant/skills is a symlink, when inventory/prune fails, or when inventory cannot be parsed (builder owns those paths; listing/rm through a link would hit application files)
Other .brilliant/Logs, dev-*.active, scripts stay container-local — still not pushed (use in-exec writes, e.g. #402 run_script)

GOTCHAS: gotchas/containers.md (“Skills read File not found”). Live occap verification of built-in/custom container read/glob after deploy was still called out as required on the PR.

Adopt / heartbeat observation (#406, merged) ​

blockConcurrencyWhile around containerHost.adopt() resets the DO if the callback outlasts ~30s. Safety timeout and heartbeat arm (onReady / storage getAlarm/setAlarm) are bounded and run together; container.adopted logs the time. A late storage settlement after the bound stops waiting logs container.on_ready_settled_late (outcome, ms) — observation only; it does not cancel, retry, or rearm. While the heartbeat alarm is unarmed, the only idle stop is CONTAINER_INACTIVITY_SAFETY_MS if setSafetyTimeout succeeded.

Long heartbeat alarm stages log alarm.step_slow / alarm.step_settled_late (boot, list_pending_forms, sync_deadlines, expire_due) without changing resume/cancellation semantics. Pre-event snapshot / media waits similarly observe after 15s (snapshot.capture.phase_slow / context_hook.phase_slow + …phase_settled_late) with no new timeout, race, or retry behaviour. New observer logs do not inspect rejection objects or payloads.

GOTCHAS: gotchas/containers.md (adopt bound) · gotchas/opencode-and-turns.md (silent turn / phase observation).

Native durable_object containers (#239, merged) ​

Moves the conductor off the Sandbox SDK and the root /sandbox server. Live probe: time to first command p50 986ms → 507ms (300 randomized starts). Staging and prod are not switched yet — only side envs deploy natively for now.

PieceBehaviour
HostNativeContainerHost (container-host-impl.ts): single-flight ensureStarted, monitor() → rehydrate, 10-minute idle deadline checked by the DO alarm
Idle clockLast real activity persisted in DO KV. The DO can be evicted mid-idle while the VM keeps running; an in-memory clock never expires on adopt
I/Onative-io.ts: exec / readFile / writeFile / inotify watcher over ctx.container.exec
ConfinementBuilder under setpriv (clear caps + NoNewPrivs); probe fails closed. UID alone is not confinement
TimeoutsSignal → await exit → kill tagged survivors → recycle VM only if something survives; timed-out changes are never pulled back
ImageNo /sandbox; entrypoint tini -- sleep infinity. Apt/Node/Bun split across layers so prepared blobs stay under ~200 MiB (#192). Push fails if any layer exceeds 110 MB compressed
WranglerDeployable workers on 4.145 (named-image preparation); packages/template stays on 4.125
Deploy gateconductor.sh refuses scheduling_policy: "durable_object" unless --native is passed. Digests are never trusted from a rendered config — registry tags (<sha12> / dirty) are the record
Sync shellSync rm/chown use shQuote (not JSON.stringify); hostile filenames covered by a real-shell test. Workspace ops that touch builder-writable paths run as builder, not root

Verified on side env containers: e2e five pillars + smoke 5/5 PASS; warm start → first answered command 184 ms; idle stop ~10m24s after last use; same-class migration drained then deleted the legacy default-policy app.

Not in #239 / still open: rolling staging+prod (#185, #187); snapshot resume needs reconciliation (#186); #235 image reuse on native (#276 merged the findReusableImage digest-pin guard; true tag → digest reuse landed in #538, merged 2026-10-07, see Side environments); #237 publish 409 after a turn. #238 / #262 (kill() after exit) fixed in #251 + #263 — see Tool / driver kill.

GOTCHAS (gotchas/containers.md): UID ≠ confinement / root relay; named images must be prepared (Wrangler ≥4.145) or monitor() says “Image not found”; ~200 MiB prepared per-layer schedule cap; idle clock across DO eviction; JSON.stringify shell injection + symlink-followed root sync.

Spike evidence that established the decision lives in git at 8c88636b and 9eff910d (removed from the merge branch once conductor itself verified).

Placement failure backoff (#268 via #295, merged) ​

Alarm storms from Cloudflare container placement (“no container instance” / “throttling the container service”) no longer retry every tick.

PieceBehaviour
ClassifierisContainerPlacementFailure walks the cause chain for those strings
ReadinessLoop stops on the first placement failure (container.placement_failed)
Start retryBacks off 15 / 30 / 60 s
AlarmBacks off 60 s → 10 min (alarmPlacementBackoffMs, persisted). Cleared on a successful boot or lease renewal
Contractsalarm-backs-off-on-placement-failure, lease-renewal-ends-placement-backoff

Caveat: the 2026-10-01 incident ran the pre-native Sandbox SDK build; #295 hardens the native path that side envs run now. Live placement failure still cannot be forced on a side env; backoff progression is covered by test/do/preview-lease-alarm.test.ts and readiness bail-out by test/do/container-host-impl.test.ts.

Cold-wake hydrate-before-start (#267 via #295, merged) ​

Symptom was a cold-wake preview probing NONE / empty disk after the container vanished unnoticed.

PieceBehaviour
Race (fixed)pipeExecResult used to read the sync engine’s in-memory hydrated flag before the command’s ensureStarted(); a vanished container was restarted after the check, so the probe ran on empty disk
Order nowExec is counted in-flight and the container is started before the hydration check (exec-starts-container-before-hydration-check)
Mid-hydrate replaceEngine refuses to report hydrated if replaced mid-hydrate; marker is written only where its claim file survives (hydrate-observes-replacement)
Dev-server probeLogs dev.layout_probe_none and recovers by replacing the container when the DO store still has the app
Busy deferral (#406)When the store has the app, the container lacks it, and an exec is in flight, recovery refuses to replace (would kill the command) and the preview answers waking. That throws the fixed message dev_layout_pending: exec_in_flight (dev.layout_probe_none with reason: "exec_in_flight", then dev.proxy_failed with reason: "layout_pending"). Only that exact deferral is treated as expected and not sent to Sentry. Every other dev_layout_missing (no app in store, replacement unavailable, still missing after replace) remains reportable. This explains reporting of the busy path only — not why a cold wake sometimes finds an empty container

Verified on side env issues: workspace idle 20 min (container destroyed) → preview document: container.start → container.ready → fresh hydrate (claim /tmp/.workspace-hydrating-…), first response 200 in ~10 s, no waking 503, no dev.layout_probe_none / dev.proxy_failed.

Isolate memory — bounded session rereads (#289 via #295, merged) ​

Long turns were blowing isolate memory by rescanning session / sync state. Bounded loaders + cheaper walks:

AreaBehaviour
RepairParses only unfinished tool rows bounded by the last local compaction
Plan-build gateLoaded only the rows it inspected (parity test gate-loader-matches-full-scan). Gate and contract deleted in #520
TracingTruncates at parse time, drops image base64, caps the queue at 2 and only while a turn exists
Sync walkPer-exec live walk no longer enters .git (list-live-walks-git-only-to-push)
Turn endBilling / memprobe maps cleared
MemprobeSamples sessionBytes vs contextBytes so the next reset can be attributed

Side findings: #293 plan-build gate never fired in prod (stored messages carry no type), resolved by removing the gate in #520 (merged 2026-10-06); #294 tracing retry misalignment (open).

Verified on issues: one prompt → 40 tools / 24 model steps / 3 new pages finished with no isolate reset; memprobe at turn.end showed sessionBytes = contextBytes and sampleMs 0.

Major surfaces ​

SurfacePurpose
/w/:id/oc/**OpenCode API proxy (studio)
/w/:id/dev/**Live preview + HMR. /dev/<segment> is an app only if the workspace has apps/<segment>; otherwise it is a route of web (#511, merged)
POST /w/:id/warmPre-start container/dev server on workspace open (#308, merged)
/llm/**, /langsmith/**Proxies — credentials stay in Worker. Worker-side only. Since #640 (merged 2026-10-08) they are gone from the container dispatcher, so container code gets 404; see Container egress
/session/deploy, /w/:id/deployPublish pipeline
/w/:id/db/execDraft DB via PlatformData hop (not D1 query REST)
Admin sweep / destroyTeardown

Container egress has no model or LangSmith routes (#640, merged) ​

Merged 2026-10-08 15:13 IDT by yoni-monday (merge dca27ba0). Fixes #282. Before this, any code in a preview container (app server code, user- or agent-written) could call http://brilliant.internal/llm/* and /langsmith. Those calls reached Claude, GPT, Gemini and Workers AI on the platform's gateway credentials with no metering, credit check, rate limit or tenant attribution.

PieceBehaviour now
Container dispatcher (handleContainerRequest, llm/brilliant-proxy.ts)Model and LangSmith routes are gone. /llm/anthropic/…, /llm/openai/…, /llm/v1/chat/completions, /llm/vertex/… and /langsmith/… now return 404 like any unknown path
Coding agent model callsUnchanged. The agent calls models through the in-isolate llm.internal fetch (createLlmProxyFetch), not the container
App code that needs AIUse /ai/*, which the control plane meters and rate-limits
CleanupDead containerBaseUrl() helper removed. docs/ARCHITECTURE.md no longer claims these routes check an llm-session token
TestsNew test: every model/LangSmith path from the container returns 404 and neither fetch nor env.AI.run is called (fails on main). Container-only cases in brilliant-proxy.test.ts and gateway-responses.test.ts dropped; the in-isolate path stays covered in gateway-native.test.ts

Still open: an AI Gateway rate limit (rateLimitingLimit: 0 in infra/pulumi) is left for a human as an infra change.

Verification (from the PR): conductor tsc clean, bun test 1995 pass. On side env sec-batch, curl from inside a running workspace container (via /w/:id/exec): /__ping returned 200 (egress interception armed), all model and LangSmith paths returned 404, and e2e.ts still passed 5/5, so the agent's model path is unaffected.

Follow-up (#648, merged 2026-10-08 15:41 IDT): #640 was merged before its review-fix commit, so these landed separately. The regression test now also hits made-up paths under both prefixes (/llm/new-provider/…, /llm, /langsmith, /langsmith-next/…), so a catch-all /llm or /langsmith handler added later fails it. A new exact-path route would not fail it, so review any new container route by hand. The rule is written down as a gotcha in gotchas/containers.md: never add a model route to brilliant.internal; app code uses /ai/*. The stale llm.ts comment saying the LangSmith proxy is reached through brilliant.internal was fixed. Test and docs only, no behaviour change.

Pre-start on intent / warm (#308, merged) ​

Opening a workspace used to start its container only when the preview iframe finally requested /dev/ (after workspace fetch, token mint, cookie prime). Chat boots OpenCode in the Durable Object and never touches the container, so cold preview waited on that late path.

PieceBehaviour
Conductor POST /w/:id/warmGated: user ws:<id> token or guard; 410 for a tombstoned workspace (via the dispatcher). Answers 202 {"warming":true} at once and runs exactly what the first preview document request runs — ensureDevServer(wsId, "web", llmBaseUrl) — in waitUntil. Never boots OpenCode. Idempotent through ensureDevServer’s in-flight map and 30 s ready memo. Not reported to Sentry (the preview path reports its own failures). Contract warm-is-a-preview-open-without-the-page.
dev.warm logWritten by the Durable Object (warm-logs-its-own-outcome), not the Worker whose waitUntil ends ~30 s after the 202. One line per call: outcome started / ready / probed / failed, plus ms. probed = memo lapsed but Vite still running (distinct from a real launch).
Control plane POST /workspaces/:id/warmSession + current membership in an active tenant (sessionStillActive, #371 merged) + workspace in that tenant, same gate as thumb; 404 / no conductor call otherwise; 202 before the conductor answers; conductor errors only logged. Forwards with the guard. Contract workspace-warm-fire-and-forget.
Studio/w/$workspaceId fires warm from route onEnter + onStay (router-core runs those only from commitMatches, never from a preload), without awaiting, once per workspace per minute. No hover preloading — a pointer sweep over the project grid would start a billable VM per card.
Fresh createNo separate markWorkspaceWarmed — warm’s init and the composer’s /init share the same in-flight promise, and /init never launches Vite. A workspace just created from the composer is already warming via POST /apps init.

Verified on side env issues (conductor + control plane at 551f09c0): cold POST …/w/<id>/warm with the guard → 202 in 0.25 s, DO logged dev.warm outcome=started ms=9156; 12 s later → ready ms=0; 47 s later (memo lapsed, Vite still up) → probed ms=199. GET → 405, no auth → 401. Playwright: hover 800 ms sends nothing; click fires POST /workspaces/<id>/warm at the same instant as GET /workspaces/<id> (202 ~0.3 s later), before POST /tokens and ~1.6 s before the iframe’s first GET /w/<id>/dev/. bun scripts/e2e-smoke.ts --env issues: 6/6 PASS.

See also Control plane — Workspace warm on open.

Dev route: sub-pages are not apps (#511, merged; fixes #116) ​

Merged #511 (yoni-monday, 2026-10-06 09:10 IDT, merge 20a2773d). Before it, reloading the draft preview on a sub-page such as /w/<id>/dev/ui failed with "redirected too many times": the conductor took ui as an app name and 302'd to /dev/ui/, and the web app's router 307'd back to /dev/ui.

PieceBehaviour
Which segments are apps (services/conductor/src/lib/dev-app.ts, resolveDevApp)The first segment after /dev/ is only a candidate app name (router.ts parseRoute appName). The handler asks ensureDevServer which port it resolves to. The dev server already answers with web's port for any name without an apps/<name>/package.json, so a segment that comes back on web's port is a route of web.
Trailing-slash redirect (routes/dev.ts)Resolved before the redirect decision. Only real apps (for example /dev/admin when apps/admin exists) still 302 to /dev/admin/ (contract dev-root-trailing-slash, still turned off by PREVIEW_DEV_BASE_RECOVER=off). Route segments get no redirect and are proxied to web with the full path, nested paths included (/dev/pricing/enterprise). The bare dev root /w/<id>/dev still redirects without asking the dev server.
CachePer isolate: 5 min for a real app, 10 s for a route segment (so an app the agent creates shows up on the next load), max 1000 entries. Document and websocket requests always re-ask (a cached app could outlive one the agent removed); only the module/asset fast path uses the cache.
Not-a-route paths/dev/pricing when the app has no such route returns the app's own 404 page, with no loop.

Contract dev-route-segment-is-not-an-app (owner:yoni-monday, label:operations): a segment that is not an app in the workspace MUST resolve to web, MUST NOT get the trailing-slash redirect, and MUST be proxied with its full path. The answer MUST come from the port the dev server resolves, not from a list of segment names. The gotchas/containers.md entry says the same: do not go back to a denylist of segment names in parseRoute.

Verification: test services/conductor/test/dev-route-segment.test.ts; conductor tsc --noEmit and bun run verify pass. Live on side env fixwave-ebf8: on main /dev/ui looped 302/307, on the branch it returned 200, and a Playwright reload of /w/<id>/dev/ui was one navigation with status 200. Shared staging/prod rollout was not part of the PR.

Tool / driver kill skips exited (#251 + #263, merged) ​

The native Container API raises an uncaught internal error if you signal a process that has already exited. Two kill paths needed the same guard (#238 / #262).

Contract tool-process-kill-skips-exited (owner:yoni-monday, label:operations): once the process exitCode has settled (resolved or rejected), kill() must be a no-op.

PathWhereGuard
Tool handle (#251)openProcess → toolProcessHandle in services/conductor/src/do/opencode-runtime.ts (LSP, shells)Marks exited when exitCode settles; kill() closes stdin best-effort then calls proc.kill() only if not exited. Returns undefined when stdin/stdout missing.
Workspace driver (#263)Explicit kill effect in services/conductor/src/coding-agent/host/workspace-driver.ts (OpenCode process tools on timeout/abort)Returns early when !isRunningBool (cleared in proc.exitCode.finally(...)), matching the scope finalizer in the same file.

Best-effort caveat (both): an exit that exitCode has not reported yet can still be signalled.

Tests: services/conductor/test/tool-process-handle.test.ts (#251); services/conductor/test/opencode-driver.test.ts — kill() does not signal a process that has already exited (#263). Fakes throw if signalled after exit.

Verified: side env fix-224 for #251; side env fix-262 for #263 (e2e 5/5; wrangler tail showed 0 internal error lines during the run).

Coding agent layout ​

Everything agent-shaped lives under services/conductor/src/coding-agent/:

  • pi/ — Pi Durable runtime since #546: runtime.ts (AgentRuntime), wire.ts, models.ts, tools.ts, llm-fetch-scope.ts, billing.ts
  • host/ — shared host pieces (e.g. durable-inbox.ts, detached-work.ts); the OpenCode host was removed by #546
  • tools/ — deploy, create_app, typecheck, search, integrations, …
  • prompts/ — composed system prompt + overlays
  • workspace/ — seed conventions / skills bundle

Contract: coding-agent-is-self-contained in root CONTRACTS (file removed in #592; the design still holds).

Operational truths ​

  • The DO store is authoritative for source; container disk is a replica. Prefer DO reads for “what the platform thinks”; after an exec, pull-back has already landed before return.
  • Image rebuild required when any path in IMAGE_INPUT_PATHS / conductor.sh IMAGE_INPUTS changes (template//opt / syncd / entrypoint, plus baked AGENTS.md and tsconfig.base.json). Prompt/tool and sync-engine Worker code still ship with Worker deploy. Uncommitted image inputs force an image push. Staging/prod selective rebuild covers the full list since #252; IMAGE_INPUT_PATHS ⊆ IMAGE_INPUTS is enforced by test since #274 (see Side environments — Conductor image reuse).
  • Conductor deploys on staging evict running turns (and can replace containers) — verify on a side-env. Since #488 (merged 2026-10-05) there is no idle wait before a conductor deploy or secrets push, so this eviction is unguarded.
  • Follow-ups still open after #115 / #239: undo (per-prompt git checkpoints since #546) + full agent-turn tool writes on a model-enabled side-env; staging/prod native cutover (#185, #187); snapshot resume (#186); native image reuse (#235; #276 merged the digest-pin guard, #538 merged true digest reuse). Kill-after-exit (#238 / #262) is closed by #251 (tool handle) + #263 (workspace-driver kill). Placement backoff / cold-wake hydrate order / bounded session rereads landed in #295 (#268, #267, #289). The /w/<id>/dev/<route> reload loop (#116) is fixed by #511, see Dev route: sub-pages are not apps.

Background deploy / deploy-state ​

Landed in #141 (MCP agents need a durable outcome when publish runs past the client timeout). Studio Publish/rollback stay synchronous.

SurfaceBehaviour
POST /w/:id/deploy?background=1After the same busy / in-progress checks as today (409 workspace_busy / deploy_in_progress), returns 202 { state: "deploying", kind, started_at }; the run finishes in the DO.
POST /w/:id/rollback?background=1Same pattern as deploy.
GET /w/:id/deploy-stateAdds deploying (in memory — cannot stick after an eviction) and last_result { kind, ok, finished_at, version_id?, commit_sha?, error? } (DO storage, written for every run, sync or background; error message ≤300 chars, never a stack).

Without background=1, both routes are unchanged.

MCP side: tools poll this endpoint and recover via get_app — see MCP — Publish / rollback outcome observability.

Eviction gotcha: if the DO is evicted mid-run, the run dies; deploying is gone and callers see idle with the previous last_result.

Screenshots wait for data (#373, merged) ​

Thumbnails (turn-end, published) and POST /w/:id/screenshot used to capture at load plus a fixed 800 ms. Apps that fetch data after load were pictured mid-fetch (“Loading invoices…”, skeletons) — reported from template share cards.

services/conductor/src/lib/page-settled.ts adds settledCaptureOptions(), used by screenshotPreview (thumbs and the screenshot route). Contract: @cc screenshots-wait-for-data.

PieceBehaviour
WaitwaitUntil: ["load", "networkidle2"] — a Vite preview keeps its HMR socket open, so networkidle0 never arrives
Settle markInjected in-page script sets <html data-brilliant-settled> once no loading state has been visible for 500 ms
Loading stateVisible aria-busy="true", .animate-pulse, [data-loading="true"], or .skeleton; or status-shaped text (Loading, Loading…, Loading invoices...). Prose such as “Loading dock schedule” does not count
Permanently busyScript marks timeout after 12 s (SETTLE_GIVE_UP_MS) so a stuck spinner still gets a picture; broken navigation / script that never runs fails
Thumbnails (THUMB_SETTLE)25 s navigation, 15 s selector cap, no bestAttempt — cached; a half-booted page fails and is retried later
Screenshot route first attempt (ROUTE_FIRST_SETTLE)2 s navigation, 3 s settle, bestAttempt: true — must fit the ~5 s an MCP hold leaves after the wake budget
Route re-encodes (ROUTE_RETRY_SETTLE)settleMs: 0 → load + 800 ms (same as before); only the first attempt waits for data
Source formSettle check is source text, not fn.toString(), because the conductor is minified; tests evaluate the same text

Wake / clip (unchanged): the screenshot route accepts wake_ms (MCP caps wake budget at 15s; studio default unchanged). Full-page screenshots clip to 8000×4000 CSS px with clipped: true (header x-brilliant-screenshot-clipped: 1) instead of failing.

Not the same helper: the #358 template share-card OG path waits for data its own way; #384 tracks unifying them.

Live: not yet. Every preview screenshot on side envs currently returns 502 capture_failed (#328); tracked in #385. Unit + mutation tests cover the settle helper; full conductor suite passed on the PR.

Destroy tombstone-first (#241 + #258, merged) ​

A preview that raced teardown could renew a lease and re-init the workspace (orphan D1). Destroy now tombstones first:

  • handleDestroy calls stub.markDestroyed() right after auth (before deleting scripts / D1 / R2).
  • forget() writes destroyedAt as its first line (before awaiting OpenCode close).
  • Gated routes on a destroyed workspace answer 410 labelled gone.
  • Exemptions that must not wake the DO: POST /w/:id/destroy (teardown stays retryable) and GET /w/:id/thumb (R2 only; studio cards no longer wake a DO each).

Ungated /w/:id routes also refuse destroyed (#258, merged) ​

#241 covered gated routes, preview, init, and OpenCode. Ungated handlers that do their own auth still missed the tombstone, so an old token could call them on a deleted workspace (#221).

Contract ungated-routes-refuse-destroyed-workspace (refuseDestroyed in worker-routes.ts):

CallerBehaviour
Authorized + tombstone set410 without running the handler
Anyone else (no / bad auth)Handler runs as usual (401/403); isDestroyed is never called, so an unauthenticated probe cannot wake the DO or learn the id was real

Routes wrapped: db/exec, assets (GET/POST/DELETE), images, files/record, apps, screenshot. Dev POST …/dev/__blob checks the tombstone after its existing auth (contract dev-destroyed-workspace-is-gone).

Telemetry: an ungated tombstone 410 keeps that route’s own label (e.g. db-exec, assets) — it is not relabelled gone (gated-only).

Verified on side env fix-224: authorized probes → 410; no-auth → 401/403 (not 410). Follow-ups: #270 (isDestroyed RPC cost on gated routes / db/exec), #271 (dispatch 410 passthrough), #272 (__blob non-multipart 500).

Thumbs table after forget (#418, merged) ​

Fixes #417. On staging and side envs, thumb.capture / thumb.mirror logged Error: no such table: _brilliant_thumbs (~2s after POST /w/<ws>/destroy) — one event per e2e teardown.

Root cause: ThumbsManager.table() cached tableReady = true on the live WorkspaceDO instance. forget() → wipeWorkspaceStorage → deleteAll() drops _brilliant_thumbs, but the DO (and this.thumbs) stays alive, so a capture that finished after the wipe skipped CREATE and getThumb threw.

Fix (merged): drop the per-instance cache so table() always runs CREATE TABLE IF NOT EXISTS (no-op when the table exists). Chose that over reset() + afterWipe because workspace-do.ts is at the file-size cap, the screenshot path already constructs a fresh uncached ThumbsManager per call, and uncached CREATE IF NOT EXISTS covers any wipe under a live manager without each caller remembering reset().

Also (merged): capture can span forget(), so recreating the table on use would otherwise let a late write put the DO row and R2 card picture that destroy just deleted. Contract thumb-no-write-after-destroy: captureThumb re-reads isDestroyed after the screenshot and before putThumb; mirrorToR2 re-reads before every bucket.put. Once true, neither writes; a failed tombstone read aborts the write.

Repo note in gotchas/containers.md: manager state survives forget()'s wipe; any write that follows an await re-reads the tombstone first.

Live: not yet verified (env:up image reuse still blocked by #277 / #319). After staging conductor deploy, Workers logs should show no _brilliant_thumbs errors after e2e teardown.

Waking / DO-reset & Sentry (#217) ​

Landed in #217 (Sentry triage BRILLIANT-3..8). Transient conductor failures must not look like unexplained 500s in Sentry or to clients.

Response contract ​

CaseClient seesSentry
DO reset / lost container / retryable stub failure (eviction, code update, overload)503 { error: "workspace_unavailable" } + x-brilliant-waking: 1 + retry-after: 2. Incoming CORS headers (e.g. /oc) are kept.Not reported (response telemetry skips waking 503)
Preview proxy failure classified as waking / capacity / etc.Same waking page / 503 path as todayNot reported
Preview start_failed / unexpectedError pathReported once per workspace per 5 min (waking page polls every ~2s — without the throttle this flooded Sentry)
Generated-app dev-server 5xx proxied through conductorPass-through status; x-brilliant-upstream: app on ≥500 from the app (#243; was x-brilliant-app-origin: 1)Not reported (app bug, not platform)
Real platform 5xxFixed message codes in the body (no String(err) echo)Reported with static route tag

Route tags ​

Every conductor route sets a static Sentry route tag (handler label matching /^[a-z-]{1,32}$/). Raw paths, ids, and query strings are dropped by the sanitizer so they never leave the Worker. Filter the brilliant project by route when triaging.

Fixed diagnostic messages ​

Worker telemetry maps known free-text platform errors to fixed strings (no customer/path leakage):

Pattern in exception textReported message
Durable Object reset / code updated / script upgradedDurable Object reset by a new Worker version
Dev server failed to become healthy within 60sDev server health timeout
confinement self-check failedConfinement self-check failed

Anything else stays Exception message omitted (existing minimization).

Cause of DO-reset bursts on secrets push ​

wrangler secret bulk creates a new Worker version and resets every WorkspaceDO (same eviction as a code deploy). From #217, secrets:push for conductor ran wait-for-idle.sh first and failed the push if the env was not idle. #488 (merged 2026-10-05, owner decision) removed that wait and the pre-deploy one in conductor.sh, because on a busy staging it never cleared and CD stopped shipping. Every conductor deploy or secrets push now evicts running turns; clients get the waking 503 and reconnect — see Idle wait removed.

Not yet proven in staging: that retryable / durableObjectReset / overloaded always survive the DO RPC hop in workerd; that BRILLIANT-6 bursts actually stop after the next secrets push (verify in Sentry).

See Troubleshooting — Sentry triage.

OpenCode event stream CPU cap (#372, merged; refs #354) ​

Historical (pre-#546). OpenCode and /__oc/api/event were removed by #546. The Pi wire's GET events stream also ends cleanly (on the proof lifetime) and the client reconnects with a fresh snapshot. See Coding agent: Pi Durable.

Landed in #372 (merged 2026-10-03, yoni-monday). Mitigation for #354 (idle CPU source inside OpenCode still unidentified; not closed).

Prod WorkspaceDO was reset repeatedly while a single /__oc/api/event SSE stayed open for hours with no turn (≈4 ms/s idle CPU over hours, just over the 30 s per-request budget). A Durable Object's CPU budget is per request and only a new request refreshes it, so one long-lived stream is charged for everything in-isolate OpenCode does in the background until the isolate resets.

PieceBehaviour
CaphandleOcRequest wraps GET /api/event responses in capStreamLifetime with OC_EVENT_STREAM_MAX_MS = 10 minutes (services/conductor/src/do/oc-dispatch.ts)
Busy deferralCap must not cut while a turn is executing (deps.isExecuting / BUSY_RECHECK_MS = 30 s); timer re-arms until idle, then ends cleanly
On expiryBody ends cleanly; upstream cancelled
ClientSPA reconnects on clean end (use-opencode-session.ts onDisconnect / subscribeEventStream) — fresh request, fresh CPU budget. Treating the clean end as final breaks chat
ScopeMitigation only; idle CPU source inside OpenCode still unidentified (#354 not closed)

After deploy: prod exceededCpu on /__oc/api/event should stop. Watch for mid-turn “reconnecting” flicker if a reconnect races a finishing turn.

Models & LLM gateway (GPT-6.1 Sol) ​

Landed in #173.

PieceBehaviour
Catalogue / picker / evals nightlygpt-6-sol → gpt-6.1-sol (openai.gpt-6.1-sol on Bedrock). A saved GPT-6 Sol picker choice rewrites to the new id. Old id stays routable on chat for leftover sessions; nothing offers it.
Coding turnsThis model rejects chat-completions tool turns (reasoning_effort: "none" unsupported; function tools require /v1/responses). Since #546 it uses pi-ai's openai-responses API through the in-isolate proxy. Before that, conductor routed it through OpenCode’s Responses package → llm/gateway-responses.ts → AI Gateway aws-bedrock/bedrock-runtime/<region>/openai/v1/responses with system profile us.openai.gpt-6.1-sol. Chat route answers responses_required instead of fetching.
IAMGateway IAM user needs bedrock:InvokeModel on project/default as well as the model profile (infra/pulumi/src/bedrock.ts). Applied on staging with the PR.
Workerd package (pre-#546)Stock @opencode-ai/ai/providers/openai/responses throws Config.redacted at import on our Effect; wrangler aliases it to openai-responses-workerd-shim.ts over openai-compatible-responses. Model entry sets per-model package:.
Transcript clueResponses turns carry providerState.responseId: resp_…; chat would be chatcmpl-….

Prompt: IDENTITY no longer says “Always identify yourself as Brilliant” — the GPT family took it literally and opened every reply with “I’m Brilliant”.

GOTCHAS traps (Mantle vs bedrock-runtime, project ARN 401, un-importable package) are summarised under Troubleshooting. Full text: repo GOTCHAS.md.

Studio chat signal gaps ​

Frontend chat & plan-mode work (#247, merged; brief docs/design/chat-plan-mode/CHAT_PLAN_MODE_BRIEF.md) is driven by events, tool calls, and message fields the conductor already emits. Features without a backend signal were simplified or left out:

Desired UIGap today
Status verbs with rich objectsObjects come from tool names only — no structured “what I’m doing” field
Plan vs build modeNo mode event — stage labels inferred from the first tool calls
Recommended question optionNo structured recommended/default field — parsed from a “(Recommended)” label suffix
Question context / lead-inNo context field — lead-in sentence split out of question text
Reopened answersReopened answer can’t re-answer a closed form → sent as a chat message
RetryNo backend retry action — UI resends the last user message
Preview readyNo preview-ready push — no “App ready” step
Per-block build stagesNone — no processing / abstract-build card yet (build.block.stage still future)

When adding conductor events for studio chat, prefer structured fields over label-parsing so the docked interrupt, status line, and canvas timeline stay honest. Product decisions: Control plane — Chat & plan mode.

Question / plan auto-answer (#317, merged) ​

Server-side deadlines for unanswered question cards and plan approvals. Product behaviour (including the admin Config key and what never auto-answers): Control plane — Server-side question / plan auto-answer.

PieceWhere
HeartbeatExisting WorkspaceDO 30s alarm lists pending forms, arms deadlines, settles past-due ones (question-timeout / question-expiry / question-deadlines)
Defaultsquestion-defaults.ts — recommended option + (default) tag; dismiss when none
Plan approveplan-auto-approve.ts — after #316, approve label only (Approve - start building (default)); no design-style bracket (Look is its own question before propose_plan)
Plan-build gateRemoved in #520 (merged 2026-10-06): plan-build-gate*.ts deleted, nothing refuses writes or shell commands before approval. See Control plane — No plan-build gate
Agent plan skillplan-with-user: section titles follow question headers, Overview last, connections never block, progress via update_tasks not plan.md markers (#316)
Config@brilliant/config QUESTION_AUTO_ANSWER_SECONDS; conductor wrangler binds CONFIG_KV (side envs too)

Since #546: the question tool is replay-safe and keys its form by Pi tool call; the deadline auto-answer runs on the alarm (expireQuestions) with the same timeout reader. Pre-#546 trap (OpenCode): do not listen for form.* on the plugin event bus or use form.request.list — see gotchas/opencode-and-turns.md. Poll session.active() + form.list({ sessionID }).

Product UI for Plan mode canvas / chat widget: Control plane — Plan mode canvas.

Agent-proposed custom integrations (#369, merged) ​

Conductor tool integration_propose_custom (services/conductor/src/coding-agent/tools/integrations/propose-custom.ts). Returns only { providerId, status, skillPath? } or probe_failed — never key material. Key entry and definition creation live on the control plane; see Integrations.

Template demo bundles (#358, merged with #345) ​

Publish builds a demo script tpl-<versionId> into the demos dispatch namespace (no D1, BRILLIANT_DEMO=1). The template runtime reads each request's demo token from the header. OG capture can screenshot a fresh sample-data demo session. Retire of the previous script is delayed 30 minutes. See Template demos.

Turn recovery across resets (#441, merged; closes #404) ​

Superseded in part by #546. Pi Durable now owns recovery: durable-forms.ts form recovery, inbox recovery and dangling-tool repair (~2,000 lines) are gone; billing feeds the same outbox from Pi's afterResponse hook; deployIntent / deployAudit stay. See Coding agent: Pi Durable.

Adopts Pi Durable recovery patterns around the existing OpenCode harness. A runtime reset or lost response must not strand an accepted prompt, duplicate a write or credit debit, lose an unanswered question, or report an unusable app as successfully published. It does not replace the coding agent or the execution container, and it does not promise exactly-once third-party side effects.

Status: merged 2026-10-04 (yoni-monday). Shared staging and production were not deployed from the PR branch at merge time — cut over with the next conductor/control-plane ship.

ConcernBehaviour
Tool replayRead-only tools may re-run (tool-replay-policy.ts). Uncertain mutations are outcome_unknown so the model inspects state first. run_script is never transport-replayed, including model-selected read mode (that label is not a security boundary). integration_run / non-GET integration_call that threw after send are also unknown. Tools not listed as read-only are unsafe by default.
Inbox / event sequenceDurable inbox + event-sequence recovery and heartbeat ownership. Respects user Stop, unknown storage state, backoff, and workspace tombstones. Versioned event types (session.execution.succeeded.1, …); match the <type>. prefix.
Prompts & studio handoffStable prompt IDs; connected-stream / snapshot handoff with stale-read and overlap guards (session/handoff.ts, prompt-sender.ts, session-connection.ts). The /oc/api/event stream is live-only (no replay cursor) — reconnect must reload session history / outcome / idle and dedupe by event.id.
Native questionsForms live in DO storage (durable-forms.ts), not only OpenCode’s in-memory Form.Service. On resume, OpenCode never reruns stored tool fibers, so form-recovery.ts reopens owed questions (original deadlines kept). Confirmed shutdown ≠ user Stop. Platform approvals are not carried into a replayed mutation. The DO constructor waits for form-aware lazy boot instead of prematurely repairing the original tool.
Usage outboxEffect-backed usage outbox: each completed step is written in the DO before send and resent with a frozen body until control-plane 2xx; 409 / final 4xx stays marked. Rebuild from durable events after reset; usageLedger / checkpoint prevent double billing. Unattributable steps are refused, not guessed. Billing delivery is durable and unbounded. A step already in usageLedger is billed even when its usageStep: context is gone (onUsage deletes it); Since #457 (merged 2026-10-05, fixes #456), reconcile asks the ledger first (UsageReconcileStore.accounted(id) reads usageLedgerKey(id)): an accounted step returns skipped (no log, no enqueue, not counted as enqueued or held, so no extra drain), while the checkpoint still advances past it and prunes its records. Only a step with neither a ledger entry nor a start context is held and logged as usage.reconcile_unattributable. Contract usage-reconciled-from-committed-steps now says a ledger-held step MUST NOT be logged as unattributable; billing rules unchanged. See Troubleshooting. Since the Pi switch (#546), rebuilt steps went out with an empty model and were refused (a refused entry is marked rejected and never resent); #653 (merged 2026-10-08, fixes #638) bills them under the model Pi committed and posts nothing for empty steps. Steps already refused on staging and prod are not resent by the fix.
Publish / deploy intentdeployIntent + frozen deployAudit before provider work. Lost runs settle from script settings / marker or uncertain — never re-run. Unresolved intent → 409 deploy_outcome_unknown. Publish is complete only after access-policy activation (APP_POLICIES); optional Artifacts delivery is durable but does not block status or activation. Provider/activation failures back off and settle explicit non-success after eight failed attempts and thirty minutes (does not lock out future deliberate publishes forever).
Control-plane receiptsMigrations 0030 / 0031: turn_usage_receipts and deployment_receipts keyed by (workspace_id, event_id). Atomic receiver receipts + usage / deployment / credit records. Shared ingest schemas in @brilliant/service-contracts/ingest. Conflicting bodies → 409.
Model policy (AGENTS.md)Names the model, not a provider (claude-sonnet-5-5, gemini-3.8-flash, …). Resolve against the current registry; do not switch families to work around provider availability.

Limits: uncertain mutations stay conservative; platform approvals are not automatically carried into a replayed action; unconfirmed terminal states fail closed rather than inventing user intent. No speed or cost claim.

Deferred (tracked, not hidden): operator stop/restart alarm #449 (fixed by #508, see Stop keeps the alarm), receipt retention #450, boot typing / duplicate repair / near-cap cleanup #451, remaining agent ingest schemas #452, initial execution progress diagnosis #453, phone card overflow #454.

Detail and traps: gotchas/opencode-and-turns.md. Related product-facing receipts: Control plane — Usage & deployment receipts.

Stop keeps the alarm while durable work remains (#508, merged; fixes #449) ​

Merged #508 (yoni-monday, 2026-10-06 09:56 IDT, merge 62105e6b). Before it, an operator or control-plane stop (POST /w/:id/restart-container, and the stop step of the destroy route) deleted the WorkspaceDO alarm even when work was still owed: usage the control plane had not accepted, a publish intent or its audit records, a session, or an open question. The alarm is the only thing that finishes that work without a browser, so it waited for a visit that might never come. This was the "operator stop/restart alarm" item deferred by Turn recovery.

PieceBehaviour
stopPreviewLease(storage) (services/conductor/src/do/preview-lease.ts)Always drops the preview lease (previewLeaseUntil). If durableWork is "none", deletes the alarm. Otherwise re-arms it at max(heartbeat 30 s, min(durableWorkDueIn, 10 min)), the same wait the alarm itself picks for backed-off work (shared helper deferredDelay, also used by stopIfIdle). Work that cannot be read counts as pending, so the alarm is kept
TombstoneA destroyed workspace (tombstone present) always ends with no alarm, since an alarm left behind would boot a deleted workspace. If the tombstone read itself fails, the stop leaves the existing alarm untouched and handleAlarm, which re-reads the tombstone, decides
CallersstopContainerInstance (do/container-process.ts) uses it instead of clearPreviewLeaseAndAlarm. WorkspaceDO.stopContainer no longer clears the lease and alarm a second time first
Destroy / wipeUnchanged: wipeWorkspaceStorage still deletes the alarm last, and the tombstone check covers a stop that runs after the wipe
Mid-turn stop (pre-#546 wording; since #546 durable work is read from Pi's tables and a detached tool body also counts as pending)OpenCode claims a session (time_suspended) when its execution starts, so a turn running at stop time counts as pending and keeps the 30 s heartbeat. The next alarm calls bootRuntime, which starts the container again to finish the turn, and the idle stop tears it down once idle (the same thing an evicted workspace already does under alarm-retries-while-durable-work-remains). An unclaimed session with nothing admitted leaves no alarm

Contract stop-keeps-alarm-while-durable-work-remains (owner:yoni-monday, label:reliability): stopping a container MUST drop the preview lease but MUST NOT leave the object without an alarm while durableWork is not "none"; unreadable work counts as pending; a tombstoned workspace MUST end with no alarm.

Behaviour change to expect: restarting a container whose session still has a turn to resume now resumes that turn on the next alarm, even with no tab open.

Verification: test services/conductor/test/do/stop-keeps-alarm.test.ts (usage due now and backing off, publish intent, unreadable storage, claimed and unclaimed mid-turn sessions, nothing owed, wipe, stop after wipe, unreadable tombstone, tombstoned workspace); the durable-work cases fail with the fix reverted. Conductor tsc --noEmit and bun test pass. Live on side env fixwave-ebf8, restart-container returned {"container":"stopped"} and a later preview reload cold-started the workspace with a 200. Not observed live: the re-armed alarm firing after a stop (the DO has no alarm introspection and wrangler tail alarm events carry no workspace id). That live check (park a turn, restart the container, close the tab, watch it finish) is noted on the PR but not filed as an issue yet. Shared staging/prod rollout was not part of the PR.

No preview-host fallback (#447, open) ​

Open #447 (closes #443): conductor never defaults PREVIEW_HOST to a live brilliant.lighting address. requirePreviewHost fails closed (contract preview-host-never-defaulted). routes/dev.ts drops studio.brilliant.lighting from frame-ancestors / CORS — the studio origin is CONTROL_PLANE_URL only (same as app.brilliant.rocks).

Agent id: brilliant-conductor-${BRILLIANT_ENV} (was "staging" iff the preview host contained brilliant.lighting, else "dev"). LangSmith / trace agent ids become per-env.

Full host table: Hosting — no lighting fallbacks.

Task list clears when done (#489, merged) ​

Merged #489 (yoni-monday, 2026-10-05, merge 6ad398be): a finished update_tasks list no longer stays in storage. Before this, the agent appended to (or re-sent) the all-done list on the next request, and a reconnecting studio reloaded stale checked-off tasks.

PieceBehaviour
Store (tools/tasks-store.ts)The write that marks the last task done stores an empty list. Revision still bumps. Task ids keep counting up across lists (they are never reused). A done item whose id the store issued but no longer holds (a re-sent task from a cleared list) is dropped, so it can't come back under a new id. Open or in-progress items with unknown ids still get a fresh id.
Tool (tools/tasks-tool.ts)That write returns "All tasks done, so the task list was cleared. If more multi-step work follows, send a fresh list then." The tool description says the list clears itself when the last task is marked done.
RPC event tasks.completed (packages/rpc){ revision, completed: Task[] }, emitted by the brilliant plugin before the cleared tasks.updated at the same revision. TaskStore.onChange(snapshot, completed?) carries the finished list.
Field namecompleted, not tasks, because the studio's reduce-events.ts treats any rpc.brilliant.* event carrying tasks as a task-list update.
Studio (apps/control-plane/web/.../reduce-events.ts)Shows the finished list from tasks.completed and ignores the empty tasks.updated at that revision, in either arrival order. The next session.execution.started retires the list, as before. User-visible behaviour is unchanged: "N of N done" stays until the next message.

Contracts: finished-task-list-is-cleared and cleared-done-tasks-stay-gone (on createTaskStore), tasks-completed-precedes-cleared-update (on BrilliantRpc).

Known edge (left as is): if the agent re-sends only stale done tasks while the finished list is on screen, that write stores [] at a new revision with no tasks.completed, so the studio clears the list mid-turn. Harmless and rare.

Verification: typecheck and unit tests (conductor tasks/plugin/tools, studio session/chat) pass; not live-verified on a side env at merge time.

Publish typecheck failures go back to the agent (#490, merged) ​

#490 (yoni-monday, merged into main 2026-10-05 20:16 IDT, merge d6aba6e8). Before it, a Publish that deploy's own typecheck refused stopped at a generic Studio error, the coding agent never heard about it, and the prompt told the agent not to typecheck before deploy. Only side env occap was deployed for verification; shared staging and production were not rolled out by the PR.

What happens now when Publish hits type errors

StepBehaviour
Conductor build (deploy/deploy.ts, new deploy/typecheck-errors.ts)A failed build whose stdout has a standalone TYPECHECK_FAILED line becomes Build failed for <app>: TYPECHECK_FAILED plus the first 20 complete tsc diagnostic lines read after the last marker. Before, the error kept only the last 800 characters (about seven diagnostics), so with more errors the marker fell off and Publish showed a plain failure
Conductor routes (routes/ops.ts Studio publish, deploy/worker-deploy.ts session deploy)Only that definite message returns HTTP 422 { error: "typecheck_failed", message: <tsc lines> }. Everything else keeps the fixed deploy_failed token (500). The log line is now DEPLOY_TYPECHECK_FAILED app=… lines=… and never carries compiler text (the old DEPLOY_ERROR log of the raw error is gone)
Control plane (operations/apps.ts publishApp)Keeps typecheck_failed only for a conductor 422 with that exact code. A message that merely looks like compiler output stays deploy_failed. The app is not marked live and the provider call is not repeated
Studio (usePreviewDeploy.ts, publish-typecheck-feedback.ts, use-publish-typecheck-repair.ts)When Publish starts, Studio pins the workspace, app, chat session id and a Stop counter. On a typecheck_failed answer it sends one normal chat message to that original session, with the diagnostics (max 20 lines of 300 chars) fenced inside <untrusted_compiler_output> as data, asking the agent to fix the draft, run the typecheck tool, not publish, and report a blocker if the fix needs read-only platform/SDK files
When the repair is droppedStop pressed after Publish started, a different workspace, app or session, a chat that is busy, connecting or in an unknown state, no session id at start, or the page unmounted. A dropped repair is never queued, retried or replayed into a later chat, and nothing ever publishes again automatically
Notice the user seesSent: "Publish stopped: the draft has type errors. They were sent to the chat for a fix. Publish again once it is done." Dropped: "Publish stopped: the draft has type errors. Ask Brilliant in the chat to fix them, then publish again."

Agent prompt change (prompts/sections/deploy-workflow.ts, live-preview.ts, tools/typecheck-tool.ts). The old rule "do NOT run typecheck routinely or before deploy" is reversed. There is now an end-of-work check: when a turn changed app code and the work is done, the agent calls the typecheck tool once per changed app (a packages/ change counts for its apps) before the closing summary, suggest_next and any deploy, fixes errors and re-runs it until clean, or names a blocker. Questions, plans, read-only looks and cancelled work skip it. It is never run per edit, between build steps, or in a shell. Deploy keeps its own independent typecheck gate, and a request to fix errors that stopped a publish is not a request to publish. The assembled prompt stays within 32,000 characters.

Contracts: publish-keeps-definite-typecheck-failure (control plane), studio-publish-passes-only-definite-tsc-lines, typecheck-failure-message-is-bounded-tsc-lines, deploy-error-passes-only-tsc-lines, deploy-failure-log-has-no-compiler-text (conductor), publish-typecheck-classifier, publish-typecheck-repair-origin, publish-typecheck-repair-no-autopublish (Studio).

Verification (from the PR): bun run verify, focused regression tests and contracts passed. On occap, a real browser Publish returned 422 typecheck_failed, the original session got exactly one repair message, the agent fixed the injected error and ran the typecheck tool, and no second Publish happened. A fully clean typecheck and a successful publish were still blocked there by the template SDK permission defect (#470, see the next section), so the PR proves the feedback loop, not that fix.

Template SDK readable to builder (#498, on main via #490) ​

#498 (yoni-monday, merged 2026-10-05 into fix/publish-typecheck-repair, the branch of #490; on main since #490 merged 2026-10-05 20:16 IDT; refs #470). The PRs only deployed side env occap; shared staging and production get it from their next image rebuild and deploy.

Symptom. A generated app's typecheck fails with TS2307 Cannot find module './adapter' (in packages/db/src/{database,index}.ts), ./db.server (in runtime/index.server.ts), and TS2305 for a missing createAppDb, while the image boots and a Studio smoke passes.

Cause. COPY packages/template /opt/template keeps the build host's file modes. A checkout made under umask 077 has 600 files and 700 directories, so in the image they are root:root owner-only. Every agent command runs as builder under setpriv with no capabilities, which cannot read them, so the TypeScript resolver reports "not found". Root-run steps, like the Dockerfile's vite bake, never notice.

PieceBehaviour
Mode normalisation (infra/agent-image/Dockerfile)Right after the overlay COPY and before the seed tarball is cut: find /opt/template -name node_modules -prune -o -type d -exec chmod 755 {} + -o -type f -exec chmod u=rwX,go=rX {} +. Owner stays root, group/other never get write, executables keep x. Seeded files get the same modes
Do notUse chmod -R on /opt/template or drop the node_modules prune. A metadata pass over the 1.1 GB of node_modules rewrites it into a fresh layer on every build. The normalisation layer is about 1.6 MB. find does not follow symlinks, so bun's relative workspace links are untouched
Secrets out of the context (root .dockerignore)Excludes **/.env, **/.env.*, **/.dev.vars, **/.dev.vars.* at any depth, because the overlay is now readable to builder and a gitignored env file in a developer checkout would otherwise be baked in
Image identityRoot .dockerignore is now in IMAGE_INPUT_PATHS (scripts/env/lib/state.ts), so changing context exclusions rebuilds side-env images. See Side environments — Conductor image reuse
Testsservices/conductor/test/image-sdk-readability.test.ts runs the Dockerfile's own step against a 600/700 fixture (independent of your umask) and checks .dockerignore excludes secret files. Opt-in real COPY probe (needs a local agent image, never pulls or pushes): AGENT_IMAGE_PROBE_BASE=<local image> bun test test/image-sdk-readability.test.ts. Red without the step (test -r exits 1), green with it (builder reads, imports createAppDb, tsc --noEmit passes, writes denied, no secret files in the image)

After rollout: the test proves the step, not a deploy. A workspace only gets the fix from a rebuilt image, so check a live turn's typecheck after deploying. Repo note: gotchas/containers.md ("Generated-app typecheck says TS2307…", on main since #490).

Explicit Plan/Build mode (#558, merged) ​

Merged 2026-10-08 11:07 IDT (merge 9e767fea; danfishbein, merged by yoni-monday; closes #601). The coding agent's session now has a durable lifecycle mode instead of the studio inferring Plan vs Build from file writes and questions. Studio side: Control plane — Desktop polish and explicit Plan/Build mode.

PieceBehavior
Mode store (pi/mode.ts)One SQLite row per Pi session in brilliant_agent_mode (session, mode, plan_id), default build, so it survives restarts. Transitions dedupe by Pi tool call id in brilliant_agent_mode_call, so a replayed call can't re-enter planning or erase a newer proposal's claim. The mode reports the phase; it never gates a tool.
enter_plan_mode / exit_plan_mode (tools/mode-tool.ts)Zero-argument, idempotent. A successful result carries metadata.mode, the marker clients split history on; an interrupted or failed call is no transition. plan-with-user calls enter_plan_mode at the start of the interview and on every replan. exit_plan_mode is only for "skip / stop planning", never after an approval.
propose_plan (tools/plan-tool.ts)Claims the session (plan_id), then asks and waits on its own durable approval form with metadata.planId = its call id, and returns the user's decision. The form's settle writes build inside FormStore.settle, before the waiter wakes, and stamps metadata.mode: "build"; the answer tells the model transitioned: true only when that settle moved the mode, so a superseded proposal's approval never says "build". Every result (approve, changes, cancelled) carries planId.
RPC (packages/rpc)New AgentMode = "plan" | "build"; AgentSession.mode; AgentForm.metadata gains optional planId and mode.
Undo / fork (pi/mode-boundary.ts)A fork's mode comes from the newest successful mode marker in its retained history (paging past compactions), never the source session's current row; no marker means build. The child starts with no claim.

Rollout: two-way door, no Postgres migration or new binding (only the new SQLite rows, unused after a revert). Release control plane/SPA first and the conductor last; an older conductor sends no mode, and old approvals without planId keep their cards via the studio's legacy adapter. Repo write-ups: gotchas/piharness.md (fork mode, plan approval settle), gotchas/deploying.md (non-atomic SPA/conductor upgrade), gotchas/studio-frontend.md.

Progressive real-section builds (#562, merged) ​

Merged 2026-10-07 12:16 IDT by yoni-monday (merge e02c082c, head 0c3e30c9, branch yonibr/render-kyx4l). It changes how the coding agent builds a new app in the live preview. Before it, the prompt told the agent to write a whole-page shell first, with one "Building this section…" or "Coming next" slot per planned section, then build ONE feature for real and stop. The preview looked like a throwaway wireframe instead of the real screen taking shape. Now every write is real content that stays in place.

The merged version differs from the first draft of the PR: the first real section now comes before the theme, the single-edit mounting rule became "never JSX first", and the shimmer clause was removed. The prompt wording is positive only (it says what to build, with no explicit "no skeleton" prohibitions).

PieceOld behaviourNew behaviour (#562)
Build order (prompts/sections/live-preview.ts)Shell route first, theme second, then a placeholder slot for every sectionFirst real section first, before any design skill or reference is read and before apply_style or new image generation (with a plan, only after approval; until then only plan.md is written). That first visible app write renders the real navigation (links only to screens that exist) and the first section of the main screen, using the existing template tokens and available assets. Then the theme: apply_style writes styles.css and the first section picks it up in place; design.md comes after. Then each next section top to bottom. Completed sections stay visible, and nothing is drawn for sections not started
Where the turn stopsAfter one feature, then suggest_nextAfter the whole requested main screen is finished, then the end-of-work check, a short summary and suggest_next with 2–3 additional features or screens from plan.md. A later turn builds the picked feature the same way. Edit turns keep the existing UI and change only what the request names
Mounting a sectionImport into routes/index.tsx "in the same batch"Mount only once the component and every file it imports (directly or transitively) exist, and before starting the next section. Add the import first, or import and JSX in one edit, never the JSX first. Vite hot-reloads each save, not the whole tool batch, so JSX saved before its import briefly breaks the preview (see the gotcha below). Never mount an incomplete component
LoadersNot coveredLoaders for real runtime data are fine. The draft's optional construction shimmer was dropped; component-owned shimmer is tracked in #567
Design direction (prompts/sections/design-direction.ts)Set right after the shell is upSet once the first real section is on screen, with the research budget kept tight
Preview-progress hook (tools/preview-progress-hook.ts, was shell-first-hook.ts)registerShellFirst: when a component or server file lands while index.tsx still shows "Brilliant is building your app", the tool result said "Write the shell"Renamed registerPreviewProgress (wired in host/brilliant-plugin.ts). placeholderRouteNudge keeps the same trigger but asks to mount the real navigation and first section once its imports exist, import first, then the next sections top to bottom. The same hook still carries unwiredComponentNudge (component nothing imports) and fontImportNudge (Google Fonts @import not on line 1 of styles.css)
Planning skill (skills/plan-with-user/SKILL.md and the generated workspace/bundle.ts)"no route shell" before approval; to-dos start with "the shell and look"; on approve, shell then theme then one section then stop"no page or route" before approval; to-dos are the look and first real section, then remaining sections top to bottom, then other screens; on approve, first real section, then theme, then the rest

Gotcha added (gotchas/template-and-apps.md): Progressive builds briefly show Classes is not defined. The route saved <Classes /> before its import, so the preview went blank until the agent repaired it. JSX first is the order that breaks; import first, or both in one edit, is safe. A clean typecheck at the end does not prove the preview stayed renderable while it was being built.

Measured (from the PR, one run each, side env renderkyx4l, same River Run Club request, same image, Claude Opus 5.5 medium; no staging deploy):

MeasurementMain-prompt baselineFirst draft 235ebd9cMerged 0c3e30c9
Smoke: readable iframe47.3 s, passover the 90 s budget, fail50.8 s, pass
First home-route write11 s (construction shell)73 s (real hero)20 s (real hero)
First real-hero route write76 s73 s20 s
Turn 1 duration150.1 s161.5 s137.4 s

In the merged run the hero route lands at 20 s, the first design-skill load at 22 s and apply_style at 36 s. Conductor tests: 2,100 pass, typecheck clean. New and renamed regression tests: test/preview-progress-hook.test.ts, test/prompt-conventions.test.ts (first-section-before-theme ordering, retired wording, source and bundle consistency).

Known limits: one run per revision is not a benchmark. Route-save time is not pixel first paint (the DOM-ready screenshot was still blank at that instant). The model grouped later sections into one route save, so section-by-section painted progress is not proven. Mounting order is prompt guidance plus a nudge, not enforced. The earlier failing smoke report stays under #559.

Preview socket lease renewal (#588, merged; fixes #563) ​

Problem (on main since #516): every open draft preview reloaded about every 36 s, with nothing in Sentry and a healthy container. leasePreviewSocket (services/conductor/src/workspace/socket-lease.ts) closed the Vite HMR WebSocket at the 30 s control-plane authority deadline, and Vite's HMR client answers any server close with a vite-ping and then location.reload(). The tell is a vite-ping WebSocket upgrade (CF filter $workers.event.request.headers.sec-websocket-protocol eq "vite-ping") right before each iframe document GET.

Decision: renew the lease in-band (option 1 on #563, chosen by Yoni) instead of closing the socket at each deadline. #588 was merged to main 2026-10-07 20:59 IDT by yoni-monday (merge 4f2129bc, head 10163b99; opened 16:12 IDT by Brilliant Fixer, branch fix-563-renew-preview-lease; 4 files, +231/−11). It is live on staging since 2026-10-08 09:22 IDT (deploy dce2558b, run 37735680926); the earlier staging runs for 4f2129bc were cancelled (37664290151) or failed in candidate e2e (37664483627). What landed:

PieceBehavior
bridgeLeasedSockets (workspace/socket-lease.ts)Holds the lease logic. While the socket is open it calls renew() 12 s before the current deadline (LEASE_RENEW_LEAD_MS = 12_000, so a slow 5 s CP answer plus one retry still land) and moves the deadline to the fresh proof's deadline. leasePreviewSocket(response, validUntil, renew?) now just pairs the sockets and delegates to it
Failed renewalA rejected or late renewal leaves the deadline where it is, so the socket closes 1008 authority_expired within one lease of a revoke. Failures log preview.socket_renew_failed with the error name
RetryAn unavailable CP (BuilderAccessUnavailable: 5 s timeout or 5xx) is retried once. A rejection (BuilderAccessRejected) is never retried
GuardsA renewal that resolves after the deadline does not extend it (and does not reopen the socket). A proof that doesn't move the deadline forward is not retried in a loop
renew source (do/preview-socket.ts)(await currentBuilderProof(env, admission.request)).expiresAt: the existing conductor → CP route (/internal/app-access/conductor) for the exact original signed request (same scope, caller and requestId). No new CP route or key. Reconnecting still needs fresh admission
Token expRenewal is not capped by the user token's 15 min exp: withPreviewContext strips the token before the request reaches the DO, so the cap would need it passed in. Each renewal re-checks current CP builder authority, which is what a revoke changes. This was the PR's flagged decision for review and landed as is
CostAbout one CP call per open HMR socket every 18 s (30 s lease minus the 12 s lead)

Contracts: the open PR reworded preview-socket-cannot-outlive-authority and internal-builder-proof-matches-stored-environment. After #592 removed all code contracts, the merged diff no longer touches do/builder-proof.ts; the rule (the deadline moves only to a fresh CP builder proof for the same request, obtained before the current deadline) now lives in the code and tests.

Gotcha added (gotchas/containers.md): Draft preview reloads every ~36s, no error anywhere. Whatever closes the HMR socket reloads the user's page. If reloads come back on a period, check the renewal first (preview.socket_renew_failed in conductor logs). The gotcha text still says "10s before the deadline"; the merged code uses 12 s.

Verification (from the PR): conductor bun test 1948 pass, tsc --noEmit, biome, cc-check format, knip and file-size clean. New test/socket-lease.test.ts (8 cases: no-renewal close, fresh proof extends, rejected keeps deadline, late answer doesn't reopen, non-extending proof not looped, renews one lead before the deadline, unavailable retried once, rejection not retried); each guard broken in turn goes red. Live on side env fix563 with Playwright, a held draft preview reloaded 5 times in 180 s on main and 0 times in 180 s and 300 s on the branch, with the HMR socket open the whole time. Revoking mid-hold (app_resources.lifecycle='retiring') got BuilderAccessRejected on renewal at 16:07:08 IDT and a 1008 authority_expired close at the current deadline 10 s later. The live run used a 10 s lead; the 12 s lead and the retry are unit-tested only. bun scripts/e2e-smoke.ts --env fix563 8/8 pass.

Noted out of scope: the template realtime client (packages/template/apps/web/src/lib/realtime.ts) opens /dev/__realtime, but in draft previews the dev server never completes that handshake (no lease is created; it retries about every 4 min), so live updates there are polling-only. Deleting a tenant membership row doesn't revoke an app owner's builder access (resources/access.ts:187, appOwner counts by itself), which may be intended.

Chat screenshots served again (#591, merged) ​

Problem (on main since #516): chat screenshot cards ("Screenshot · /") from browse_screenshot and browse_act show "Image unavailable" on prod. #516 made the conductor's /w/<ws>/dev/__thumb/<id> route always answer a no-store 404, so the version-thumbnail cache (not bound to a viewer) is never served (contract dev-version-thumbnails-cannot-serve-owner-pixels). Browse screenshots live in the same _brilliant_thumbs table (do/agent-runtime.ts) and the studio loads them through that same route (getThumbUrl), so they broke too.

Decision (Yoni, in Slack): any admitted builder may see the agent's screenshots, since they can already read the chat that shows them. #591 was merged to main 2026-10-07 17:29 IDT (merge cb3f4291; opened 16:26 IDT by Brilliant Fixer, branch fix-chat-screenshots; services/conductor/src/routes/dev.ts). It is live on staging since 2026-10-08 09:22 IDT (deploy dce2558b, run 37735680926); its own deploy run 37637848258 failed in candidate e2e. What landed:

  • __thumb/<id> reads the table only for a 32-hex browse screenshot id, and only after the existing builder admission. Hits return 200 image/jpeg with private, no-store; a missing id is a no-store 404.
  • 40- or 64-hex version shas (and malformed ids) still get the no-store 404 without touching the table, and a non-builder gets 403 before any read. HEAD works too (200 with content-length, no body).
  • Responses stay no-store so a revoked builder can't replay screenshots from cache.
  • Caveat kept as a code comment: this is safe only because the chat is one transcript per environment. If that transcript is ever scoped per actor, scope __thumb screenshots the same way.
  • The PR first reworded the @cc contract dev-version-thumbnails-cannot-serve-owner-pixels; after #592 removed all code contracts, the merged version keeps the rule as a plain comment instead.

Verification (from the PR): conductor bun test 1941 pass; a new case (later extended to HEAD and malformed ids) in test/thumb-current-admission.test.ts covers screenshot 200, unknown id 404, version sha 404 with no read, and non-builder 403 with no read (fails with the fix stashed). Live on side env fix-shots, a real Pi turn called browse_screenshot, the card's __thumb request returned 200 image/jpeg (naturalWidth 1280) and no tile showed "Image unavailable" at 1440x900 or 390x844.

Merged #642 (Brilliant Fixer, opened 2026-10-08 15:09 IDT; merged 15:21 IDT by yoni-monday, merge 4ef2a57b; keep #285 open). Problem: draft previews are served from the conductor's own origin and the iframe is sandboxed with allow-same-origin, so workspace A's preview JS could fetch('/w/B/exec'), /w/B/fs/* or /w/B/agent/*. The browser attached the viewer's brilliant_token cookie for B (Path=/w/B/) and the response was readable, which meant shell, source read/write and agent control in a workspace the attacker cannot access.

  • Cookie only on /w/:id/dev. extractUserToken (services/conductor/src/lib/auth.ts) reads the brilliant_token cookie only on /w/:id/dev paths (not /devtools). Every other /w/:id/* route (exec, fs, agent, screenshot, assets, deploy, history) needs a Bearer token or the guard; a new browser caller that relies on the cookie outside /dev gets a 401 by design. (The brilliant_token query param is still read on any path.) Nothing legitimate used the cookie there: the studio reaches exec/fs/agent through the control plane with Bearer, and the agent client sends Bearer.
  • Dev proxy strips platform cookies. routes/dev.ts drops any brilliant_* / __Host-brilliant_* Set-Cookie from a draft app's dev-server HTTP responses; the app's own cookies pass through. It does not cover the HMR WebSocket 101 (left alone on purpose so HMR is not broken). This is defence in depth, not a cookie-tossing fix: a preview's own JS can still write document.cookie = "brilliant_token=junk; Path=/w/B/dev/; ...", which shadows B's HttpOnly cookie (more specific path) and gets that viewer a 401/403 on B's preview.
  • Tests: new test/preview-cookie-isolation.test.ts; test/lib/auth.test.ts replaces the old "cookie authorizes /w/:id/history" test (it encoded the bug). Verified on side env sec-batch: cookie-only exec / fs / agent session return 401, /w/<ws>/dev/ with the cookie returns 200, Bearer still returns 200; e2e.ts and e2e-smoke.ts pass (iframe preview, HMR and blobs still work). New entry in gotchas/containers.md.

Still open (#285 stays open): cookie tossing (above, including the HMR 101) and the read-only gap. A's JS can still read B's /w/B/dev/* responses with the viewer's B cookie, including B's rendered draft and B's preview server routes, which run as the viewer. Closing it needs previews on a per-workspace origin (<wsId>.preview.<domain>), a DNS, Pulumi and route change left for a human; only per-workspace origins stop both tossing and cross-preview reads. Related: No preview-host fallback.

Preview admission reuses signed leases (#679, merged; closes #674) ​

Merged to main 2026-10-08 21:54 IDT by yoni-monday (merge 95ed8f58, branch worktree/brave-cloud-cbc8, final head f48d96ab; opened 20:14 IDT; 2 commits, +420/−7 in 4 files). Code-only: no schema, secret or infra change. Staging and prod were not deployed from the PR itself; it ships with the next conductor deploy. The durable contract now lives in gotchas/cloudflare.md — Preview permission reuse and near-expiry data identity.

Problem (on main since #516, worse after Neon): every draft preview /w/:ws/dev/* request awaits a fresh control-plane app-access snapshot before the proxy. After a reload the browser fetches ~30 modules; each pays an admission round trip (staging median jumped to ~1.8 s after the Neon cutover), so hydration can land ~30 s after the document and STUDIO-PREVIEW-001 persistence checks time out (#674).

Decision: for preview page/module GET/HEAD only, reuse a matching signed authority proof only while it has at least 15 s left, instead of fetching a new control-plane snapshot on every file. On a miss or low remaining lifetime, fetch and verify a new proof. Uses the existing Effect AppAccessPeer path; no new deps, infra, or migration.

PieceBehavior
Reuse gate (builder-admission.ts)reusePreviewLease only when source === "preview", method is GET/HEAD, path matches /w/:id/dev..., and is not __/blob or __/thumb
Cache (app-access.ts)Isolate-local WeakMap keyed by WorkspaceDO binding (survives Sentry's per-request env proxies) → Map of request digests to { proof, expiresAt }, capped at 256 proofs (evict oldest + expired)
KeyFull signed request digest: actor, tenant, project, app, environment and source. Cache hits never extend the authority's original deadline (at most 30 s)
Headroom (MIN_PREVIEW_REUSE_SECONDS = 15)Every cached proof is re-verified on each hit; one with less than 15 s left is treated as a miss and evicted, so SSR / server functions still have time to make data calls with the forwarded data identity. Added in review after a cached admission at t+29 forwarded an identity with 1 s left
Always freshWrites, media (__blob/__thumb), non-preview routes, runtime data authority, and WebSocket / socket renewals (currentBuilderProof without reuse) still hit the control plane
Fail closedDenials, outages and mismatched signed replies do not poison the cache; expired leases are not served during an authority outage; key / config changes reject warm proofs
TestsNew test/preview-admission-cache.test.ts (30-module reuse without extending the lease, actor/scope isolation, absolute/shorter expiry, revocation, outages, cache bounds, fresh sensitive ops). Includes exactly-15 s reuse vs 16 s recheck, the t+29 refresh, shorter authority expiry, and no near-expiry fallback during outages. Conductor bun test: 2,012 passed (6 documented skips). Side env auth674 at f48d96ab: full 5-pillar e2e and all 8 studio smoke checks (preview reload persistence, Code tab, publish, published data); missing/expired tokens still 403

Measured result (PR evidence: same app, 30 sequential module GETs, warmed Vite, base cb5619c0 vs f48d96ab; repeated-module evidence, not a cold-browser hydration benchmark):

MetricBeforeAfter
CF conductor module median773 ms343 ms
CF conductor module p901,430 ms352 ms
Recorded CP admission calls281
Client batch duration30.412 s11.732 s

Blast radius (preview): permission can be reused until the existing signed lease is within 15 s of expiry (the lease is at most 30 s after observation); revocation is decided by the next fresh lookup, not on every module read, so it is not an immediate-revocation guarantee. Identity is still verified on every request; actual data access stays fresh. The cache is isolate-local, so cold concurrent requests may each perform an authority check. Code-only rollback (a conductor deploy or rollback still evicts active turns as usual); tear down auth674 now that it merged. When changing this boundary keep the remaining-lifetime and revocation tests in services/conductor/test/preview-admission-cache.test.ts.

Related: Preview socket lease renewal (HMR socket renews with a fresh proof; this PR does not change that), Permissions — Revocation.

App card draft screenshots (#684, merged) ​

Status: merged 2026-10-09 01:07 IDT by yoni-monday (merge 5b468464, branch app-card-thumbs, head 0a87129f; 6 commits, +661/−43 in 26 files). On main. Distinct from chat browse screenshots (#591): this is the Projects / app card picture of the draft preview, not the in-chat __thumb tiles.

Problem (before this PR, since #516): app cards showed no draft screenshot. Two breaks: (1) the control plane stopped returning pictures when #516 removed the old /workspaces list and its thumb proxy — the new app list had no picture field and the cards hard-coded none; (2) the conductor stopped taking them — every turn logged thumb.capture … skipped: "no_builder_or_tenant" because #516 stopped reusing a stored builder identity for the preview, and turn-end capture had no other identity. Staging's newest R2 picture before this work was from Oct 6.

How it works now:

turn ends ──► conductor resolves the run's verified user ──► re-checks builder access (control plane)
                                                         └─► screenshot as them ──► R2 thumbs/<ns>/<env>/dev.jpg
GET /apps (builder) ──► item.thumbUrl = /app-thumbs/:appId?w=<env>&e=<hour>&s=<hmac>
<img src> ──► GET /app-thumbs/:appId ──► signature + expiry ──► R2   (no session, DB read or conductor call)
  • Who sees a picture: only callers with builder authority on the app; viewers get the placeholder. The picture is taken as the user who ran the last turn, and builders' data roles can differ, so a builder may see records on the card their own preview would not show — accepted as a trade-off for a card picture. A URL keeps working for 1–2h after its holder loses access.
  • Capture identity: the user who ran the turn, after the control plane confirms they can still build the app. A revoked user, a run with no user, or a reconnect snapshot takes no picture. Nothing is stored for reuse. Publish still skips.
  • Serving: AppSummary gains optional thumbUrl. New route GET /app-thumbs/:appId is deliberately outside /apps/:id/* (whose middleware re-reads the tenant per request) and is on the studio path prefixes. Signed URL (HMAC + hour expiry); image is private, no-cache with ETag (browser keeps it but re-asks; cheap 304 from R2), so a new turn's picture shows on the next visit. A draft with no picture yet is not cached. URLs are hour-aligned so a list re-fetched within the hour returns the same URL.
  • Config: control plane gains DISPATCH_NAMESPACE (rendered per env like the conductor's; tests keep the two equal in base configs and side envs).
  • Ship order: control plane first, then conductor. Rollback of conductor stops new pictures; rollback of control plane drops the field and route.

Evidence (PR, side env studio633): real turn → conductor logs thumb.capture … bytes: 15742 → builder list carries the URL → JPEG with no cookie in ~55s (private, no-cache); repeat with ETag is 304; forged signature 403; re-list same URL; desktop and phone Projects cards render. Official smoke 8/8. Tests: control plane 8, web 1, side-env config 2, conductor 5; full suites CP 1593 / conductor 2004, 0 fail. Secrets catalog lists the new var as a plain wrangler var.

Related: Permissions — Revocation · Chat screenshots (#591) · Troubleshooting.

Readiness gate and launch-row hardening (PR #810) ​

Merged 2026-10-12 (PR #810, follow-up to #805/#806). No migration; two-way door.

  • WorkspaceGate.ready: workspace prepare is raced against a 180s timeout (WorkspaceNotReady … did not finish within). A failure is remembered for 15s, so tool calls during back-off replay the error instead of re-running prepare.
  • Agent-dispatch behind a staged undo: readiness is raced against the admission lease. If the lease runs out, the request returns a retriable 503 workspace_not_ready with retry-after, and nothing commits.
  • First-prompt launch rows: settle and ready can arrive in either order; whichever comes later drops the row. Launch recovery sweeps unsettled rows older than 24h (with their unsent prompt); legacy tombstones, starting apps, and young rows are left alone.
  • First-build marker: building → failed on a failed turn, back to building on the next turn. A reload never shows the ready toast or auto-publishes for a build that faulted.
  • App moves (still disabled, APP_MOVES_ENABLED unset): stale_rebind / identity_conflict now return a terminal 409 conflict instead of 503 move_pending, and the rebind ack carries a requestId that must match.

Non-image attachments become text stubs (PR #822, merged, fixes #821) ​

Status: merged 2026-10-12 12:56 IDT by yoni-monday (PR #822, merge 9f772a29, fixes #821). Opened earlier the same day by Brilliant Fixer.

Problem (prod, on main at 86b500a): a builder prompt with a PDF or AVIF attachment ended the turn after one step. Anthropic rejected it with 400 invalid_request_error: … image.source.base64.media_type: Input should be 'image/jpeg', 'image/png', 'image/gif' or 'image/webp'. Uploads (POST /apps/:id/files) accept application/pdf and image/avif, but materializePiMedia (services/conductor/src/coding-agent/host/media-offload.ts) turned every Attached: … /__blob/<id> line into an image part using the R2 content type unchecked, and toolPartsToPiContent let any inline image/* through.

Behavior on main:

  • Only image/png, image/jpeg, image/gif and image/webp reach the model as images. That is the same set sniffImageMime uses in pi/tool-read-image.ts.
  • Any other type, from an attachment or a tool result, is sent as text: [attachment "<name>" (<mime>) is not an image the model can view]. The turn keeps going and the agent knows the file exists.
  • Type is checked before bytes are read (files-row type skips R2; unsupported types never arrayBuffer()). Mime is sent bare and lowercased. The composer's upload allowlist is unchanged.
  • PDFs are handled by #824 (merged into #822's stack branch, not on main yet): kept as application/pdf parts and rewritten per provider instead of stubbed. AVIF and other non-model types stay as the text stub.

Evidence: media-offload.test.ts (vii)/(viii)/(ix)/(x); conductor bun test 1864 pass on the final branch tip. Side env fix-821: main reproduced the 400 (stopReason: error); the branch finished normally (stopReason: stop).

Related: Troubleshooting: turn ends with media_type 400, PDF attachments reach the model (#824).

PDF attachments reach the model (PR #824, merged, follow-up to #822) ​

Status: merged 2026-10-12 12:56 IDT by yoni-monday (PR #824, merge f40d31b6 into the stacked branch fix-821-non-image-attachments, not into main; pdf-payload.ts is absent on main, so PDFs still get the #822 stub in prod until a follow-up PR lands it; follow-up to #822 / #821). Opened earlier the same day by Brilliant Fixer. Product ask from Yoni: "the models should support pdf".

Problem after #822: a PDF in the composer still reached the model only as a "not an image" stub. pi-ai 1.0.4 has no document content type, so each adapter encoded an image part as an image block (the original #821 400).

Behavior on main:

  • host/media-offload.ts: an attached application/pdf blob is placed as an application/pdf part under the same 3 MB inline cap (MAX_INLINE_IMAGE_BYTES). Over the cap it keeps the existing "omitted" stub. Mime parameters are stripped (application/pdf; charset=binary → application/pdf). AVIF and other non-model types still get the #822 stub.
  • pi/pdf-payload.ts (new) + pi/models.ts: pi-ai's onPayload hook rewrites those parts in each API's request body (chained ahead of any caller onPayload):
    • Anthropic Messages: image with a PDF source → document
    • OpenAI Responses: input_image with a PDF data URL → input_file (filename: attachment.pdf)
    • Gemini (Vertex): unchanged (inlineData with application/pdf is native)
    • Workers AI chat completions (Kimi, no PDF input): text note [a PDF attachment was omitted: this model cannot read PDFs]
  • Defaults: the 3 MB cap stays, and Workers AI gets the note rather than hiding the attachment.

Evidence: pi/pdf-payload.test.ts (one case per API + image left alone); media-offload.test.ts (vii) expects PDF as application/pdf part and AVIF as stub; conductor tsc --noEmit clean, bun test 1867 pass. Live on side env fix-821: one-page PDF reading "App title: MARMALADE" — Claude Opus, GPT, and Gemini answered MARMALADE; Kimi said it cannot read the PDF.

Related: #822 non-image stubs, Troubleshooting: media_type 400.

Files accept archives (PR #960, merged) ​

#960 (merged 2026-10-15 14:47 IDT by yoni-monday, merge 927566a2, head 6af0686a, branch files-archives, +250/−16 in 14 files). Builders can add archives in Studio › Files (/app/$appId/settings?tab=files). They are stored whole and download under their original filename.

The blob sniff (sniffType in packages/capabilities/src/blobs.ts) accepts eight archive containers by magic bytes:

ContainerSniffed MIMEStored id extension
zipapplication/zip.zip
gzip (including .tar.gz; the deflate byte 08 is required)application/gzip.gz
tar (ustar at byte 257)application/x-tar.tar
7zapplication/x-7z-compressed.7z
rarapplication/vnd.rar.rar
bzip2application/x-bzip2.bz2
xzapplication/x-xz.xz
zstdapplication/zstd.zst
  • Builder files first (#960). End-user uploads originally refused archives with blob_type_rejected (415, "Archives can't be uploaded here") on the published-app path in dispatch and the draft kind === "upload" path in conductor. Merged #979 lifts that refusal so draft and published uploads accept the same archive types.
  • Size: archives share the 25 MB document limit (MAX_DOC_BYTES); video stays at 100 MB.
  • Stored whole, never unpacked or rendered. ARCHIVE_MIME (exported from @brilliant/capabilities) is not in INLINE_SAFE, so archives are always served as attachments with nosniff. A container can hold HTML, which is why it is never rendered inline.
  • Downloads keep the original filename. At upload time, any type outside INLINE_SAFE gets a stored R2 contentDisposition built by downloadDisposition(name) (attachment; filename*=UTF-8''<name>). blobHeaders serves that stored value when it starts with attachment; and has no line breaks, otherwise plain attachment. Files stored before #960 have no stored disposition and still download as plain attachment.
  • Office files become zips. A .docx or .xlsx matches zip magic, so it is stored as application/zip with a .zip id, but downloads as report.docx thanks to filename*.
  • HTML stays blocked. Declaring application/zip or application/gzip on HTML bytes is still refused. Only the real magic bytes count.
  • Chat attachments are unchanged: the composer still takes images and PDFs only. The Files caption now reads "Images, documents, audio and archives up to 25 MB; video up to 100 MB", and archive rows get a zip icon (FileRowItems.tsx).
  • Templates: referencedAssetIds collects a .zip asset id that app code points at with blobUrl(...), so archive assets travel with templates like other assets.
  • Generated apps (#960): the brilliant-files skill listed archives as builder-only and said uploadFile refuses them. Merged #979 updates that skill so uploadFile and Studio › Files share the same archive allowlist.

Evidence (from the PR): bun test packages/capabilities/test/blobs.test.ts (archive magics, gzip needs the deflate byte, HTML declared as zip refused, downloads keep a safe filename); conductor test stores a builder zip asset with filename*=report.docx and (as of #960) returned 415 for a draft end-user zip; dispatch test (as of #960) returned 415 for a published-app zip and stored nothing; template references test collects a .zip id. Still unchecked in the PR: uploading a real zip and a .docx in Files and downloading them. (#979 later flipped those draft/published zip uploads from 415 to 201.)

Related: In-app uploads accept archives (#979, merged), #822 non-image attachments become text stubs, #824 PDF attachments reach the model.

In-app uploads accept archives (PR #979, merged) ​

#979 (merged 2026-10-15 22:01 IDT by yoni-monday, merge 11138ba8, head 22af2d22, branch files-app-archives, +335/−38 in 10 files). Follow-up to #960: #960 merged while end-user uploads still refused kind: "upload" archives, and that head could not move after the merge, so this PR finished the policy.

What landed:

  • Draft and published in-app uploads accept the same eight archive containers as Studio › Files (zip, gzip, tar, 7z, rar, bzip2, xz, zstd), stored whole up to 25 MB (MAX_DOC_BYTES), downloaded under the original filename.
  • Always attachment + nosniff, never inline (@cc on both upload handlers). A container can hold HTML, so archives stay out of INLINE_SAFE. A .docx still sniffs as zip and saves as .docx. Zip magic also matches .apk / .jar; those are stored as application/zip and never rendered. SVG and HTML stay refused.
  • Abuse guards (not a per-app quota): published upload needs a signed-in user; draft upload needs the builder; magic-byte allowlist; 25 MB per file (video stays on the 100 MB streamed video/* path); 1 GB workspace quota (WORKSPACE_QUOTA_BYTES) shared by every app in the workspace; published uploads also take the per-IP rate limit when UPLOAD_RATELIMIT is bound (a missing limiter does not block). The draft path has no separate per-IP limit. There is no per-app quota.
  • Framed downloads: in studio preview and the live tab (window.top !== window.self), an archive link or any download link is fetched from the app's own origin (blobUrl(id) → /w/<ws>/dev/.../__blob/<id> in preview, /a/<app>/__blob/<id> or the app host when published) and saved in JS (capped at 25 MB). A published app opened top-level uses the browser download. Chat attachments stay images and PDFs only.
  • Disposition: downloadDisposition now sets both ASCII filename="..." and filename*=UTF-8''... so browsers that ignore filename* still get a name.
  • Generated apps: brilliant-files (skill + harness bundle) now says uploadFile and Studio › Files share the archive allowlist, archives stay whole, and downloads should use <a href={blobUrl(id)} download={name}> (not target="_blank").

Code: removed the ARCHIVE_MIME refusal from services/conductor/src/workspace/blob-storage.ts (storeUpload) and services/dispatch/src/blob.ts; added downloadFile + framed link saver in packages/template/apps/web/src/lib/blobs.ts.

Evidence (from the PR): unit tests flipped from 415 to 201 for draft and published zip uploads (original name + attachment/nosniff on GET); framed archive link saves, image link navigates, top-level link left to the browser. Still unchecked: upload a real zip from an app and from Files, then download each in preview. bun scripts/e2e-smoke.ts was not run (would not click an archive link).

Related: Files accept archives (#960, merged).

Muse Spark 1.3 and per-model thinking levels (PR #820, merged) ​

#820 (merged to main 2026-10-12 14:22 IDT, merge 77de74fa).

Muse Spark 1.3 (MODEL_IDS.MUSE_SPARK_1_3 = meta/muse-spark-1.3):

  • Route: Pi Responses API, then the Workers AI binding, then the brilliant gateway. Declared in packages/models/src/proxy-models.ts because it is not in Cloudflare Models Search (provider: WORKERS_AI_PROVIDER_ID, api: "openai-responses").
  • Text and image input, 1,048,576-token context, 32,000 max output tokens, agentEligible: false.
  • Billing rates in packages/models/src/pricing.ts: $1.25 input, $4.25 output, $0.16 cache read, $1.25 cache write per million tokens (third-party rates apply even though it is served through the AI binding).
  • BrilliantModel gained optional api, input and thinkingLevelMap fields; pi/models.ts merges a model's own thinkingLevelMap over the pi-ai catalogue entry.

Effort validation is per model now:

  • THINKING_LEVELS in pi/models.ts is low, medium, high, xhigh, max. thinkingLevelsFor(model) filters it by pi-ai's getSupportedThinkingLevels, and isOfferedThinkingLevel(model, level) is the single check.
  • AgentRuntime.setModel and wire.ts readPrompt reject a level the model does not offer with thinking_level_not_offered (before, a global gate accepted Gemini max).
  • Opus 5.5 max is withheld (thinkingLevelMap: { max: null }): in hosted testing it spent the whole 64K output budget thinking and returned no visible text (stop: length, ~572 s). xhigh on the same prompt completed in ~132 s. Budget and recovery work is tracked in #827.
  • GPT no longer gets a second idle watchdog. The 90 s inter-chunk idle limit is unchanged (it is not a total-turn limit); no completed test run hit llm_stream_idle.

Evidence at merge (from the PR): conductor suite 1,865 passed; model-effort-scale mutation proven; hosted max turns completed on GPT-6 Luna (~132 s) and Muse Spark 1.3 (~84 s, including reading an image asset).

Related: Control plane: per-model effort scales, Troubleshooting: thinking_level_not_offered.

Auto tiers and admin default model (#905, merged) ​

#905 (merged to main 2026-10-14 11:39 IDT, merge 978dedc2) moves Studio's model choice out of code and into admin Config.

Auto is resolved at setModel and never stored. A prompt or /model may send model: "auto" with a tier id (quick, balanced, deep, brilliant) as thinkingLevel. AgentRuntime.setModel maps the tier through the admin STUDIO_AUTO_TIERS key and configures the session with that concrete model and effort, so info().agent.model is never auto.

  • A mapping change reaches the next Auto prompt, not ones already run. That is why the SPA sends auto plus the tier on every prompt; a client that sends a concrete model once keeps that model.
  • A non-tier level with auto is refused with thinking_level_not_offered (in wire.ts readPrompt, before the prompt is pinned).
  • A tier mapped to a model this conductor cannot run is refused with model_not_offered and stores nothing.
  • info().autoTiers lists the tiers a conductor resolves. A conductor without it predates Auto, and the SPA falls back to a concrete model.

A session has no model until its first prompt. PiHarness is opened with no boot defaults, so a new conversation (the root, or a fresh undo fork of a never-prompted session) stores no model. AgentRuntime.prompt sets one through prepareAgentFor (coding-agent/pi/session-agent.ts): the prompt's own model when setModel ran first, otherwise the admin STUDIO_DEFAULT_MODEL key. A boot default would be fixed at session creation, so an operator's change would never reach that session. New code that runs a conversation outside prompt must call prepareAgentFor first.

Config reads: services/conductor/src/do/studio-models.ts reads both keys from CONFIG_KV and reuses each read for 60 s, falling back to the code default when the KV binding is missing or the read fails. So an admin change reaches running workspaces within about a minute, on a later prompt.

Code defaults and validation are on Admin Config: Studio model keys. The picker side is Control plane: Studio Auto mode.

Evidence at merge (from the PR): test/pi/auto-mode.test.ts (auto plus deep runs the configured model; a config change after boot changes the next Auto prompt; an invalid tier is refused; an unrunnable mapping is refused and stores nothing; explicit models unaffected); full conductor suite 2,007 passed.

PostHog LLM analytics replaces LangSmith (#959, merged) ​

#959 (merged 2026-10-15 14:48 IDT by yoni-monday, merge e2107120, head 28de255f, branch posthog-3-llm-analytics) is PostHog stack step 3. Live tracing goes through PostHog (gated by POSTHOG_TOKEN / POSTHOG_HOST); LangSmith is removed from the codebase.

What landed:

  • host/posthog-tracer.ts replaces the LangSmith sink; pi/tracing.ts spans become $ai_trace / $ai_generation / $ai_span in PostHog projects staging 666164 / prod 664776.
  • Gated by existing POSTHOG_TOKEN + POSTHOG_HOST (no new secret). Full prompt/response text, capped at 16k chars per payload, every env.
  • Dormant keyless /langsmith/* proxy branch and 404 pin are deleted.
  • ADR docs/decisions/posthog-llm-tracing.md is on main (replaces langsmith-live-tracing.md).

Full design notes: PostHog — LLM analytics (#959, merged).

Follow-up #970 (merged 2026-10-15 15:47 IDT, merge 88633182) adds app_id, tenant_id and user_id (plus the tenant group) to every trace event; the Pi tracer resolves the run's user at run start because the invocation identity isn't readable from the event stream. See PostHog — trace ids (#970, merged).

Follow-up #1001 (merged 2026-10-17 09:13 IDT, merge 74ecb3d0) adds catalogue-priced $ai_cache_read_cost_usd / $ai_cache_write_cost_usd to every generation (host/posthog-tracer.ts), plus turn_source, which pi/tracing.ts resolves at run start through AgentRuntime.turnSourceFor (the run's caller source, else the turn's header) and waits for at most about a second per generation. Don't add the cache costs to PostHog's $ai_total_cost_usd. See PostHog — cache cost and turn source (#1001, merged).

Root publish base (#994, merged) ​

With PR #994 (opened 2026-10-16 22:36 IDT by yoni-monday; merged 2026-10-17 09:32 IDT by yoni-monday, merge cd675e63, final head 3216707c), deploy and rollback accept base_path: "/" (or basePath). resolvePublishBase allows only /; anything else keeps the historical /a/<script>/ base, so an older control plane still publishes. The deploy result reports the base it used, and the control plane marks the app serves_at_root from that report.

An agent publish has no request body for the base, so the conductor reads publish_base: "/" from the control plane's workspace app list. Rollback uses that same value, so a rollback body without base_path still rebuilds at / on staging and prod. Side envs have no apps domain and keep the prefixed base. Deploy order for this change is dispatch, then the control plane, then the conductor.

If the control plane answers ingest with 503 activation_pending, the public host wasn't stored yet; retry the same deployment body.

See Dispatch — Public host at / (#994).

Semantic lint after typecheck (#981, merged) ​

PR #981 (merged 2026-10-17 09:07 IDT by yoni-monday, merge 644fe79c) adds an advisory "Semantic lint" section to the coding agent's typecheck tool result. It runs only after a passing typecheck and only when the semantic_lint flag is on for the tenant (off everywhere at merge).

  • runSemanticLint probes GET /internal/workspaces/:wsId/semantic-lint (cached 10 seconds per workspace as off, unconfigured or ready), runs bun /opt/brilliant/semantic-lint.mjs in the container, then POSTs up to 64 { id, state, ruleIds } requests to the control plane.
  • Each rule is reported once per sibling cluster (oncePerSiblingCluster), on the file Jev is most confident about.
  • The section never changes the typecheck result. Early returns log semantic_lint.skipped with a stage (probe, unconfigured, exec, report, ask).
  • Since #1008 (merged 2026-10-17 14:28 IDT), each run and each rule answer is also a PostHog product event (semantic_lint_run, semantic_lint_finding), sent through productEventTracker and the trackProductEvent tool dep. See Analytics in PostHog.

Full design, rules and cutoffs: Semantic lint (Jev linter).