Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): improve eve init recovery semantics (#2072)

OwenKephart10a09a1bf621
diff --git a/.changeset/fuzzy-ravens-init.md b/.changeset/fuzzy-ravens-init.md
new file mode 100644
index 000000000..434d52106
--- /dev/null
+++ b/.changeset/fuzzy-ravens-init.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Make failed `eve init` runs recoverable: new targets are cleaned up, preexisting empty targets are restored, and existing projects receive clear dependency-install recovery guidance.
diff --git a/packages/eve/src/cli/commands/init-git.scenario.test.ts b/packages/eve/src/cli/commands/init-git.scenario.test.ts
index 93a364d67..133881536 100644
--- a/packages/eve/src/cli/commands/init-git.scenario.test.ts
+++ b/packages/eve/src/cli/commands/init-git.scenario.test.ts
@@ -1,4 +1,4 @@
-import { writeFile } from "node:fs/promises";
+import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -11,31 +11,50 @@ import { tryInitializeGit } from "./init-git.js";
const createScratchDirectory = useTemporaryDirectories();
+async function withoutGitIdentity(projectPath: string, run: () => Promise<void>): Promise<void> {
+ const isolatedConfig = join(projectPath, "gitconfig");
+ await writeFile(isolatedConfig, "");
+
+ const previousEnv = { ...process.env };
+ process.env.GIT_CONFIG_COUNT = "1";
+ process.env.GIT_CONFIG_KEY_0 = "user.useConfigOnly";
+ process.env.GIT_CONFIG_VALUE_0 = "true";
+ process.env.GIT_CONFIG_GLOBAL = isolatedConfig;
+ process.env.GIT_CONFIG_NOSYSTEM = "1";
+ process.env.HOME = join(tmpdir(), "eve-init-no-git-identity");
+ delete process.env.EMAIL;
+ delete process.env.GIT_AUTHOR_EMAIL;
+ delete process.env.GIT_AUTHOR_NAME;
+ delete process.env.GIT_COMMITTER_EMAIL;
+ delete process.env.GIT_COMMITTER_NAME;
+
+ try {
+ await run();
+ } finally {
+ process.env = previousEnv;
+ }
+}
+
describe("tryInitializeGit", () => {
it("removes a partial repository when the initial commit fails", async () => {
const projectPath = await createScratchDirectory("eve-init-git-failure-");
- const isolatedConfig = join(projectPath, "gitconfig");
await writeFile(join(projectPath, "package.json"), "{}\n");
- await writeFile(isolatedConfig, "");
-
- const previousEnv = { ...process.env };
- process.env.GIT_CONFIG_COUNT = "1";
- process.env.GIT_CONFIG_KEY_0 = "user.useConfigOnly";
- process.env.GIT_CONFIG_VALUE_0 = "true";
- process.env.GIT_CONFIG_GLOBAL = isolatedConfig;
- process.env.GIT_CONFIG_NOSYSTEM = "1";
- process.env.HOME = join(tmpdir(), "eve-init-no-git-identity");
- delete process.env.EMAIL;
- delete process.env.GIT_AUTHOR_EMAIL;
- delete process.env.GIT_AUTHOR_NAME;
- delete process.env.GIT_COMMITTER_EMAIL;
- delete process.env.GIT_COMMITTER_NAME;
-
- try {
+
+ await withoutGitIdentity(projectPath, async () => {
await expect(tryInitializeGit(projectPath)).resolves.toMatchObject({ kind: "failed" });
await expect(pathExists(join(projectPath, ".git"))).resolves.toBe(false);
- } finally {
- process.env = previousEnv;
- }
+ });
+ });
+
+ it("skips initialization when Git metadata already exists", async () => {
+ const projectPath = await createScratchDirectory("eve-init-existing-git-");
+ const gitPath = join(projectPath, ".git");
+ await mkdir(gitPath);
+ await writeFile(join(gitPath, "keep"), "preexisting\n");
+ await writeFile(join(projectPath, "package.json"), "{}\n");
+
+ await expect(tryInitializeGit(projectPath)).resolves.toEqual({ kind: "skipped" });
+ await expect(readdir(gitPath)).resolves.toEqual(["keep"]);
+ await expect(readFile(join(gitPath, "keep"), "utf8")).resolves.toBe("preexisting\n");
});
});
diff --git a/packages/eve/src/cli/commands/init-git.ts b/packages/eve/src/cli/commands/init-git.ts
index 61371461f..86445d1ff 100644
--- a/packages/eve/src/cli/commands/init-git.ts
+++ b/packages/eve/src/cli/commands/init-git.ts
@@ -1,5 +1,5 @@
import { execFile, type ExecFileOptions } from "node:child_process";
-import { rm } from "node:fs/promises";
+import { rm, stat } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -52,7 +52,19 @@ async function runGit(cwd: string, args: readonly string[]): Promise<void> {
* failure (without failing `eve init`) is the caller's job.
*/
export async function tryInitializeGit(projectPath: string): Promise<GitInitResult> {
- if (!(await isGitAvailable()) || (await isInsideExistingRepository(projectPath))) {
+ const gitPath = join(projectPath, ".git");
+ const gitMetadataExists = await stat(gitPath).then(
+ () => true,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return false;
+ throw error;
+ },
+ );
+ if (
+ gitMetadataExists ||
+ !(await isGitAvailable()) ||
+ (await isInsideExistingRepository(projectPath))
+ ) {
return { kind: "skipped" };
}
@@ -70,7 +82,7 @@ export async function tryInitializeGit(projectPath: string): Promise<GitInitResu
return { kind: "initialized" };
} catch (error) {
if (initialized) {
- await rm(join(projectPath, ".git"), { recursive: true, force: true }).catch(() => {});
+ await rm(gitPath, { recursive: true, force: true }).catch(() => {});
}
const reason = error instanceof Error ? error.message : String(error);
diff --git a/packages/eve/src/cli/commands/init-recovery.ts b/packages/eve/src/cli/commands/init-recovery.ts
new file mode 100644
index 000000000..b5075c032
--- /dev/null
+++ b/packages/eve/src/cli/commands/init-recovery.ts
@@ -0,0 +1,32 @@
+import { readdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+
+export type InitFailurePolicy = "clear" | "preserve" | "remove";
+
+export async function cleanupFreshInitTarget(
+ projectPath: string,
+ policy: Exclude<InitFailurePolicy, "preserve">,
+ preservedEntries: readonly string[] = [],
+): Promise<boolean> {
+ try {
+ if (policy === "remove") {
+ await rm(projectPath, { recursive: true, force: true });
+ } else {
+ const preserved = new Set(preservedEntries);
+ for (const entry of await readdir(projectPath)) {
+ if (!preserved.has(entry)) {
+ await rm(join(projectPath, entry), { recursive: true, force: true });
+ }
+ }
+ }
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function workspaceFailureNote(workspaceMember: boolean): string {
+ return workspaceMember
+ ? "\n\nShared workspace files may have changed. Review your workspace changes before committing."
+ : "";
+}
diff --git a/packages/eve/src/cli/commands/init-target.ts b/packages/eve/src/cli/commands/init-target.ts
new file mode 100644
index 000000000..0f2694e86
--- /dev/null
+++ b/packages/eve/src/cli/commands/init-target.ts
@@ -0,0 +1,117 @@
+import { readdir, stat } from "node:fs/promises";
+import { join, resolve } from "node:path";
+
+import { pathExists } from "#setup/path-exists.js";
+import { parseProjectName } from "#setup/project-name.js";
+import { blockingCreateInPlaceEntries } from "#setup/scaffold/create-in-place.js";
+
+import type { InitNonEmptyDirectoryTarget } from "./init-confirm.js";
+import type { InitFailurePolicy } from "./init-recovery.js";
+
+const CURRENT_DIRECTORY_PROJECT_NAME = ".";
+
+export type InitTarget =
+ | {
+ kind: "existing";
+ projectPath: string;
+ }
+ | {
+ failurePolicy: InitFailurePolicy;
+ kind: "fresh";
+ overwriteExisting: boolean;
+ preservedEntries: readonly string[];
+ projectName: string;
+ projectPath: string;
+ };
+
+interface ResolveInitTargetInput {
+ agentLaunched: boolean;
+ confirmInitInNonEmptyDirectory(entries: readonly string[]): Promise<InitNonEmptyDirectoryTarget>;
+ parentDirectory: string;
+ target: string | undefined;
+}
+
+function isCurrentDirectoryTarget(target: string): boolean {
+ return /^\.(?:[/\\]+\.?)*$/u.test(target.trim());
+}
+
+async function resolveNamedTarget(parentPath: string, rawTarget: string): Promise<InitTarget> {
+ const projectName = parseProjectName(rawTarget);
+ const projectPath = join(parentPath, projectName);
+ const stats = await stat(projectPath).then(
+ (result) => result,
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return undefined;
+ throw error;
+ },
+ );
+ if (stats === undefined) {
+ return {
+ failurePolicy: "remove",
+ kind: "fresh",
+ overwriteExisting: false,
+ preservedEntries: [],
+ projectName,
+ projectPath,
+ };
+ }
+ if (!stats.isDirectory()) {
+ throw new Error(`Cannot create project because "${projectPath}" already exists.`);
+ }
+
+ const entries = await readdir(projectPath);
+ if (entries.length > 0) {
+ return { kind: "existing", projectPath };
+ }
+ return {
+ failurePolicy: "clear",
+ kind: "fresh",
+ overwriteExisting: false,
+ preservedEntries: [],
+ projectName,
+ projectPath,
+ };
+}
+
+export async function resolveInitTarget(input: ResolveInitTargetInput): Promise<InitTarget> {
+ const parentPath = resolve(input.parentDirectory);
+ const rawTarget = input.target ?? CURRENT_DIRECTORY_PROJECT_NAME;
+ if (!isCurrentDirectoryTarget(rawTarget)) {
+ return resolveNamedTarget(parentPath, rawTarget);
+ }
+
+ if (await pathExists(join(parentPath, "package.json"))) {
+ return { kind: "existing", projectPath: parentPath };
+ }
+
+ const entries = await readdir(parentPath);
+ const blocking = blockingCreateInPlaceEntries(entries);
+ if (blocking.length === 0) {
+ return {
+ failurePolicy: "clear",
+ kind: "fresh",
+ overwriteExisting: false,
+ preservedEntries: entries,
+ projectName: CURRENT_DIRECTORY_PROJECT_NAME,
+ projectPath: parentPath,
+ };
+ }
+ if (input.agentLaunched) {
+ throw new Error(
+ "Coding-agent launches cannot choose where to initialize a non-empty current directory. Pass a new directory name, for example: eve init my-agent.",
+ );
+ }
+
+ const selection = await input.confirmInitInNonEmptyDirectory(blocking);
+ if (selection.kind === "subdirectory") {
+ return resolveNamedTarget(parentPath, selection.name);
+ }
+ return {
+ failurePolicy: "preserve",
+ kind: "fresh",
+ overwriteExisting: true,
+ preservedEntries: entries,
+ projectName: CURRENT_DIRECTORY_PROJECT_NAME,
+ projectPath: parentPath,
+ };
+}
diff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.ts
index ed394518a..4d668750f 100644
--- a/packages/eve/src/cli/commands/init.integration.test.ts
+++ b/packages/eve/src/cli/commands/init.integration.test.ts
@@ -1,4 +1,4 @@
-import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -439,6 +439,48 @@ describe("runInitCommand", () => {
expect(deps.tryInitializeGit).toHaveBeenCalledWith(subdirectory);
});
+ it("refuses a selected existing nonempty subdirectory without changing it", async () => {
+ const projectPath = await mkdtemp(join(tmpdir(), "eve-init-selected-existing-"));
+ await writeFile(join(projectPath, "notes.md"), "parent\n", "utf8");
+ const subdirectory = join(projectPath, "research-agent");
+ await mkdir(subdirectory);
+ await writeFile(join(subdirectory, "keep.txt"), "keep me\n", "utf8");
+ const output = logger();
+ const deps = dependencies();
+ deps.confirmInitInNonEmptyDirectory.mockResolvedValue({
+ kind: "subdirectory",
+ name: "research-agent",
+ });
+
+ await expect(runInitCommand(output, projectPath, undefined, {}, deps)).rejects.toThrow(
+ "no package.json",
+ );
+
+ await expect(readFile(join(subdirectory, "keep.txt"), "utf8")).resolves.toBe("keep me\n");
+ await expect(pathExists(join(subdirectory, "agent"))).resolves.toBe(false);
+ expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
+ });
+
+ it("restores a selected existing empty subdirectory after install failure", async () => {
+ const projectPath = await mkdtemp(join(tmpdir(), "eve-init-selected-fresh-"));
+ await writeFile(join(projectPath, "notes.md"), "parent\n", "utf8");
+ const subdirectory = join(projectPath, "research-agent");
+ await mkdir(subdirectory);
+ const output = logger();
+ const deps = dependencies();
+ deps.confirmInitInNonEmptyDirectory.mockResolvedValue({
+ kind: "subdirectory",
+ name: "research-agent",
+ });
+ deps.runPackageManagerInstall.mockResolvedValue(false);
+
+ await expect(runInitCommand(output, projectPath, undefined, {}, deps)).rejects.toThrow(
+ "restored",
+ );
+
+ await expect(readdir(subdirectory)).resolves.toEqual([]);
+ });
+
it("leaves a non-empty current directory unchanged when location selection is cancelled", async () => {
const projectPath = await mkdtemp(join(tmpdir(), "eve-init-nonempty-cancel-"));
await writeFile(join(projectPath, "notes.md"), "keep me\n", "utf8");
@@ -981,10 +1023,11 @@ describe("runInitCommand", () => {
);
});
- it("refuses a target directory without package.json before writing anything", async () => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-no-pkg-"));
+ it("refuses a preexisting Git-only named directory without changing it", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-git-only-"));
const projectRoot = join(parentDirectory, "host-app");
- await mkdir(projectRoot, { recursive: true });
+ await mkdir(join(projectRoot, ".git"), { recursive: true });
+ await writeFile(join(projectRoot, ".git/HEAD"), "ref: refs/heads/main\n", "utf8");
const output = logger();
const deps = dependencies();
@@ -992,9 +1035,56 @@ describe("runInitCommand", () => {
"no package.json",
);
+ await expect(readdir(projectRoot)).resolves.toEqual([".git"]);
+ await expect(readFile(join(projectRoot, ".git/HEAD"), "utf8")).resolves.toBe(
+ "ref: refs/heads/main\n",
+ );
+ await expect(pathExists(join(projectRoot, "agent"))).resolves.toBe(false);
+ expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
+ });
+
+ it("uses a preexisting empty named directory for a fresh project", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-empty-"));
+ const projectRoot = join(parentDirectory, "host-app");
+ await mkdir(projectRoot, { recursive: true });
+ const output = logger();
+ const deps = dependencies();
+
+ await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+
+ await expect(pathExists(join(projectRoot, "agent/agent.ts"))).resolves.toBe(true);
+ expect(deps.tryInitializeGit).toHaveBeenCalledWith(projectRoot);
+ });
+
+ it("restores a preexisting empty named directory when installation fails", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-empty-fail-"));
+ const projectRoot = join(parentDirectory, "host-app");
+ await mkdir(projectRoot, { recursive: true });
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockResolvedValue(false);
+
+ await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
+ "restored",
+ );
+
+ await expect(readdir(projectRoot)).resolves.toEqual([]);
+ });
+
+ it("refuses an invalid host package.json before writing agent files", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-invalid-pkg-"));
+ const projectRoot = join(parentDirectory, "host-app");
+ await mkdir(projectRoot, { recursive: true });
+ await writeFile(join(projectRoot, "package.json"), '{ "name": }\n', "utf8");
+ const output = logger();
+ const deps = dependencies();
+
+ await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
+ "not valid JSON",
+ );
+
await expect(pathExists(join(projectRoot, "agent"))).resolves.toBe(false);
expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
- expect(deps.spawnPackageManager).not.toHaveBeenCalled();
});
it.each([
@@ -1211,12 +1301,44 @@ describe("runInitCommand", () => {
"Failed to install dependencies",
);
- await expect(pathExists(join(parentDirectory, "my-agent"))).resolves.toBe(true);
+ await expect(pathExists(join(parentDirectory, "my-agent"))).resolves.toBe(false);
expect(output.errors).toEqual(["Packages: +12", "ERR_PNPM_FETCH_404 not found"]);
expect(deps.tryInitializeGit).not.toHaveBeenCalled();
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
});
+ it("preserves a chosen nonempty in-place target after install failure", async () => {
+ const projectRoot = await mkdtemp(join(tmpdir(), "eve-init-nonempty-install-fail-"));
+ await writeFile(join(projectRoot, "notes.md"), "keep me\n", "utf8");
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockResolvedValue(false);
+
+ await expect(runInitCommand(output, projectRoot, ".", {}, deps)).rejects.toThrow(
+ `install dependencies with pnpm in "${projectRoot}"`,
+ );
+
+ await expect(readFile(join(projectRoot, "notes.md"), "utf8")).resolves.toBe("keep me\n");
+ await expect(pathExists(join(projectRoot, "agent/agent.ts"))).resolves.toBe(true);
+ });
+
+ it("preserves an existing host after install failure and prints the retry command", async () => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-host-install-fail-"));
+ const projectRoot = await createHostProject(parentDirectory);
+ const output = logger();
+ const deps = dependencies();
+ deps.runPackageManagerInstall.mockResolvedValue(false);
+
+ await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
+ `install dependencies with pnpm in "${projectRoot}"`,
+ );
+
+ await expect(pathExists(join(projectRoot, "agent/agent.ts"))).resolves.toBe(true);
+ expect(JSON.parse(await readFile(join(projectRoot, "package.json"), "utf8"))).toMatchObject({
+ dependencies: { eve: "^0.6.0" },
+ });
+ });
+
it("replays only the actionable npm error, dropping silly/verbose/http/timing noise", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-npm-noise-"));
const output = logger();
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index 28e8bb8a5..d6e9c8935 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -1,4 +1,4 @@
-import { mkdtemp, readdir, rename, rm, stat } from "node:fs/promises";
+import { mkdtemp, readdir, rename, rm } from "node:fs/promises";
import { basename, join, resolve } from "node:path";
import { performance } from "node:perf_hooks";
@@ -18,7 +18,6 @@ import {
type PackageManagerKind,
} from "#setup/package-manager.js";
import { pathExists } from "#setup/path-exists.js";
-import { parseProjectName } from "#setup/project-name.js";
import {
eveDevArguments,
runPackageManagerInstall,
@@ -26,11 +25,13 @@ import {
} from "#setup/primitives/index.js";
import type { ProcessOutputLine } from "#setup/primitives/process-output.js";
import { addAgentToProject } from "#setup/scaffold/create/add-to-project.js";
-import { blockingCreateInPlaceEntries } from "#setup/scaffold/create-in-place.js";
import { ensureChannel, scaffoldBaseProject } from "#setup/scaffold/index.js";
import { WizardCancelledError } from "#setup/step.js";
import { validateModelSlug } from "#setup/flows/model-source-change.js";
-import type { WorkspaceRootMutation } from "#setup/scaffold/workspace-root.js";
+import {
+ isPackageManagerWorkspaceMember,
+ type WorkspaceRootMutation,
+} from "#setup/scaffold/workspace-root.js";
import {
DEFAULT_EVE_PACKAGE_CONTRACT,
type EvePackageContract,
@@ -38,8 +39,14 @@ import {
import { initAgentDevHandoff, initAgentReplPrompt } from "./agent-instructions.js";
import { confirmInitInNonEmptyDirectory } from "./init-confirm.js";
+import {
+ cleanupFreshInitTarget,
+ workspaceFailureNote,
+ type InitFailurePolicy,
+} from "./init-recovery.js";
import { tryInitializeGit, type GitInitResult } from "./init-git.js";
import { selectInitHandoff, spawnCodingAgentRepl, type InitHandoff } from "./init-repl.js";
+import { resolveInitTarget } from "./init-target.js";
export interface InitCliLogger {
error(message: string): void;
@@ -94,20 +101,6 @@ export const EVE_INIT_PACKAGE_SPEC_ENV = "EVE_INIT_PACKAGE_SPEC";
const initLog = createLogger("init");
-/** Resolves `target` to an existing directory, or undefined for name mode. */
-async function resolveTargetDirectory(
- parentDirectory: string,
- target: string,
-): Promise<string | undefined> {
- const targetPath = resolve(parentDirectory, target);
- const stats = await stat(targetPath).catch(() => undefined);
- return stats?.isDirectory() ? targetPath : undefined;
-}
-
-function isCurrentDirectoryTarget(target: string): boolean {
- return /^\.(?:[/\\]+\.?)*$/u.test(target.trim());
-}
-
async function moveDirectoryContents(sourceRoot: string, targetRoot: string): Promise<void> {
for (const entry of await readdir(sourceRoot)) {
await rename(join(sourceRoot, entry), join(targetRoot, entry));
@@ -201,7 +194,9 @@ async function scaffoldProject(
const parentPath = resolve(parentDirectory);
const createInPlace = projectName === CURRENT_DIRECTORY_PROJECT_NAME;
const projectPath = createInPlace ? parentPath : join(parentPath, projectName);
- if (!createInPlace && (await pathExists(projectPath))) {
+ const populateExistingEmptyDirectory =
+ !createInPlace && (await pathExists(projectPath)) && (await readdir(projectPath)).length === 0;
+ if (!createInPlace && (await pathExists(projectPath)) && !populateExistingEmptyDirectory) {
throw new Error(`Cannot create project because "${projectPath}" already exists.`);
}
@@ -250,7 +245,7 @@ async function scaffoldProject(
}
if (stagingDirectory !== undefined) {
- if (createInPlace) {
+ if (createInPlace || populateExistingEmptyDirectory) {
await moveDirectoryContents(stagedProjectPath, projectPath);
} else {
await rename(stagedProjectPath, projectPath);
@@ -269,15 +264,20 @@ async function scaffoldProject(
type PreparedInitProject =
| {
+ failurePolicy: "preserve";
kind: "added";
nodeEngineOverride?: NodeEngineOverride;
packageManager: PackageManagerKind;
projectPath: string;
}
| {
+ failurePolicy: InitFailurePolicy;
kind: "created";
packageManager: PackageManagerKind;
+ preservedTargetEntries: readonly string[];
projectPath: string;
+ retryCommand: string;
+ workspaceMember: boolean;
workspaceRootMutations: WorkspaceRootMutation[];
};
@@ -331,68 +331,74 @@ async function runInitSteps(input: {
const { dependencies, logger, options, parentDirectory, target } = input;
const debug = isLogLevelEnabled("debug");
const agentLaunched = await dependencies.isCodingAgentLaunch();
- let rawTarget = target ?? CURRENT_DIRECTORY_PROJECT_NAME;
- let currentDirectoryTarget = isCurrentDirectoryTarget(rawTarget);
- const parentPath = resolve(parentDirectory);
- const existingDirectory = currentDirectoryTarget
- ? (await pathExists(join(parentPath, "package.json")))
- ? parentPath
- : undefined
- : await resolveTargetDirectory(parentDirectory, rawTarget);
+ const initTarget = await resolveInitTarget({
+ agentLaunched,
+ confirmInitInNonEmptyDirectory: dependencies.confirmInitInNonEmptyDirectory,
+ parentDirectory,
+ target,
+ });
const evePackage = resolveInitEvePackageOverride();
- let overwriteExisting = false;
- if (currentDirectoryTarget && existingDirectory === undefined) {
- const blocking = blockingCreateInPlaceEntries(await readdir(parentPath));
- if (blocking.length > 0) {
- if (agentLaunched) {
- throw new Error(
- "Coding-agent launches cannot choose where to initialize a non-empty current directory. Pass a new directory name, for example: eve init my-agent.",
- );
- }
- const selection = await dependencies.confirmInitInNonEmptyDirectory(blocking);
- if (selection.kind === "current-directory") {
- overwriteExisting = true;
- } else {
- rawTarget = selection.name;
- currentDirectoryTarget = false;
- }
- }
- }
const progress = startCliLiveRow(logger);
progress.update("Preparing project");
try {
- const scaffoldPhase = existingDirectory === undefined ? "creating agent" : "adding agent";
- progress.update(existingDirectory === undefined ? "Creating agent" : "Adding agent");
+ const scaffoldPhase = initTarget.kind === "fresh" ? "creating agent" : "adding agent";
+ progress.update(initTarget.kind === "fresh" ? "Creating agent" : "Adding agent");
initLog.debug(scaffoldPhase);
const agentStartedAt = dependencies.now();
let project: PreparedInitProject;
- if (existingDirectory === undefined) {
- const projectName = currentDirectoryTarget
- ? CURRENT_DIRECTORY_PROJECT_NAME
- : parseProjectName(rawTarget);
- const parentPath = resolve(parentDirectory);
- const plannedProjectPath =
- projectName === CURRENT_DIRECTORY_PROJECT_NAME ? parentPath : join(parentPath, projectName);
- const packageManager = await resolveScaffoldPackageManager(plannedProjectPath, dependencies);
- const scaffold = await scaffoldProject(
- parentDirectory,
- projectName,
- packageManager,
- options,
+ if (initTarget.kind === "fresh") {
+ const packageManager = await resolveScaffoldPackageManager(
+ initTarget.projectPath,
dependencies,
- evePackage,
- overwriteExisting,
);
+ const workspaceMember = isPackageManagerWorkspaceMember(
+ packageManager,
+ initTarget.projectPath,
+ );
+ let scaffold: Awaited<ReturnType<typeof scaffoldProject>>;
+ try {
+ scaffold = await scaffoldProject(
+ parentDirectory,
+ initTarget.projectName,
+ packageManager,
+ options,
+ dependencies,
+ evePackage,
+ initTarget.overwriteExisting,
+ );
+ } catch (error) {
+ if (initTarget.failurePolicy === "clear") {
+ const cleaned = await cleanupFreshInitTarget(
+ initTarget.projectPath,
+ initTarget.failurePolicy,
+ initTarget.preservedEntries,
+ );
+ const detail = error instanceof Error ? error.message : String(error);
+ const cleanup = cleaned
+ ? `eve restored "${initTarget.projectPath}" to its original state.`
+ : `eve could not completely clean "${initTarget.projectPath}".`;
+ throw new Error(`${detail}\n\n${cleanup}${workspaceFailureNote(workspaceMember)}`);
+ }
+ if (initTarget.failurePolicy === "remove" && workspaceMember) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new Error(`${detail}${workspaceFailureNote(true)}`);
+ }
+ throw error;
+ }
project = {
+ failurePolicy: initTarget.failurePolicy,
kind: "created",
packageManager,
+ preservedTargetEntries: initTarget.preservedEntries,
projectPath: scaffold.projectPath,
+ retryCommand: `eve init ${initTarget.projectName}`,
+ workspaceMember,
workspaceRootMutations: scaffold.workspaceRootMutations,
};
} else {
const addition = await addToExistingProject(
- existingDirectory,
+ initTarget.projectPath,
options,
dependencies,
evePackage,
@@ -400,15 +406,17 @@ async function runInitSteps(input: {
project =
addition.nodeEngineOverride === undefined
? {
+ failurePolicy: "preserve",
kind: "added",
packageManager: addition.packageManager,
- projectPath: existingDirectory,
+ projectPath: initTarget.projectPath,
}
: {
+ failurePolicy: "preserve",
kind: "added",
nodeEngineOverride: addition.nodeEngineOverride,
packageManager: addition.packageManager,
- projectPath: existingDirectory,
+ projectPath: initTarget.projectPath,
};
}
const agentElapsedMs = dependencies.now() - agentStartedAt;
@@ -450,7 +458,35 @@ async function runInitSteps(input: {
const failureOutput =
installFailureOutput.length > 0 ? installFailureOutput : recentInstallOutput;
for (const line of failureOutput) logger.error(line);
- throw new Error(`Failed to install dependencies in "${project.projectPath}".`);
+
+ if (project.failurePolicy !== "preserve") {
+ const cleaned = await cleanupFreshInitTarget(
+ project.projectPath,
+ project.failurePolicy,
+ project.preservedTargetEntries,
+ );
+ if (cleaned) {
+ const cleanup =
+ project.failurePolicy === "remove"
+ ? `eve removed the incomplete project at "${project.projectPath}".`
+ : `eve restored "${project.projectPath}" to its original state.`;
+ const workspaceChanged =
+ project.workspaceMember || project.workspaceRootMutations.length > 0;
+ throw new Error(
+ `Failed to install dependencies.\n\n${cleanup}\n\nResolve the package-manager error above, then retry:\n ${project.retryCommand}${workspaceFailureNote(workspaceChanged)}`,
+ );
+ }
+
+ const workspaceChanged =
+ project.workspaceMember || project.workspaceRootMutations.length > 0;
+ throw new Error(
+ `Failed to install dependencies, and eve could not completely clean "${project.projectPath}".\n\nResolve the package-manager error above, then install dependencies with ${project.packageManager} in that directory. Or clean the target manually before rerunning eve init.${workspaceFailureNote(workspaceChanged)}`,
+ );
+ }
+
+ throw new Error(
+ `The eve agent was added, but dependency installation failed.\n\nResolve the package-manager error above, then install dependencies with ${project.packageManager} in "${project.projectPath}".\n\nDo not rerun eve init; the agent is already configured.`,
+ );
}
initLog.debug("dependencies installed", { ms: installElapsedMs });
diff --git a/packages/eve/src/setup/scaffold/create/add-to-project.ts b/packages/eve/src/setup/scaffold/create/add-to-project.ts
index fceae7127..e9844d735 100644
--- a/packages/eve/src/setup/scaffold/create/add-to-project.ts
+++ b/packages/eve/src/setup/scaffold/create/add-to-project.ts
@@ -87,6 +87,16 @@ export async function addAgentToProject(
);
}
+ let packageJson: unknown;
+ try {
+ packageJson = JSON.parse(await readFile(packageJsonPath, "utf8"));
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ throw new Error(
+ `Cannot add an eve agent because "${packageJsonPath}" is not valid JSON. No files were changed. Fix the file, then retry eve init. ${detail}`,
+ );
+ }
+
const files = agentTemplateFiles(options.model, options.reasoning);
const conflicts: string[] = [];
for (const relativePath of Object.keys(files)) {
@@ -128,7 +138,6 @@ export async function addAgentToProject(
filesWritten.push(filePath);
}
- const packageJson: unknown = JSON.parse(await readFile(packageJsonPath, "utf8"));
const wanted: Record<string, string> = {
"@vercel/connect": connectVersion,
ai: aiVersion,