Files
PaperClipAI/server/src/services/managed-environments.test.ts
T
Nicky LeachandClaude Sonnet 5 9effe51b63 fix(server): let the cloud-harness sandbox environment self-heal past operator-drift protection (#13177)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Every cloud-harness-managed stack gets one platform-owned "Paperclip
Computer" sandbox environment, reconciled from
`PAPERCLIP_MANAGED_CONFIG` on boot
> - That reconciler deliberately refuses to overwrite a row it
classifies as operator-modified, to protect a self-hosted operator's
hand-edited environment (#10979)
> - But for the cloud-harness-managed row specifically, no operator has
any path to hand-edit it at all — so a hash mismatch there can only be
drift between two platform-driven reconciliation passes, never a real
customization
> - Roughly 10 staging stacks got stuck on a broken sandbox image
because of exactly this: a `sandbox_image` campaign correctly delivered
a fixed snapshot, but the reconciler classified the row as
operator-modified and silently skipped applying it
> - This pull request adds an explicit `platformFullyManaged` flag so
the cloud-harness caller can assert that guarantee and let its own drift
self-heal, without weakening the protection for every other caller
(self-hosted kubernetes-execution-mode, tests, admin routes) where an
operator genuinely can edit the row
> - The benefit is that a sandbox-image rollout can no longer get
silently stuck fleet-wide, while self-hosted operator customization
keeps exactly the protection #10979 built

## Linked Issues or Issue Description

No public issue exists for this internal-instance-discovered bug;
opening directly per CONTRIBUTING.md path B, following the bug report
template fields.

**What happened?**
After a `sandbox_image` campaign delivered a fixed Daytona snapshot
fleet-wide, ~10 of 79 active staging stacks kept booting agents against
the old, broken snapshot. Their `PAPERCLIP_MANAGED_CONFIG` env var and
the reconciler's own bookkeeping (`built_in_managed_resources`) both
correctly showed the new snapshot — but `environments.config.snapshot`,
the field the runtime actually reads to acquire a sandbox lease, was
never updated on those rows.

**Expected behavior**
A `sandbox_image` campaign (or any `PAPERCLIP_MANAGED_CONFIG` delivery)
to the cloud-harness-managed sandbox environment should always converge
that row's `config` to the newly-desired value, since no operator can
have a competing edit to protect.

**Steps to reproduce**
1. Boot a cloud-harness-managed stack; let the reconciler create the
managed sandbox row and record its stock hash in
`built_in_managed_resources`.
2. Somehow cause the row's live content hash to no longer match the
recorded binding hash without an operator ever touching it (in the
field, this happened via drift between two platform-driven
reconciliation passes carried out across a catalog-version bump — the
exact trigger wasn't fully pinned down, but is irrelevant to the fix).
3. Deliver a new `PAPERCLIP_MANAGED_CONFIG` (e.g. via a `sandbox_image`
campaign).
4. Observe `ensureManagedSandboxEnvironment` classify the row
`operator_modified` and skip writing `config`, even though
`updateAvailable: true` is reported and the binding itself already
advanced to the new stock hash.

**Paperclip version or commit**
`master` as of this PR.

**Deployment mode**
Cloud-managed stacks with `enableManagedSandboxOnly` declared (any
Paperclip Cloud–provisioned staging or production stack).

Related PR for context (not a duplicate — this is additive to it, not a
revert): #10979, which introduced the `operator_modified` classification
this PR narrowly opts the cloud-harness path out of.

## What Changed

- `server/src/services/environments.ts`: added `platformFullyManaged?:
boolean` to `ManagedSandboxEnvironmentInput`. When set, a plain
content-hash mismatch against a real prior binding (i.e.
`operator_modified` that isn't an archive-reaffirmation) is reclassified
as `stock_update_available` before the skip-vs-apply branch, so it flows
through the normal update path instead of being frozen.
- `server/src/services/managed-environments.ts`: pass
`platformFullyManaged: true` from both `ensureManagedSandboxEnvironment`
call sites — the main boot ensure and the provider-recovery reactivation
path. These are the *only* two callers driven by
`PAPERCLIP_MANAGED_CONFIG`; `ensureKubernetesEnvironment` (self-hosted
`kubernetes-execution-mode` bootstrap) and every other caller are
untouched and keep the original protective default.
- `server/src/services/managed-environments.test.ts`: updated the two
`toHaveBeenCalledWith` assertions that now include the flag.
- `server/src/__tests__/environment-service.test.ts`: two new tests —
one confirming the bypass applies drift under `platformFullyManaged`,
one confirming archive-reaffirmation still wins even under the flag.

Archive-reaffirmation is deliberately *not* bypassed even under
`platformFullyManaged`: a `sandbox_image` update must never resurrect a
row something else deliberately kept archived after Paperclip's own
provider-unavailability archival. That's a distinct, still-real signal,
orthogonal to config drift.

## Verification

- `vitest run` on `managed-environments.test.ts` and
`managed-resource-drift.test.ts`: 26/26 pass, including the two updated
assertions.
- `environment-service.test.ts` — the file both new tests live in, and
the file holding the two pre-existing tests this change must not regress
("classifies operator drift, preserves the row, and exposes the pending
stock update" and "preserves an existing unmanaged sandbox row holding
the desired name") — requires a real embedded-Postgres instance
(`describeEmbeddedPostgres`) not available in the sandbox this was
developed in; `getEmbeddedPostgresTestSupport()` reports unsupported
there, so the whole file is skipped locally. I traced the reconciliation
logic by hand against all four relevant tests (the two new ones plus the
two pre-existing ones) line by line to confirm the expected outcomes,
but **CI running this suite for real is the actual gate here**, not this
description — please don't merge on a green run of everything else alone
if this suite doesn't show as executed.
- `tsc --noEmit`: zero errors in any of the four touched files. The
pre-existing ~229 errors elsewhere in `server` are unrelated
missing-module issues from packages needing a build step first,
confirmed unchanged by this diff.
- Manually reproduced the underlying bug against real staging data (a
`paperclip-cloud`-managed stack whose `environments` row was stuck
exactly this way) before writing the fix, and confirmed via direct SQL
inspection that the recorded `built_in_managed_resources` baseline
already held the correct desired snapshot on every affected stack — i.e.
the reconciler already *knew* the right answer, it was just refusing to
apply it. That data point is what ruled out "the campaign didn't
actually deliver the update" as the cause.

## Risks

- Scope is intentionally narrow: only the two
`PAPERCLIP_MANAGED_CONFIG`-driven call sites pass the new flag; every
other caller of
`ensureManagedSandboxEnvironment`/`ensureKubernetesEnvironment` is
byte-for-byte unchanged. The two pre-existing regression tests that
specifically cover self-hosted operator-edit protection don't pass this
flag and are unmodified.
- The main residual risk is the unresolved root cause of *why* the hash
drifted in the first place (a race between two close-together
reconciliation passes, or a catalog-version-dependent change to what
gets hashed, most likely) — this PR makes that drift self-healing rather
than fixing whatever produces it. If the drift is being caused by a
genuine concurrency bug (rather than an expected, occasional side effect
of a stock-field/catalog-version change), that bug still exists and
could recur; it just no longer gets stuck when it does.
- Low risk of behavior change for real self-hosted deployments: none of
them can reach the new code path, since only the two now-flagged call
sites exist inside `managed-environments.ts`, itself gated to
`PAPERCLIP_MANAGED_CONFIG` (which self-hosted
`kubernetes-execution-mode` explicitly refuses to run alongside — see
the existing mutual-exclusivity check this PR does not touch).

## Model Used

Claude Sonnet 5 (`claude-sonnet-5`), via Claude Code, with tool use
(file edits, shell/git, `gh` CLI, direct Postgres inspection of live
staging data via `psql`/`pg`, Railway SSH for on-host diagnosis). No
extended-thinking mode. Standard Claude Code context window.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass — see Verification: the
file holding the four load-bearing tests can't run in this sandbox (no
embedded-Postgres support); traced by hand instead, CI is the real gate
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes — none
applicable beyond the inline doc comments this PR adds
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green — pending CI run on this PR
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
pending review
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 19:23:13 -07:00

655 lines
23 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { MANAGED_CONFIG_ENV_KEY, parseManagedConfigEnv } from "./managed-config.js";
import {
applyManagedEnvironments,
type ApplyManagedEnvironmentsOptions,
} from "./managed-environments.js";
const noDb = null as unknown as Db;
function parsedConfig(overrides: Record<string, unknown> = {}) {
const config = parseManagedConfigEnv({
[MANAGED_CONFIG_ENV_KEY]: JSON.stringify({
v: 1,
mode: "cloud",
catalogVersion: "2026.720.0",
features: {},
plugins: { autoInstall: ["daytona"] },
...overrides,
}),
});
if (!config) throw new Error("expected a parsed managed config");
return config;
}
function environmentRow(overrides: Record<string, unknown> = {}) {
const now = new Date();
return {
id: "env-1",
name: "Daytona",
description: null,
driver: "sandbox",
status: "active",
config: {},
envVars: {},
metadata: {},
createdAt: now,
updatedAt: now,
...overrides,
};
}
function reconciliationResult(
overrides: Record<string, unknown> = {},
) {
return {
environment: environmentRow(),
action: "added" as const,
stockStatus: "missing" as const,
updateAvailable: false,
stockHash: "sha256:stock",
...overrides,
};
}
function readyDriverResolver(status = "ready") {
return vi.fn(async () => ({
plugin: { id: "plugin-1", pluginKey: "sandbox-providers/daytona", status },
}));
}
function runningWorkerManager(running = true) {
return { isRunning: vi.fn(() => running), getWorker: vi.fn(() => undefined) };
}
type WorkerManagerSeam = NonNullable<ApplyManagedEnvironmentsOptions["workerManager"]>;
type RecoveryHandle = NonNullable<ReturnType<WorkerManagerSeam["getWorker"]>>;
/** A worker handle fake that records `ready` listeners so tests can fire them. */
function recoveryHandle() {
const readyListeners: Array<(payload: { pluginId: string }) => void> = [];
const handle: RecoveryHandle = {
on: vi.fn((_event, listener) => {
readyListeners.push(listener);
}),
off: vi.fn((_event, listener) => {
const at = readyListeners.indexOf(listener);
if (at !== -1) readyListeners.splice(at, 1);
}),
};
return {
handle,
fireReady: () => {
for (const listener of [...readyListeners]) listener({ pluginId: "plugin-1" });
},
};
}
/** Lets the fire-and-forget recovery ensure settle. */
function tick() {
return new Promise((resolve) => setImmediate(resolve));
}
type EnvironmentsSeam = NonNullable<ApplyManagedEnvironmentsOptions["environments"]>;
type InstanceSettingsSeam = NonNullable<ApplyManagedEnvironmentsOptions["instanceSettings"]>;
function environmentsSeam(overrides: Partial<EnvironmentsSeam> = {}): EnvironmentsSeam {
return {
ensureManagedSandboxEnvironment:
overrides.ensureManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(reconciliationResult()),
archiveManagedSandboxEnvironment:
overrides.archiveManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(null),
getById: overrides.getById ?? vi.fn().mockResolvedValue(null),
update: overrides.update ?? vi.fn().mockResolvedValue(environmentRow()),
findManagedSandboxEnvironment:
overrides.findManagedSandboxEnvironment ?? vi.fn().mockResolvedValue(null),
};
}
function instanceSettingsSeam(overrides: Partial<InstanceSettingsSeam> = {}): InstanceSettingsSeam {
return {
get:
overrides.get ??
(vi.fn().mockResolvedValue({ defaultEnvironmentId: null }) as InstanceSettingsSeam["get"]),
update:
overrides.update ??
(vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["update"]),
};
}
describe("applyManagedEnvironments", () => {
it("no-ops for self-hosted instances and for documents without environments", async () => {
expect(await applyManagedEnvironments(noDb, null)).toBeNull();
expect(await applyManagedEnvironments(noDb, parsedConfig())).toBeNull();
});
it("refuses startup when a forced execution mode also claims the managed sandbox slot", async () => {
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
await expect(
applyManagedEnvironments(noDb, config, {
env: { PAPERCLIP_EXECUTION_MODE: "kubernetes" },
}),
).rejects.toThrow(/mutually exclusive/);
});
it("ensures each declared environment through the provider-agnostic service call", async () => {
const ensureManagedSandboxEnvironment = vi
.fn()
.mockResolvedValue(reconciliationResult());
const config = parsedConfig({
environments: [
{
name: "Daytona",
description: "Managed Daytona sandbox.",
provider: "daytona",
config: { target: "us" },
},
],
});
const resolveSandboxProviderDriver = readyDriverResolver();
const workerManager = runningWorkerManager();
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
instanceSettings: instanceSettingsSeam(),
environments: environmentsSeam({ ensureManagedSandboxEnvironment }),
resolveSandboxProviderDriver,
});
expect(result).toMatchObject({ ensured: 1, failed: 0, added: 1, skipped: 0 });
expect(result).toMatchObject({ removed: 0, backedUp: 0 });
expect(resolveSandboxProviderDriver).toHaveBeenCalledWith({ db: noDb, driverKey: "daytona" });
expect(workerManager.isRunning).toHaveBeenCalledWith("plugin-1");
expect(ensureManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
expect(ensureManagedSandboxEnvironment).toHaveBeenCalledWith({
name: "Daytona",
description: "Managed Daytona sandbox.",
provider: "daytona",
config: { target: "us" },
stockVersion: "2026.720.0",
platformFullyManaged: true,
});
// The frozen parsed config must not leak into the service (the row's
// config is mutated downstream when the provider key is forced in).
const passedConfig = ensureManagedSandboxEnvironment.mock.calls[0]?.[0]?.config;
expect(Object.isFrozen(passedConfig)).toBe(false);
});
it("waits for the bundled-plugin startup pass before ensuring anything", async () => {
const ensureManagedSandboxEnvironment = vi
.fn()
.mockResolvedValue(reconciliationResult());
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
let releasePlugins!: () => void;
const pluginsReady = new Promise<void>((resolve) => {
releasePlugins = resolve;
});
const pending = applyManagedEnvironments(noDb, config, {
env: {},
pluginsReady,
workerManager: runningWorkerManager(),
instanceSettings: instanceSettingsSeam(),
environments: environmentsSeam({ ensureManagedSandboxEnvironment }),
resolveSandboxProviderDriver: readyDriverResolver(),
});
// Give the ensure every chance to (incorrectly) run early.
await new Promise((resolve) => setImmediate(resolve));
expect(ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
releasePlugins();
expect(await pending).toMatchObject({ ensured: 1, failed: 0, added: 1 });
expect(ensureManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
});
it("reports operator-modified rows as skipped with a stock update still available", async () => {
const environments = environmentsSeam({
ensureManagedSandboxEnvironment: vi.fn().mockResolvedValue(reconciliationResult({
action: "skipped",
stockStatus: "operator_modified",
updateAvailable: true,
})),
});
const result = await applyManagedEnvironments(noDb, parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
}), {
env: {},
workerManager: runningWorkerManager(),
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(result).toMatchObject({
ensured: 0,
failed: 0,
added: 0,
updated: 0,
unchanged: 0,
skipped: 1,
outcomes: [{
action: "skipped",
stockStatus: "operator_modified",
updateAvailable: true,
}],
});
});
it("skips an entry whose provider plugin is missing and archives its stale row", async () => {
const environments = environmentsSeam({
archiveManagedSandboxEnvironment: vi.fn().mockResolvedValue(environmentRow({ status: "archived" })),
});
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
environments,
resolveSandboxProviderDriver: vi.fn(async () => null),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
expect(environments.archiveManagedSandboxEnvironment).toHaveBeenCalledWith({
provider: "daytona",
});
});
it("skips (and counts failed) an entry whose provider plugin is not ready", async () => {
const environments = environmentsSeam();
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
environments,
resolveSandboxProviderDriver: readyDriverResolver("disabled"),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
expect(environments.archiveManagedSandboxEnvironment).toHaveBeenCalledWith({
provider: "daytona",
});
});
it("skips an entry whose plugin record is ready but whose worker is not running", async () => {
const environments = environmentsSeam();
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const workerManager = runningWorkerManager(false);
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(workerManager.isRunning).toHaveBeenCalledWith("plugin-1");
expect(environments.ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
expect(environments.archiveManagedSandboxEnvironment).toHaveBeenCalledWith({
provider: "daytona",
});
// No registered handle → no respawn is coming; degraded until next boot.
expect(workerManager.getWorker).toHaveBeenCalledWith("plugin-1");
});
it("reactivates the archived environment once when the provider worker recovers", async () => {
const environments = environmentsSeam();
const config = parsedConfig({
environments: [
{ name: "Daytona", provider: "daytona", config: { target: "us" } },
],
});
const { handle, fireReady } = recoveryHandle();
const workerManager = {
isRunning: vi.fn(() => false),
getWorker: vi.fn(() => handle),
};
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
// The boot pass itself stays degraded: archived, counted failed.
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.archiveManagedSandboxEnvironment).toHaveBeenCalledWith({
provider: "daytona",
});
expect(environments.ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
// Worker manager respawns the worker → the handle re-emits `ready`.
fireReady();
fireReady();
await tick();
expect(environments.ensureManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
expect(environments.ensureManagedSandboxEnvironment).toHaveBeenCalledWith({
name: "Daytona",
description: undefined,
provider: "daytona",
config: { target: "us" },
stockVersion: "2026.720.0",
platformFullyManaged: true,
});
expect(handle.off).toHaveBeenCalledTimes(1);
});
it("re-checks isRunning after subscribing so a recovery during the archive is not missed", async () => {
const environments = environmentsSeam();
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const { handle } = recoveryHandle();
// Down at the gate check, already back up by the time the listener is
// registered — the `ready` event has been missed.
const workerManager = {
isRunning: vi
.fn()
.mockReturnValueOnce(false)
.mockReturnValue(true),
getWorker: vi.fn(() => handle),
};
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
await tick();
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.ensureManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
});
it("does not subscribe for recovery when the plugin record is missing or not ready", async () => {
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
for (const resolveSandboxProviderDriver of [
vi.fn(async () => null),
readyDriverResolver("disabled"),
]) {
const workerManager = runningWorkerManager(false);
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
instanceSettings: instanceSettingsSeam(),
environments: environmentsSeam(),
resolveSandboxProviderDriver,
});
expect(workerManager.getWorker).not.toHaveBeenCalled();
}
});
it("logs, not throws, when the recovery re-ensure fails", async () => {
const environments = environmentsSeam({
ensureManagedSandboxEnvironment: vi.fn().mockRejectedValue(new Error("db exploded")),
});
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const { handle, fireReady } = recoveryHandle();
const workerManager = {
isRunning: vi.fn(() => false),
getWorker: vi.fn(() => handle),
};
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager,
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
fireReady();
await tick();
// The rejection is swallowed into a log line; reaching this point without
// an unhandled rejection is the assertion.
expect(environments.ensureManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
});
it("fails closed when no worker manager is provided", async () => {
const environments = environmentsSeam();
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const result = await applyManagedEnvironments(noDb, config, {
env: {},
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.ensureManagedSandboxEnvironment).not.toHaveBeenCalled();
});
it("counts a skipped entry once even when archiving its stale row fails", async () => {
const environments = environmentsSeam({
archiveManagedSandboxEnvironment: vi.fn().mockRejectedValue(new Error("db exploded")),
});
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
environments,
resolveSandboxProviderDriver: vi.fn(async () => null),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.archiveManagedSandboxEnvironment).toHaveBeenCalledTimes(1);
});
it("is fail-safe per entry: an ensure failure is counted, not thrown", async () => {
const environments = environmentsSeam({
ensureManagedSandboxEnvironment: vi.fn().mockRejectedValue(new Error("db exploded")),
});
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
const result = await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(result).toMatchObject({ ensured: 0, failed: 1 });
expect(environments.archiveManagedSandboxEnvironment).not.toHaveBeenCalled();
});
it("points an unset instance default at the managed sandbox environment", async () => {
const instanceSettings = instanceSettingsSeam();
const config = parsedConfig({
features: { enableManagedSandboxOnly: true },
environments: [{ name: "Daytona", provider: "daytona" }],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings,
environments: environmentsSeam(),
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(instanceSettings.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });
});
it("records the stamp marker on the managed row so a revert is attributable", async () => {
const instanceSettings = instanceSettingsSeam();
const environments = environmentsSeam();
const config = parsedConfig({
features: { enableManagedSandboxOnly: true },
environments: [{ name: "Daytona", provider: "daytona" }],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings,
environments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(environments.update).toHaveBeenCalledWith("env-1", {
metadata: expect.objectContaining({ managedDefaultStamped: true }),
});
});
it("moves a local (or dangling) instance default onto the managed sandbox environment", async () => {
const localDefault = instanceSettingsSeam({
get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-local" }) as InstanceSettingsSeam["get"],
});
const config = parsedConfig({
features: { enableManagedSandboxOnly: true },
environments: [{ name: "Daytona", provider: "daytona" }],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings: localDefault,
environments: environmentsSeam({
getById: vi.fn().mockResolvedValue(environmentRow({ id: "env-local", driver: "local" })),
}),
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(localDefault.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });
// A default pointing at a deleted row is repaired the same way.
const danglingDefault = instanceSettingsSeam({
get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-gone" }) as InstanceSettingsSeam["get"],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings: danglingDefault,
environments: environmentsSeam({ getById: vi.fn().mockResolvedValue(null) }),
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(danglingDefault.update).toHaveBeenCalledWith({ defaultEnvironmentId: "env-1" });
});
it("leaves the instance default alone while managed-sandbox-only is not declared", async () => {
// Without the mode, local execution is a legitimate default; provisioning
// the managed environment must not silently move runs into the sandbox.
const instanceSettings = instanceSettingsSeam();
const config = parsedConfig({
environments: [{ name: "Daytona", provider: "daytona" }],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings,
environments: environmentsSeam(),
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(instanceSettings.update).not.toHaveBeenCalled();
});
it("reverts a stamped managed default when managed-sandbox-only turns off", async () => {
// Turning the mode off must not keep routing default-following runs
// into the sandbox off the stale stamp — even when the document no
// longer declares any environments or the row was archived, which
// skip per-entry reconciliation entirely. Only a default pointing at
// the managed row AND carrying the reconciliation stamp reverts.
const stampedRow = environmentRow({
status: "archived",
metadata: { managedByPaperclip: true, managedDefaultStamped: true },
});
const stamped = instanceSettingsSeam({
get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["get"],
});
const stampedEnvironments = environmentsSeam({
findManagedSandboxEnvironment: vi.fn().mockResolvedValue(stampedRow),
});
// No environments declaration at all: the cleanup must still run.
const config = parsedConfig({});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings: stamped,
environments: stampedEnvironments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(stampedEnvironments.findManagedSandboxEnvironment).toHaveBeenCalledWith(undefined, {
includeArchived: true,
});
expect(stamped.update).toHaveBeenCalledWith({ defaultEnvironmentId: null });
// The marker clears with the revert so a later deliberate tenant
// selection of the managed row is never mistaken for a stamp.
expect(stampedEnvironments.update).toHaveBeenCalledWith("env-1", {
metadata: { managedByPaperclip: true },
});
// The tenant's own deliberate managed-row default (no stamp marker)
// survives the mode turning off.
const tenantManagedDefault = instanceSettingsSeam({
get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-1" }) as InstanceSettingsSeam["get"],
});
const unmarkedEnvironments = environmentsSeam({
findManagedSandboxEnvironment: vi.fn().mockResolvedValue(
environmentRow({ metadata: { managedByPaperclip: true } }),
),
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings: tenantManagedDefault,
environments: unmarkedEnvironments,
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(tenantManagedDefault.update).not.toHaveBeenCalled();
});
it("never overrides a tenant-chosen custom default environment", async () => {
const instanceSettings = instanceSettingsSeam({
get: vi.fn().mockResolvedValue({ defaultEnvironmentId: "env-ssh" }) as InstanceSettingsSeam["get"],
});
const config = parsedConfig({
features: { enableManagedSandboxOnly: true },
environments: [{ name: "Daytona", provider: "daytona" }],
});
await applyManagedEnvironments(noDb, config, {
env: {},
workerManager: runningWorkerManager(),
instanceSettings,
environments: environmentsSeam({
getById: vi.fn().mockResolvedValue(environmentRow({ id: "env-ssh", driver: "ssh" })),
}),
resolveSandboxProviderDriver: readyDriverResolver(),
});
expect(instanceSettings.update).not.toHaveBeenCalled();
});
});