The Open Framework for Building Agents
fix(eve): isolate each dev generation in disposable processes and workers (#5238)
Andrew Barba7066b20949f9
diff --git a/.changeset/dev-generation-isolation.md b/.changeset/dev-generation-isolation.mdnew file mode 100644index 000000000..c35b880e2--- /dev/null+++ b/.changeset/dev-generation-isolation.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`eve dev` memory no longer grows with every save. Each rebuild now compiles and bundles your agent in a short-lived child process, and each new version of your code is served by a fresh worker, so old copies of authored modules no longer stay loaded. Modules imported by relative path now keep their package's `sideEffects` setting, so identical source bundles the same way on every save; in `"type": "module"` apps, default imports of older CommonJS packages that set `__esModule` now follow Node's rules. Thanks @callicles for reporting this in #5203.diff --git a/packages/eve/src/cli/dev/local-server-child.ts b/packages/eve/src/cli/dev/local-server-child.tsindex e6774eb5d..1bccb452c 100644--- a/packages/eve/src/cli/dev/local-server-child.ts+++ b/packages/eve/src/cli/dev/local-server-child.ts@@ -1,7 +1,14 @@-import { createDevelopmentServer } from "#internal/nitro/host/start-development-server.js";import type { DevelopmentServerOptions } from "#internal/nitro/host/types.js";import { getDevelopmentSandboxRunId } from "#execution/sandbox/development-run.js";-import { reconcileCleanupIntents, recordCleanupIntent } from "#cli/dev/local-server-cleanup.js";+import { prewarmDevelopmentBuildProcess } from "#internal/nitro/host/dev-build-host.js";++// The first build process loads the compiler while this process loads the server.+prewarmDevelopmentBuildProcess();+const [{ createDevelopmentServer }, { reconcileCleanupIntents, recordCleanupIntent }] =+ await Promise.all([+ import("#internal/nitro/host/start-development-server.js"),+ import("#cli/dev/local-server-cleanup.js"),+ ]);const options = JSON.parse(process.argv[2] ?? "{}") as Pick<DevelopmentServerOptions,diff --git a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts b/packages/eve/src/execution/sandbox/bindings/docker-cli.tsindex 83f2dff9d..8eb789f9f 100644--- a/packages/eve/src/execution/sandbox/bindings/docker-cli.ts+++ b/packages/eve/src/execution/sandbox/bindings/docker-cli.ts@@ -106,19 +106,36 @@ function resolveDockerExecutable(): string {let cachedLinuxDockerAvailability: boolean | undefined;+/**+ * Carries one probe result to every process and worker `eve dev` starts+ * later: `"1"` when a Linux Docker daemon is available, `"0"` when it is not.+ */+export const LINUX_DOCKER_AVAILABILITY_ENV = "EVE_DEVELOPMENT_LINUX_DOCKER_AVAILABLE";+/*** Synchronously probes whether a reachable Docker daemon runs Linux* containers, for `defaultSandbox()`'s availability chain. eve's Docker* sandbox image is Linux-only, so a Windows-container daemon is not a* compatible default even though it answers the Docker CLI. The result is- * cached for the process lifetime: provider selection must be stable, and- * the probe costs a subprocess round-trip.+ * cached, and adopted from {@link LINUX_DOCKER_AVAILABILITY_ENV} when set:+ * provider selection must be stable for the whole dev server, and the probe+ * costs a subprocess round-trip.*/export function isLinuxDockerDaemonAvailableSync(): boolean {- cachedLinuxDockerAvailability ??= probeLinuxDockerDaemonSync();+ cachedLinuxDockerAvailability ??= readAdoptedAvailability() ?? probeLinuxDockerDaemonSync();+ return cachedLinuxDockerAvailability;+}++/** This module instance's probe result, or `undefined` before the first probe. */+export function peekLinuxDockerDaemonAvailability(): boolean | undefined {return cachedLinuxDockerAvailability;}+function readAdoptedAvailability(): boolean | undefined {+ const value = process.env[LINUX_DOCKER_AVAILABILITY_ENV];+ return value === "1" ? true : value === "0" ? false : undefined;+}+function probeLinuxDockerDaemonSync(): boolean {try {const result = spawnSync(resolveDockerExecutable(), ["version", "--format", "{{.Server.Os}}"], {diff --git a/packages/eve/src/internal/authored-module-build-options.ts b/packages/eve/src/internal/authored-module-build-options.tsindex 33a282b1d..d92791c75 100644--- a/packages/eve/src/internal/authored-module-build-options.ts+++ b/packages/eve/src/internal/authored-module-build-options.ts@@ -36,6 +36,15 @@ export function createAuthoredModuleBuildOptions(input: {};}+/**+ * Source maps for bundles evaluated in this process. Node reads inline maps only+ * when source maps are enabled; otherwise V8 retains the map comment as part of+ * every imported module's source text, often most of its size.+ */+export function evaluatedBundleSourcemap(): "inline" | false {+ return process.sourceMapsEnabled ? "inline" : false;+}+export function resolveAuthoredTsConfigPath(packageRoot: string): string | false {for (const fileName of ["tsconfig.json", "jsconfig.json"]) {const path = join(packageRoot, fileName);diff --git a/packages/eve/src/internal/authored-module-graph.ts b/packages/eve/src/internal/authored-module-graph.tsindex ebcd5bf5a..e4eafc17f 100644--- a/packages/eve/src/internal/authored-module-graph.ts+++ b/packages/eve/src/internal/authored-module-graph.ts@@ -1,7 +1,10 @@import { existsSync, mkdirSync, writeFileSync } from "node:fs";import { join, resolve } from "node:path";-import { createAuthoredModuleBuildOptions } from "#internal/authored-module-build-options.js";+import {+ createAuthoredModuleBuildOptions,+ evaluatedBundleSourcemap,+} from "#internal/authored-module-build-options.js";import {AUTHORED_BUNDLED_MODULE_EXTENSION,AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH,@@ -66,6 +69,9 @@ async function writeAuthoredModuleGraph(.filter((modulePath) => resolveAuthoredPackageRoot(modulePath) === packageRoot).map((modulePath, index) => [`entry-${index}`, modulePath]),);+ const sourcemap = evaluatedBundleSourcemap();+ // The content hash ignores inline maps, so cached chunks with and without one need distinct names.+ const fileName = sourcemap === false ? "[name]-[hash].mjs" : "[name]-[hash]-mapped.mjs";const result = await buildWithNitroRolldown({...createAuthoredModuleBuildOptions({packageBoundaryPlugin: createRuntimeLoaderPackageBoundaryPlugin({@@ -80,12 +86,12 @@ async function writeAuthoredModuleGraph(preserveEntrySignatures: "strict",write: false,output: {- chunkFileNames: "[name]-[hash].mjs",+ chunkFileNames: fileName,codeSplitting: true,comments: false,- entryFileNames: "[name]-[hash].mjs",+ entryFileNames: fileName,format: "esm",- sourcemap: "inline",+ sourcemap,},});const directoryPath = join(packageRoot, AUTHORED_MODULE_BUNDLE_DIRECTORY_PATH);diff --git a/packages/eve/src/internal/authored-module-loader.integration.test.ts b/packages/eve/src/internal/authored-module-loader.integration.test.tsindex 8c62d4bdb..2f078ec4f 100644--- a/packages/eve/src/internal/authored-module-loader.integration.test.ts+++ b/packages/eve/src/internal/authored-module-loader.integration.test.ts@@ -552,6 +552,54 @@ export default defineWorkflowTool({ description: "Probe", inputSchema: { type: "}});+ it("applies a workspace package's sideEffects to modules it imports by relative path", async () => {+ const app = await createApp({+ files: {+ "agent/tools/probe.ts": [+ 'import { report } from "@repo/shared/report";',+ "",+ "export const result = report;",+ "",+ ].join("\n"),+ },+ name: "side-effect-free-relative-import",+ });+ const workspaceRoot = await mkdtemp(join(tmpdir(), "eve-side-effect-free-package-"));++ try {+ const packageRoot = join(workspaceRoot, "packages", "shared");+ await mkdir(join(packageRoot, "src"), { recursive: true });+ await writeFile(+ join(packageRoot, "package.json"),+ JSON.stringify({+ exports: { "./*": "./src/*.ts" },+ name: "@repo/shared",+ sideEffects: false,+ type: "module",+ }),+ );+ await writeFile(+ join(packageRoot, "src", "registry.ts"),+ "globalThis.sharedRegistryLoaded = true;\nexport const registry = {};\n",+ );+ await writeFile(+ join(packageRoot, "src", "report.ts"),+ 'import "./registry";\nexport const report = "weekly report";\n',+ );+ await mkdir(join(app.appRoot, "node_modules", "@repo"), { recursive: true });+ await symlink(packageRoot, join(app.appRoot, "node_modules", "@repo", "shared"), "junction");++ const code = await bundleAuthoredModuleForGeneration(+ join(app.appRoot, "agent", "tools", "probe.ts"),+ );++ expect(code).toContain("weekly report");+ expect(code).not.toContain("sharedRegistryLoaded");+ } finally {+ await rm(workspaceRoot, { force: true, recursive: true });+ }+ });+it("does not collide with authored modules that already declare __dirname", async () => {// Regression: the Node ESM compatibility banner used to unconditionally// prepend `const __dirname = ...` / `const __filename = ...` /diff --git a/packages/eve/src/internal/authored-module-loader.ts b/packages/eve/src/internal/authored-module-loader.tsindex 36bded3c8..61d1f9c1b 100644--- a/packages/eve/src/internal/authored-module-loader.ts+++ b/packages/eve/src/internal/authored-module-loader.ts@@ -8,6 +8,7 @@ import { createCompiledModuleMapSource } from "#compiler/module-map.js";import { createAuthoredAssetImportPlugin } from "#internal/authored-asset-import-plugin.js";import {createAuthoredModuleBuildOptions,+ evaluatedBundleSourcemap,resolveAuthoredTsConfigPath,} from "#internal/authored-module-build-options.js";import type { AuthoredModuleGraph } from "#internal/authored-module-graph.js";@@ -211,7 +212,7 @@ export async function bundleAuthoredModuleCode(createAuthoredWorkflowDirectivePlugin({ appRoot: options.appRoot ?? packageRoot }),...(mount === undefined ? [] : [createExtensionMountPlugin(mountChain)!]),],- sourcemap: "inline",+ sourcemap: evaluatedBundleSourcemap(),});}diff --git a/packages/eve/src/internal/authored-relative-extension-resolver.ts b/packages/eve/src/internal/authored-relative-extension-resolver.tsindex ec1384bf9..fdbda8c4f 100644--- a/packages/eve/src/internal/authored-relative-extension-resolver.ts+++ b/packages/eve/src/internal/authored-relative-extension-resolver.ts@@ -38,14 +38,32 @@ export function createAuthoredRelativeExtensionResolverPlugin(input: {// reaches store-installed extension source through the consumer's// node_modules symlink) must get the same treatment, and it keeps one// canonical module identity per real file.- return {- id: isNodeModulesPath(resolvedPath) ? toRealModulePath(resolvedPath) : resolvedPath,- };+ const id = isNodeModulesPath(resolvedPath) ? toRealModulePath(resolvedPath) : resolvedPath;+ // Rolldown applies package metadata such as `sideEffects: false` only+ // to ids tied to their package.json. Without it, a module reached both+ // here and through a package specifier would be tree-shaken or kept+ // depending on which import resolved first.+ const packageJsonPath = findPackageJsonPath(id, isFile);+ return packageJsonPath === undefined ? { id } : { id, packageJsonPath };},},};}+function findPackageJsonPath(path: string, isFile: (path: string) => boolean): string | undefined {+ for (let directory = dirname(path); ; directory = dirname(directory)) {+ const candidate = join(directory, "package.json");++ if (isFile(candidate)) {+ return candidate;+ }++ if (dirname(directory) === directory) {+ return undefined;+ }+ }+}+function createCachedFileProbe(): (path: string) => boolean {const cache = new Map<string, boolean>();diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.tsindex a4c5b406c..356a0713a 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.test.ts@@ -6,6 +6,7 @@ import {DevelopmentWorkflowWorldChangeRequiresRestartError,PostCommitDevelopmentRebuildError,} from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";+import { createDevelopmentBuilds } from "#internal/nitro/host/dev-build-host.js";import { DrainedNitroDevServer } from "#internal/nitro/host/drained-nitro-dev-server.js";import type { DevelopmentRunnerFactory } from "#internal/nitro/host/dev-runner.js";import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";@@ -128,6 +129,7 @@ async function createCoordinatorWithServer(onRuntimePruned?: () => Promise<void>const devServer = new DrainedNitroDevServer({ error: () => undefined }, createRunner);mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");const coordinator = await createDevelopmentAuthoredRebuildCoordinator({+ builds: createDevelopmentBuilds(),devServer,initialHost: createHost("initial", "run-1"),onRuntimePruned,@@ -223,6 +225,41 @@ describe("transactional authored rebuild coordinator", () => {await devServer.close();});+ it("serves each runtime generation from a fresh worker and retires the previous one", async () => {+ const runners: Array<ReturnType<DevelopmentRunnerFactory>> = [];+ const devServer = new DrainedNitroDevServer({ error: () => undefined }, (options) => {+ const runner = createRunner(options);+ runners.push(runner);+ return runner;+ });+ mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");+ const coordinator = await createDevelopmentAuthoredRebuildCoordinator({+ builds: createDevelopmentBuilds(),+ devServer,+ initialHost: createHost("initial", "run-1"),+ });+ await devServer.replaceWorker({ entry: "/tmp/initial.mjs", workerData: {} });++ for (const [index, id] of ["second", "third"].entries()) {+ mocks.prepareDevelopmentApplicationHost.mockResolvedValueOnce(+ createHost(id, `run-${String(index + 2)}`),+ );+ mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");+ await expect(coordinator.rebuild({ changedPaths: [] })).resolves.toMatchObject({+ kind: "runtime",+ });+ }++ // Each generation retired the worker before it; only the active worker and+ // a spare stay open.+ await vi.waitFor(() => {+ expect(runners[0]?.closed).toBe(true);+ expect(runners.filter((runner) => runner.closed).length).toBeGreaterThanOrEqual(2);+ expect(runners.filter((runner) => !runner.closed).length).toBeLessThanOrEqual(2);+ });+ await devServer.close();+ });+it("discards the candidate and keeps prior state when the swap itself fails", async () => {const failingFactory: DevelopmentRunnerFactory = () => {const runner = createRunner({ entry: "/tmp/eve-test/entry.mjs", name: "t", workerData: {} });@@ -236,6 +273,7 @@ describe("transactional authored rebuild coordinator", () => {const devServer = new DrainedNitroDevServer({ error: () => undefined }, failingFactory);mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");const coordinator = await createDevelopmentAuthoredRebuildCoordinator({+ builds: createDevelopmentBuilds(),devServer,initialHost: createHost("initial", "run-1"),});@@ -265,6 +303,7 @@ describe("transactional authored rebuild coordinator", () => {const devServer = new DrainedNitroDevServer({ error: () => undefined }, createRunner);mocks.computeDevelopmentHostFingerprint.mockResolvedValueOnce("host-1");const coordinator = await createDevelopmentAuthoredRebuildCoordinator({+ builds: createDevelopmentBuilds(),devServer,initialHost: createHost("initial", "run-1", initialWorld),});diff --git a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.tsindex b864a4308..19a336086 100644--- a/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts+++ b/packages/eve/src/internal/nitro/host/dev-authored-rebuild-coordinator.ts@@ -1,9 +1,11 @@import { stageDevelopmentEnvironmentFiles } from "#cli/dev/environment.js";-import { createDevelopmentApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";-import { buildDevelopmentHostCandidate } from "#internal/nitro/host/dev-host-candidate.js";+import type {+ DevelopmentBuilds,+ DevelopmentBuildSession,+} from "#internal/nitro/host/dev-build-host.js";import { computeDevelopmentHostFingerprint } from "#internal/nitro/host/dev-host-fingerprint.js";import { removeDevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";-import { prepareDevelopmentApplicationHost } from "#internal/nitro/host/prepare-application-host.js";+import { toErrorMessage } from "#shared/errors.js";import type { DevelopmentExtensionSelection } from "#compiler/development-extensions.js";import { DrainedNitroDevServer } from "#internal/nitro/host/drained-nitro-dev-server.js";import { usesParentDevelopmentWorkflowWorld } from "#internal/workflow/development-world-protocol.js";@@ -54,12 +56,14 @@ export interface DevelopmentAuthoredRebuildCoordinator {}export async function createDevelopmentAuthoredRebuildCoordinator(input: {+ readonly builds: DevelopmentBuilds;readonly developmentExtensions?: DevelopmentExtensionSelection;readonly devServer: DrainedNitroDevServer;readonly initialHost: PreparedDevelopmentApplicationHost;readonly onRuntimePruned?: () => Promise<void>;}): Promise<DevelopmentAuthoredRebuildCoordinator> {return new TransactionalDevelopmentAuthoredRebuildCoordinator({+ builds: input.builds,currentHostFingerprint: await computeDevelopmentHostFingerprint(input.initialHost),developmentExtensions: input.developmentExtensions,currentRuntimeFingerprint: input.initialHost.generation.fingerprint,@@ -72,14 +76,17 @@ export async function createDevelopmentAuthoredRebuildCoordinator(input: {/*** Serializes authored rebuilds into a transaction whose commit order makes* rollback unnecessary: a candidate generation and worker are prepared while- * the previous worker keeps serving, the ready worker is swapped in first,- * and the generation pointer is activated second. Workers are- * generation-neutral (they load authored modules through the pointer), so+ * the previous worker keeps serving. On a structural change the ready worker+ * is swapped in first and the generation pointer is activated second. Workers+ * are generation-neutral (they load authored modules through the pointer), so* every intermediate state serves consistent code, and any failure before* the swap simply discards the candidate. Failures after the swap must* never travel the discard path — see {@link PostCommitDevelopmentRebuildError}.+ * A runtime change keeps the host, so it activates first and then moves to a+ * fresh worker on the same host.*/class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAuthoredRebuildCoordinator {+ readonly #builds: DevelopmentBuilds;#currentHost: PreparedDevelopmentApplicationHost;#currentHostFingerprint: string;#currentRuntimeFingerprint: string;@@ -89,6 +96,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAreadonly #onRuntimePruned: (() => Promise<void>) | undefined;constructor(input: {+ readonly builds: DevelopmentBuilds;readonly currentHostFingerprint: string;readonly currentRuntimeFingerprint: string;readonly developmentExtensions: DevelopmentExtensionSelection | undefined;@@ -96,6 +104,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAreadonly initialHost: PreparedDevelopmentApplicationHost;readonly onRuntimePruned?: () => Promise<void>;}) {+ this.#builds = input.builds;this.#currentHost = input.initialHost;this.#onRuntimePruned = input.onRuntimePruned;this.#currentHostFingerprint = input.currentHostFingerprint;@@ -116,10 +125,12 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA// edit are consumed by that attempt — a later retry would otherwise// commit without ever reapplying the change.const environmentReload = stageDevelopmentEnvironmentFiles(previousHost.appRoot);+ const build = this.#builds.begin();let nextHost: PreparedDevelopmentApplicationHost | undefined;try {- nextHost = await prepareDevelopmentApplicationHost(previousHost.appRoot, {+ nextHost = await build.prepare({+ appRoot: previousHost.appRoot,changedPaths: input.changedPaths,developmentExtensions: this.#developmentExtensions,previousExtensions: previousHost.workspaceExtensions,@@ -163,10 +174,15 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAthis.#commitState(committedHost, nextHostFingerprint, nextRuntimeFingerprint);nextHost = undefined;environmentReload.commit();+ // A worker keeps every generation it imports, so each generation gets a fresh+ // one. Activating first keeps the retired worker from loading the new+ // generation when the spare is ready.+ await this.#recycleWorker();return { host: committedHost, kind: "runtime" };}const result = await this.#commitStructuralHost({+ build,hasRuntimeChange,nextHost,nextHostFingerprint,@@ -174,6 +190,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA});nextHost = undefined;environmentReload.commit();+ this.#devServer.prepareSpareWorker();return result;} catch (error) {if (error instanceof PostCommitDevelopmentRebuildError) {@@ -187,10 +204,25 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentAthrow error;}throw await discardFailedHost(error, nextHost);+ } finally {+ build.close();}}+ async #recycleWorker(): Promise<void> {+ try {+ await this.#devServer.recycleWorker();+ } catch (error) {+ // The new generation is already active, and the current worker serves it too.+ console.warn(+ `[eve:dev] could not start a fresh dev worker; the current worker keeps serving: ${toErrorMessage(error)}`,+ );+ }+ this.#devServer.prepareSpareWorker();+ }+async #commitStructuralHost(input: {+ readonly build: DevelopmentBuildSession;readonly hasRuntimeChange: boolean;readonly nextHost: PreparedDevelopmentApplicationHost;readonly nextHostFingerprint: string;@@ -206,8 +238,7 @@ class TransactionalDevelopmentAuthoredRebuildCoordinator implements DevelopmentA};}- const nitro = await createDevelopmentApplicationNitro(committedHost);- const payload = await buildDevelopmentHostCandidate({ host: committedHost, nitro });+ const payload = await input.build.buildHost(committedHost);// Worker first, pointer second: a failed candidate leaves both the// previous worker and the previous pointer untouched, and thediff --git a/packages/eve/src/internal/nitro/host/dev-build-host.ts b/packages/eve/src/internal/nitro/host/dev-build-host.tsnew file mode 100644index 000000000..958766c15--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-build-host.ts@@ -0,0 +1,307 @@+// Type-only imports keep this module cheap: the dev server forks its first build+// process before it loads the compiler, Nitro, or its own server modules.+import { type ChildProcess, fork } from "node:child_process";+import { fileURLToPath } from "node:url";++import type { DevelopmentExtensionSelection } from "#compiler/development-extensions.js";+import { LINUX_DOCKER_AVAILABILITY_ENV } from "#execution/sandbox/bindings/docker-cli.js";+import {+ createDevelopmentHostWorkspace,+ type DevelopmentHostWorkspace,+ removeDevelopmentHostWorkspace,+} from "#internal/nitro/host/dev-host-workspace.js";+import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";+import type { WorkspaceExtension } from "#internal/nitro/host/workspace-extensions.js";+import { toError } from "#shared/errors.js";++export interface DevelopmentPrepareInput {+ readonly appRoot: string;+ readonly changedPaths?: readonly string[];+ readonly developmentExtensions?: DevelopmentExtensionSelection;+ readonly previousExtensions?: readonly WorkspaceExtension[];+ /** Created by the dev server, so it can remove the workspace if the build process dies. */+ readonly workspace?: DevelopmentHostWorkspace;+}++/** Worker entry and data for a built Nitro host. */+export interface DevelopmentHostBuild {+ readonly entry: string;+ readonly workerData: Readonly<Record<string, unknown>>;+}++interface DevelopmentBuildOperations {+ readonly buildHost: {+ readonly input: PreparedDevelopmentApplicationHost;+ readonly value: DevelopmentHostBuild;+ };+ readonly prepare: {+ readonly input: DevelopmentPrepareInput;+ readonly value: PreparedDevelopmentApplicationHost;+ };+}++export type DevelopmentBuildOperation = keyof DevelopmentBuildOperations;++// Authored code also runs in the build process and may send its own IPC messages.+export const DEVELOPMENT_BUILD_MESSAGE_KIND = "eve:development-build";++export interface DevelopmentBuildRequest {+ /** The dev server's environment, including `.env` changes staged for this rebuild. */+ readonly environment: Readonly<Record<string, string | undefined>>;+ readonly id: number;+ readonly input: unknown;+ readonly kind: typeof DEVELOPMENT_BUILD_MESSAGE_KIND;+ readonly operation: DevelopmentBuildOperation;+}++export type DevelopmentBuildOutcome =+ | { readonly ok: true; readonly value: unknown }+ | { readonly ok: false; readonly error: SerializedError };++export type DevelopmentBuildResponse = {+ /** The build's Docker probe result, if it probed. */+ readonly dockerAvailability: boolean | undefined;+ readonly id: number;+ readonly kind: typeof DEVELOPMENT_BUILD_MESSAGE_KIND;+} & DevelopmentBuildOutcome;++export interface DevelopmentBuildSession {+ prepare(input: DevelopmentPrepareInput): Promise<PreparedDevelopmentApplicationHost>;+ buildHost(host: PreparedDevelopmentApplicationHost): Promise<DevelopmentHostBuild>;+ /** Ends the session. Its build process exits, releasing everything it loaded. */+ close(): void;+}++/** The build processes owned by one dev server. */+export interface DevelopmentBuilds {+ /**+ * Starts a build session for one rebuild. Every step that evaluates+ * authored code or runs Rolldown happens in the session's child process,+ * which exits when the session closes. Node never unloads an imported+ * module and Rolldown's native memory belongs to the whole process, so+ * exiting is the only way to release both.+ */+ begin(): DevelopmentBuildSession;+ /** Stops every build process, including the spare. Later sessions fail. */+ close(): void;+}++interface SerializedError {+ cause?: SerializedError;+ message: string;+ name: string;+ stack?: string;+}++const MAX_SERIALIZED_CAUSE_DEPTH = 8;++let prewarmedProcess: DevelopmentBuildProcess | undefined;+let nextRequestId = 0;++/**+ * Forks a build process before the dev server loads its own modules, so the+ * two startups overlap. The first {@link createDevelopmentBuilds} adopts it.+ */+export function prewarmDevelopmentBuildProcess(): void {+ if (!isSourceCheckout()) {+ prewarmedProcess ??= new DevelopmentBuildProcess();+ }+}++export function createDevelopmentBuilds(): DevelopmentBuilds {+ if (isSourceCheckout()) {+ return { begin: createInProcessSession, close() {} };+ }++ let spare = prewarmedProcess;+ prewarmedProcess = undefined;+ const active = new Set<DevelopmentBuildProcess>();+ let closed = false;++ return {+ begin() {+ if (closed) {+ throw new Error("The dev server is closed, so it cannot start another build.");+ }+ const buildProcess = spare?.alive === true ? spare : new DevelopmentBuildProcess();+ if (spare !== buildProcess) spare?.close();+ spare = undefined;+ active.add(buildProcess);+ let ended = false;++ return {+ async prepare(input) {+ const workspace = await createDevelopmentHostWorkspace(input.appRoot);+ try {+ return await buildProcess.request("prepare", { ...input, workspace });+ } catch (error) {+ await removeDevelopmentHostWorkspace(workspace).catch(() => undefined);+ throw error;+ }+ },+ buildHost: async (host) => await buildProcess.request("buildHost", host),+ close() {+ if (ended) return;+ ended = true;+ active.delete(buildProcess);+ buildProcess.close();+ // The next rebuild should not wait for a process to start and load the compiler.+ if (!closed) spare ??= new DevelopmentBuildProcess();+ },+ };+ },+ close() {+ closed = true;+ spare?.close();+ spare = undefined;+ for (const buildProcess of active) buildProcess.close();+ active.clear();+ },+ };+}++// Running from TypeScript source (eve's own tests, or a source checkout): a+// child process cannot import the source without the caller's transform.+function isSourceCheckout(): boolean {+ return import.meta.url.endsWith(".ts");+}++function createInProcessSession(): DevelopmentBuildSession {+ const operations = import("#internal/nitro/host/dev-build-operations.js");+ return {+ prepare: async (input) => await (await operations).prepareDevelopmentBuild(input),+ buildHost: async (host) => await (await operations).buildDevelopmentHost(host),+ close() {},+ };+}++class DevelopmentBuildProcess {+ readonly #child: ChildProcess;+ #exitError: Error | undefined;+ readonly #pending = new Map<+ number,+ { readonly reject: (error: Error) => void; readonly resolve: (value: unknown) => void }+ >();++ constructor() {+ this.#child = fork(fileURLToPath(new URL("./dev-build-process.js", import.meta.url)), [], {+ serialization: "advanced",+ stdio: ["ignore", "inherit", "inherit", "ipc"],+ });+ this.#child.on("message", (message: Partial<DevelopmentBuildResponse> | null) => {+ if (message?.kind !== DEVELOPMENT_BUILD_MESSAGE_KIND || message.id === undefined) return;+ const pending = this.#pending.get(message.id);+ if (pending === undefined) return;+ this.#pending.delete(message.id);+ this.#idleWhenSettled();+ publishDockerAvailability(message.dockerAvailability);+ const response = message as DevelopmentBuildResponse;+ if (response.ok) pending.resolve(response.value);+ else pending.reject(deserializeError(response.error));+ });+ this.#child.once("error", (error) => this.#fail(error));+ this.#child.once("exit", (code, signal) => this.#fail(createExitError(code, signal)));+ this.#idleWhenSettled();+ }++ get alive(): boolean {+ return this.#exitError === undefined && this.#child.connected;+ }++ request<Operation extends DevelopmentBuildOperation>(+ operation: Operation,+ input: DevelopmentBuildOperations[Operation]["input"],+ ): Promise<DevelopmentBuildOperations[Operation]["value"]> {+ if (this.#exitError !== undefined) return Promise.reject(this.#exitError);++ const id = ++nextRequestId;+ const request: DevelopmentBuildRequest = {+ environment: { ...process.env },+ id,+ input,+ kind: DEVELOPMENT_BUILD_MESSAGE_KIND,+ operation,+ };+ return new Promise((resolve, reject) => {+ this.#pending.set(id, { reject, resolve: resolve as (value: unknown) => void });+ this.#child.ref();+ this.#child.channel?.ref?.();+ this.#child.send(request, (error) => {+ if (error !== null) this.#fail(error);+ });+ });+ }++ close(): void {+ if (this.#child.connected) this.#child.disconnect();+ if (this.#child.exitCode === null && this.#child.signalCode === null) this.#child.kill();+ }++ #fail(error: Error): void {+ this.#exitError ??= error;+ for (const pending of this.#pending.values()) pending.reject(this.#exitError);+ this.#pending.clear();+ }++ // An idle build process must not keep the dev server alive. Bun's channel has no ref/unref.+ #idleWhenSettled(): void {+ if (this.#pending.size > 0) return;+ this.#child.unref();+ this.#child.channel?.unref?.();+ }+}++// Later build processes receive it with their environment, and runtime workers+// copy it when they start, so neither probes Docker again.+function publishDockerAvailability(available: boolean | undefined): void {+ if (available !== undefined && process.env[LINUX_DOCKER_AVAILABILITY_ENV] === undefined) {+ process.env[LINUX_DOCKER_AVAILABILITY_ENV] = available ? "1" : "0";+ }+}++function createExitError(code: number | null, signal: NodeJS.Signals | null): Error {+ if (code === 0) {+ return new Error(+ "The agent build stopped before it finished: its process ran out of work to do. This usually means an authored module awaits a promise that never settles at the top level, or calls process.exit().",+ );+ }+ if (signal === "SIGABRT" || code === 134) {+ return new Error(+ "The agent build process aborted, most likely because it ran out of memory. Reduce what authored modules import when they load, or raise the heap limit by starting eve dev with NODE_OPTIONS=--max-old-space-size=<megabytes>.",+ );+ }+ if (signal === "SIGKILL") {+ return new Error(+ "The agent build process was killed before it finished. If the system ran low on memory, reduce what authored modules import when they load.",+ );+ }+ return new Error(+ `The agent build process exited (${signal ?? `code ${String(code)}`}) before finishing.`,+ );+}++export function serializeError(error: unknown, depth = 0): SerializedError {+ const value = toError(error);+ const cause = (value as { cause?: unknown }).cause;+ const serialized: SerializedError = { message: value.message, name: value.name };++ if (value.stack !== undefined) {+ serialized.stack = value.stack;+ }++ if (cause !== undefined && depth < MAX_SERIALIZED_CAUSE_DEPTH) {+ serialized.cause = serializeError(cause, depth + 1);+ }++ return serialized;+}++function deserializeError(serialized: SerializedError): Error {+ const error = toError(serialized);++ if (serialized.cause !== undefined) {+ (error as Error & { cause?: unknown }).cause = deserializeError(serialized.cause);+ }++ return error;+}diff --git a/packages/eve/src/internal/nitro/host/dev-build-operations.ts b/packages/eve/src/internal/nitro/host/dev-build-operations.tsnew file mode 100644index 000000000..dc67608b9--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-build-operations.ts@@ -0,0 +1,28 @@+import { createDevelopmentApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";+import type {+ DevelopmentHostBuild,+ DevelopmentPrepareInput,+} from "#internal/nitro/host/dev-build-host.js";+import { buildDevelopmentHostCandidate } from "#internal/nitro/host/dev-host-candidate.js";+import { prepareDevelopmentApplicationHost } from "#internal/nitro/host/prepare-application-host.js";+import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";++/** Compiles the agent and stages a candidate generation in its own host workspace. */+export async function prepareDevelopmentBuild(+ input: DevelopmentPrepareInput,+): Promise<PreparedDevelopmentApplicationHost> {+ return await prepareDevelopmentApplicationHost(input.appRoot, {+ changedPaths: input.changedPaths,+ developmentExtensions: input.developmentExtensions,+ previousExtensions: input.previousExtensions,+ workspace: input.workspace,+ });+}++/** Builds the Nitro host for a prepared candidate and returns its worker entry. */+export async function buildDevelopmentHost(+ host: PreparedDevelopmentApplicationHost,+): Promise<DevelopmentHostBuild> {+ const nitro = await createDevelopmentApplicationNitro(host);+ return await buildDevelopmentHostCandidate({ host, nitro });+}diff --git a/packages/eve/src/internal/nitro/host/dev-build-process.ts b/packages/eve/src/internal/nitro/host/dev-build-process.tsnew file mode 100644index 000000000..105234344--- /dev/null+++ b/packages/eve/src/internal/nitro/host/dev-build-process.ts@@ -0,0 +1,65 @@+import { peekLinuxDockerDaemonAvailability } from "#execution/sandbox/bindings/docker-cli.js";+import {+ DEVELOPMENT_BUILD_MESSAGE_KIND,+ type DevelopmentBuildOutcome,+ type DevelopmentBuildRequest,+ type DevelopmentBuildResponse,+ type DevelopmentPrepareInput,+ serializeError,+} from "#internal/nitro/host/dev-build-host.js";+import {+ buildDevelopmentHost,+ prepareDevelopmentBuild,+} from "#internal/nitro/host/dev-build-operations.js";+import type { PreparedDevelopmentApplicationHost } from "#internal/nitro/host/types.js";++// IPC disconnect is the dev server's death signal: it fires however that process exits.+process.once("disconnect", () => process.exit(0));++process.on("message", async (request: Partial<DevelopmentBuildRequest> | null) => {+ if (request?.kind !== DEVELOPMENT_BUILD_MESSAGE_KIND || request.id === undefined) {+ return;+ }++ // Also carries an earlier build's Docker probe result, which the probe adopts.+ if (request.environment !== undefined) {+ replaceEnvironment(request.environment);+ }++ // While a build runs, only its own work keeps this process alive. A build that+ // can never settle then exits the process and fails, instead of hanging.+ process.channel?.unref();+ let outcome: DevelopmentBuildOutcome;++ try {+ outcome = {+ ok: true,+ value:+ request.operation === "buildHost"+ ? await buildDevelopmentHost(request.input as PreparedDevelopmentApplicationHost)+ : await prepareDevelopmentBuild(request.input as DevelopmentPrepareInput),+ };+ } catch (error) {+ outcome = { ok: false, error: serializeError(error) };+ }++ process.channel?.ref();+ const response: DevelopmentBuildResponse = {+ ...outcome,+ dockerAvailability: peekLinuxDockerDaemonAvailability(),+ id: request.id,+ kind: DEVELOPMENT_BUILD_MESSAGE_KIND,+ };+ process.send?.(response);+});++// Each build sees exactly the dev server's environment, and nothing an earlier build set.+function replaceEnvironment(environment: Readonly<Record<string, string | undefined>>): void {+ for (const key of Object.keys(process.env)) {+ if (environment[key] === undefined) delete process.env[key];+ }++ for (const [key, value] of Object.entries(environment)) {+ if (value !== undefined) process.env[key] = value;+ }+}diff --git a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.tsindex 74d411998..3b85d0460 100644--- a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts+++ b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.scenario.test.ts@@ -237,6 +237,41 @@ describe("drained Nitro dev server", () => {expect(dispose).toHaveBeenCalledOnce();});+ it("keeps a host's workspace until its last recycled or spare worker retires", async () => {+ const { createRunner, runners } = createRunnerFactory(+ async (_request, runnerIndex) => new Response(`runner-${String(runnerIndex)}`),+ );+ const server = new DrainedNitroDevServer(LOGGER, createRunner);+ const listener = await listen(server);+ const disposeFirst = vi.fn(async () => undefined);+ const disposeSecond = vi.fn(async () => undefined);+ const body = async () => await (await fetch(new URL("/", listener.url))).text();++ await server.replaceWorker(replacement("/tmp/first.mjs", disposeFirst));+ await server.recycleWorker();+ await expect(body()).resolves.toBe("runner-1");+ await vi.waitFor(() => expect(runners[0]?.closeMock).toHaveBeenCalled());+ expect(disposeFirst).not.toHaveBeenCalled();++ server.prepareSpareWorker();+ await vi.waitFor(() => expect(runners[2]?.waitForReady).toHaveBeenCalled());+ await server.recycleWorker();+ await expect(body()).resolves.toBe("runner-2");+ expect(runners).toHaveLength(3);++ server.prepareSpareWorker();+ await server.replaceWorker(replacement("/tmp/second.mjs", disposeSecond));+ await expect(body()).resolves.toBe("runner-4");+ await vi.waitFor(() => {+ expect(runners[3]?.closeMock).toHaveBeenCalled();+ expect(disposeFirst).toHaveBeenCalledOnce();+ });+ expect(disposeSecond).not.toHaveBeenCalled();++ await server.close();+ expect(disposeSecond).toHaveBeenCalledOnce();+ });+it("destroys the socket when an upgrade fails and closes idempotently", async () => {const { createRunner, runners } = createRunnerFactory(async () => new Response("ok"));const server = new DrainedNitroDevServer(LOGGER, createRunner);@@ -458,6 +493,28 @@ describe("drained Nitro dev server", () => {await expect(pending).rejects.toThrow();});+ it("closes within a bounded interval while a recycle waits for a booting spare", async () => {+ const { createRunner } = createRunnerFactory(+ async () => new Response("ok"),+ async (runnerIndex) => {+ if (runnerIndex === 1) {+ await new Promise<never>(() => undefined);+ }+ },+ );+ const server = new DrainedNitroDevServer(LOGGER, createRunner);+ await listen(server);+ await server.replaceWorker(replacement("/tmp/first.mjs"));+ server.prepareSpareWorker();++ const recycling = server.recycleWorker();+ recycling.catch(() => undefined);+ // Let the recycle start waiting on the spare before closing.+ await new Promise((resolve) => setTimeout(resolve, 20));+ await withinDeadline(server.close(), "Timed out closing while a recycle waited for its spare.");+ await expect(recycling).rejects.toThrow();+ });+it("terminates the client connection when a worker response fails mid-stream", async () => {let failStream: (() => void) | undefined;const { createRunner } = createRunnerFactory(async () => {diff --git a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.tsindex 9c658ae28..2cf131ae5 100644--- a/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts+++ b/packages/eve/src/internal/nitro/host/drained-nitro-dev-server.ts@@ -30,15 +30,28 @@ interface DevelopmentWorkerReplacement {readonly workerData: Readonly<Record<string, unknown>>;}-interface RunnerSlot {- activeExchanges: number;+/** One built host. Its workspace outlives every runner started from it. */+interface WorkerHost {readonly dispose?: () => Promise<void>;disposed: boolean;readonly entry: string;+ /** Runners started from this host that have not been released yet. */+ runners: number;+ readonly workerData: Readonly<Record<string, unknown>>;+}++interface RunnerSlot {+ activeExchanges: number;+ readonly host: WorkerHost;quietListeners: Array<() => void>;releasePromise: Promise<void> | undefined;readonly runner: DevelopmentRunner;- readonly workerData: Readonly<Record<string, unknown>>;+}++interface SpareRunner {+ /** Resolves to whether the spare became ready. */+ readonly ready: Promise<boolean>;+ readonly slot: RunnerSlot;}interface DevServerLogger {@@ -66,7 +79,10 @@ export class DrainedNitroDevServer {#closed = false;#clientAddressSecret: string | undefined;#controlHandler: ((request: Request) => Promise<Response | undefined>) | undefined;+ /** Host of the active worker; its workspace stays until another host replaces it. */+ #currentHost: WorkerHost | undefined;#pendingSlot: RunnerSlot | undefined;+ #spare: SpareRunner | undefined;#replaceChain: Promise<void> = Promise.resolve();#runnerCounter = 0;@@ -98,43 +114,94 @@ export class DrainedNitroDevServer {* closed at shutdown), so a caller can tie workspace cleanup to it.*/replaceWorker(replacement: DevelopmentWorkerReplacement): Promise<void> {- const next = this.#replaceChain- .catch(() => undefined)- .then(async () => await this.#replaceWorker(replacement));+ const host: WorkerHost = {+ dispose: replacement.dispose,+ disposed: false,+ entry: replacement.entry,+ runners: 0,+ workerData: replacement.workerData,+ };+ return this.#enqueueSwap(async () => await this.#swapTo(host, false));+ }++ /**+ * Swaps the active worker for a fresh one started from the same host, and+ * drains the old one. Node never unloads a module, so a worker keeps every+ * generation it imported; a fresh worker loads only the active one. Uses the+ * spare from {@link prepareSpareWorker} when it is ready.+ */+ recycleWorker(): Promise<void> {+ return this.#enqueueSwap(async () => {+ const host = this.#currentHost;+ if (host === undefined) {+ throw new Error("Development server has no worker to recycle.");+ }+ await this.#swapTo(host, true);+ });+ }++ /**+ * Starts a spare worker from the active host in the background, so the next+ * {@link recycleWorker} does not wait for a worker to boot. A spare for an+ * older host is discarded.+ */+ prepareSpareWorker(): void {+ const host = this.#currentHost;+ if (this.#closed || host === undefined || this.#spare?.slot.host === host) {+ return;+ }+ this.#discardSpare();++ const slot = this.#createSlot(host);+ let settle: (ready: boolean) => void = () => undefined;+ const spare: SpareRunner = {+ ready: new Promise<boolean>((resolve) => {+ settle = resolve;+ }),+ slot,+ };+ // A spare that closes or fails readiness is never ready, so a recycle+ // waiting on it moves on instead of waiting out the readiness timeout.+ const forget = () => {+ settle(false);+ if (this.#spare !== spare) return;+ this.#spare = undefined;+ void this.#releaseSlot(slot);+ };+ this.#spare = spare;+ slot.runner.onceClosed(forget);+ slot.runner.waitForReady(RUNNER_READY_TIMEOUT_MS).then(() => settle(true), forget);+ }++ #enqueueSwap(swap: () => Promise<void>): Promise<void> {+ const next = this.#replaceChain.catch(() => undefined).then(swap);this.#replaceChain = next.catch(() => undefined);return next;}- async #replaceWorker(replacement: DevelopmentWorkerReplacement): Promise<void> {+ async #swapTo(host: WorkerHost, useSpare: boolean): Promise<void> {if (this.#closed) {throw new Error("Development server is closed.");}- const slot: RunnerSlot = {- activeExchanges: 0,- dispose: replacement.dispose,- disposed: false,- entry: replacement.entry,- quietListeners: [],- releasePromise: undefined,- runner: this.#createRunner({- entry: replacement.entry,- name: `eve-dev-${String(this.#runnerCounter++)}`,- workerData: replacement.workerData,- }),- workerData: replacement.workerData,- };-- this.#pendingSlot = slot;- try {- await slot.runner.waitForReady(RUNNER_READY_TIMEOUT_MS);- } catch (error) {- await slot.runner.close(error).catch(() => undefined);- // The candidate never served; its workspace has no further use.- await this.#disposeSlot(slot);- throw error;- } finally {- this.#pendingSlot = undefined;+ let slot = useSpare ? await this.#takeSpare(host) : undefined;+ if (this.#closed) {+ if (slot !== undefined) await this.#releaseSlot(slot);+ throw new Error("Development server is closed.");+ }+ if (slot === undefined) {+ slot = this.#createSlot(host);+ this.#pendingSlot = slot;+ try {+ await slot.runner.waitForReady(RUNNER_READY_TIMEOUT_MS);+ } catch (error) {+ await slot.runner.close(error).catch(() => undefined);+ // A candidate host that never served has no further use for its workspace.+ await this.#releaseSlot(slot);+ throw error;+ } finally {+ this.#pendingSlot = undefined;+ }}if (this.#closed) {@@ -143,9 +210,19 @@ export class DrainedNitroDevServer {}const previous = this.#active;- this.#active = slot;- slot.runner.onceClosed(() => {- void this.#handleRunnerClose(slot);+ const previousHost = this.#currentHost;+ const activeSlot = slot;+ this.#active = activeSlot;+ this.#currentHost = host;+ if (this.#spare !== undefined && this.#spare.slot.host !== host) {+ this.#discardSpare();+ }+ // A host whose restart failed has no runner left to dispose it on release.+ if (previousHost !== undefined && previousHost !== host && previousHost.runners === 0) {+ void this.#disposeHost(previousHost);+ }+ activeSlot.runner.onceClosed(() => {+ void this.#handleRunnerClose(activeSlot);});this.#wakeActiveWaiters();@@ -154,6 +231,42 @@ export class DrainedNitroDevServer {}}+ #createSlot(host: WorkerHost): RunnerSlot {+ host.runners += 1;+ return {+ activeExchanges: 0,+ host,+ quietListeners: [],+ releasePromise: undefined,+ runner: this.#createRunner({+ entry: host.entry,+ name: `eve-dev-${String(this.#runnerCounter++)}`,+ workerData: host.workerData,+ }),+ };+ }++ // Waits for a spare that is still booting: it started earlier than a new worker would.+ async #takeSpare(host: WorkerHost): Promise<RunnerSlot | undefined> {+ const spare = this.#spare;+ if (spare === undefined || spare.slot.host !== host || !(await spare.ready)) {+ return undefined;+ }+ if (this.#spare !== spare || spare.slot.runner.closed) {+ return undefined;+ }+ this.#spare = undefined;+ return spare.slot;+ }++ #discardSpare(): void {+ const spare = this.#spare;+ this.#spare = undefined;+ if (spare !== undefined) {+ void this.#releaseSlot(spare.slot);+ }+ }+listen(input: { readonly hostname: string; readonly port: number }): DrainedDevServerListener {if (this.#closed) {throw new Error("Development server is closed.");@@ -250,20 +363,32 @@ export class DrainedNitroDevServer {// Terminate a candidate still waiting on readiness so the replace chain// settles within a bounded interval instead of the readiness timeout.- await this.#pendingSlot?.runner- .close(new Error("Development server is closing."))- .catch(() => undefined);+ // Terminate a booting spare too: a recycle may be waiting on it.+ await Promise.all(+ [this.#pendingSlot, this.#spare?.slot].map(+ async (slot) =>+ await slot?.runner+ .close(new Error("Development server is closing."))+ .catch(() => undefined),+ ),+ );await this.#replaceChain.catch(() => undefined);const listeners = [...this.#listeners];const listenerClosePromises = listeners.map((listener) => listener.beginClose());- const slots = [this.#active, ...this.#draining].filter(+ const slots = [this.#active, this.#spare?.slot, ...this.#draining].filter((slot): slot is RunnerSlot => slot !== undefined,);+ const currentHost = this.#currentHost;this.#active = undefined;+ this.#currentHost = undefined;+ this.#spare = undefined;this.#draining.clear();await Promise.all(slots.map(async (slot) => await this.#releaseSlot(slot)));+ if (currentHost !== undefined && currentHost.runners === 0) {+ await this.#disposeHost(currentHost);+ }for (const listener of listeners) {listener.destroySockets();@@ -278,15 +403,18 @@ export class DrainedNitroDevServer {async #releaseSlotOnce(slot: RunnerSlot): Promise<void> {await slot.runner.close().catch(() => undefined);- await this.#disposeSlot(slot);+ slot.host.runners -= 1;+ if (slot.host.runners === 0 && slot.host !== this.#currentHost) {+ await this.#disposeHost(slot.host);+ }}- async #disposeSlot(slot: RunnerSlot): Promise<void> {- if (slot.dispose === undefined || slot.disposed) {+ async #disposeHost(host: WorkerHost): Promise<void> {+ if (host.dispose === undefined || host.disposed) {return;}- slot.disposed = true;- await slot.dispose().catch((error) => {+ host.disposed = true;+ await host.dispose().catch((error) => {this.#logger.error(`[eve:dev] failed to dispose a retired dev host: ${toErrorMessage(error)}`,);@@ -309,16 +437,9 @@ export class DrainedNitroDevServer {await this.#releaseSlot(slot);return;}- // The crashed worker's workspace must survive for the restart, so the- // replacement inherits its dispose and the crashed slot releases- // nothing itself.- slot.disposed = true;- slot.releasePromise = Promise.resolve();- await this.#replaceWorker({- dispose: slot.dispose,- entry: slot.entry,- workerData: slot.workerData,- });+ // The host stays current, so releasing the crashed runner keeps its workspace.+ await this.#releaseSlot(slot);+ await this.#swapTo(slot.host, true);});this.#replaceChain = next.catch(() => undefined);try {diff --git a/packages/eve/src/internal/nitro/host/prepare-application-host.ts b/packages/eve/src/internal/nitro/host/prepare-application-host.tsindex bf777f255..c338f337e 100644--- a/packages/eve/src/internal/nitro/host/prepare-application-host.ts+++ b/packages/eve/src/internal/nitro/host/prepare-application-host.ts@@ -16,6 +16,7 @@ import {} from "#internal/nitro/development-generation.js";import {createDevelopmentHostWorkspace,+ type DevelopmentHostWorkspace,removeDevelopmentHostWorkspace,} from "#internal/nitro/host/dev-host-workspace.js";import {@@ -38,6 +39,8 @@ export async function prepareDevelopmentApplicationHost(readonly changedPaths?: readonly string[];readonly developmentExtensions?: DevelopmentExtensionSelection;readonly previousExtensions?: readonly WorkspaceExtension[];+ /** An empty workspace created by the caller; one is created otherwise. */+ readonly workspace?: DevelopmentHostWorkspace;} = {},): Promise<PreparedDevelopmentApplicationHost> {const extensionPreparation: {@@ -52,7 +55,7 @@ export async function prepareDevelopmentApplicationHost(extensionPreparation.previousExtensions = options.previousExtensions;}const workspaceExtensions = await prepareDevelopmentWorkspaceExtensions(extensionPreparation);- const workspace = await createDevelopmentHostWorkspace(appRoot);+ const workspace = options.workspace ?? (await createDevelopmentHostWorkspace(appRoot));let generation: Awaited<ReturnType<typeof stageDevelopmentGeneration>> | undefined;try {diff --git a/packages/eve/src/internal/nitro/host/start-development-server.test.ts b/packages/eve/src/internal/nitro/host/start-development-server.test.tsindex 4ae0a622f..cab12655c 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.test.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.test.ts@@ -35,6 +35,8 @@ const mocks = vi.hoisted(() => {close: vi.fn(async () => undefined),discardCandidate: vi.fn(async () => undefined),listen: vi.fn(() => listenerServer),+ prepareSpareWorker: vi.fn(),+ recycleWorker: vi.fn(async () => undefined),replaceWorker: vi.fn(async () => undefined),setClientAddressSecret: vi.fn(),setControlHandler: vi.fn(),diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.tsindex 7c61adac6..4056b353b 100644--- a/packages/eve/src/internal/nitro/host/start-development-server.ts+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts@@ -2,13 +2,12 @@ import { handleDevelopmentModelCredentialRequest } from "#internal/model-auth/deimport { EVE_DEV_ENV_FLAG } from "#internal/application/optional-package-install.js";import { defaultDevelopmentExtensions } from "#compiler/development-extensions.js";-import type { Nitro } from "nitro/types";--import { createDevelopmentApplicationNitro } from "#internal/nitro/host/create-application-nitro.js";+import {+ createDevelopmentBuilds,+ type DevelopmentBuilds,+} from "#internal/nitro/host/dev-build-host.js";import { DrainedNitroDevServer } from "#internal/nitro/host/drained-nitro-dev-server.js";import type { AuthoredSourceWatcherHandle } from "#internal/nitro/host/dev-authored-source-watcher.js";-import { prepareDevelopmentApplicationHost } from "#internal/nitro/host/prepare-application-host.js";-import { buildDevelopmentHostCandidate } from "#internal/nitro/host/dev-host-candidate.js";import { removeDevelopmentHostWorkspace } from "#internal/nitro/host/dev-host-workspace.js";import { createDevelopmentAuthoredRebuildCoordinator } from "#internal/nitro/host/dev-authored-rebuild-coordinator.js";import {@@ -241,9 +240,9 @@ function addDevelopmentControlHandler(input: {async function closeDevelopmentServerResources(input: {readonly appRoot: string;readonly authoredSourceWatcher: AuthoredSourceWatcherHandle | undefined;+ readonly builds: DevelopmentBuilds;readonly devServer: NitroDevelopmentServer | undefined;readonly developmentSandboxRunId: string;- readonly nitro: Nitro | undefined;readonly workflowWorld: ParentDevelopmentWorkflowWorld | undefined;}): Promise<{ readonly errors: readonly unknown[]; readonly listenerClosed: boolean }> {const errors: unknown[] = [];@@ -257,6 +256,9 @@ async function closeDevelopmentServerResources(input: {}};+ // Before the watcher, which waits for an in-flight rebuild: that rebuild's+ // build process exits, so the rebuild fails instead of finishing first.+ input.builds.close();const authoredSourceWatcher = input.authoredSourceWatcher;if (authoredSourceWatcher !== undefined) {await attempt(() => authoredSourceWatcher.close());@@ -267,10 +269,6 @@ async function closeDevelopmentServerResources(input: {}const devServer = input.devServer;const listenerClosed = devServer === undefined ? true : await attempt(() => devServer.close());- const nitro = input.nitro;- if (nitro !== undefined) {- await attempt(() => nitro.close());- }await attempt(() =>stopDevelopmentSandboxResources({devRunId: input.developmentSandboxRunId,@@ -399,7 +397,8 @@ async function startNitroDevelopmentServer(const previousDevelopmentSandboxRunId = process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV];const developmentSandboxRunId = createDevelopmentSandboxRunId();process.env[EVE_DEVELOPMENT_SANDBOX_RUN_ID_ENV] = developmentSandboxRunId;- let nitro: Nitro | undefined;+ const builds = createDevelopmentBuilds();+ const build = builds.begin();let devServer: NitroDevelopmentServer | undefined;let restoreLocalDevCapabilityEnvironment: (() => void) | undefined;let restoreWorkflowLocalQueueEnvironment: (() => void) | undefined;@@ -413,18 +412,12 @@ async function startNitroDevelopmentServer(try {const preparedHost = await devBootPhase("compiling agent",- () => prepareDevelopmentApplicationHost(project.appRoot, { developmentExtensions }),+ () => build.prepare({ appRoot: project.appRoot, developmentExtensions }),options.onBootProgress,);preparedDevelopmentHost = preparedHost;pruneLocalSandboxTemplatesInBackground(preparedHost.appRoot);- const activeNitro = await devBootPhase(- "creating dev server",- () => createDevelopmentApplicationNitro(preparedHost),- options.onBootProgress,- );- nitro = activeNitro;- devServer = new DrainedNitroDevServer(activeNitro.logger);+ devServer = new DrainedNitroDevServer();const activeDevServer = devServer;const workflowTransportSecret = randomBytes(32).toString("base64url");activeDevServer.setClientAddressSecret(workflowTransportSecret);@@ -453,8 +446,7 @@ async function startNitroDevelopmentServer(workflowWorld,transportSecret: workflowTransportSecret,});- const hostname =- options.host ?? activeNitro.options.devServer.hostname ?? DEFAULT_DEVELOPMENT_SERVER_HOST;+ const hostname = options.host ?? DEFAULT_DEVELOPMENT_SERVER_HOST;const retryOnAddressInUse = requestedPort === undefined;const server = await devBootPhase("binding port",@@ -483,11 +475,8 @@ async function startNitroDevelopmentServer(await devBootPhase("building dev bundle",async () => {- const payload = await buildDevelopmentHostCandidate({- host: preparedHost,- nitro: activeNitro,- });- nitro = undefined;+ const payload = await build.buildHost(preparedHost);+ build.close();const workspace = preparedHost.workspace;initialWorkspaceTransferred = true;await activeDevServer.replaceWorker({@@ -504,9 +493,11 @@ async function startNitroDevelopmentServer(},options.onBootProgress,);+ activeDevServer.prepareSpareWorker();await workflowWorld?.start();const rebuildCoordinator = await createDevelopmentAuthoredRebuildCoordinator({+ builds,developmentExtensions,devServer: activeDevServer,initialHost: preparedHost,@@ -542,9 +533,9 @@ async function startNitroDevelopmentServer(const cleanup = await closeDevelopmentServerResources({appRoot: project.appRoot,authoredSourceWatcher: authoredSourceWatcherOnClose,+ builds,devServer: devServerOnClose,developmentSandboxRunId,- nitro: undefined,workflowWorld: workflowWorldOnClose,});if (cleanup.listenerClosed) {@@ -573,11 +564,12 @@ async function startNitroDevelopmentServer(const cleanup = await closeDevelopmentServerResources({appRoot: project.appRoot,authoredSourceWatcher,+ builds,devServer,developmentSandboxRunId,- nitro,workflowWorld,});+ build.close();const cleanupErrors = [...cleanup.errors];if (preparedDevelopmentHost !== undefined && !initialGenerationPublished) {await discardDevelopmentGeneration(preparedDevelopmentHost.generation).catch(diff --git a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.tsindex d67374dad..583add306 100644--- a/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts+++ b/packages/eve/test/scenarios/dev-server-rebuild.scenario.test.ts@@ -1,6 +1,6 @@import { createFakeVercelOidcToken } from "../../src/internal/testing/vercel-oidc-token.js";import { existsSync } from "node:fs";-import { realpath, rm, writeFile } from "node:fs/promises";+import { readFile, realpath, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { describe, expect, it } from "vitest";@@ -151,7 +151,7 @@ describe("eve dev server rebuild transactions", () => {);it(- "publishes authored tool removals without replacing the active host",+ "publishes authored tool removals on a fresh worker without rebuilding the host",async () => {const app = await scenarioApp(TRANSACTIONAL_REBUILD_DESCRIPTOR);const server = await startEveDev(app.appRoot);@@ -167,7 +167,8 @@ describe("eve dev server rebuild transactions", () => {await forceDevelopmentRebuild(server.url);await expect(readDevelopmentRevision(server.url)).resolves.not.toBe(initialRevision);- await expect(fetchText(server.url, "/worker-id")).resolves.toBe(initialWorkerId);+ await expect(fetchText(server.url, "/worker-id")).resolves.not.toBe(initialWorkerId);+ expect(server.stdout()).not.toContain(STRUCTURAL_RELOAD_LOG_LINE);expect((await fetchAgentInfo(server.url)).tools.static.map((tool) => tool.name),).not.toContain("get_weather");@@ -179,6 +180,64 @@ describe("eve dev server rebuild transactions", () => {DEV_SERVER_SCENARIO_TIMEOUT_MS,);+ it(+ "fails a build that never settles, then builds with the current .env",+ async () => {+ const app = await scenarioApp(DEV_SERVER_AGENT_DESCRIPTOR);+ const server = await startEveDev(app.appRoot);+ const output = () => `${server.stdout()}\n${server.stderr()}`;+ const toolPath = join(app.appRoot, "agent", "tools", "get_weather.ts");+ const toolSource = await readFile(toolPath, "utf8");++ try {+ const initialRevision = await readDevelopmentRevision(server.url);++ await writeFile(toolPath, `await new Promise(() => {});\n${toolSource}`);+ await forceDevelopmentRebuild(server.url);+ await waitForCondition(+ async () => output().includes("awaits a promise that never settles"),+ `Timed out waiting for the stalled build to fail.\n\n${output()}`,+ );+ await expect(readDevelopmentRevision(server.url)).resolves.toBe(initialRevision);++ // Converges on the latest files, so intermediate watcher rebuilds cannot make it flaky.+ const probeDescription = async () =>+ (await fetchAgentInfo(server.url)).tools.static.find((tool) => tool.name === "env_probe")+ ?.description;+ await writeFile(toolPath, toolSource);+ await writeFile(join(app.appRoot, ".env"), "EVE_SCENARIO_BUILD_VALUE=from-env\n");+ await writeFile(+ join(app.appRoot, "agent", "tools", "env_probe.ts"),+ [+ 'import { defineTool } from "eve/tools";',+ 'import { z } from "zod";',+ "export default defineTool({",+ ' description: `build saw ${process.env.EVE_SCENARIO_BUILD_VALUE ?? "nothing"}`,',+ " inputSchema: z.object({}),",+ ' execute: async () => "ok",',+ "});",+ "",+ ].join("\n"),+ );+ await forceDevelopmentRebuild(server.url);+ await waitForCondition(+ async () => (await probeDescription()) === "build saw from-env",+ () => `Timed out waiting for the build to see .env.\n\n${output()}`,+ );++ await rm(join(app.appRoot, ".env"));+ await forceDevelopmentRebuild(server.url);+ await waitForCondition(+ async () => (await probeDescription()) === "build saw nothing",+ () => `Timed out waiting for the build without .env.\n\n${output()}`,+ );+ } finally {+ await server.stop();+ }+ },+ DEV_SERVER_SCENARIO_TIMEOUT_MS,+ );+it("keeps the complete prior generation active when a structural candidate fails",async () => {diff --git a/research/dev-generation-isolation.md b/research/dev-generation-isolation.mdnew file mode 100644index 000000000..77690707b--- /dev/null+++ b/research/dev-generation-isolation.md@@ -0,0 +1,206 @@+---+issue: https://github.com/vercel/eve/issues/5203+status: in-progress+last_updated: "2026-10-22"+---++# Generation-scoped isolation for `eve dev`++## Summary++`eve dev` memory grows on every save until the process is killed. The cause is structural, not+one leaky module: eve keeps long-lived isolates alive and loads each new generation of authored+code into them. Node never unloads an imported ES module, and Rolldown's native memory is+allocated per process, so neither kind of memory comes back while the isolate lives.++This plan gives every generation its own disposable isolates and leaves the dev server process+as a coordinator that never imports authored code and never runs the bundler:++- **Build process per rebuild.** A fresh child process prepares each candidate generation. It+ builds workspace extensions, compiles the agent, stages the generation, and builds the Nitro+ host when the change is structural. Then it exits. A spare process is forked ahead of time, so+ process startup and module loading stay off the save's critical path.+- **Runtime worker per generation.** Activating a new generation also swaps in a fresh Nitro+ worker, using the drain machinery structural rebuilds already use. A pre-started spare worker+ keeps the swap off the critical path.++The plan also fixes the nondeterminism that made unchanged modules produce new bundles on each+save. The relative-extension resolver now attaches each module's `package.json` metadata.++## Problem++Measured on `main` with the built CLI and a synthetic agent of 10 tools sharing a 2.9 MB module.+Heap figures are taken after a forced GC:++| Isolate | What it loads per save | Observed |+| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |+| Dev server main thread | Compile-time `import()` of authored bundles. Rolldown keeps finished generation builds' plugins (and their copies of source) reachable | Heap 61 → 93 MB over 8 runtime saves |+| Dev server process (native) | Rolldown builds on the main thread: generation module map, and the Nitro host on structural saves | RSS 1.0 → 2.2 GB over 8 structural saves |+| Nitro runtime worker | `import()` of each activated generation's module map under a new URL. The worker survives every runtime save | About +58 MB per save after a session uses the new generation |++#5203 reports the same failure for extension modules: a 4 GB host was OOM-killed on rebuild 4. A+separate report showed an agent with about 600 authored modules growing by 1–6 GB per rebuild.++Recycling isolates inside the same process is not enough. Rolldown builds in worker threads that+are then terminated still raise process RSS from 105 MB to 1.2 GB over 36 builds, and it keeps+growing. The same builds in a child process leave the parent at 106 MB.++A user also reported that the relative-extension resolver returned bare ids. Rolldown therefore+lost `"sideEffects": false` for modules reached by relative path, and which import resolved first+decided whether a module was tree-shaken. Unchanged sources produced different bundles, so+`eve dev` reloaded modules that had not changed.++## Goals and non-goals++Goals:++- Memory in `eve dev` stays bounded by construction, without heap thresholds or heuristics.+- The dev server process never imports authored code and never runs Rolldown.+- Rebuild latency stays close to `main` for runtime saves.+- Identical inputs produce identical bundles.+- Behavior is unchanged for `eve build`, `eve start`, durable runs, and the public API.++Non-goals:++- A module runner or in-process HMR. That needs Vite's transform pipeline, and user code's side+ effects would still live in the host.+- Static extraction of definitions. Tool schemas built with zod and computed definitions need+ evaluation.+- One shared bundle for compile and runtime. Generations inline ordinary dependencies on purpose,+ so a durable run can resume on its generation after the workspace changes.+- Caching the Nitro host across boots, and lazy-loading CLI commands. Both are separate boot-time+ work.++## Architecture++```text+ eve dev (CLI)+ └─ dev server process: coordinator, HTTP proxy, file watcher, Workflow World+ │ never imports authored code, never runs Rolldown+ │+ ├─ build process (one per rebuild, plus one spare)+ │ prepare: workspace extensions → compile → stage generation ─┐+ │ build host (structural only): create Nitro → build host │ plain data over IPC+ │ exits when the rebuild finishes ◄┘+ │+ └─ Nitro runtime workers (one per generation, plus one spare)+ active ── serves requests for the active generation+ draining ── finishes admitted exchanges, then terminates+ spare ── booted on the current host, waiting for the next generation+```++### One rebuild++1. The watcher reports changes.+2. The coordinator creates an empty host workspace, takes the spare build process, and sends+ `prepare` with the workspace, the changed paths, the previous workspace extensions, and the+ current environment.+3. The build process returns the prepared host as plain data.+4. The coordinator computes the host and runtime fingerprints itself, because it owns the+ authoritative environment.+5. It then acts on the kind of change:+ - **unchanged**: discard the candidate.+ - **runtime**: activate the new generation, then swap to a fresh runtime worker on the same+ host, preferring the ready spare.+ - **structural**: send `build host` to the same build process, swap to a worker running the+ new host, then activate the new generation.+6. The coordinator ends the session, which terminates the build process, and forks the next+ spare. It also asks the dev server to boot a spare runtime worker for the active host.++On structural saves the worker swap comes first and the pointer second, as before. Workers are+generation-neutral, so the new worker serves the previous generation correctly until the pointer+moves, and a failed swap leaves the old worker and the old pointer untouched. On runtime saves+the host is the same, so order does not affect correctness. Activating first keeps the retired+worker from loading the new generation when the spare is ready.++### Boot++- The dev server process forks its first build process before it loads its own server modules,+ so the two startups overlap.+- The same build process prepares the first generation and builds the first host.+- The dev server then starts the first runtime worker and its spare.+- Nitro is no longer created in the dev server process. The listen host therefore comes from+ `--host` or eve's default, and no longer falls back to Nitro's `devServer.hostname`, which only+ an undocumented `nitro.config` could set.++## Invariants++- No isolate imports a generation that it outlives, with one exception: a runtime worker may load+ an older, unpruned generation to resume a durable run on it. That is bounded by snapshot+ retention.+- Build processes carry no state between rebuilds. Everything they need arrives in the request,+ and everything they produce returns as plain data or files in the host workspace.+- Each request replaces the build process's environment with the dev server's, so staged `.env`+ changes apply and nothing from an earlier build leaks in.+- The Docker probe that picks the default sandbox runs at most once per dev server. The dev+ server publishes the first result in an internal environment variable. Later build processes+ receive it with their environment and runtime workers copy it when they start, so the sandbox+ choice stays stable for the session.+- Build processes belong to one dev server. Closing it stops its build processes, including the+ spare, and later rebuilds fail instead of forking new ones.+- The dev server creates each candidate's host workspace and removes it if `prepare` fails, so a+ build process that dies mid-build leaves no workspace behind. A generation snapshot it staged is+ removed later by snapshot retention.+- A host workspace is removed only after the last runtime worker using it has retired. That+ includes active, draining, and spare workers.++## Failure semantics++- A compile error, an evaluation error, or an exhausted heap in the build process fails that+ rebuild. The server keeps serving the previous generation. Errors keep their message, stack,+ and cause chain across the boundary. An abort exit says the build most likely ran out of+ memory and names `--max-old-space-size`.+- A build that waits on work that can never complete makes the build process exit instead of+ hanging. The build process unrefs its IPC channel while a build runs. The rebuild then fails+ with an actionable message.+- On a structural save, a runtime worker that fails readiness leaves the active worker in place,+ and the rebuild fails before activation. On a runtime save the generation is already active,+ so a failed swap is logged and the current worker keeps serving.+- The build process exits when its IPC channel disconnects, so it never outlives the dev server,+ including when the dev server is killed.+- A spare that crashes or goes stale is discarded and replaced. The next swap waits for readiness+ instead.+- Closing the dev server terminates every build process and runtime worker, including spares.++## Performance++Measured with the built CLI against `main`, using the synthetic agent from the problem section:++| Measure | `main` | This design |+| --------------------------------------------------- | ------------------- | ----------------------------------------------- |+| Dev server RSS, 8 runtime saves each with a session | 1094 → 1298 MB | 677 → 568 MB, plus a 247 MB spare build process |+| Dev server main-thread heap, same run | 64 → 98 MB | 37 → 40 MB |+| Dev server RSS, 8 structural saves | 1033 → 2194 MB | 591 → 639 MB |+| Runtime save, file write to rebuild log line | 0.59–0.66 s | 0.70–0.88 s |+| Boot, 1-tool and 10-tool agents | ~1.80 s and ~1.92 s | ~1.83 s and ~1.98 s |++Runtime saves cost about 0.1 s more. The build process starts with its modules loaded, but its+first compile still runs cold: 180–260 ms against about 80 ms for a warm in-process compile on a+small agent. On large agents, where compile takes seconds, the difference is proportionally+smaller. The runtime worker swap uses the spare and adds nothing measurable.++## Alternatives considered++- **A warm compile worker recycled at a heap threshold** (closed #5191). This bounds JavaScript+ heap but not Rolldown's per-process native memory, and it leaves the runtime worker leak in+ place.+- **Reusing extension module instances across compiles** (#5206). This fixes the #5203 trigger+ but leaves app modules, Rolldown memory, and the runtime worker unchanged.+- **A module runner** (Vite `ModuleRunner`, Nuxt, SvelteKit). This frees inlined modules without+ restarting, but it depends on Vite's transform pipeline, and user code's side effects stay in+ the host.+- **Disposable isolates.** Nitro starts a new worker per `dev:reload`. Vitest recycles workers at+ a memory limit and destroys them on watch reruns. SvelteKit runs build analysis in a fresh+ process. This plan uses that pattern, with a child process where Rolldown runs.++## Testing++- An integration regression covers the resolver: a `"sideEffects": false` workspace module+ reached by relative import is tree-shaken.+- The coordinator's unit tests cover a fresh runtime worker per runtime generation, including+ reuse of the prepared spare. The drained dev server's scenario tests cover workspace disposal+ across recycled, spare, and replaced workers.+- Scenario tests run the packed CLI through boot, rebuilds, shutdown, and the Bun runtime, which+ exercises the build process path end to end.+- Manual measurements on the built CLI cover heap per isolate and process RSS across runtime and+ structural saves, plus rebuild and boot latency against `main`.