Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): make local workflow recovery explicit (#3823)

prha0ac01f6bc85d
diff --git a/.changeset/compatible-development-recovery.md b/.changeset/compatible-development-recovery.md
new file mode 100644
index 000000000..e78a69bc1
--- /dev/null
+++ b/.changeset/compatible-development-recovery.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Local development leaves previous invocations' workflows dormant by default. `eve dev --resume` attempts to recover runs with valid retained snapshots even when framework or authored workflow sources changed; replay can fail after executing work. Missing snapshots are cancelled, while runs with malformed generation metadata remain stored and dormant. Requests addressed to dormant conversations fail instead of appearing accepted without a response.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 626c2f492..c142aa07b 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -208,36 +208,55 @@ eve dev [options]
Starts a local development server and terminal UI. To connect the UI to an existing agent, use `eve remote connect --url <url>`.
-| Flag | Type | Default | Description |
-| ----------------------------------- | ------ | ------------------ | ------------------------------------------- |
-| `--host <host>` | string | all interfaces | Host interface to bind |
-| `--port <port>` | number | `$PORT`, then 2000 | Port to listen on |
-| `--no-ui` | flag | UI on | Start the server without an interactive UI |
-| `--no-default-extensions` | flag | extensions on | Do not mount bundled development extensions |
-| `--name <name>` | string | app folder name | Title shown in the terminal UI |
-| `--input <text>` | string | none | Pre-fill the prompt input |
-| `--tools <mode>` | enum | `auto-collapsed` | Tool-call rendering |
-| `--reasoning <mode>` | enum | `full` | Reasoning rendering |
-| `--subagents <mode>` | enum | `auto-collapsed` | Subagent-section rendering |
-| `--connection-auth <mode>` | enum | `full` | Connection-authorization rendering |
-| `--assistant-response-stats <mode>` | enum | `tokensPerSecond` | Assistant header statistic |
-| `--context-size <tokens>` | number | none | Model context window size |
-| `--logs <mode>` | enum | `stderr` | Server and agent logs to show |
+| Flag | Type | Default | Description |
+| ----------------------------------- | ------ | ------------------ | --------------------------------------------------------------- |
+| `--host <host>` | string | all interfaces | Host interface to bind |
+| `--port <port>` | number | `$PORT`, then 2000 | Port to listen on |
+| `--no-ui` | flag | UI on | Start the server without an interactive UI |
+| `--resume` | flag | off | Attempt recovery of retained runs from previous dev invocations |
+| `--no-default-extensions` | flag | extensions on | Do not mount bundled development extensions |
+| `--name <name>` | string | app folder name | Title shown in the terminal UI |
+| `--input <text>` | string | none | Pre-fill the prompt input |
+| `--tools <mode>` | enum | `auto-collapsed` | Tool-call rendering |
+| `--reasoning <mode>` | enum | `full` | Reasoning rendering |
+| `--subagents <mode>` | enum | `auto-collapsed` | Subagent-section rendering |
+| `--connection-auth <mode>` | enum | `full` | Connection-authorization rendering |
+| `--assistant-response-stats <mode>` | enum | `tokensPerSecond` | Assistant header statistic |
+| `--context-size <tokens>` | number | none | Model context window size |
+| `--logs <mode>` | enum | `stderr` | Server and agent logs to show |
Local development mounts bundled development extensions without adding files to your project. Pass `--no-default-extensions` to disable them. See [Self-Modification](../guides/self-modification) for details.
A fresh `eve init` opens the TUI and reuses an available model connection or opens `/login`. No Vercel project, channels, integrations, or review step is required before chat. Use `/model` to change models and settings, and `/add` to install an addition. Other `--input` text stays editable in the prompt. See [Terminal UI](../guides/dev-tui) for credential precedence and login options.
+### Local development lifecycle
+
Local dev records the last ready URL per resolved app root in `.eve/dev-server-state.v1.json`. A second interactive `eve dev` reconnects only when that URL is loopback and healthy; each terminal UI creates a fresh client session while sharing the server process. A stale or malformed record is replaced when eve starts a new server. Passing `--host`, `--port`, or a `PORT` environment value skips reconnection and reports a healthy recorded server instead.
Local dev keeps immutable runtime generations under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. Each generation contains the compiled authored module graph and runtime resources rather than a recursive copy of the app or workspace. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; `/new` terminally retires that session before clearing the transcript, and the next prompt starts a fresh session with a new session-scoped sandbox on first sandbox use. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
-With the built-in local Workflow World, `eve dev` cancels unfinished runs whose runtime snapshots are missing, at startup and after snapshot pruning. This includes waiting conversations and session timeout workflows. Cancellation records the reason in the run history without a terminal warning; normal run-data retention still applies. Stopping `eve dev` does not cancel runs whose snapshots remain available: the next start recovers them. This cleanup does not apply to a custom Workflow World.
-
Local development records traces under `.eve/traces/` by default and bounds that store by age, size, and a keep-newest floor. Configure it with `EVE_TRACES*` in `.env.local`, or disable the destination with `agent/instrumentation/local.ts`; see [`eve traces`](#retention) for the rules and defaults.
`eve acp` reserves stdin and stdout for newline-delimited JSON-RPC and sends diagnostics to stderr. Without a URL, it supervises an isolated local development server. With a URL, it bridges ACP to that server's existing eve HTTP API. See [Agent Client Protocol (ACP)](../protocols/acp) for client configuration and capability limits.
+### Local workflow recovery
+
+With the built-in local Workflow World, a new `eve dev` server leaves previous invocations' runs dormant by default, including deliveries triggered by timers or hooks. A new message or control request addressed to a dormant conversation fails instead of being accepted without a response; the HTTP channel reports its usual request failure. Start a new conversation, or restart `eve dev` with `--resume` to attempt recovery. Already-open event streams are not changed by this request guard. Source-watcher rebuilds and worker restarts within the same server retain current runs' eligibility.
+
+Pass `eve dev --resume` to attempt recovery of unfinished runs from previous invocations. Recovery requires a retained snapshot with readable generation metadata. Snapshots from older eve versions with a valid `runtimeAppRoot` remain eligible. Changes to the eve framework or authored workflow sources do not prevent the attempt, but replay can fail and leave the run terminally failed after executing some work. Use `--resume` only when you want to try continuing those previous runs.
+
+Runs with malformed generation metadata remain stored and dormant for that server invocation, including later timer and hook deliveries. Startup with `--resume` reports why recovery was skipped without blocking other eligible runs. Restore malformed snapshot metadata from a backup or start a new session.
+
+Recovery eligibility is decided before startup queue delivery begins. Hot reload does not recheck admitted runs against the latest workflow sources, so follow-up turns, cancellation, and `/new` retain their existing behavior. Changing an authored workflow body while it is running can likewise cause replay failure.
+
+With the built-in local Workflow World, `eve dev` cancels unfinished runs whose runtime snapshots are missing, at startup and after snapshot pruning. This includes waiting conversations and session timeout workflows. Cancellation records the reason in the run history without a terminal warning; normal run-data retention still applies. Stopping `eve dev` does not cancel runs whose snapshots remain available, but recovering them on the next start requires `--resume`.
+
+Recovery limits:
+
+- Custom Workflow Worlds do not use this cleanup and recovery policy; `eve dev --resume` rejects them.
+- `eve dev --resume` refuses to attach to an already running local server. The flag requires starting a server.
+- `eve dev --resume` recovers workflows, not the terminal transcript or a particular TUI conversation.
+
## `eve remote`
Use `eve remote` only with an explicit existing agent URL:
diff --git a/packages/eve/src/cli/dev/command-options.ts b/packages/eve/src/cli/dev/command-options.ts
index 54397a855..80167097a 100644
--- a/packages/eve/src/cli/dev/command-options.ts
+++ b/packages/eve/src/cli/dev/command-options.ts
@@ -19,6 +19,7 @@ export interface DevelopmentCliOptions {
name?: string;
port?: number;
reasoning?: TerminalPartDisplayMode;
+ resume?: boolean;
subagents?: TerminalPartDisplayMode;
tools?: TerminalPartDisplayMode;
ui?: boolean;
diff --git a/packages/eve/src/cli/dev/command.ts b/packages/eve/src/cli/dev/command.ts
index def464a36..768454ea9 100644
--- a/packages/eve/src/cli/dev/command.ts
+++ b/packages/eve/src/cli/dev/command.ts
@@ -188,6 +188,7 @@ export function registerDevelopmentCommand(input: {
.option("--host <host>", "Host interface to bind")
.option("--port <port>", "Port to listen on (defaults to $PORT, then 2000)", parsePortOption)
.option("--no-ui", "Start the server without an interactive UI")
+ .option("--resume", "Attempt recovery of retained runs from previous local dev invocations")
.option("--no-default-extensions", "Do not mount default development extensions")
.option("--name <name>", "Title shown in the terminal UI (defaults to the app folder name)")
.option("--input <text>", "Pre-fill the prompt input")
@@ -274,6 +275,7 @@ export function registerDevelopmentCommand(input: {
...(options.defaultExtensions === false
? { developmentExtensions: noDevelopmentExtensions() }
: {}),
+ resume: options.resume,
existing: mode === "tui" ? "attach-if-unconfigured" : "reject",
host: options.host,
onBootProgress,
diff --git a/packages/eve/src/cli/dev/local-server-child.ts b/packages/eve/src/cli/dev/local-server-child.ts
index a5441b2c4..e6774eb5d 100644
--- a/packages/eve/src/cli/dev/local-server-child.ts
+++ b/packages/eve/src/cli/dev/local-server-child.ts
@@ -5,7 +5,7 @@ import { reconcileCleanupIntents, recordCleanupIntent } from "#cli/dev/local-ser
const options = JSON.parse(process.argv[2] ?? "{}") as Pick<
DevelopmentServerOptions,
- "developmentExtensions" | "existing" | "host" | "port"
+ "developmentExtensions" | "existing" | "host" | "port" | "resume"
>;
const server = createDevelopmentServer(process.cwd(), {
...options,
diff --git a/packages/eve/src/cli/dev/local-server-process.test.ts b/packages/eve/src/cli/dev/local-server-process.test.ts
index 0c96f5ed6..7abf25c30 100644
--- a/packages/eve/src/cli/dev/local-server-process.test.ts
+++ b/packages/eve/src/cli/dev/local-server-process.test.ts
@@ -60,9 +60,14 @@ describe("createDevelopmentServer", () => {
});
it("starts and hands cleanup to the child", async () => {
- const server = createDevelopmentServer("/tmp/app", { port: 2000 });
+ const server = createDevelopmentServer("/tmp/app", { port: 2000, resume: true });
const started = server.start();
await vi.waitFor(() => expect(mocks.fork).toHaveBeenCalled());
+ expect(mocks.fork).toHaveBeenCalledWith(
+ expect.any(String),
+ [JSON.stringify({ port: 2000, resume: true })],
+ expect.any(Object),
+ );
child.emit("message", {
type: "started",
handle: { kind: "started", appRoot: "/tmp/app", url: "http://127.0.0.1:2000" },
diff --git a/packages/eve/src/cli/dev/local-server-process.ts b/packages/eve/src/cli/dev/local-server-process.ts
index 56540a5b3..977bebae9 100644
--- a/packages/eve/src/cli/dev/local-server-process.ts
+++ b/packages/eve/src/cli/dev/local-server-process.ts
@@ -96,6 +96,7 @@ export function createDevelopmentServer(
existing: options.existing,
host: options.host,
port: options.port,
+ resume: options.resume,
}),
],
{
diff --git a/packages/eve/src/cli/run.test.ts b/packages/eve/src/cli/run.test.ts
index 5b8c0e286..45eac96f0 100644
--- a/packages/eve/src/cli/run.test.ts
+++ b/packages/eve/src/cli/run.test.ts
@@ -383,6 +383,7 @@ describe("bare eve command", () => {
expect(findApplicationRoot).toHaveBeenCalledWith(resolve(process.cwd()));
expect(startHost).toHaveBeenCalledWith("/resolved/app", {
+ resume: undefined,
existing: "attach-if-unconfigured",
host: undefined,
onBootProgress: expect.any(Function),
@@ -623,6 +624,22 @@ describe("eve dev --input", () => {
);
});
+ it("passes explicit recovery to the local host", async () => {
+ const startHost = vi.fn(() => ({
+ start: async () => ({
+ kind: "started" as const,
+ appRoot: "/canonical/app",
+ url: "http://127.0.0.1:4321/",
+ }),
+ close: async () => {},
+ }));
+ await runInteractiveDev(["dev", "--resume"], { startHost });
+ expect(startHost).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ resume: true }),
+ );
+ });
+
it("forwards the internal init onboarding handoff to the local TUI", async () => {
const startHost = vi.fn(() => ({
start: async () => ({
@@ -1075,6 +1092,7 @@ describe("eve dev local server ownership", () => {
const runDevelopmentTui = await runInteractiveDev(["dev"], { startHost });
expect(startHost).toHaveBeenCalledWith(expect.any(String), {
+ resume: undefined,
existing: "attach-if-unconfigured",
host: undefined,
onBootProgress: expect.any(Function),
diff --git a/packages/eve/src/execution/continuation-conflict-step.ts b/packages/eve/src/execution/continuation-conflict-step.ts
index 05f6062a3..426134ea3 100644
--- a/packages/eve/src/execution/continuation-conflict-step.ts
+++ b/packages/eve/src/execution/continuation-conflict-step.ts
@@ -1,13 +1,8 @@
-import {
- EntityConflictError,
- RunExpiredError,
- WorkflowRunNotFoundError,
-} from "#compiled/@workflow/errors/index.js";
+import { isInactiveWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";
import type { SessionCommand } from "#channel/types.js";
import { resumeSessionInbox } from "#execution/session-inbox/resume.js";
import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
-import { walkCauseChain } from "#shared/errors.js";
/** Settles side effects owned by a session candidate that lost its continuation claim. */
export async function settleContinuationConflictStep(input: {
@@ -34,19 +29,6 @@ async function cancelCollector(runId: string): Promise<void> {
cancelReason: "Session candidate did not acquire continuation ownership",
});
} catch (error) {
- if (!isInactiveRun(error)) throw error;
+ if (!isInactiveWorkflowRunError(error)) throw error;
}
}
-
-function isInactiveRun(error: unknown): boolean {
- for (const candidate of walkCauseChain(error)) {
- if (
- WorkflowRunNotFoundError.is(candidate) ||
- RunExpiredError.is(candidate) ||
- EntityConflictError.is(candidate)
- ) {
- return true;
- }
- }
- return false;
-}
diff --git a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
index 32373b9f4..e8a8ba254 100644
--- a/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
+++ b/packages/eve/src/internal/nitro/dev-generation-artifacts.scenario.test.ts
@@ -5,6 +5,7 @@ import { basename, dirname, join, relative } from "node:path";
import { describe, expect, it } from "vitest";
import { compileAgent } from "#compiler/compile-agent.js";
+import { readDevelopmentGenerationAvailability } from "#internal/workflow/development-runtime-compatibility.js";
import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";
import { loadCompiledModuleMapFromAuthoredSource } from "#internal/authored-module-map-loader.js";
import { resolvePackageRoot } from "#internal/application/package.js";
@@ -652,6 +653,9 @@ describe("development generation artifacts", () => {
const compileResult = await compileAgent({ startPath: app.appRoot });
const generation = await stageDevelopmentGeneration(compileResult);
expect(generation.workflowSourceFingerprint).toEqual(expect.any(String));
+ await expect(
+ readDevelopmentGenerationAvailability(app.appRoot, basename(generation.snapshotRoot)),
+ ).resolves.toEqual({ kind: "ready", runtimeAppRoot: generation.runtimeAppRoot });
const moduleMap = await loadCompiledModuleMapFromAuthoredSource({
compiledArtifactsSource: createAuthoredSourceRuntimeCompiledArtifactsSource(
@@ -679,6 +683,9 @@ describe("development generation artifacts", () => {
await compileAgent({ startPath: app.appRoot }),
);
expect(helperChanged.workflowSourceFingerprint).not.toBe(generation.workflowSourceFingerprint);
+ await expect(
+ readDevelopmentGenerationAvailability(app.appRoot, basename(generation.snapshotRoot)),
+ ).resolves.toEqual({ kind: "ready", runtimeAppRoot: generation.runtimeAppRoot });
await writeFile(
join(app.appRoot, "agent", "tools", "plain.mjs"),
@@ -688,6 +695,9 @@ describe("development generation artifacts", () => {
await compileAgent({ startPath: app.appRoot }),
);
expect(plainChanged.workflowSourceFingerprint).toBe(helperChanged.workflowSourceFingerprint);
+ await expect(
+ readDevelopmentGenerationAvailability(app.appRoot, basename(helperChanged.snapshotRoot)),
+ ).resolves.toEqual({ kind: "ready", runtimeAppRoot: helperChanged.runtimeAppRoot });
expect(plainChanged.fingerprint).not.toBe(helperChanged.fingerprint);
});
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts-retention.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts-retention.ts
index c1e68a130..2d31504cb 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts-retention.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts-retention.ts
@@ -19,7 +19,7 @@ export async function recordRetiredDevelopmentRuntimeArtifactsSnapshot(
);
}
-/** Applies the bounded retention policy within one dev snapshot directory. */
+/** Applies retention and reports whether any snapshots were removed. */
export async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
readonly activeSnapshotRoot: string | undefined;
readonly gracePeriodMs?: number;
@@ -27,9 +27,9 @@ export async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
readonly protectAll: boolean;
readonly retainCount?: number;
readonly snapshotsDirectory: string;
-}): Promise<void> {
+}): Promise<boolean> {
if (input.protectAll) {
- return;
+ return false;
}
const now = input.now ?? Date.now();
const gracePeriodMs = Math.max(
@@ -45,7 +45,7 @@ export async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
entries = await readdir(input.snapshotsDirectory, { withFileTypes: true });
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
- return;
+ return false;
}
throw error;
}
@@ -101,7 +101,7 @@ export async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
.map((snapshot) => snapshot.path),
);
- await Promise.all(
+ const removed = await Promise.all(
snapshots.map(async (snapshot) => {
if (
snapshot.active ||
@@ -111,11 +111,13 @@ export async function pruneDevelopmentRuntimeArtifactsSnapshotDirectory(input: {
(snapshot.retiredAt !== undefined && now - snapshot.retiredAt <= gracePeriodMs) ||
(!snapshot.activated && now - snapshot.mtimeMs <= gracePeriodMs)
) {
- return;
+ return false;
}
await rm(snapshot.path, { force: true, recursive: true });
+ return true;
}),
);
+ return removed.some(Boolean);
}
async function readRetiredAt(snapshotRoot: string): Promise<number | undefined> {
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
index 22dc83184..1e9457e81 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.integration.test.ts
@@ -163,9 +163,9 @@ describe("development runtime artifact snapshots", () => {
expect(readDevelopmentRuntimeArtifactsRevision(appRoot)).toEqual({
revision: appRoot,
});
- expect(
- JSON.parse(await readFile(join(snapshot.snapshotRoot, "generation.json"), "utf8")),
- ).toEqual({ runtimeAppRoot: snapshot.runtimeAppRoot });
+ await expect(readFile(join(snapshot.snapshotRoot, "generation.json"), "utf8")).resolves.toBe(
+ `${JSON.stringify({ runtimeAppRoot: snapshot.runtimeAppRoot })}\n`,
+ );
await activateSnapshot({
appRoot,
diff --git a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
index 034a67078..3d49a8c8c 100644
--- a/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
+++ b/packages/eve/src/internal/nitro/dev-runtime-artifacts.ts
@@ -19,6 +19,7 @@ import {
} from "#internal/nitro/dev-runtime-artifacts-retention.js";
import { renameWithTransientBusyRetry } from "#shared/rename-with-retry.js";
import { resolvePackageRoot } from "#internal/application/package.js";
+import { resolveDevelopmentRuntimeArtifactsSnapshotsDirectory } from "#internal/nitro/dev-runtime-generation-metadata.js";
const DEV_RUNTIME_ARTIFACTS_DIRECTORY = "dev-runtime";
const DEV_RUNTIME_ARTIFACTS_GENERATION_METADATA = "generation.json";
@@ -68,10 +69,6 @@ export function resolveDevelopmentRuntimeArtifactsPointerPath(appRoot: string):
return join(appRoot, ".eve", DEV_RUNTIME_ARTIFACTS_DIRECTORY, "current.json");
}
-function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(appRoot: string): string {
- return join(appRoot, ".eve", DEV_RUNTIME_ARTIFACTS_DIRECTORY, "snapshots");
-}
-
function isDevelopmentRuntimeArtifactsSnapshotRoot(appRoot: string, snapshotRoot: string): boolean {
return (
dirname(resolve(snapshotRoot)) ===
@@ -340,11 +337,11 @@ export async function pruneDevelopmentRuntimeArtifactsSnapshots(input: {
readonly gracePeriodMs?: number;
readonly now?: number;
readonly retainCount?: number;
-}): Promise<void> {
+}): Promise<boolean> {
const pointer = readDevelopmentRuntimeArtifactsPointer(
resolveDevelopmentRuntimeArtifactsPointerPath(input.appRoot),
);
- await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({
+ return await pruneDevelopmentRuntimeArtifactsSnapshotDirectory({
activeSnapshotRoot:
pointer?.version === DEV_RUNTIME_ARTIFACTS_POINTER_VERSION ? pointer.snapshotRoot : undefined,
gracePeriodMs: input.gracePeriodMs,
diff --git a/packages/eve/src/internal/nitro/dev-runtime-generation-metadata.ts b/packages/eve/src/internal/nitro/dev-runtime-generation-metadata.ts
new file mode 100644
index 000000000..d660c790e
--- /dev/null
+++ b/packages/eve/src/internal/nitro/dev-runtime-generation-metadata.ts
@@ -0,0 +1,78 @@
+import { readFile, readdir } from "node:fs/promises";
+import { basename, join } from "node:path";
+
+export interface DevelopmentGenerationMetadata {
+ readonly runtimeAppRoot: string;
+}
+
+const GENERATION_METADATA = "generation.json";
+
+export function resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(appRoot: string): string {
+ return join(appRoot, ".eve", "dev-runtime", "snapshots");
+}
+
+export async function listDevelopmentGenerationIds(appRoot: string): Promise<string[]> {
+ try {
+ const entries = await readdir(resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(appRoot), {
+ withFileTypes: true,
+ });
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
+ throw error;
+ }
+}
+
+export async function readDevelopmentGenerationMetadata(
+ appRoot: string,
+ generationId: string,
+): Promise<
+ | { readonly kind: "ready"; readonly metadata: DevelopmentGenerationMetadata }
+ | { readonly kind: "missing" }
+ | { readonly kind: "invalid" }
+> {
+ if (
+ !generationId ||
+ generationId === "." ||
+ generationId === ".." ||
+ basename(generationId) !== generationId
+ ) {
+ throw new Error("Workflow run references an invalid development generation.");
+ }
+ let source: string;
+ try {
+ source = await readFile(
+ join(
+ resolveDevelopmentRuntimeArtifactsSnapshotsDirectory(appRoot),
+ generationId,
+ GENERATION_METADATA,
+ ),
+ "utf8",
+ );
+ } catch (error) {
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
+ return { kind: "missing" };
+ }
+ throw error;
+ }
+ let metadata: unknown;
+ try {
+ metadata = JSON.parse(source);
+ } catch {
+ return { kind: "invalid" };
+ }
+ if (
+ typeof metadata !== "object" ||
+ metadata === null ||
+ Array.isArray(metadata) ||
+ !("runtimeAppRoot" in metadata) ||
+ typeof metadata.runtimeAppRoot !== "string" ||
+ metadata.runtimeAppRoot.length === 0
+ ) {
+ return { kind: "invalid" };
+ }
+ return {
+ kind: "ready",
+ metadata: { runtimeAppRoot: metadata.runtimeAppRoot },
+ };
+}
diff --git a/packages/eve/src/internal/nitro/development-generation.test.ts b/packages/eve/src/internal/nitro/development-generation.test.ts
index 05b383f90..ae83c898d 100644
--- a/packages/eve/src/internal/nitro/development-generation.test.ts
+++ b/packages/eve/src/internal/nitro/development-generation.test.ts
@@ -5,7 +5,7 @@ import type { CompileAgentResult } from "#compiler/compile-agent.js";
const mocks = vi.hoisted(() => ({
activateTransaction: vi.fn(),
- prune: vi.fn(async (): Promise<void> => undefined),
+ prune: vi.fn(async (): Promise<boolean> => false),
prepare: vi.fn(),
stage: vi.fn(),
materialize: vi.fn(),
@@ -13,6 +13,9 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("node:fs/promises", () => ({ rm: mocks.rm }));
+vi.mock("#internal/nitro/dev-runtime-generation-metadata.js", () => ({
+ finalizeDevelopmentGenerationMetadata: vi.fn(async () => undefined),
+}));
vi.mock("#internal/authored-runtime-modules.js", () => ({
prepareAuthoredRuntimeModules: mocks.prepare,
}));
@@ -105,7 +108,8 @@ describe("development generation staging", () => {
describe("development generation activation", () => {
beforeEach(() => {
mocks.activateTransaction.mockReset();
- mocks.prune.mockClear();
+ mocks.prune.mockReset();
+ mocks.prune.mockResolvedValue(false);
});
it("requests background storage pruning only after activation commits", async () => {
@@ -123,9 +127,24 @@ describe("development generation activation", () => {
expect(mocks.prune).toHaveBeenCalledWith({ appRoot: "/tmp/app-commit" });
});
- it("reconciles only after pruning and preserves requests made during failed reconciliation", async () => {
+ it("skips reconciliation after a no-op prune", async () => {
+ mocks.activateTransaction.mockResolvedValue({ commit: vi.fn(), rollback: vi.fn() });
+ const pruning = Promise.withResolvers<boolean>();
+ mocks.prune.mockReturnValueOnce(pruning.promise);
+ const onRuntimePruned = vi.fn(async () => undefined);
+ await activateDevelopmentGeneration({
+ appRoot: "/tmp/app-no-op-prune",
+ generation: createGeneration("retained"),
+ onRuntimePruned,
+ });
+ pruning.resolve(false);
+ await pruning.promise;
+ expect(onRuntimePruned).not.toHaveBeenCalled();
+ });
+
+ it("retries failed reconciliation on a later activation even when pruning is a no-op", async () => {
mocks.activateTransaction.mockResolvedValue({ commit: vi.fn(), rollback: vi.fn() });
- const pruning = Promise.withResolvers<void>();
+ const pruning = Promise.withResolvers<boolean>();
const reconciliation = Promise.withResolvers<void>();
mocks.prune.mockReturnValueOnce(pruning.promise);
const onRuntimePruned = vi
@@ -141,17 +160,18 @@ describe("development generation activation", () => {
try {
await activateDevelopmentGeneration(input);
expect(onRuntimePruned).not.toHaveBeenCalled();
- pruning.resolve();
+ pruning.resolve(true);
await vi.waitFor(() => expect(onRuntimePruned).toHaveBeenCalledOnce());
- await activateDevelopmentGeneration({ ...input, generation: createGeneration("two") });
reconciliation.reject(new Error("storage unavailable"));
+ await vi.waitFor(() => expect(warning).toHaveBeenCalledOnce());
+ await activateDevelopmentGeneration({ ...input, generation: createGeneration("two") });
await vi.waitFor(() => expect(onRuntimePruned).toHaveBeenCalledTimes(2));
expect(mocks.prune).toHaveBeenCalledTimes(2);
expect(warning).toHaveBeenCalledExactlyOnceWith(
"[eve:dev] failed to reconcile expired Workflow runs: Error: storage unavailable",
);
} finally {
- pruning.resolve();
+ pruning.resolve(false);
reconciliation.resolve();
warning.mockRestore();
}
@@ -159,8 +179,8 @@ describe("development generation activation", () => {
it("does not reconcile failed pruning and retries a pending prune request", async () => {
mocks.activateTransaction.mockResolvedValue({ commit: vi.fn(), rollback: vi.fn() });
- const pruning = Promise.withResolvers<void>();
- mocks.prune.mockReturnValueOnce(pruning.promise);
+ const pruning = Promise.withResolvers<boolean>();
+ mocks.prune.mockReturnValueOnce(pruning.promise).mockResolvedValueOnce(false);
const onRuntimePruned = vi.fn(async () => undefined);
const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const input = {
@@ -178,7 +198,7 @@ describe("development generation activation", () => {
"[eve:dev] failed to prune runtime generations: Error: filesystem unavailable",
);
} finally {
- pruning.resolve();
+ pruning.resolve(false);
warning.mockRestore();
}
});
diff --git a/packages/eve/src/internal/nitro/development-generation.ts b/packages/eve/src/internal/nitro/development-generation.ts
index f1b279df6..df318b21f 100644
--- a/packages/eve/src/internal/nitro/development-generation.ts
+++ b/packages/eve/src/internal/nitro/development-generation.ts
@@ -21,6 +21,7 @@ export interface DevelopmentGeneration extends DevelopmentRuntimeArtifactsSnapsh
interface DevelopmentGenerationPruneState {
requested: boolean;
+ reconciliationPending: boolean;
running: Promise<void> | undefined;
onRuntimePruned?: () => Promise<void>;
}
@@ -133,6 +134,7 @@ function requestDevelopmentGenerationPrune(
): void {
const state: DevelopmentGenerationPruneState = developmentGenerationPruneStates.get(appRoot) ?? {
requested: false,
+ reconciliationPending: false,
running: undefined,
};
developmentGenerationPruneStates.set(appRoot, state);
@@ -151,9 +153,20 @@ function startDevelopmentGenerationPruning(
while (state.requested) {
state.requested = false;
const onRuntimePruned = state.onRuntimePruned;
- await pruneDevelopmentRuntimeArtifactsSnapshots({ appRoot });
+ let removedSnapshots: boolean;
try {
- await onRuntimePruned?.();
+ removedSnapshots = await pruneDevelopmentRuntimeArtifactsSnapshots({ appRoot });
+ } catch (error) {
+ // A failed prune may already have removed some snapshots.
+ state.reconciliationPending ||= onRuntimePruned !== undefined;
+ throw error;
+ }
+ state.reconciliationPending ||= removedSnapshots && onRuntimePruned !== undefined;
+ try {
+ if (state.reconciliationPending && onRuntimePruned !== undefined) {
+ await onRuntimePruned();
+ state.reconciliationPending = false;
+ }
} catch (error) {
console.warn(`[eve:dev] failed to reconcile expired Workflow runs: ${String(error)}`);
}
@@ -166,8 +179,11 @@ function startDevelopmentGenerationPruning(
state.running = undefined;
if (state.requested) {
startDevelopmentGenerationPruning(appRoot, state);
- } else {
+ } else if (!state.reconciliationPending) {
developmentGenerationPruneStates.delete(appRoot);
+ } else {
+ // Retry failed cleanup on the next activation, even if its prune is a no-op.
+ state.onRuntimePruned = undefined;
}
});
}
diff --git a/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts b/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts
index 2d6bd8558..4d3ba21ec 100644
--- a/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts
+++ b/packages/eve/src/internal/nitro/host/dev-workflow-world-setup.ts
@@ -18,6 +18,7 @@ const PORT_ENV = "PORT";
export function createDevelopmentWorkflowWorld(input: {
readonly appRoot: string;
+ readonly resume?: boolean;
readonly preparedHost: PreparedDevelopmentApplicationHost;
readonly transportSecret: string;
}): ParentDevelopmentWorkflowWorld | undefined {
@@ -30,10 +31,13 @@ export function createDevelopmentWorkflowWorld(input: {
input.preparedHost.compileResult.manifest.config.experimental?.workflow?.world,
)
) {
+ if (input.resume)
+ throw new Error("--resume is supported only with the built-in local Workflow World.");
return undefined;
}
return createParentDevelopmentWorkflowWorld({
agentName: input.preparedHost.compileResult.manifest.config.name,
+ resume: input.resume,
appRoot: input.appRoot,
resolveActiveGenerationId: () => {
const snapshot = readActiveDevelopmentRuntimeArtifactsSnapshot(input.appRoot);
diff --git a/packages/eve/src/internal/nitro/host/start-development-server.ts b/packages/eve/src/internal/nitro/host/start-development-server.ts
index d34abc5bd..04636d80d 100644
--- a/packages/eve/src/internal/nitro/host/start-development-server.ts
+++ b/packages/eve/src/internal/nitro/host/start-development-server.ts
@@ -375,6 +375,7 @@ async function startNitroDevelopmentServer(
const environmentPort = readEnvironmentPort();
const requestedPort = options.port ?? environmentPort;
const hasExplicitServerConfiguration =
+ options.resume === true ||
options.developmentExtensions !== undefined ||
options.host !== undefined ||
options.port !== undefined ||
@@ -435,6 +436,7 @@ async function startNitroDevelopmentServer(
workflowWorld = createDevelopmentWorkflowWorld({
appRoot: project.appRoot,
preparedHost,
+ resume: options.resume,
transportSecret: workflowTransportSecret,
});
const localWorkflowWorld = workflowWorld;
diff --git a/packages/eve/src/internal/nitro/host/types.ts b/packages/eve/src/internal/nitro/host/types.ts
index a943645b2..cbf151612 100644
--- a/packages/eve/src/internal/nitro/host/types.ts
+++ b/packages/eve/src/internal/nitro/host/types.ts
@@ -63,6 +63,8 @@ export interface DevelopmentServer<H extends DevelopmentServerHandle = Developme
}
export interface DevelopmentServerOptions {
+ /** Recover compatible unfinished runs from previous local dev invocations. Defaults to false. */
+ readonly resume?: boolean;
/** Development-only source extensions. Defaults to the framework catalog. */
readonly developmentExtensions?: DevelopmentExtensionSelection;
readonly existing?: "attach-if-unconfigured" | "reject";
diff --git a/packages/eve/src/internal/workflow/cancel-expired-development-run.ts b/packages/eve/src/internal/workflow/cancel-expired-development-run.ts
index 21081d575..42b8b4f26 100644
--- a/packages/eve/src/internal/workflow/cancel-expired-development-run.ts
+++ b/packages/eve/src/internal/workflow/cancel-expired-development-run.ts
@@ -1,6 +1,6 @@
import type { World } from "#compiled/@workflow/world/index.js";
import { cancelRun } from "#internal/workflow/runtime.js";
-import { isInactiveDevelopmentRunError } from "#internal/workflow/is-inactive-development-run-error.js";
+import { isInactiveWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";
export async function cancelExpiredDevelopmentRun(world: World, runId: string): Promise<void> {
try {
@@ -11,12 +11,12 @@ export async function cancelExpiredDevelopmentRun(world: World, runId: string):
cancelReason: "Development runtime snapshot is no longer available",
});
} catch (error) {
- if (isInactiveDevelopmentRunError(error)) return;
+ if (isInactiveWorkflowRunError(error)) return;
// A delivery can finish between the scan and cancellation.
const current = await world.runs.get(runId, { resolveData: "none" });
if (current.status === "pending" || current.status === "running") throw error;
}
} catch (error) {
- if (!isInactiveDevelopmentRunError(error)) throw error;
+ if (!isInactiveWorkflowRunError(error)) throw error;
}
}
diff --git a/packages/eve/src/internal/workflow/development-runtime-compatibility.test.ts b/packages/eve/src/internal/workflow/development-runtime-compatibility.test.ts
new file mode 100644
index 000000000..060efd03e
--- /dev/null
+++ b/packages/eve/src/internal/workflow/development-runtime-compatibility.test.ts
@@ -0,0 +1,39 @@
+import { beforeEach, expect, it, vi } from "vitest";
+
+const files = vi.hoisted(() => new Map<string, string>());
+vi.mock("node:fs/promises", () => ({
+ readFile: async (path: string) => {
+ const value = files.get(path);
+ if (value === undefined) throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ return value;
+ },
+}));
+
+beforeEach(() => files.clear());
+
+it.each([
+ ["old", { runtimeAppRoot: "/old" }, "ready"],
+ ["invalid-schema", { runtimeAppRoot: 42 }, "ineligible"],
+] as const)("reads %s generation metadata", async (generationId, metadata, kind) => {
+ files.set(
+ `/app/.eve/dev-runtime/snapshots/${generationId}/generation.json`,
+ JSON.stringify(metadata),
+ );
+ const { readDevelopmentGenerationAvailability } =
+ await import("./development-runtime-compatibility.js");
+ await expect(readDevelopmentGenerationAvailability("/app", generationId)).resolves.toMatchObject({
+ kind,
+ });
+});
+
+it("distinguishes a missing snapshot from malformed metadata", async () => {
+ const { readDevelopmentGenerationAvailability } =
+ await import("./development-runtime-compatibility.js");
+ await expect(readDevelopmentGenerationAvailability("/app", "missing")).resolves.toMatchObject({
+ kind: "missing",
+ });
+ files.set("/app/.eve/dev-runtime/snapshots/bad/generation.json", "{");
+ await expect(readDevelopmentGenerationAvailability("/app", "bad")).resolves.toMatchObject({
+ kind: "ineligible",
+ });
+});
diff --git a/packages/eve/src/internal/workflow/development-runtime-compatibility.ts b/packages/eve/src/internal/workflow/development-runtime-compatibility.ts
new file mode 100644
index 000000000..498b4fd17
--- /dev/null
+++ b/packages/eve/src/internal/workflow/development-runtime-compatibility.ts
@@ -0,0 +1,25 @@
+import { readDevelopmentGenerationMetadata } from "#internal/nitro/dev-runtime-generation-metadata.js";
+
+export type DevelopmentGenerationAvailability =
+ | { readonly kind: "ready"; readonly runtimeAppRoot: string }
+ | { readonly kind: "missing"; readonly reason: string }
+ | { readonly kind: "ineligible"; readonly reason: string };
+
+/** Recovery checks snapshot readability, not whether changed code will replay successfully. */
+export async function readDevelopmentGenerationAvailability(
+ appRoot: string,
+ generationId: string,
+): Promise<DevelopmentGenerationAvailability> {
+ const retained = await readDevelopmentGenerationMetadata(appRoot, generationId);
+ if (retained.kind === "missing") {
+ return { kind: "missing", reason: "Development runtime snapshot is no longer available" };
+ }
+ if (retained.kind === "invalid") {
+ return {
+ kind: "ineligible",
+ reason:
+ "Development generation metadata is invalid. Restore the affected snapshot from a backup or start a new session.",
+ };
+ }
+ return { kind: "ready", runtimeAppRoot: retained.metadata.runtimeAppRoot };
+}
diff --git a/packages/eve/src/internal/workflow/development-world-client.ts b/packages/eve/src/internal/workflow/development-world-client.ts
index 57b21519a..ee79001a2 100644
--- a/packages/eve/src/internal/workflow/development-world-client.ts
+++ b/packages/eve/src/internal/workflow/development-world-client.ts
@@ -6,8 +6,6 @@ import type {
World,
} from "#compiled/@workflow/world/index.js";
import { resolvePackageSourceFilePath } from "#internal/application/package.js";
-import { readFile } from "node:fs/promises";
-import { basename, join } from "node:path";
import {
decodeDevelopmentWorldJson,
@@ -20,7 +18,7 @@ import {
withDevelopmentWorkflowGeneration,
} from "#internal/workflow/development-generation-context.js";
import { cancelExpiredDevelopmentRun } from "#internal/workflow/cancel-expired-development-run.js";
-import { isMissingDevelopmentRunError } from "#internal/workflow/is-inactive-development-run-error.js";
+import { isMissingWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";
import {
DEVELOPMENT_WORKER_APP_ROOT_ENV,
DEVELOPMENT_WORKFLOW_DELIVERY_HEADER,
@@ -29,6 +27,8 @@ import {
DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,
DEVELOPMENT_WORKFLOW_WORLD_ROUTE,
DEVELOPMENT_WORLD_OPERATIONS,
+ type DevelopmentGenerationAdmission,
+ type DevelopmentGenerationAvailabilityCall,
type DevelopmentWorldCall,
type DevelopmentWorldOperation,
} from "#internal/workflow/development-world-protocol.js";
@@ -67,6 +67,19 @@ async function call<T>(
return decodeDevelopmentWorldValue(await response.text()) as T;
}
+async function getGenerationAvailability(
+ generationId: string,
+): Promise<DevelopmentGenerationAdmission> {
+ const response = await fetchDevelopmentWorld(DEVELOPMENT_WORKFLOW_WORLD_ROUTE, {
+ body: encodeDevelopmentWorldValue({
+ operation: "eve.getGenerationAvailability",
+ generationId,
+ } satisfies DevelopmentGenerationAvailabilityCall),
+ method: "POST",
+ });
+ return decodeDevelopmentWorldValue(await response.text()) as DevelopmentGenerationAdmission;
+}
+
/**
* Worker-side Workflow World: an interface-faithful shim whose every method
* forwards to the real local World in the CLI parent process.
@@ -191,7 +204,12 @@ function createQueueHandler(
const appRoot = readRequiredEnvironment(DEVELOPMENT_WORKER_APP_ROOT_ENV);
const generationId = await resolveDeliveryGenerationId(message);
if (generationId === undefined) return Response.json({ ok: true });
- const runtimeAppRoot = await readGenerationRuntimeAppRoot(appRoot, generationId);
+ const availability = await getGenerationAvailability(generationId);
+ if (availability.kind === "missing")
+ throw new MissingDevelopmentGenerationError(generationId);
+ if (availability.kind === "ineligible" || availability.kind === "dormant")
+ return Response.json({ ok: true });
+ const runtimeAppRoot = availability.runtimeAppRoot;
const result = await withDevelopmentWorkflowGeneration(
{
generationId,
@@ -261,7 +279,7 @@ async function resolveDeliveryGenerationId(message: unknown): Promise<string | u
]);
return run.deploymentId;
} catch (error) {
- if (!isMissingDevelopmentRunError(error)) throw error;
+ if (!isMissingWorkflowRunError(error)) throw error;
return undefined;
}
}
@@ -275,53 +293,6 @@ function resolveDeliveryRunId(message: unknown): string | undefined {
: undefined;
}
-async function readGenerationRuntimeAppRoot(
- appRoot: string,
- generationId: string,
-): Promise<string> {
- if (
- generationId.length === 0 ||
- generationId === "." ||
- generationId === ".." ||
- basename(generationId) !== generationId
- ) {
- throw new Error(`Workflow run references invalid development generation "${generationId}".`);
- }
- const metadataPath = join(
- appRoot,
- ".eve",
- "dev-runtime",
- "snapshots",
- generationId,
- "generation.json",
- );
- let source: string;
- try {
- source = await readFile(metadataPath, "utf8");
- } catch (error) {
- if (isFileNotFoundError(error)) {
- throw new MissingDevelopmentGenerationError(generationId, error);
- }
- throw error;
- }
- let metadata: unknown;
- try {
- metadata = JSON.parse(source);
- } catch (error) {
- throw new Error(`Development generation "${generationId}" has invalid metadata.`, {
- cause: error,
- });
- }
- if (!isRecord(metadata) || typeof metadata.runtimeAppRoot !== "string") {
- throw new Error(`Development generation "${generationId}" has invalid metadata.`);
- }
- return metadata.runtimeAppRoot;
-}
-
-function isFileNotFoundError(error: unknown): boolean {
- return error instanceof Error && "code" in error && error.code === "ENOENT";
-}
-
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/packages/eve/src/internal/workflow/development-world-protocol.ts b/packages/eve/src/internal/workflow/development-world-protocol.ts
index 8249cf56c..843d8e736 100644
--- a/packages/eve/src/internal/workflow/development-world-protocol.ts
+++ b/packages/eve/src/internal/workflow/development-world-protocol.ts
@@ -1,3 +1,4 @@
+import type { DevelopmentGenerationAvailability } from "#internal/workflow/development-runtime-compatibility.js";
import type { AgentWorkflowWorldDefinition } from "#shared/agent-definition.js";
import { resolveWorkflowWorldImport } from "#internal/workflow/world-target.js";
@@ -61,3 +62,14 @@ export interface DevelopmentWorldCall {
readonly arguments: readonly unknown[];
readonly operation: DevelopmentWorldOperation;
}
+
+export type DevelopmentGenerationAdmission =
+ | DevelopmentGenerationAvailability
+ | { readonly kind: "dormant" };
+
+export interface DevelopmentGenerationAvailabilityCall {
+ readonly operation: "eve.getGenerationAvailability";
+ readonly generationId: string;
+}
+
+export type DevelopmentWorldRequest = DevelopmentWorldCall | DevelopmentGenerationAvailabilityCall;
diff --git a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
index b207e5111..4ceced177 100644
--- a/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
+++ b/packages/eve/src/internal/workflow/development-world-server.integration.test.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { EntityConflictError, RunExpiredError } from "#compiled/@workflow/errors/index.js";
import { workflowEntryReference } from "#execution/workflow-runtime.js";
-import { pruneDevelopmentRuntimeArtifactsSnapshots } from "#internal/nitro/dev-runtime-artifacts.js";
+import { activateDevelopmentGeneration } from "#internal/nitro/development-generation.js";
import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
import { getDevelopmentWorkflowGeneration } from "#internal/workflow/development-generation-context.js";
import { deriveEveWorkflowQueuePrefix } from "#internal/workflow/queue-namespace.js";
@@ -106,10 +106,9 @@ describe("parent development Workflow World", () => {
}
});
- it("pins every workflow delivery to its recorded generation", async () => {
+ it("keeps current-invocation deliveries eligible after authored workflow changes", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-world-");
await seedGeneration(appRoot, "generation-a");
- await seedGeneration(appRoot, "generation-b");
let activeGenerationId = "generation-a";
const world = createWorld({ activeGenerationId: () => activeGenerationId, appRoot });
connectWorkerToWorld(world, appRoot);
@@ -130,9 +129,39 @@ describe("parent development Workflow World", () => {
},
]);
const runId = readCreatedRunId(created);
+ const token = `review-live-${runId}`;
+ await callWorld(world, "events.create", [
+ runId,
+ {
+ eventType: "run_started",
+ specVersion: 6,
+ },
+ ]);
+ await callWorld(world, "events.create", [
+ runId,
+ {
+ eventType: "hook_created",
+ specVersion: 6,
+ correlationId: "hook_01J00000000000000000000001",
+ eventData: { token },
+ },
+ ]);
+ await seedGeneration(appRoot, "generation-b", {
+ workflowSourceFingerprint: "added-workflow",
+ });
activeGenerationId = "generation-b";
- await expect(deliverToWorker({ runId })).resolves.toBe("generation-a");
+ await expect(callWorld(world, "hooks.getByToken", [token])).resolves.toMatchObject({ runId });
+ for (const message of [
+ { runId },
+ { workflowRunId: runId },
+ { runInput: { deploymentId: "generation-a" } },
+ { runInput: { deploymentId: "generation-b" } },
+ ]) {
+ await expect(deliverToWorker(message)).resolves.toBe(
+ message.runInput?.deploymentId ?? "generation-a",
+ );
+ }
} finally {
await world.close();
}
@@ -142,7 +171,7 @@ describe("parent development Workflow World", () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-routing-");
await seedGeneration(appRoot, "generation-a");
await seedGeneration(appRoot, "generation-b");
- const world = createWorld({ activeGenerationId: () => "generation-b", appRoot });
+ const world = createWorld({ activeGenerationId: () => "generation-b", appRoot, resume: true });
connectWorkerToWorld(world, appRoot);
try {
@@ -223,11 +252,35 @@ describe("parent development Workflow World", () => {
it("recovers retained runs across restarts without recovering cancelled orphans", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-recovery-");
await seedGeneration(appRoot, "retained");
+ await seedGeneration(appRoot, "changed-framework", { frameworkFingerprint: "old-framework" });
+ await seedGeneration(appRoot, "legacy");
+ await seedGeneration(appRoot, "queued-only", { workflowSourceFingerprint: "old-workflow" });
+ await seedGeneration(appRoot, "changed-workflow", {
+ workflowSourceFingerprint: "old-workflow",
+ });
+ for (const [generationId, source] of [
+ ["invalid-json", '{"runtimeAppRoot":'],
+ ["invalid-schema", JSON.stringify({ runtimeAppRoot: 42 })],
+ ] as const) {
+ await seedGeneration(appRoot, generationId);
+ await writeFile(
+ join(appRoot, ".eve", "dev-runtime", "snapshots", generationId, "generation.json"),
+ source,
+ );
+ }
const first = createWorld({ activeGenerationId: () => "retained", appRoot });
await first.start();
const runIds: string[] = [];
try {
- for (const deploymentId of ["retained", "missing"]) {
+ for (const deploymentId of [
+ "retained",
+ "missing",
+ "changed-framework",
+ "legacy",
+ "changed-workflow",
+ "invalid-json",
+ "invalid-schema",
+ ]) {
runIds.push(
readCreatedRunId(
await callWorld(first, "events.create", [
@@ -258,19 +311,146 @@ describe("parent development Workflow World", () => {
deliveries.push(message.runId);
return Response.json({ ok: true });
}) as typeof fetch;
- const restarted = createWorld({ activeGenerationId: () => "retained", appRoot });
+ let activeGenerationId = "retained";
+ const restarted = createWorld({
+ activeGenerationId: () => activeGenerationId,
+ appRoot,
+ resume: true,
+ });
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
try {
await restarted.start();
- await expect.poll(() => deliveries).toEqual([runIds[0]]);
+ await expect
+ .poll(() => [...deliveries].sort())
+ .toEqual([runIds[0], runIds[2], runIds[3], runIds[4]].sort());
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining('"invalid-json": Development generation metadata is invalid.'),
+ );
await expect(callWorld(restarted, "runs.get", [runIds[1]])).resolves.toMatchObject({
status: "cancelled",
});
+ connectWorkerToWorld(restarted, appRoot);
+ await seedGeneration(appRoot, "rebuilt", { workflowSourceFingerprint: "old-workflow" });
+ activeGenerationId = "rebuilt";
+ await expect(deliverToWorker({ runId: runIds[0] })).resolves.toBe("retained");
+ for (const [index, runId] of runIds.entries()) {
+ if (index < 2) continue;
+ const expected =
+ index === 2
+ ? "changed-framework"
+ : index === 3
+ ? "legacy"
+ : index === 4
+ ? "changed-workflow"
+ : undefined;
+ await expect(deliverToWorker({ runId })).resolves.toBe(expected);
+ await expect(deliverToWorker({ workflowRunId: runId })).resolves.toBe(expected);
+ await expect(callWorld(restarted, "runs.get", [runId])).resolves.toMatchObject({
+ status: "pending",
+ });
+ }
+ await expect(
+ deliverToWorker({ runId: RUN_ID, runInput: { deploymentId: "queued-only" } }),
+ ).resolves.toBe("queued-only");
} finally {
+ warning.mockRestore();
await restarted.close();
}
});
- it("reconciles explicitly after pruning, preserves retained runs, and skips cleanup after close", async () => {
+ it("keeps previous invocations dormant across deliveries while new generations stay live", async () => {
+ const appRoot = await createScratchDirectory("eve-parent-workflow-dormant-");
+ for (const id of ["old", "new"]) await seedGeneration(appRoot, id);
+ const first = createWorld({ activeGenerationId: () => "old", appRoot });
+ await first.start();
+ const created = await callWorld(first, "events.create", [
+ null,
+ {
+ eventType: "run_created",
+ specVersion: 6,
+ eventData: {
+ deploymentId: "old",
+ executionContext: {},
+ input: new Uint8Array(),
+ workflowName: workflowEntryReference.workflowId,
+ },
+ },
+ ]);
+ const runId = readCreatedRunId(created);
+ const token = `review-dormant-${runId}`;
+ await callWorld(first, "events.create", [
+ runId,
+ {
+ eventType: "run_started",
+ specVersion: 6,
+ },
+ ]);
+ await callWorld(first, "events.create", [
+ runId,
+ {
+ eventType: "hook_created",
+ specVersion: 6,
+ correlationId: "hook_01J00000000000000000000002",
+ eventData: { token },
+ },
+ ]);
+ await first.close();
+
+ let active = "new";
+ const second = createWorld({ activeGenerationId: () => active, appRoot });
+ connectWorkerToWorld(second, appRoot);
+ const startupFetch = vi.spyOn(globalThis, "fetch");
+ try {
+ await second.start();
+ expect(startupFetch).not.toHaveBeenCalled();
+ startupFetch.mockRestore();
+ await expect(createDevelopmentWorkflowWorld().hooks.getByToken(token)).rejects.toThrow(
+ "Local Workflow run was not resumed",
+ );
+ for (const message of [
+ { runId },
+ { workflowRunId: runId },
+ { runId, runInput: { deploymentId: "old" } },
+ ]) {
+ await expect(deliverToWorker(message)).resolves.toBeUndefined();
+ }
+ await expect(callWorld(second, "runs.get", [runId])).resolves.toMatchObject({
+ status: "running",
+ });
+ await expect(callWorld(second, "events.list", [{ runId }])).resolves.toMatchObject({
+ data: expect.not.arrayContaining([expect.objectContaining({ eventType: "hook_received" })]),
+ });
+ await seedGeneration(appRoot, "reloaded");
+ active = "reloaded";
+ await expect(deliverToWorker({ runInput: { deploymentId: "reloaded" } })).resolves.toBe(
+ "reloaded",
+ );
+ await expect(deliverToWorker({ runInput: { deploymentId: "new" } })).resolves.toBe("new");
+ await expect(deliverToWorker({ runId })).resolves.toBeUndefined();
+ } finally {
+ await second.close();
+ }
+ const resumed = createWorld({ activeGenerationId: () => "reloaded", appRoot, resume: true });
+ // Capture startup recovery without opening a port.
+ const deliveries: string[] = [];
+ globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
+ deliveries.push(JSON.parse(new TextDecoder().decode(init?.body as Uint8Array)).runId);
+ return Response.json({ ok: true });
+ }) as typeof fetch;
+ try {
+ await resumed.start();
+ await expect.poll(() => deliveries).toEqual([runId]);
+ connectWorkerToWorld(resumed, appRoot);
+ await expect(callWorld(resumed, "hooks.getByToken", [token])).resolves.toMatchObject({
+ runId,
+ });
+ await expect(deliverToWorker({ runId })).resolves.toBe("old");
+ } finally {
+ await resumed.close();
+ }
+ });
+
+ it("reconciles after activation prunes snapshots, preserves retained runs, and skips cleanup after close", async () => {
const appRoot = await createScratchDirectory("eve-parent-workflow-pruning-");
await seedGeneration(appRoot, "old");
await seedGeneration(appRoot, "retained");
@@ -310,15 +490,49 @@ describe("parent development Workflow World", () => {
join(appRoot, ".eve", "dev-runtime", "snapshots", "old", "retired.json"),
JSON.stringify({ retiredAt: 0 }),
);
- await pruneDevelopmentRuntimeArtifactsSnapshots({
+ for (let index = 0; index < 5; index++) {
+ const generationId = `recent-${index}`;
+ await seedGeneration(appRoot, generationId);
+ const root = join(appRoot, ".eve", "dev-runtime", "snapshots", generationId);
+ await writeFile(join(root, "activated"), "");
+ await writeFile(join(root, "retired.json"), JSON.stringify({ retiredAt: Date.now() }));
+ }
+ const snapshotRoot = join(appRoot, ".eve", "dev-runtime", "snapshots", "retained");
+ const runtimeAppRoot = join(snapshotRoot, "source", "app");
+ const compileRoot = join(runtimeAppRoot, ".eve", "compile");
+ await mkdir(compileRoot, { recursive: true });
+ await writeFile(
+ join(compileRoot, "module-map.mjs"),
+ "export const moduleMap = { nodes: {} };\n",
+ );
+ await writeFile(
+ join(compileRoot, "authored-modules.json"),
+ JSON.stringify({
+ fingerprint: "test",
+ moduleMap: "module-map.mjs",
+ version: 3,
+ }),
+ );
+ const reconciled = Promise.withResolvers<void>();
+ await activateDevelopmentGeneration({
appRoot,
- gracePeriodMs: 60_000,
- retainCount: 0,
- });
- await expect(callWorld(world, "runs.get", [old])).resolves.toMatchObject({
- status: "pending",
+ generation: {
+ fingerprint: "test",
+ runtimeAppRoot,
+ snapshotRoot,
+ snapshotSourceRoot: join(snapshotRoot, "source"),
+ sourceRoot: appRoot,
+ },
+ onRuntimePruned: async () => {
+ try {
+ await world.reconcileExpiredRuns();
+ reconciled.resolve();
+ } catch (error) {
+ reconciled.reject(error);
+ }
+ },
});
- await world.reconcileExpiredRuns();
+ await reconciled.promise;
for (const runId of [old, running]) {
await expect(callWorld(world, "runs.get", [runId])).resolves.toMatchObject({
status: "cancelled",
@@ -332,7 +546,6 @@ describe("parent development Workflow World", () => {
});
await world.close();
await rm(join(appRoot, ".eve", "dev-runtime", "snapshots", "retained"), { recursive: true });
- await pruneDevelopmentRuntimeArtifactsSnapshots({ appRoot });
await world.reconcileExpiredRuns();
await expect(callWorld(world, "runs.get", [retained])).resolves.toMatchObject({
status: "pending",
@@ -640,11 +853,21 @@ function deliveryHeaders(input: { readonly secret?: string }): Record<string, st
};
}
-async function seedGeneration(appRoot: string, generationId: string): Promise<void> {
+async function seedGeneration(
+ appRoot: string,
+ generationId: string,
+ overrides: {
+ frameworkFingerprint?: string;
+ workflowSourceFingerprint?: string;
+ } = {},
+): Promise<void> {
const snapshotRoot = join(appRoot, ".eve", "dev-runtime", "snapshots", generationId);
const runtimeAppRoot = join(snapshotRoot, "source", "app");
await mkdir(runtimeAppRoot, { recursive: true });
- await writeFile(join(snapshotRoot, "generation.json"), `${JSON.stringify({ runtimeAppRoot })}\n`);
+ await writeFile(
+ join(snapshotRoot, "generation.json"),
+ `${JSON.stringify({ runtimeAppRoot, ...overrides })}\n`,
+ );
}
function readCreatedRunId(value: unknown): string {
@@ -665,9 +888,11 @@ function readCreatedRunId(value: unknown): string {
function createWorld(input: {
readonly activeGenerationId: () => string;
readonly appRoot: string;
+ readonly resume?: boolean;
}): ParentDevelopmentWorkflowWorld {
return createParentDevelopmentWorkflowWorld({
agentName: AGENT_NAME,
+ resume: input.resume,
appRoot: input.appRoot,
resolveActiveGenerationId: input.activeGenerationId,
transportSecret: SECRET,
diff --git a/packages/eve/src/internal/workflow/development-world-server.ts b/packages/eve/src/internal/workflow/development-world-server.ts
index 098618638..fac0c9d73 100644
--- a/packages/eve/src/internal/workflow/development-world-server.ts
+++ b/packages/eve/src/internal/workflow/development-world-server.ts
@@ -1,5 +1,8 @@
-import { existsSync } from "node:fs";
-import { basename, join } from "node:path";
+import {
+ readDevelopmentGenerationAvailability,
+ type DevelopmentGenerationAvailability,
+} from "#internal/workflow/development-runtime-compatibility.js";
+import { listDevelopmentGenerationIds } from "#internal/nitro/dev-runtime-generation-metadata.js";
import { cancelExpiredDevelopmentRun } from "#internal/workflow/cancel-expired-development-run.js";
import type { ValidQueueName, World } from "#compiled/@workflow/world/index.js";
@@ -22,7 +25,8 @@ import {
DEVELOPMENT_WORKFLOW_TRANSPORT_HEADER,
DEVELOPMENT_WORKFLOW_WORLD_ROUTE,
DEVELOPMENT_WORLD_OPERATIONS,
- type DevelopmentWorldCall,
+ type DevelopmentGenerationAdmission,
+ type DevelopmentWorldRequest,
} from "#internal/workflow/development-world-protocol.js";
/**
@@ -52,6 +56,7 @@ export function createParentDevelopmentWorkflowWorld(input: {
readonly agentName: string;
readonly appRoot: string;
readonly resolveActiveGenerationId: () => string;
+ readonly resume?: boolean;
readonly transportSecret: string;
}): ParentDevelopmentWorkflowWorld {
return new LocalParentDevelopmentWorkflowWorld(input);
@@ -63,6 +68,13 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
readonly #resolveActiveGenerationId: () => string;
readonly #transportSecret: string;
readonly #world: World;
+ readonly #resume: boolean;
+ // Owned by the host, not a worker: rebuilds preserve the startup admission decision.
+ readonly #unrecoveredGenerations = new Map<
+ string,
+ | Extract<DevelopmentGenerationAvailability, { kind: "ineligible" }>
+ | { readonly kind: "dormant" }
+ >();
#closed = false;
#started = false;
#reconciliation: Promise<void> = Promise.resolve();
@@ -71,11 +83,13 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
readonly agentName: string;
readonly appRoot: string;
readonly resolveActiveGenerationId: () => string;
+ readonly resume?: boolean;
readonly transportSecret: string;
}) {
if (input.transportSecret.length < 16) {
throw new Error("Development Workflow transport secret is too short to be trusted.");
}
+ this.#resume = input.resume === true;
this.#agentName = input.agentName;
this.#appRoot = input.appRoot;
this.#resolveActiveGenerationId = input.resolveActiveGenerationId;
@@ -91,14 +105,40 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
if (this.#started) {
return;
}
+ // Queue redelivery starts with the World. Decide admission before it can wake retained runs.
+ const recoveryGenerationId = this.#resolveActiveGenerationId();
+ this.#unrecoveredGenerations.clear();
+ for (const generationId of await listDevelopmentGenerationIds(this.#appRoot)) {
+ if (generationId === recoveryGenerationId) continue;
+ if (!this.#resume) {
+ this.#unrecoveredGenerations.set(generationId, { kind: "dormant" });
+ continue;
+ }
+ const availability = await readDevelopmentGenerationAvailability(this.#appRoot, generationId);
+ if (availability.kind === "ineligible") {
+ this.#unrecoveredGenerations.set(generationId, availability);
+ }
+ }
await this.#world.start?.();
this.#started = true;
try {
await this.#reconcileExpiredRuns();
+ if (!this.#resume) return;
+ const skippedGenerations = new Set<string>();
await reenqueueActiveDevelopmentRuns({
enqueue: this.#queue.bind(this),
prefix: deriveEveWorkflowQueuePrefix(this.#agentName),
world: this.#world,
+ canRecover: async (generationId) => {
+ const availability = await this.#generationAvailability(generationId);
+ if (availability.kind === "ineligible" && !skippedGenerations.has(generationId)) {
+ skippedGenerations.add(generationId);
+ console.warn(
+ `[eve:dev] Skipping retained Workflow generation "${generationId}": ${availability.reason}`,
+ );
+ }
+ return availability.kind === "ready";
+ },
});
} catch (error) {
this.#started = false;
@@ -167,7 +207,11 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
);
}
for (const run of page.data) {
- if (!this.#generationExists(run.deploymentId)) runIds.push(run.runId);
+ const availability = await readDevelopmentGenerationAvailability(
+ this.#appRoot,
+ run.deploymentId,
+ );
+ if (availability.kind === "missing") runIds.push(run.runId);
}
cursor = page.hasMore ? (page.cursor ?? undefined) : undefined;
} while (cursor !== undefined);
@@ -180,7 +224,7 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
return Response.json({ error: "Workflow World request is not trusted." }, { status: 401 });
}
try {
- const call = decodeDevelopmentWorldValue(await request.text()) as DevelopmentWorldCall;
+ const call = decodeDevelopmentWorldValue(await request.text());
const result = await this.#call(call);
return new Response(encodeDevelopmentWorldValue(result));
} catch (error) {
@@ -225,10 +269,13 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
});
}
- async #call(call: DevelopmentWorldCall): Promise<unknown> {
- if (!isDevelopmentWorldCall(call)) {
+ async #call(call: unknown): Promise<unknown> {
+ if (!isDevelopmentWorldRequest(call)) {
throw new Error("Development Workflow World call is malformed.");
}
+ if (call.operation === "eve.getGenerationAvailability") {
+ return await this.#generationAvailability(call.generationId);
+ }
const args = [...call.arguments];
// Deployment identity and enqueueing carry eve semantics (generation
// resolution, the delivery header); everything else forwards to the
@@ -239,6 +286,23 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
if (call.operation === "queue") {
return await this.#queue(...(args as Parameters<World["queue"]>));
}
+ if (call.operation === "hooks.getByToken" || call.operation === "hooks.get") {
+ if (!this.#started) throw new Error("Local Workflow World is still starting.");
+ const hook =
+ call.operation === "hooks.getByToken"
+ ? await this.#world.hooks.getByToken(
+ ...(args as Parameters<World["hooks"]["getByToken"]>),
+ )
+ : await this.#world.hooks.get(...(args as Parameters<World["hooks"]["get"]>));
+ const run = await this.#world.runs.get(hook.runId, { resolveData: "none" });
+ const availability = await this.#generationAvailability(run.deploymentId);
+ if (availability.kind === "dormant" || availability.kind === "ineligible") {
+ throw new Error(
+ "Local Workflow run was not resumed. Start a new conversation, or restart eve dev with --resume to attempt recovery.",
+ );
+ }
+ return hook;
+ }
if (call.operation === "streams.writeMulti" && this.#world.streams.writeMulti === undefined) {
for (const chunk of args[2] as readonly (string | Uint8Array)[]) {
await this.#world.streams.write(args[0] as string, args[1] as string, chunk);
@@ -264,33 +328,23 @@ class LocalParentDevelopmentWorkflowWorld implements ParentDevelopmentWorkflowWo
return header !== null && timingSafeEqualStrings(header, this.#transportSecret);
}
- #generationExists(generationId: string): boolean {
- if (!isValidGenerationId(generationId)) {
- return false;
- }
- return existsSync(
- join(this.#appRoot, ".eve", "dev-runtime", "snapshots", generationId, "generation.json"),
- );
+ async #generationAvailability(generationId: string): Promise<DevelopmentGenerationAdmission> {
+ const availability = await readDevelopmentGenerationAvailability(this.#appRoot, generationId);
+ // Pruning still expires a run, even when startup refused its recovery.
+ if (availability.kind !== "ready") return availability;
+ return this.#unrecoveredGenerations.get(generationId) ?? availability;
}
}
-function isValidGenerationId(generationId: string): boolean {
- return (
- generationId.length > 0 &&
- generationId !== "." &&
- generationId !== ".." &&
- basename(generationId) === generationId
- );
-}
-
const DEVELOPMENT_WORLD_OPERATION_SET: ReadonlySet<string> = new Set(DEVELOPMENT_WORLD_OPERATIONS);
-function isDevelopmentWorldCall(value: unknown): value is DevelopmentWorldCall {
+function isDevelopmentWorldRequest(value: unknown): value is DevelopmentWorldRequest {
return (
isObject(value) &&
typeof value.operation === "string" &&
- DEVELOPMENT_WORLD_OPERATION_SET.has(value.operation) &&
- Array.isArray(value.arguments)
+ (value.operation === "eve.getGenerationAvailability"
+ ? typeof value.generationId === "string"
+ : DEVELOPMENT_WORLD_OPERATION_SET.has(value.operation) && Array.isArray(value.arguments))
);
}
@@ -300,6 +354,7 @@ function isObject(value: unknown): value is Record<string, unknown> {
async function reenqueueActiveDevelopmentRuns(input: {
readonly enqueue: World["queue"];
+ readonly canRecover: (generationId: string) => Promise<boolean>;
readonly prefix: string;
readonly world: World;
}): Promise<void> {
@@ -321,6 +376,7 @@ async function reenqueueActiveDevelopmentRuns(input: {
);
}
for (const run of page.data) {
+ if (!(await input.canRecover(run.deploymentId))) continue;
await input.enqueue(`${input.prefix}${run.workflowName}` as ValidQueueName, {
runId: run.runId,
});
diff --git a/packages/eve/src/internal/workflow/is-inactive-development-run-error.ts b/packages/eve/src/internal/workflow/is-inactive-workflow-run-error.ts
similarity index 68%
rename from packages/eve/src/internal/workflow/is-inactive-development-run-error.ts
rename to packages/eve/src/internal/workflow/is-inactive-workflow-run-error.ts
index 70781db2c..c38f36bd8 100644
--- a/packages/eve/src/internal/workflow/is-inactive-development-run-error.ts
+++ b/packages/eve/src/internal/workflow/is-inactive-workflow-run-error.ts
@@ -5,15 +5,15 @@ import {
} from "#compiled/@workflow/errors/index.js";
import { walkCauseChain } from "#shared/errors.js";
-export function isMissingDevelopmentRunError(error: unknown): boolean {
+export function isMissingWorkflowRunError(error: unknown): boolean {
return [...walkCauseChain(error)].some(
(cause) => WorkflowRunNotFoundError.is(cause) || RunExpiredError.is(cause),
);
}
-export function isInactiveDevelopmentRunError(error: unknown): boolean {
+export function isInactiveWorkflowRunError(error: unknown): boolean {
return (
- isMissingDevelopmentRunError(error) ||
+ isMissingWorkflowRunError(error) ||
[...walkCauseChain(error)].some((cause) => EntityConflictError.is(cause))
);
}
diff --git a/packages/eve/test/scenarios/dev-server-harness.ts b/packages/eve/test/scenarios/dev-server-harness.ts
index 0b49ac84f..2e390219c 100644
--- a/packages/eve/test/scenarios/dev-server-harness.ts
+++ b/packages/eve/test/scenarios/dev-server-harness.ts
@@ -33,6 +33,7 @@ export interface RunningEveDev {
export interface StartEveDevOptions {
readonly defaultExtensions?: boolean;
+ readonly resume?: boolean;
readonly env?: Readonly<Record<string, string | undefined>>;
/** Runtime executing the CLI. Defaults to the current Node executable. */
readonly runtime?: "bun" | "node";
@@ -223,6 +224,7 @@ function spawnEveDev(
const args = [eveBinPath, "dev", "--no-ui", "--host", "127.0.0.1", "--port", "0"];
if (options.defaultExtensions === false) args.push("--no-default-extensions");
+ if (options.resume) args.push("--resume");
return spawn(command, args, {
cwd: appRoot,
diff --git a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
index ee252920e..a11bbe4c1 100644
--- a/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
+++ b/packages/eve/test/scenarios/dev-server-workflow-generations.scenario.test.ts
@@ -142,9 +142,9 @@ describe("eve dev server workflow generations", () => {
DEV_SERVER_SCENARIO_TIMEOUT_MS,
);
- it(
- "makes a newly added tool available to the next turn in a continued session",
- async () => {
+ it.each(["tool", "workflow"] as const)(
+ "makes a newly added %s available to the next turn and allows session reset",
+ async (kind) => {
const app = await scenarioApp(WORKFLOW_GENERATION_DESCRIPTOR);
const server = await startEveDev(app.appRoot);
@@ -159,7 +159,20 @@ describe("eve dev server workflow generations", () => {
await writeFile(
join(app.appRoot, "agent", "tools", "get_added_marker.ts"),
- createGenerationMarkerToolSource("added-tool", false),
+ kind === "tool"
+ ? createGenerationMarkerToolSource("added-tool", false)
+ : [
+ 'import { defineWorkflowTool } from "eve/tools";',
+ 'import { z } from "zod";',
+ "export default defineWorkflowTool({",
+ ' description: "Return the added workflow marker.",',
+ " inputSchema: z.object({ city: z.string().optional() }),",
+ " async execute() {",
+ ' "use workflow";',
+ ' return { marker: "added-tool" };',
+ " },",
+ "});",
+ ].join("\n"),
);
await forceDevelopmentRebuild(server.url);
@@ -171,6 +184,13 @@ describe("eve dev server workflow generations", () => {
expect(secondResult.sessionId).toBe(firstSessionId);
expect(readCompletedMessages(secondResult.events)).toContain("added-tool");
+ const reset = await fetch(new URL(`/eve/v1/session/${firstSessionId}/reset`, server.url), {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ reason: "Start a new conversation after rebuilding" }),
+ signal: AbortSignal.timeout(10_000),
+ });
+ expect(reset.status, await reset.text()).toBe(200);
} finally {
await server.stop();
}
diff --git a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
index 149ddf476..c094b38c1 100644
--- a/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
+++ b/packages/eve/test/scenarios/dynamic-tool-cold-replay.scenario.test.ts
@@ -175,6 +175,7 @@ describe("dynamic tool cold replay", () => {
}
}, "The crashed development server did not release its state record.");
server = await startEveDev(app.appRoot, {
+ resume: true,
env: { ...pinnedEnv, EVE_SCHEMA_TEST_SUFFIX: ":changed" },
});
diff --git a/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts
index c281e2ac7..8b1896a61 100644
--- a/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts
+++ b/packages/eve/test/scenarios/dynamic-tool-source-edit.scenario.test.ts
@@ -133,7 +133,7 @@ describe("dynamic tool source edits across a restart", () => {
return error instanceof Error && "code" in error && error.code === "ENOENT";
}
}, "The crashed development server did not release its state record.");
- server = await startEveDev(app.appRoot, { env: pinnedEnv });
+ server = await startEveDev(app.appRoot, { env: pinnedEnv, resume: true });
const resumedSession = new Client({ host: server.url }).sessions.attach(
sessionState.sessionId,