Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): safely initialize agent directories (#2135)

OwenKephart7a8f43b609a8
diff --git a/.changeset/safe-init-targets.md b/.changeset/safe-init-targets.md
new file mode 100644
index 000000000..135638014
--- /dev/null
+++ b/.changeset/safe-init-targets.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Treat `eve init` targets as filesystem paths and classify non-empty targets before writing. When the generated initial Git commit fails, retain the repository and staged files and print the command to retry it.
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 133881536..82ec9ba80 100644
--- a/packages/eve/src/cli/commands/init-git.scenario.test.ts
+++ b/packages/eve/src/cli/commands/init-git.scenario.test.ts
@@ -36,13 +36,17 @@ async function withoutGitIdentity(projectPath: string, run: () => Promise<void>)
}
describe("tryInitializeGit", () => {
- it("removes a partial repository when the initial commit fails", async () => {
+ it("retains an initialized repository when the initial commit fails", async () => {
const projectPath = await createScratchDirectory("eve-init-git-failure-");
await writeFile(join(projectPath, "package.json"), "{}\n");
await withoutGitIdentity(projectPath, async () => {
- await expect(tryInitializeGit(projectPath)).resolves.toMatchObject({ kind: "failed" });
- await expect(pathExists(join(projectPath, ".git"))).resolves.toBe(false);
+ await expect(tryInitializeGit(projectPath)).resolves.toMatchObject({
+ kind: "failed",
+ repositoryInitialized: true,
+ stage: "commit",
+ });
+ await expect(pathExists(join(projectPath, ".git"))).resolves.toBe(true);
});
});
@@ -53,7 +57,10 @@ describe("tryInitializeGit", () => {
await writeFile(join(gitPath, "keep"), "preexisting\n");
await writeFile(join(projectPath, "package.json"), "{}\n");
- await expect(tryInitializeGit(projectPath)).resolves.toEqual({ kind: "skipped" });
+ await expect(tryInitializeGit(projectPath)).resolves.toEqual({
+ kind: "skipped",
+ reason: "existing-metadata",
+ });
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 86445d1ff..08b5fa68c 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, stat } from "node:fs/promises";
+import { stat } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -8,8 +8,13 @@ const runFile = promisify(execFile);
export type GitInitResult =
| { kind: "initialized" }
- | { kind: "skipped" }
- | { kind: "failed"; reason: string };
+ | { kind: "skipped"; reason: "existing-metadata" | "git-unavailable" | "parent-repository" }
+ | {
+ kind: "failed";
+ repositoryInitialized: boolean;
+ reason: string;
+ stage: "initialize" | "default-branch" | "stage" | "commit";
+ };
async function commandSucceeds(
command: string,
@@ -45,11 +50,29 @@ async function runGit(cwd: string, args: readonly string[]): Promise<void> {
await runFile("git", [...args], { cwd, timeout: GIT_TIMEOUT_MS, windowsHide: true });
}
+async function runGitStage(
+ cwd: string,
+ stage: "initialize" | "default-branch" | "stage" | "commit",
+ args: readonly string[],
+ repositoryInitialized: boolean,
+): Promise<GitInitResult | undefined> {
+ try {
+ await runGit(cwd, args);
+ return undefined;
+ } catch (error) {
+ return {
+ kind: "failed",
+ repositoryInitialized,
+ reason: error instanceof Error ? error.message : String(error),
+ stage,
+ };
+ }
+}
+
/**
* Initializes a Git repository and records the generated files in an initial
- * commit. Missing Git and parent repositories are skips. A failed partial
- * initialization is removed and returned as a `failed` result; presenting the
- * failure (without failing `eve init`) is the caller's job.
+ * commit. Missing Git and parent repositories are skips. Repository metadata
+ * is retained when a later step fails so eve never destroys useful Git state.
*/
export async function tryInitializeGit(projectPath: string): Promise<GitInitResult> {
const gitPath = join(projectPath, ".git");
@@ -60,32 +83,33 @@ export async function tryInitializeGit(projectPath: string): Promise<GitInitResu
throw error;
},
);
- if (
- gitMetadataExists ||
- !(await isGitAvailable()) ||
- (await isInsideExistingRepository(projectPath))
- ) {
- return { kind: "skipped" };
+ if (gitMetadataExists) return { kind: "skipped", reason: "existing-metadata" };
+ if (!(await isGitAvailable())) return { kind: "skipped", reason: "git-unavailable" };
+ if (await isInsideExistingRepository(projectPath)) {
+ return { kind: "skipped", reason: "parent-repository" };
}
- let initialized = false;
- try {
- await runGit(projectPath, ["init"]);
- initialized = true;
+ const initFailure = await runGitStage(projectPath, "initialize", ["init"], false);
+ if (initFailure !== undefined) return initFailure;
- if (!(await hasConfiguredDefaultBranch(projectPath))) {
- await runGit(projectPath, ["checkout", "-b", "main"]);
- }
+ if (!(await hasConfiguredDefaultBranch(projectPath))) {
+ const branchFailure = await runGitStage(
+ projectPath,
+ "default-branch",
+ ["checkout", "-b", "main"],
+ true,
+ );
+ if (branchFailure !== undefined) return branchFailure;
+ }
- await runGit(projectPath, ["add", "-A"]);
- await runGit(projectPath, ["commit", "-m", "Initial commit from eve"]);
- return { kind: "initialized" };
- } catch (error) {
- if (initialized) {
- await rm(gitPath, { recursive: true, force: true }).catch(() => {});
- }
+ const stageFailure = await runGitStage(projectPath, "stage", ["add", "-A"], true);
+ if (stageFailure !== undefined) return stageFailure;
- const reason = error instanceof Error ? error.message : String(error);
- return { kind: "failed", reason };
- }
+ const commitFailure = await runGitStage(
+ projectPath,
+ "commit",
+ ["commit", "-m", "Initial commit from eve"],
+ true,
+ );
+ return commitFailure ?? { kind: "initialized" };
}
diff --git a/packages/eve/src/cli/commands/init-target.integration.test.ts b/packages/eve/src/cli/commands/init-target.integration.test.ts
new file mode 100644
index 000000000..cd7774126
--- /dev/null
+++ b/packages/eve/src/cli/commands/init-target.integration.test.ts
@@ -0,0 +1,76 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+
+import { resolveInitTarget } from "./init-target.js";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+function resolveTarget(parentDirectory: string, target?: string) {
+ return resolveInitTarget({ parentDirectory, target });
+}
+
+describe("resolveInitTarget", () => {
+ it("treats nested and absolute targets as filesystem paths", async () => {
+ const parentDirectory = await createScratchDirectory("eve-init-target-path-");
+ const nested = join(parentDirectory, "apps", "weather");
+
+ await expect(resolveTarget(parentDirectory, "apps/weather")).resolves.toMatchObject({
+ kind: "fresh",
+ projectName: "weather",
+ projectPath: nested,
+ });
+ await expect(resolveTarget(parentDirectory, nested)).resolves.toMatchObject({
+ kind: "fresh",
+ projectName: "weather",
+ projectPath: nested,
+ });
+ });
+
+ it("preserves the small environment-only allowlist", async () => {
+ const parentDirectory = await createScratchDirectory("eve-init-target-environment-");
+ const projectPath = join(parentDirectory, "weather");
+ await mkdir(projectPath);
+ await mkdir(join(projectPath, ".git"));
+ await mkdir(join(projectPath, ".vscode"));
+ await writeFile(join(projectPath, ".gitignore"), "node_modules\n");
+
+ await expect(resolveTarget(projectPath, ".")).resolves.toMatchObject({
+ kind: "fresh",
+ overwriteExisting: false,
+ preservedEntries: [".git", ".gitignore", ".vscode"],
+ projectPath,
+ });
+ });
+
+ it("requires explicit current-directory syntax for an existing package", async () => {
+ const projectPath = await createScratchDirectory("eve-init-target-package-");
+ await writeFile(join(projectPath, "package.json"), "{}\n");
+
+ await expect(resolveTarget(projectPath)).rejects.toThrow("explicit `eve init .`");
+ await expect(resolveTarget(projectPath, ".")).resolves.toEqual({
+ kind: "existing",
+ projectPath,
+ });
+ });
+
+ it("stops when the target is already an eve project", async () => {
+ const projectPath = await createScratchDirectory("eve-init-target-eve-");
+ await mkdir(join(projectPath, "agent"));
+ await writeFile(join(projectPath, "agent", "instructions.md"), "You are helpful.\n");
+ await writeFile(join(projectPath, "package.json"), "{}\n");
+
+ await expect(resolveTarget(projectPath, ".")).rejects.toThrow("An eve project already exists");
+ });
+
+ it("lists arbitrary content instead of guessing how to integrate it", async () => {
+ const projectPath = await createScratchDirectory("eve-init-target-content-");
+ await writeFile(join(projectPath, "README.md"), "# Existing\n");
+ await writeFile(join(projectPath, ".unknown"), "value\n");
+
+ await expect(resolveTarget(projectPath, ".")).rejects.toThrow(" - .unknown\n - README.md");
+ });
+});
diff --git a/packages/eve/src/cli/commands/init-target.ts b/packages/eve/src/cli/commands/init-target.ts
index 0f2694e86..816ad08f5 100644
--- a/packages/eve/src/cli/commands/init-target.ts
+++ b/packages/eve/src/cli/commands/init-target.ts
@@ -1,14 +1,20 @@
import { readdir, stat } from "node:fs/promises";
-import { join, resolve } from "node:path";
+import { basename, resolve } from "node:path";
-import { pathExists } from "#setup/path-exists.js";
+import { classifyAgentRootEntry, getDirectoryEntryType } from "#discover/filesystem.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 = ".";
+const ENVIRONMENT_ONLY_ENTRIES = new Set([
+ ".DS_Store",
+ ".editorconfig",
+ ".gitattributes",
+ ".gitignore",
+ ".git",
+ ".idea",
+ ".vscode",
+]);
export type InitTarget =
| {
@@ -16,6 +22,7 @@ export type InitTarget =
projectPath: string;
}
| {
+ createInPlace: boolean;
failurePolicy: InitFailurePolicy;
kind: "fresh";
overwriteExisting: boolean;
@@ -25,28 +32,63 @@ export type InitTarget =
};
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 pathKind(path: string): Promise<"directory" | "missing" | "other"> {
+ const stats = await stat(path).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return undefined;
+ throw error;
+ });
+ if (stats === undefined) return "missing";
+ return stats.isDirectory() ? "directory" : "other";
}
-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;
- },
+function isEnvironmentOnly(entries: readonly string[]): boolean {
+ return entries.every((entry) => ENVIRONMENT_ONLY_ENTRIES.has(entry));
+}
+
+async function isAgentRoot(directory: string): Promise<boolean> {
+ const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
+ return entries.some((entry) => {
+ const kind = classifyAgentRootEntry(entry.name, getDirectoryEntryType(entry));
+ return kind !== "unknown" && kind !== "ignored-directory" && kind !== "lib-directory";
+ });
+}
+
+async function isExistingEveProject(
+ projectPath: string,
+ entries: readonly string[],
+): Promise<boolean> {
+ if (await isAgentRoot(projectPath)) return true;
+ return (
+ (entries.includes("package.json") || entries.includes("vercel.json")) &&
+ entries.includes("agent") &&
+ (await isAgentRoot(resolve(projectPath, "agent")))
);
- if (stats === undefined) {
+}
+
+function listEntries(entries: readonly string[]): string {
+ return entries.map((entry) => ` - ${entry}`).join("\n");
+}
+
+/** Classifies the target itself without walking ancestor projects. */
+export async function resolveInitTarget(input: ResolveInitTargetInput): Promise<InitTarget> {
+ const parentPath = resolve(input.parentDirectory);
+ const targetProvided = input.target !== undefined;
+ const projectPath = resolve(parentPath, input.target ?? ".");
+ const createInPlace = projectPath === parentPath;
+ const kind = await pathKind(projectPath);
+
+ if (kind === "other") {
+ throw new Error(`Cannot initialize an agent because "${projectPath}" is not a directory.`);
+ }
+
+ if (kind === "missing") {
+ const projectName = parseProjectName(basename(projectPath));
return {
+ createInPlace: false,
failurePolicy: "remove",
kind: "fresh",
overwriteExisting: false,
@@ -55,63 +97,37 @@ async function resolveNamedTarget(parentPath: string, rawTarget: string): Promis
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) {
+ const entries = (await readdir(projectPath)).sort();
+ if (entries.length === 0 || isEnvironmentOnly(entries)) {
+ const projectName = createInPlace ? "." : parseProjectName(basename(projectPath));
return {
+ createInPlace: createInPlace || entries.length > 0,
failurePolicy: "clear",
kind: "fresh",
overwriteExisting: false,
preservedEntries: entries,
- projectName: CURRENT_DIRECTORY_PROJECT_NAME,
- projectPath: parentPath,
+ projectName,
+ projectPath,
};
}
- if (input.agentLaunched) {
+
+ if (await isExistingEveProject(projectPath, entries)) {
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.",
+ `An eve project already exists at "${projectPath}". Run an existing-project command from that directory instead.`,
);
}
- const selection = await input.confirmInitInNonEmptyDirectory(blocking);
- if (selection.kind === "subdirectory") {
- return resolveNamedTarget(parentPath, selection.name);
+ if (entries.includes("package.json")) {
+ if (!targetProvided || input.target !== ".") {
+ throw new Error(
+ `Adding eve to an existing package requires an explicit \`eve init .\` from "${projectPath}".`,
+ );
+ }
+ return { kind: "existing", projectPath };
}
- return {
- failurePolicy: "preserve",
- kind: "fresh",
- overwriteExisting: true,
- preservedEntries: entries,
- projectName: CURRENT_DIRECTORY_PROJECT_NAME,
- projectPath: parentPath,
- };
+
+ throw new Error(
+ `Cannot initialize an agent in the non-empty directory "${projectPath}". Move or remove these entries, or choose an empty target:\n${listEntries(entries)}`,
+ );
}
diff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.ts
index 4d668750f..326665c0b 100644
--- a/packages/eve/src/cli/commands/init.integration.test.ts
+++ b/packages/eve/src/cli/commands/init.integration.test.ts
@@ -5,6 +5,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MockScreen } from "#cli/dev/tui/test/mock-terminal.js";
+import { stripAnsi } from "#cli/ui/terminal-text.js";
import { DEFAULT_AGENT_MODEL_ID } from "#shared/default-agent-model.js";
import { detectPackageManager } from "#setup/package-manager.js";
import {
@@ -332,7 +333,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
vi.stubEnv(EVE_INIT_PACKAGE_SPEC_ENV, "file:/tmp/eve-0.11.5.tgz");
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
const packageJson = JSON.parse(await readFile(join(projectRoot, "package.json"), "utf8")) as {
dependencies: Record<string, string>;
@@ -374,146 +375,21 @@ describe("runInitCommand", () => {
},
);
- it("scaffolds the current directory when mise.toml already exists", async () => {
- const projectPath = await mkdtemp(join(tmpdir(), "eve-init-mise-"));
- const miseConfig = '[tools]\nnode = "24"\n';
- await writeFile(join(projectPath, "mise.toml"), miseConfig, "utf8");
- const output = logger();
- const deps = dependencies();
-
- await runInitCommand(output, projectPath, ".", {}, deps);
-
- await expect(readFile(join(projectPath, "mise.toml"), "utf8")).resolves.toBe(miseConfig);
- await expect(pathExists(join(projectPath, "agent/agent.ts"))).resolves.toBe(true);
- await expect(pathExists(join(projectPath, "package.json"))).resolves.toBe(true);
- expect(deps.runPackageManagerInstall).toHaveBeenCalledWith(
- "pnpm",
- projectPath,
- expect.objectContaining({ bypassMinimumReleaseAge: true }),
- );
- expect(deps.confirmInitInNonEmptyDirectory).not.toHaveBeenCalled();
- });
-
- it("confirms before scaffolding a non-empty current directory", async () => {
+ it("refuses arbitrary non-empty current directories without prompting or writing", async () => {
const projectPath = await mkdtemp(join(tmpdir(), "eve-init-nonempty-"));
await writeFile(join(projectPath, "notes.md"), "keep me\n", "utf8");
- await writeFile(join(projectPath, "tsconfig.json"), "old config\n", "utf8");
const output = logger();
const deps = dependencies();
- await runInitCommand(output, projectPath, undefined, {}, deps);
-
- expect(deps.confirmInitInNonEmptyDirectory).toHaveBeenCalledWith(
- expect.arrayContaining(["notes.md", "tsconfig.json"]),
+ await expect(runInitCommand(output, projectPath, ".", {}, deps)).rejects.toThrow(
+ "Cannot initialize an agent in the non-empty directory",
);
- await expect(readFile(join(projectPath, "notes.md"), "utf8")).resolves.toBe("keep me\n");
- await expect(readFile(join(projectPath, "tsconfig.json"), "utf8")).resolves.not.toBe(
- "old config\n",
- );
- await expect(pathExists(join(projectPath, "agent/agent.ts"))).resolves.toBe(true);
- expect(deps.runPackageManagerInstall).toHaveBeenCalled();
- expect(deps.tryInitializeGit).toHaveBeenCalledWith(projectPath);
- });
-
- it("scaffolds in the selected subdirectory without changing the current directory", async () => {
- const projectPath = await mkdtemp(join(tmpdir(), "eve-init-nonempty-subdir-"));
- await writeFile(join(projectPath, "notes.md"), "keep me\n", "utf8");
- const output = logger();
- const deps = dependencies();
- deps.confirmInitInNonEmptyDirectory.mockResolvedValue({
- kind: "subdirectory",
- name: "research-agent",
- });
-
- await runInitCommand(output, projectPath, undefined, {}, deps);
-
- const subdirectory = join(projectPath, "research-agent");
- await expect(readFile(join(projectPath, "notes.md"), "utf8")).resolves.toBe("keep me\n");
- await expect(pathExists(join(projectPath, "package.json"))).resolves.toBe(false);
- await expect(pathExists(join(subdirectory, "agent/agent.ts"))).resolves.toBe(true);
- expect(deps.runPackageManagerInstall).toHaveBeenCalledWith(
- "pnpm",
- subdirectory,
- expect.any(Object),
- );
- 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");
- const output = logger();
- const deps = dependencies();
- deps.confirmInitInNonEmptyDirectory.mockRejectedValue(new WizardCancelledError());
-
- await expect(runInitCommand(output, projectPath, undefined, {}, deps)).resolves.toBeUndefined();
await expect(readFile(join(projectPath, "notes.md"), "utf8")).resolves.toBe("keep me\n");
await expect(pathExists(join(projectPath, "package.json"))).resolves.toBe(false);
await expect(pathExists(join(projectPath, "agent"))).resolves.toBe(false);
- expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
- expect(deps.tryInitializeGit).not.toHaveBeenCalled();
- });
-
- it("refuses a non-empty current directory when launched by a coding agent", async () => {
- const projectPath = await mkdtemp(join(tmpdir(), "eve-init-nonempty-agent-"));
- await writeFile(join(projectPath, "notes.md"), "keep me\n", "utf8");
- const output = logger();
- const deps = dependencies();
- deps.isCodingAgentLaunch.mockResolvedValue(true);
-
- await expect(runInitCommand(output, projectPath, undefined, {}, deps)).rejects.toThrow(
- "Coding-agent launches cannot choose where to initialize a non-empty current directory. Pass a new directory name, for example: eve init my-agent.",
- );
-
expect(deps.confirmInitInNonEmptyDirectory).not.toHaveBeenCalled();
- await expect(readFile(join(projectPath, "notes.md"), "utf8")).resolves.toBe("keep me\n");
- await expect(pathExists(join(projectPath, "package.json"))).resolves.toBe(false);
- await expect(pathExists(join(projectPath, "agent"))).resolves.toBe(false);
expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
- expect(deps.tryInitializeGit).not.toHaveBeenCalled();
});
it.each([
@@ -842,19 +718,29 @@ describe("runInitCommand", () => {
]);
});
- it("reports a Git initialization failure through the logger without failing", async () => {
+ it("reports a recoverable Git commit failure without failing init", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-git-fail-"));
const output = logger();
- const deps = dependencies({ kind: "failed", reason: "commit refused" });
+ const deps = dependencies({
+ kind: "failed",
+ reason: "commit refused",
+ repositoryInitialized: true,
+ stage: "commit",
+ });
await runInitCommand(output, parentDirectory, "my-agent", {}, deps);
- expect(output.errors.join("\n")).toContain("Git initialization failed: commit refused");
- expect(deps.spawnPackageManager).toHaveBeenCalledWith(
- "pnpm",
- join(parentDirectory, "my-agent"),
- ["exec", "eve", "dev", "--input", "/model"],
+ const projectPath = join(parentDirectory, "my-agent");
+ expect(stripAnsi(output.errors.join("\n"))).toContain(
+ `Git initialization failed during commit: commit refused\nThe Git repository and staged files were preserved at "${projectPath}".\n\nResolve the Git error above, then retry:\n git -C ${JSON.stringify(projectPath)} commit -m "Initial commit from eve"`,
);
+ expect(deps.spawnPackageManager).toHaveBeenCalledWith("pnpm", projectPath, [
+ "exec",
+ "eve",
+ "dev",
+ "--input",
+ "/model",
+ ]);
});
it("adds Web Chat without Vercel configuration and preserves the invoking eve dependency", async () => {
@@ -907,20 +793,17 @@ describe("runInitCommand", () => {
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
});
- it.each(["../escape", "nested/agent", "My Agent"])(
- "rejects path-like or invalid agent name %j before scaffolding",
- async (name) => {
- const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-name-"));
- const output = logger();
- const deps = dependencies();
+ it.each(["My Agent"])("rejects invalid target path %j before scaffolding", async (name) => {
+ const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-name-"));
+ const output = logger();
+ const deps = dependencies();
- await expect(runInitCommand(output, parentDirectory, name, {}, deps)).rejects.toThrow();
+ await expect(runInitCommand(output, parentDirectory, name, {}, deps)).rejects.toThrow();
- expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
- expect(deps.tryInitializeGit).not.toHaveBeenCalled();
- expect(deps.spawnPackageManager).not.toHaveBeenCalled();
- },
- );
+ expect(deps.runPackageManagerInstall).not.toHaveBeenCalled();
+ expect(deps.tryInitializeGit).not.toHaveBeenCalled();
+ expect(deps.spawnPackageManager).not.toHaveBeenCalled();
+ });
it("adds an agent to an existing pnpm project directory", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-"));
@@ -931,7 +814,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(await readFile(join(projectRoot, "agent/agent.ts"), "utf8")).toContain(
DEFAULT_AGENT_MODEL_ID,
@@ -973,8 +856,8 @@ describe("runInitCommand", () => {
await runInitCommand(
output,
- parentDirectory,
- "host-app",
+ projectRoot,
+ ".",
{ model: "openai/gpt-5.5", reasoning: "high" },
deps,
);
@@ -1013,7 +896,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(JSON.parse(await readFile(join(projectRoot, "package.json"), "utf8"))).toMatchObject({
engines: { node: "24.x", npm: ">=10" },
@@ -1023,7 +906,7 @@ describe("runInitCommand", () => {
);
});
- it("refuses a preexisting Git-only named directory without changing it", async () => {
+ it("preserves a preexisting Git-only directory while scaffolding it", async () => {
const parentDirectory = await mkdtemp(join(tmpdir(), "eve-init-dir-git-only-"));
const projectRoot = join(parentDirectory, "host-app");
await mkdir(join(projectRoot, ".git"), { recursive: true });
@@ -1031,16 +914,14 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
- "no package.json",
- );
+ await runInitCommand(output, projectRoot, ".", {}, deps);
- await expect(readdir(projectRoot)).resolves.toEqual([".git"]);
+ await expect(readdir(projectRoot)).resolves.toContain(".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();
+ await expect(pathExists(join(projectRoot, "agent"))).resolves.toBe(true);
+ expect(deps.runPackageManagerInstall).toHaveBeenCalled();
});
it("uses a preexisting empty named directory for a fresh project", async () => {
@@ -1050,7 +931,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
await expect(pathExists(join(projectRoot, "agent/agent.ts"))).resolves.toBe(true);
expect(deps.tryInitializeGit).toHaveBeenCalledWith(projectRoot);
@@ -1064,9 +945,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
deps.runPackageManagerInstall.mockResolvedValue(false);
- await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
- "restored",
- );
+ await expect(runInitCommand(output, projectRoot, ".", {}, deps)).rejects.toThrow("restored");
await expect(readdir(projectRoot)).resolves.toEqual([]);
});
@@ -1079,7 +958,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
+ await expect(runInitCommand(output, projectRoot, ".", {}, deps)).rejects.toThrow(
"not valid JSON",
);
@@ -1102,7 +981,7 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(await readFile(join(projectRoot, "agent/agent.ts"), "utf8")).toContain(
DEFAULT_AGENT_MODEL_ID,
@@ -1137,7 +1016,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
deps.detectInvokingPackageManager.mockReturnValue("npm");
- await runInitCommand(output, appsDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(await readFile(join(projectRoot, "agent/agent.ts"), "utf8")).toContain(
DEFAULT_AGENT_MODEL_ID,
@@ -1168,7 +1047,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
deps.detectInvokingPackageManager.mockReturnValue("npm");
- await runInitCommand(output, appsDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(await readFile(join(projectRoot, "agent/agent.ts"), "utf8")).toContain(
DEFAULT_AGENT_MODEL_ID,
@@ -1198,10 +1077,8 @@ describe("runInitCommand", () => {
const output = logger();
const deps = dependencies();
- await expect(
- runInitCommand(output, parentDirectory, "host-app", {}, deps),
- ).rejects.toMatchObject({
- message: `Cannot add an eve agent to "${projectRoot}" because it already has: agent/instructions.md.`,
+ await expect(runInitCommand(output, projectRoot, ".", {}, deps)).rejects.toMatchObject({
+ message: `An eve project already exists at "${projectRoot}". Run an existing-project command from that directory instead.`,
});
await expect(pathExists(join(projectRoot, "agent/agent.ts"))).resolves.toBe(false);
@@ -1216,7 +1093,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
await expect(
- runInitCommand(output, parentDirectory, "host-app", { channelWebNextjs: true }, deps),
+ runInitCommand(output, projectRoot, ".", { channelWebNextjs: true }, deps),
).rejects.toThrow("eve add channel/web");
await expect(pathExists(join(projectRoot, "agent"))).resolves.toBe(false);
@@ -1281,7 +1158,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
deps.isCodingAgentLaunch.mockResolvedValue(true);
- await runInitCommand(output, parentDirectory, "host-app", {}, deps);
+ await runInitCommand(output, projectRoot, ".", {}, deps);
expect(deps.spawnPackageManager).not.toHaveBeenCalled();
expect(output.messages.join("\n")).toContain("npm exec -- eve dev");
@@ -1307,21 +1184,6 @@ describe("runInitCommand", () => {
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);
@@ -1329,7 +1191,7 @@ describe("runInitCommand", () => {
const deps = dependencies();
deps.runPackageManagerInstall.mockResolvedValue(false);
- await expect(runInitCommand(output, parentDirectory, "host-app", {}, deps)).rejects.toThrow(
+ await expect(runInitCommand(output, projectRoot, ".", {}, deps)).rejects.toThrow(
`install dependencies with pnpm in "${projectRoot}"`,
);
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index d6e9c8935..920c1fc6e 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -183,17 +183,16 @@ async function resolveScaffoldPackageManager(
}
async function scaffoldProject(
- parentDirectory: string,
+ projectPath: string,
projectName: string,
+ createInPlace: boolean,
packageManager: PackageManagerKind,
options: InitCommandOptions,
dependencies: InitCommandDependencies,
evePackage: EvePackageContract | undefined,
overwriteExisting: boolean,
): Promise<{ projectPath: string; workspaceRootMutations: WorkspaceRootMutation[] }> {
- const parentPath = resolve(parentDirectory);
- const createInPlace = projectName === CURRENT_DIRECTORY_PROJECT_NAME;
- const projectPath = createInPlace ? parentPath : join(parentPath, projectName);
+ const parentPath = resolve(projectPath, "..");
const populateExistingEmptyDirectory =
!createInPlace && (await pathExists(projectPath)) && (await readdir(projectPath)).length === 0;
if (!createInPlace && (await pathExists(projectPath)) && !populateExistingEmptyDirectory) {
@@ -331,12 +330,7 @@ async function runInitSteps(input: {
const { dependencies, logger, options, parentDirectory, target } = input;
const debug = isLogLevelEnabled("debug");
const agentLaunched = await dependencies.isCodingAgentLaunch();
- const initTarget = await resolveInitTarget({
- agentLaunched,
- confirmInitInNonEmptyDirectory: dependencies.confirmInitInNonEmptyDirectory,
- parentDirectory,
- target,
- });
+ const initTarget = await resolveInitTarget({ parentDirectory, target });
const evePackage = resolveInitEvePackageOverride();
const progress = startCliLiveRow(logger);
@@ -359,8 +353,9 @@ async function runInitSteps(input: {
let scaffold: Awaited<ReturnType<typeof scaffoldProject>>;
try {
scaffold = await scaffoldProject(
- parentDirectory,
+ initTarget.projectPath,
initTarget.projectName,
+ initTarget.createInPlace,
packageManager,
options,
dependencies,
@@ -392,7 +387,7 @@ async function runInitSteps(input: {
packageManager,
preservedTargetEntries: initTarget.preservedEntries,
projectPath: scaffold.projectPath,
- retryCommand: `eve init ${initTarget.projectName}`,
+ retryCommand: `eve init ${initTarget.projectPath}`,
workspaceMember,
workspaceRootMutations: scaffold.workspaceRootMutations,
};
@@ -555,7 +550,18 @@ export async function runInitCommand(
);
if (result.kind === "created" && result.gitResult.kind === "failed") {
- logger.error(pc.yellow(`Git initialization failed: ${result.gitResult.reason}`));
+ logger.error(
+ pc.yellow(
+ `Git initialization failed during ${result.gitResult.stage}: ${result.gitResult.reason}`,
+ ),
+ );
+ if (result.gitResult.stage === "commit") {
+ logger.error(
+ pc.yellow(
+ `The Git repository and staged files were preserved at "${result.projectPath}".\n\nResolve the Git error above, then retry:\n git -C ${JSON.stringify(result.projectPath)} commit -m "Initial commit from eve"`,
+ ),
+ );
+ }
}
const agentDevCommand = [result.packageManager, ...eveDevArguments(result.packageManager)].join(