Repository navigation
revert(sandbox): remove shared agent sandboxes and the staging default - #5240
Merged
Merged
Conversation
Reverts #5112 (share agent sandboxes by branch), #5116 (always share agent sandboxes) and #5132 (use shared staging branch), restoring the pre-#5112 behaviour: hosted agent sandboxes are per-user again, and a new GitHub-backed thread gets a generated branch instead of `staging`. Reconstructed against current paths rather than reverted: #5120 split apps/mesh into apps/api + apps/web and hoisted branch-name.ts, runtime-defaults.ts and thread/schema.ts into packages/shared, and #5174 deleted vm-events.ts outright, so none of the three commits reverse-apply. Core change: SandboxId goes back to a flat `{ userId, projectRef }` and sandboxIdKey back to `userId:projectRef`, so every hosted claim handle changes. Live shared claims must be drained BEFORE this deploys. Also reverted, because they only exist inside the shared model: - #5225 withoutLegacyAgentSandboxEntries — left in place it would strip the sandboxMap entries the reverted server writes back, leaving shouldAutoStart permanently true (silent, compiles fine) - #5219 resolveSharedThreadVm and the shared-scope branch - #5183 stale-provisioning reset (lived inside the deleted storage) Deliberately preserved: - migrations 137/138 and their index.ts entries — Kysely's #ensureNoMissingMigrations runs unconditionally, so deleting an applied migration crash-loops every pod. The tables are dropped by a follow-up forward migration after the drain, not by this commit. - #5114/#5118 withClaimGitLock, #5126 org-context guard, #5143 analytics gate, #5171 owner-keyed thread graft, #5195/#5207/#5210/#5221 client auto-retry, the daemon status-code train and the settings-validation train - #5112's org-fs least-privilege narrowing and the start dedup key fix - #5116's squashed queue-tray pluralization (en + pt-br) - the remote-branch-name validations #5132 deleted, since this restores the dynamic origin/HEAD lookup that made them load-bearing Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Resolved 3 conflicts toward main's post-branch work: - use-layout-state.ts / shell-layout.tsx: keep #5231's caller-passed `branch` param over the branch's parallel readCachedTaskBranch path. main's callers already omit the branch on agent-switch, which is the same guarantee the branch's carryBranch gate provided. - connection-tools.integration.test.ts: keep userModelPreferences stub, drop agentSandboxSessions (storage class removed by the revert).
decocms Bot
pushed a commit
that referenced
this pull request
Jul 27, 2026
PR: #5240 revert(sandbox): remove shared agent sandboxes and the staging default Bump type: patch - decocms (apps/api/package.json): 4.133.1 -> 4.133.2 - @decocms/e2e (packages/e2e/package.json): 1.22.0 -> 1.22.1 - @decocms/sandbox (packages/sandbox/package.json): 1.22.9 -> 1.22.10 - @decocms/shared (packages/shared/package.json): 0.4.0 -> 0.4.1 - deploy/helm/sandbox-env (chart 0.9.28) (deploy/helm/sandbox-env/values.yaml deploy/helm/sandbox-env/Chart.yaml): image.tag/appVersion -> 1.22.10 Deploy-Scope: both
pedrofrxncx
added a commit
that referenced
this pull request
Jul 27, 2026
…5240) (#5269) #5240 restored per-user hosted sandboxes and deleted every reader/writer of agent_sandbox_sessions and agent_sandbox_runner_state, but deliberately kept both tables so the rollout had a rollback window. This is R2: the forward migration that drops them. agent_sandbox_runner_state.state holds plaintext credentials (an x-access-token:ghs_... clone URL, submodule tokens, the resolved env bag) and the table has no organization FK, so nothing ever GCs a row -- dormant rows are a standing secret leak, not just dead weight. Co-authored-by: Pedro França <[email protected]>
pedrofrxncx
pushed a commit
that referenced
this pull request
Jul 31, 2026
…tempt Shared agent sandboxes (#5112, #5116, #5132) shipped and were fully reverted by #5240, with migration 147 dropping the tables. The 16-hole audit of that attempt concluded "fix forward, do not revert" — that decision was overtaken, so the audit is a post-mortem, not an incident list, and its holes are restated here as twelve requirements a rebuild has to answer before code. Records the two judgement calls worth arguing with: Sharing must be explicit, never derived. The first attempt's root cause was not a missing lock — `(org, virtualMcp, branch)` plus a `staging` default silently collapsed every chat in an org onto one pod with nobody opting in. A session gets its own id, owner and participant list; per-user stays the default; a default-off org flag exists from the first commit. No CRDT. "Realtime editing" splits into a shared workspace (buildable now) and character-level co-editing (a document server, not a sandbox). File-level soft ownership, revisited only if per-file data shows real collisions. Also states the properties that are accepted rather than fixed: a shared sandbox is an org-wide read surface, the dev server is singular, and bash/exec cannot be serialized. Phase 1 is actor identity, which is additive and testable on today's per-user sandbox with no flag and no sharing model. Phase 0 (the daemon worktree lock) already landed. The branch model — hole 13, never decided — has to be resolved before Phase 2.
pedrofrxncx
pushed a commit
that referenced
this pull request
Jul 31, 2026
…tempt Shared agent sandboxes (#5112, #5116, #5132) shipped and were fully reverted by #5240, with migration 147 dropping the tables. The 16-hole audit of that attempt concluded "fix forward, do not revert" — that decision was overtaken, so the audit is a post-mortem, not an incident list, and its holes are restated here as twelve requirements a rebuild has to answer before code. Records the two judgement calls worth arguing with: Sharing must be explicit, never derived. The first attempt's root cause was not a missing lock — `(org, virtualMcp, branch)` plus a `staging` default silently collapsed every chat in an org onto one pod with nobody opting in. A session gets its own id, owner and participant list; per-user stays the default; a default-off org flag exists from the first commit. No CRDT. "Realtime editing" splits into a shared workspace (buildable now) and character-level co-editing (a document server, not a sandbox). File-level soft ownership, revisited only if per-file data shows real collisions. Also states the properties that are accepted rather than fixed: a shared sandbox is an org-wide read surface, the dev server is singular, and bash/exec cannot be serialized. Phase 1 is actor identity, which is additive and testable on today's per-user sandbox with no flag and no sharing model. Phase 0 (the daemon worktree lock) already landed. The branch model — hole 13, never decided — has to be resolved before Phase 2.
pedrofrxncx
added a commit
that referenced
this pull request
Jul 31, 2026
…5484) * feat(sandbox-daemon-go): Go daemon passing core/git/proxy/dispatch e2e suites Single Go module implementing the sandbox daemon wire contract behind DAEMON_E2E_CMD: startup contract, bearer auth + CORS + dual prefix, config store (classify/merge/validate), fs routes with safePath clamp, bash pipe-mode with process groups, task manager (TTL reaper, log tees, SSE streams), events broadcaster with replay + handshake order, setup orchestrator (FIFO rank subsumption, clone triage, install), git routes (status/diff/publish/discard/rebase), reverse proxy + WS splice, probe debounce, dispatch transport with HARNESS_RUNNER_CMD seam. Golden cache and org-fs mounting stubbed (deferred). * test(sandbox-daemon-go): guardrail unit tests Table-driven classify precedence tests, deepMerge env null-deletes, safePath clamp table + fuzz target, lifecycle phase exhaustiveness, dispatch write-after-close guard (closed-controller storm invariant), offload allowlist fail-closed, ring buffer tail, port-sniffer lock-in. * fix(sandbox): make the daemon e2e "no override" self-check env-independent resolveDaemonCmd defaulted `raw` to process.env.DAEMON_E2E_CMD, but a JS default parameter also fires on an explicit `undefined` — so the test asserting the no-override case could never express it, and the conformance suite failed on its own harness self-check under ANY DAEMON_E2E_CMD run. `raw` is now required; the env read moved to the single call site. * feat(sandbox-daemon-go): pass the full daemon conformance suite (153/153) Catches the Go daemon up to main and closes the remaining conformance gaps, so `DAEMON_E2E_CMD=<go binary> bun test daemon/daemon.*e2e*.test.ts` matches the TS baseline exactly. - POST /_sandbox/tools/sync + internal/toolscatalog: writes the endpoint file (dotfile, 0600) and one JSON Schema per tool under <repo>/.deco/tools/, prunes stale entries, git-excludes the dir. Carries a minimal MCP streamable-HTTP client (initialize -> notifications/initialized -> paged tools/list) rather than an MCP SDK — the daemon never calls tools itself, the in-workspace typegen CLI does, reading .endpoint.json. - ws proxy: report an unreachable dev server as a WebSocket close (complete the 101, then close 1011) instead of a 502 on the upgrade, which the client surfaces as a protocol error. - publish: push --no-verify, so a repo's own pre-push hook can't fail or hang the shutdown sync out of its grace period. - Because --no-verify skips the pre-push hook entirely, port the in-code protected-branch guard too: {main, master, origin's actual default}, refused before the commit so no stray commit lands either, mapped to 409. The hook's branch list is a data file, so an unusual ref name can't inject shell syntax. README.md documents the DAEMON_E2E_CMD contract, the package<->TS map, the invariants that must be carried, and — deliberately — the gap ledger plus what the suite does NOT prove (harness dispatch is gate-only; org-fs mounting, golden cache, decofile validation and six more behaviors are unported and untested). It replaces the docs-design RFCs, which were never committed and are lost. * docs(sandbox-daemon-go): spec the path to running a real pod Gates G0-G6 with exit criteria rather than a task list, ordered so the every-sandbox path (observability -> correctness -> boot cost -> real pod) lands before dispatch, which is one route on the daemon and gates only its own traffic. Calls out the things the conformance suite structurally cannot catch: the uid/gid drop Bun has silently ignored for years and Go will actually honor, the single-missed-probe teardown, SIGTERM-publish inside the real grace period, and the harness bridge (its e2e is gate-only). * feat(sandbox-daemon-go): close G2 (decofile, SSRF, force-push, prune) and dep telemetry Conformance suite now 176/176 on both daemons. Three TS-daemon bugs found and fixed along the way: the decofile net never fired for a new block, the URL offload routes had no SSRF validation at all, and a zero-dep install logged an error instead of its telemetry line. * feat(sandbox-daemon-go): golden L1, org-fs links, watcher, runtime impl switch Closes the remaining code-side gates from PRODUCTION-READINESS.md. The conformance suite is 184/184 on both daemons, and CI now runs it against both instead of the docs claiming it. - G3 (L1): reflink golden node_modules cache — restore/publish keyed by (repo, pm, lockfile), publish held until the probe reports the dev server healthy, TTL + per-repo cap GC, dormant behind GOLDEN_CACHE_ENABLED. The e2e asserts the publish is never even ATTEMPTED on an unhealthy boot; asserting an empty store would pass on a non-CoW filesystem while the gate was broken. - G4/G1: org-fs links for the cluster path — sidecar status gate, one-shot first-mount grace, repo/org link (git-excluded), per-run output/upload thread links. Mounting stays unported on purpose: a pod cannot mount (the sidecar does), and daemon-side mounting is the desktop path, which runs the TS bundle. - G1: catalog re-sync on dispatch (coalesced per endpoint, 60s floor) and fsnotify-based change detection, so a file written through bash — i.e. by every CLI harness — surfaces as file-changed instead of waiting on the 3s poll. The e2e for it is control-tested: it fails with the watcher disabled. - G4: probe-under-load e2e against Studio's real 500ms budget. Measured here, Go worst 1ms vs TS worst 186ms while git status runs over 4000 dirty files. - G6: both daemons ship in the image; SANDBOX_DAEMON_IMPL (default ts) selects one at container start via an exec'd entrypoint, exposed as the chart's daemonImpl. Env, not CMD — a rebuild is not a rollback. CI smokes both. Still needs a human: the harness-runner transport pick (the reading now argues for the extraction branch's loopback HTTP — no HARNESS_RUNNER_CMD runner exists in this repo at all), the real-pod session, and the canary + rollback drill. * feat(sandbox-daemon-go): dispatch harnesses over the loopback-HTTP runner Settles G5's transport (owner decision): the Go daemon now speaks the protocol `wt/harness-runner-extraction` defines — spawn with HARNESS_RUNNER_MODE=1 and a per-spawn token, parse HARNESS_RUNNER_READY, POST /run with that bearer, stream NDJSON, cancel by aborting the request. The stdio spawner is deleted rather than kept alongside it. That branch already ships the runner, its e2e, and a protocol.ts whose docblock says it is the piece a non-TS daemon reimplements; stdio had no runner in the repo at all, so picking it meant writing an untested one and discarding tested code. One shared runner, spawned on demand, never auto-respawned: a crash costs each in-flight run one harness_crashed and the next dispatch spawns fresh, where a respawn loop would turn one bad run into a storm. The daemon holds the runner's stdin open and never writes to it, so the pipe closing is what tells the runner this daemon died — including under SIGKILL. The HTTP client has no overall timeout (a run streams for minutes); only the response headers are deadlined. runner_test.go drives the bridge with the test binary re-executed as a fake runner: frame integrity, reuse across runs, respawn after a mid-stream death, cancelling one run without killing the runner, a runner that never reports ready, and a missing binary. Suite still 184/184 on both daemons. Still needed for a real run: merge wt/harness-runner-extraction so HARNESS_RUNNER_CMD has something to point at. * docs(sandbox-daemon-go): plan the targeted prod rollout Two findings drive the shape of it. Harness dispatch is not used by cluster sandboxes: localDispatch is documented as the only dispatch path for hosted harnesses, the cluster runs the harness in the API process with no HTTP, and the only callers of the daemon's /dispatch are the desktop link path and apps/native's e2e. So G5 does not gate this rollout — it gates cloud-CLI, whenever that lands. The per-sandbox opt-in cannot be a per-claim env var. SANDBOX_DAEMON_IMPL is read at container start, and in warm-pool mode the operator rejects claim.spec.env outright — so an env-based choice would force warmpool:"none" and a cold pod per Go sandbox, confounding the boot comparison the canary exists to make. What is per-claim is sandboxTemplateRef, so selection is by template: a second SandboxTemplate + small warm pool in the SAME helm release (a second release would mint a second sentinel Secret that Studio cannot authenticate against). Control is three independent layers — a global env kill switch, a per-org flag for who gets Go by default, and the SANDBOX_START prop for targeting one sandbox — resolved prop → flag → ts, with the choice persisted per sandbox so pod recovery cannot silently change implementation mid-life. * docs(sandbox-daemon-go): fold everything into one spec SPEC.md is now the single authoritative document — startup and wire contracts, carried invariants, what is proven and by which test, what is deliberately not ported and under what precondition, the targeted prod rollout, risks, and the open actions that need a human. PRODUCTION-READINESS.md is deleted rather than left beside it: two overlapping docs is how the last one ended up claiming 176/176 while the suite was at 184, and how the gap ledger kept listing work that had already landed. The gate names (G0-G6) are retired. A closed gate is just a row in the evidence table; the ones still open are phases in the rollout section, where they are actionable. README.md keeps only package orientation and points at the spec. * feat(sandbox): name the daemon implementation in one boot log line Two daemons ship in the same image behind SANDBOX_DAEMON_IMPL, so a pod's log has to say which binary ran — without it the Go canary's panels are a guess. Both daemons now emit an unconditional `impl=` boot line (`impl=go` / `impl=ts`), greppable with one pattern. * fix(sandbox): re-gate every redirect hop in the TS daemon's URL transfers CI, running on this branch for the first time, hung the SSRF test for 5s instead of failing it. Two real bugs behind that: 1. write_from_url validated only the caller's URL and then used a plain fetch, whose default redirect:"follow" chases a 302 anywhere — so an allowed origin answering `302 -> https://169.254.169.254/...` walked the daemon into the cloud metadata endpoint. The Go daemon already did this correctly via urlallow.Client's CheckRedirect; the TS daemon, the one actually in production, did not. Both transfer routes now go through fetchAllowedUrl, which re-asserts the allowlist on every hop. upload_to_url uses maxRedirects: 0 — its body is a one-shot stream that could not be replayed to a second URL even if that URL were allowed. 2. The test asserted only "not 200", which a laptop satisfies by failing to connect to that address. It now asserts the rejection *reason*, so a daemon that follows the redirect cannot pass by hitting a closed port. Also fixes the golden-cache clone probe, which cloned an empty directory: copying no data blocks succeeds under `cp --reflink=always` even on ext4, so CI picked the reflink cloner and then failed on the first real tree. The probe writes a file, and the macOS clonefile arm is GOOS-gated rather than probed (GNU cp also accepts -c, which would have made a plain copy report itself as copy-on-write). Verified: 184/184 on both daemons locally, go test -race clean. * chore(sandbox): drop the daemon-go spec docs and trim comment bloat * ci(native): re-pin the daemon-parity fail-set for the new daemon behaviors The parity oracle asserts an EXACT failing-test set against local-api, so every test this branch added for a behavior the Rust crate does not have reads as a regression. 18 new, 1 vanished (the swappable-spawn-target self-check now passes). Derived from the run's own junit with the gate's own extractor rather than transcribed, so the strings cannot drift. The header comment now says what each pinned name IS, and separates the two deliberate divergences (auth/CORS tightening, no-publish-on-close) from the 19 that are simply unported. Naming that split matters most for the 11 url-transfer SSRF entries: local-api's write_from_url / upload_to_url have no allowlist and follow redirects, which is a real hole in the desktop app, pinned only to keep this a set match — not sanctioned. * refactor(sandbox-daemon-go): route with ServeMux, serialize the working tree Two changes to the Go daemon, no change to its wire contract. Leaner routing. A 130-line if/switch ladder, three regexes, a prefix matcher and a stringly-typed `map[string]http.HandlerFunc` are replaced by declarative `http.ServeMux` registration (Go 1.22 method+wildcard patterns). `taskIdFrom` and exec's `strings.Index` arithmetic become `r.PathValue`. The routing table is now the single place that knows which routes are authenticated, which get org-fs links, and which mutate the tree. The mux deliberately covers only `/_sandbox` and `/_decopilot_vm`: ServeMux cleans and 301-redirects paths, which is right for our own API and wrong for whatever the tenant's dev server serves, so the proxy stays off it. The unauthenticated catch-all keeps returning 401 rather than 404 so routes cannot be enumerated without a token. Also dropped: a dead `ChunkBroadcaster` interface, a dead `_ = truncated`, an anonymous `interface{ Read(...) }` that was `io.Reader`, hand-rolled image magic-byte sniffing (`http.DetectContentType`), and a provably-empty loop in `orchestrator.enqueue` — the early return above it guaranteed `kept` was always empty, so the queue only ever holds one step. Serialize the working tree. The daemon had no serialization at all, and `/edit` is read-modify-write: concurrent edits to one path lose updates. The daemon is the only component that sees every writer of a tree, so the lock belongs here. `internal/worktree` holds one mutex taken by the mutating fs routes, by publish/discard/rebase, and by the shutdown sync. Reads and the frequently polled git status/diff stay unguarded; `bash`/`exec` cannot be held (they are long-running and would stall every other writer), so a bash write can still interleave with a publish — noted at the registration site. The regression test appends through the guarded handler from 50 goroutines. Without the lock 45 of 50 writes are lost. The TS daemon has the same race and no equivalent fix; it is the one in production. * feat(sandbox): ship the Go daemon as its own image, not a runtime switch The daemon implementation becomes the image: `studio-sandbox` runs the TS daemon, `studio-sandbox-go` the Go one. A SandboxTemplate picks a daemon by picking an image, and a claim picks the template — so a pod cannot disagree with the template that created it, and which daemon ran is provable by inspecting the image rather than by reading an env var out of a pod spec. This replaces `SANDBOX_DAEMON_IMPL` and `start-daemon.sh`, both deleted. The original argument for an env switch was that "a CMD change is a rebuild and a rebuild is not a rollback" — that no longer applies: with one template per image, rollback is a per-claim template swap, which is faster and finer-grained than the env switch ever was. One Dockerfile, one shared `runtime-base` carrying everything expensive (LibreOffice, Python, Node, Deno, corepack, node-pty), then two leaf stages that differ only in the daemon they copy and their CMD. The two images are therefore byte-identical below their daemon layer and the second build costs the Go compile plus one thin layer. `ts` is the LAST stage on purpose, so a bare `docker build` still produces the TS image and no existing build command changes meaning. Chart: `daemonImpl` selects image.repository vs image.goRepository instead of injecting env. One tag drives both images — they are released together from the same source revision and must never skew. `sandbox-env.validateDaemonImpl` fails at template time on an unrecognised impl or a missing goRepository: the failure mode it prevents is a typo falling through to the TS repository, which would give a canary that reads "Go is fine" while never having run Go. The default render is unchanged. CI smokes both images and asserts each logs the `impl=` it claims, so an image that shipped the wrong daemon fails there instead of in a canary panel. The release workflow builds, signs and attests both. Versions bumped because the release workflow skips a build when the tag already exists: without it studio-sandbox-go:1.28.4 would never be published while the chart already referenced it. Follow-ups, outside this commit: - deco-apps-cd's bump-image receiver matches a `repository:` line; the new `goRepository:` value is a superstring of the match target, so verify it matches on the exact value before this ships. - #5485 (second SandboxTemplate) already ranges over `$t.impl`; it needs the env block dropped, its image line selecting on impl, and its chart bump moved to 0.9.53. * docs(sandbox): spec collaboration sandboxes as a greenfield second attempt Shared agent sandboxes (#5112, #5116, #5132) shipped and were fully reverted by #5240, with migration 147 dropping the tables. The 16-hole audit of that attempt concluded "fix forward, do not revert" — that decision was overtaken, so the audit is a post-mortem, not an incident list, and its holes are restated here as twelve requirements a rebuild has to answer before code. Records the two judgement calls worth arguing with: Sharing must be explicit, never derived. The first attempt's root cause was not a missing lock — `(org, virtualMcp, branch)` plus a `staging` default silently collapsed every chat in an org onto one pod with nobody opting in. A session gets its own id, owner and participant list; per-user stays the default; a default-off org flag exists from the first commit. No CRDT. "Realtime editing" splits into a shared workspace (buildable now) and character-level co-editing (a document server, not a sandbox). File-level soft ownership, revisited only if per-file data shows real collisions. Also states the properties that are accepted rather than fixed: a shared sandbox is an org-wide read surface, the dev server is singular, and bash/exec cannot be serialized. Phase 1 is actor identity, which is additive and testable on today's per-user sandbox with no flag and no sharing model. Phase 0 (the daemon worktree lock) already landed. The branch model — hole 13, never decided — has to be resolved before Phase 2. --------- Co-authored-by: Pedro França <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Reverts #5112 (share agent sandboxes by branch), #5116 (always share agent sandboxes) and #5132 (use shared staging branch), restoring the pre-#5112 behaviour: hosted agent sandboxes are per-user again, and a new GitHub-backed thread gets a generated branch instead of
staging.This is R1 (code only). The two tables stay in place — see Migrations and Deploy order. It must not ship before the drain (below).
Why it isn't a
git revertNone of the three commits reverse-apply. Measured against
origin/main: reverting #5112 alone produces 33 conflicted paths, and resurrects three files at the deadapps/mesh/path.apps/meshintoapps/api+apps/web, and also hoistedbranch-name.ts,runtime-defaults.tsandthread/schema.tsintopackages/shared— which is whereDEFAULT_WORKSPACE_BRANCH = "staging"lives, i.e. the whole point of feat(sandbox): use shared staging branch #5132.vm-events.tsoutright, so feat(sandbox): share agent sandboxes by branch #5112's largest single-file hunk (+180) has no target.So each file was reconstructed against its current path, using
git show 5b0d71784:<old-path>as the specification, then diffed back against that baseline to prove convergence.The load-bearing change
SandboxIdreturns to a flat{ userId, projectRef }andsandboxIdKeyto`${userId}:${projectRef}`. The claim handle isslugify(branch)-sha256(idKey).slice(0,16), so every live shared claim gets a different address the moment this deploys.deleteHttpRouteIfManaged, whose call path this PR deletes → the Route leaks and 502s.Uncommitted work is mostly safe: the daemon registers
SIGTERM → shutdown() → publish(...)(packages/sandbox/daemon/entry.ts:919-960, covered bydaemon.git.e2e.test.ts:174), and the operator's teardown is an ordinary Delete → SIGTERM within the grace period.Required before deploy
provisioningrow to reachreadyso it has a handle.agent_sandbox_sessionsrow on the current code (the teardown paths are deleted by this PR). NoteSANDBOX_DELETEmarks rows terminal even when it deleted nothing — a NULL-handle row skipsrunner.delete, and a rejection is swallowed. "Zero non-terminal rows" is not a completion signal; only thekubectlcheck is.kubectl -n <ns> delete httproute -l 'studio.decocms.com/role=claimed,studio.decocms.com/org-id,!studio.decocms.com/user-id'(theorg-idterm matters —!user-idalone also matches tenant-less internal sandboxes).sandboxMapentries. fix(sandbox): stop trusting legacy agent-sandbox entries on the agent row #5225's message records ~1789 leftoveragent-sandboxcells on agent rows. They're inert today; after this PR they are authoritative again and point at long-reaped claims. Strip theagent-sandboxand legacyclusterkeys from each branch cell (keepuser-desktop) on the old code, where it's behaviourally a no-op.Migrations
Both migrations are pure
CREATE TABLE— neither alters a pre-existing table, so nothing is lossy. They are kept, byte-identical, along with theirindex.tsentries.Deleting them would crash-loop every pod. In
[email protected]'smigrator.js,#ensureNoMissingMigrationsruns at :447 — unconditionally, outside theallowUnorderedMigrationsgate at :448 — and throwscorrupted migrations: previously executed migration ... is missingat :495. SoallowUnorderedMigrations: truewould not help. Migrations run on boot (settings/pipeline.ts:50); nothing underdeploy/orselfhost/sets--skip-migrations.CI would not catch it:
storage-integration.ymlmigrates a fresh Postgres from an empty ledger, andmigrations/index.test.tsonly checks file↔registration parity, so deleting file and entry together passes both.The tables are dropped by a follow-up forward migration
145-drop-agent-sandbox-tables.tsin R2, after R1 has fully rolled out. Worth doing rather than leaving them dormant:agent_sandbox_runner_state.stateholds plaintext credentials (anx-access-token:ghs_…clone URL, submodule tokens, the env bag) and has no organization FK, so nothing ever GCs it.Deploy order
R1 = this PR (tables left in place, harmless — nothing reads them). R2 = migration 145. Same-release drops mean an old pod hits
relation "agent_sandbox_sessions" does not existon everySANDBOX_START; the chart runs migrations from the app CMD, so there's no natural barrier. Two releases also buy a rollback window.Also reverted
These exist only inside the shared model:
withoutLegacyAgentSandboxEntriesstrips exactly theagent-sandboxsandboxMap entries the reverted server writes back, while the session graft that compensated is gone —vmEntrypermanently null →shouldAutoStartpermanently true →SANDBOX_STARTon every mount and branch switch. It compiles fine; nothing but a deliberate decision catches it.resolveSharedThreadVm+ the shared-scope branch. Its hoist of the unconditional thread-map cleanup is kept — that bug is scope-independent and pre-dates sharing.provisioningreset; lived inside the deleted storage class.Deliberately preserved
withClaimGitLock, fix(virtual-mcp): require org context for id-scoped legacy MCP requests #5126 org-context guard, fix(threads): skip chat_started analytics on an id-collision replay #5143 analytics gate, fix(chat): refresh read-only teammate thread metadata so preview finds the repo #5171 owner-keyed thread graft, fix(sandbox): auto-retry transient SANDBOX_START failures without a refresh #5195/fix(sandbox): surface terminal claim failure so preview stops spinning forever #5207/fix(sandbox): auto-retry transient claim failures before showing errored #5210/fix(sandbox): scope the claim auto-retry budget to the active branch #5221 client auto-retry, the daemon status-code train (fix(sandbox): return 409 instead of 500 for publish refusals on detached HEAD/protected branch #5109/fix(sandbox): stop discard from deleting renamed files with no recovery #5124/fix(sandbox): return 409 instead of 500 for a blocked rebase #5134/fix(sandbox): return 400 instead of 500 when the diff base branch isn't on origin #5142/fix(sandbox): return 400 instead of 500 when the rebase base branch isn't on origin #5144/fix(sandbox): return 400 instead of 500 for non-string entries in git/discard filepaths #5150/fix(sandbox): reject empty base string in git/diff POST endpoint #5175/fix(sandbox): return 400 instead of 500 for empty-string entries in git/discard filepaths #5189/fix(sandbox): return 409 instead of 500 for tokenless GitHub publish #5211), the settings-validation train.{ self: ["ORG_FS_READ", "ORG_FS_WRITE"] }(reverting would re-bake a full-management key into every sandbox pod), andsandboxProviderKindstays in the start dedup key.isValidRemoteBranchNameinclone.ts,assertValidRemoteBranchNameincheckout-branch.ts). feat(sandbox): use shared staging branch #5132 removed them as dead once the base was a constant; this PR restores the dynamic, remote-controlledorigin/HEADlookup, so they are load-bearing again. This is the one place a naive revert silently drops hardening.Testing
bun run check,bun run lint(0 errors),bun run fmt— clean.apps/web: 23 failures — the identical set asorigin/main(pre-existing); the 6-test delta is exactly the deletedagent-sandbox-map.test.ts.apps/api+ packages: 245 pre-existing failures on both branches (integration tests needing Postgres/NATS). 0 new; 1 gone — the deleted shared-sandbox integration test.5b0d71784blob. Residuals are only refactor(studio): split API and web workspaces #5120 specifier rewrites plus the preserved work listed above.start.test.tsasserts{ userId, projectRef }again,handle.test.tsdrops the shared/user isolation cases,runtime-defaults.test.tsdrops thestaging/mainassertions, andchat-locked-thread.spec.tsis back to thepickWarmBranchFromSandboxMap → generateBranchName()wording.Not run locally: real-Postgres integration tests and the Playwright e2e suite — CI covers both.
Open items
branch = 'staging'(persisted column,storage/types.ts:945/:1032). Post-revert two members get separate pods on the same branch, and the second non-forcegit push -u origin stagingis rejected non-fast-forward — a failure mode that didn't exist pre-feat(sandbox): use shared staging branch #5132, when every thread had a unique generated branch. Do not null the column (that orphans theorigin/stagingwork and breaksexistingThread?.branch ?? input.branch). Either accept with a release note, or rewrite to per-thread names after pushing each staging workspace. Needs a decision + the row counts.gonefor orphaned thread sandboxes on shared scope #5219/fix(sandbox): stop trusting legacy agent-sandbox entries on the agent row #5225 intentionally lost? They fixed real symptoms ("preview stuck on Reserving sandbox", "works for me, stuck for you"). Confirm they can't recur in the per-user model.useAgentSandboxSessionpolled/api/:org/agent-sandbox-sessions/:vmidevery 5s. Already-loaded tabs will 404 until reload. Optionally leave the route mounted returning an empty list for one release.staging? The daemon'sprotectedBranches()is{main, master, origin/HEAD default}, sostagingwas freely pushable — if a customer has since protected it, post-revert publishes fail differently.🤖 Generated with Claude Code
Summary by cubic
Reverts shared agent sandboxes and the
stagingdefault. Sandboxes are per-user again, and new GitHub-backed threads pick a warm branch or get a generated name.Refactors
SandboxIdis{ userId, projectRef }andsandboxIdKeyisuserId:projectRef.computeClaimHandlenow hashesuserId:projectRef, so existing shared handles will change.agent-sandbox-sessionsAPI/routes/storage and related client hooks; provider resolution no longer looks up shared sessions and uses the acting user’ssandboxMapinstead.sandboxMap, falling back togenerateBranchName; the fixedstaging/maindefaults are removed; daemon base-branch logic readsorigin/HEADand validates remote ref names.dev-connectionresolves only to the acting user’s sandbox; branch picker/use-branches no longer depend on shared sessions; addsreadCachedTaskBranchto carry the active task’s branch into new threads; keeps fix(chat): New chat always creates, on the current branch #5231’s caller-passed branch param path; generates a branch on publish when missing.Migration
Written for commit d0c070b. Summary will update on new commits.