Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Choose where to initialize from non-empty directories (#2064)

Casey Gowriec77c661d3d0c
diff --git a/.changeset/loose-webs-clap.md b/.changeset/loose-webs-clap.md
new file mode 100644
index 000000000..04743595f
--- /dev/null
+++ b/.changeset/loose-webs-clap.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+`eve init` now asks whether to scaffold a non-empty current directory in place or create a named subdirectory. In-place scaffolds preserve unrelated files and overwrite generated paths; coding-agent and non-interactive launches must pass an explicit directory name.
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index d995581c9..e33d6e570 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -40,11 +40,14 @@ eve init [target] [--model <provider/model-id>] [--reasoning <effort>] [--channe
Creates a new agent app or adds an agent to an existing app. Always installs dependencies. New directories also initialize Git.
-| Target | What happens |
-| ----------------------------------------- | -------------------------------------------------------------------------------------------------------- |
-| `eve init my-agent` | New agent project in `my-agent/` |
-| `eve init .` (or an existing project dir) | Adds `agent/` plus missing `eve`, `ai`, and `zod` deps. Needs a `package.json` and no `agent/` files yet |
-| `eve init` with no target | Same as `eve init .` |
+| Target | What happens |
+| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `eve init my-agent` | Creates an agent project in `my-agent/` |
+| `eve init` or `eve init .` in an empty directory | Creates an agent project in the current directory |
+| `eve init` or `eve init .` in a non-empty directory without `package.json` | Asks whether to scaffold in the current directory or a named subdirectory. Using the current directory preserves unrelated files but overwrites files at generated paths |
+| `eve init .` in an existing project | Adds `agent/` plus missing `eve`, `ai`, and `zod` dependencies. Requires `package.json` and no existing `agent/` files |
+
+Coding-agent launches and non-interactive terminals cannot answer the location prompt and fail before writing. Pass a new directory name, such as `eve init my-agent`, in those environments.
After scaffolding, a human terminal usually continues into `eve dev`. If a coding-agent REPL is on `PATH`, the handoff menu can open it instead or exit without starting either process. Coding-agent launches print the next steps instead of opening the TUI, so the session does not get stuck. Fresh projects use the parent workspace's package manager when there is one; otherwise they use the manager that launched `eve init`.
diff --git a/packages/eve/src/cli/commands/init-confirm.test.ts b/packages/eve/src/cli/commands/init-confirm.test.ts
new file mode 100644
index 000000000..ea4653ae3
--- /dev/null
+++ b/packages/eve/src/cli/commands/init-confirm.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { createFakePrompter, type FakePrompterConfig } from "#internal/testing/fake-prompter.js";
+
+import { confirmInitInNonEmptyDirectory, type InitConfirmDependencies } from "./init-confirm.js";
+
+function dependencies(input: {
+ interactive: boolean;
+ onSelect?: FakePrompterConfig["single"];
+ onText?: FakePrompterConfig["text"];
+}): InitConfirmDependencies {
+ const fake = createFakePrompter({ single: input.onSelect, text: input.onText });
+ return {
+ createPrompter: vi.fn(() => fake.prompter),
+ hasInteractiveTerminal: vi.fn(() => input.interactive),
+ };
+}
+
+describe("confirmInitInNonEmptyDirectory", () => {
+ it("selects the current directory with an overwrite warning", async () => {
+ const deps = dependencies({
+ interactive: true,
+ onSelect: (options) => {
+ expect(options).toMatchObject({
+ message: "Where should eve initialize the project?",
+ description:
+ "The current directory isn't empty. Found: README.md, src, notes.txt, draft.md, data.json, and 1 more.",
+ initialValue: "subdirectory",
+ });
+ expect(options.options).toEqual([
+ {
+ value: "subdirectory",
+ label: "Create a new subdirectory",
+ hint: "Keep the current directory unchanged",
+ },
+ {
+ value: "current-directory",
+ label: "Use the current directory",
+ hint: "Overwrite files at generated paths",
+ accent: "warning",
+ },
+ ]);
+ return "current-directory";
+ },
+ });
+
+ await expect(
+ confirmInitInNonEmptyDirectory(
+ ["README.md", "src", "notes.txt", "draft.md", "data.json", "archive"],
+ deps,
+ ),
+ ).resolves.toEqual({ kind: "current-directory" });
+ });
+
+ it("asks for and normalizes a new subdirectory name", async () => {
+ const deps = dependencies({
+ interactive: true,
+ onSelect: () => "subdirectory",
+ onText: (options) => {
+ expect(options).toMatchObject({
+ message: "Subdirectory name",
+ defaultValue: "my-agent",
+ });
+ expect(options.validate?.("../escape")).toBeDefined();
+ return " research-agent ";
+ },
+ });
+
+ await expect(confirmInitInNonEmptyDirectory(["README.md"], deps)).resolves.toEqual({
+ kind: "subdirectory",
+ name: "research-agent",
+ });
+ });
+
+ it("refuses a non-interactive scaffold instead of opening a prompt", async () => {
+ const deps = dependencies({ interactive: false });
+
+ await expect(confirmInitInNonEmptyDirectory(["README.md"], deps)).rejects.toThrow(
+ "Cannot choose where to initialize the non-empty current directory without an interactive terminal. Found: README.md. Pass a new directory name, for example: eve init my-agent.",
+ );
+ expect(deps.createPrompter).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/cli/commands/init-confirm.ts b/packages/eve/src/cli/commands/init-confirm.ts
new file mode 100644
index 000000000..fd8ccecdf
--- /dev/null
+++ b/packages/eve/src/cli/commands/init-confirm.ts
@@ -0,0 +1,64 @@
+import { createPrompter, type Prompter } from "#setup/prompter.js";
+import { parseProjectName, validateProjectName } from "#setup/project-name.js";
+
+import { hasInteractiveTerminal } from "./preconditions.js";
+
+export interface InitConfirmDependencies {
+ createPrompter(): Prompter;
+ hasInteractiveTerminal(): boolean;
+}
+
+const defaultDependencies: InitConfirmDependencies = {
+ createPrompter,
+ hasInteractiveTerminal,
+};
+
+export type InitNonEmptyDirectoryTarget =
+ | { kind: "current-directory" }
+ | { kind: "subdirectory"; name: string };
+
+function formatEntries(entries: readonly string[]): string {
+ const visible = entries.slice(0, 5).join(", ");
+ const suffix = entries.length > 5 ? `, and ${entries.length - 5} more` : "";
+ return `${visible}${suffix}`;
+}
+
+export async function confirmInitInNonEmptyDirectory(
+ entries: readonly string[],
+ dependencies: InitConfirmDependencies = defaultDependencies,
+): Promise<InitNonEmptyDirectoryTarget> {
+ const found = formatEntries(entries);
+ if (!dependencies.hasInteractiveTerminal()) {
+ throw new Error(
+ `Cannot choose where to initialize the non-empty current directory without an interactive terminal. Found: ${found}. Pass a new directory name, for example: eve init my-agent.`,
+ );
+ }
+
+ const prompter = dependencies.createPrompter();
+ const choice = await prompter.select<"current-directory" | "subdirectory">({
+ message: "Where should eve initialize the project?",
+ description: `The current directory isn't empty. Found: ${found}.`,
+ options: [
+ {
+ value: "subdirectory",
+ label: "Create a new subdirectory",
+ hint: "Keep the current directory unchanged",
+ },
+ {
+ value: "current-directory",
+ label: "Use the current directory",
+ hint: "Overwrite files at generated paths",
+ accent: "warning",
+ },
+ ],
+ initialValue: "subdirectory",
+ });
+ if (choice === "current-directory") return { kind: "current-directory" };
+
+ const name = await prompter.text({
+ message: "Subdirectory name",
+ defaultValue: "my-agent",
+ validate: validateProjectName,
+ });
+ return { kind: "subdirectory", name: parseProjectName(name) };
+}
diff --git a/packages/eve/src/cli/commands/init.integration.test.ts b/packages/eve/src/cli/commands/init.integration.test.ts
index 5fe3b7760..ed394518a 100644
--- a/packages/eve/src/cli/commands/init.integration.test.ts
+++ b/packages/eve/src/cli/commands/init.integration.test.ts
@@ -64,6 +64,9 @@ function logger(): InitCliLogger & { messages: string[]; errors: string[] } {
function dependencies(
gitResult: GitInitResult = { kind: "initialized" },
): InitCommandDependencies & {
+ confirmInitInNonEmptyDirectory: ReturnType<
+ typeof vi.fn<InitCommandDependencies["confirmInitInNonEmptyDirectory"]>
+ >;
detectInvokingPackageManager: ReturnType<
typeof vi.fn<InitCommandDependencies["detectInvokingPackageManager"]>
>;
@@ -86,6 +89,7 @@ function dependencies(
}
return addAgentToProject(merged);
},
+ confirmInitInNonEmptyDirectory: vi.fn(async () => ({ kind: "current-directory" })),
// Stubbed to "no visible manager" so assertions do not depend on which
// manager launched the test runner itself.
detectInvokingPackageManager: vi.fn(() => undefined),
@@ -387,6 +391,87 @@ describe("runInitCommand", () => {
projectPath,
expect.objectContaining({ bypassMinimumReleaseAge: true }),
);
+ expect(deps.confirmInitInNonEmptyDirectory).not.toHaveBeenCalled();
+ });
+
+ it("confirms before scaffolding a non-empty current directory", 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(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("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([
@@ -828,6 +913,7 @@ describe("runInitCommand", () => {
);
// An existing project's history is its own; only fresh scaffolds get git init.
expect(deps.tryInitializeGit).not.toHaveBeenCalled();
+ expect(deps.confirmInitInNonEmptyDirectory).not.toHaveBeenCalled();
expect(deps.spawnPackageManager).toHaveBeenCalledWith("pnpm", projectRoot, [
"exec",
"eve",
diff --git a/packages/eve/src/cli/commands/init.ts b/packages/eve/src/cli/commands/init.ts
index 4ff0d7319..28e8bb8a5 100644
--- a/packages/eve/src/cli/commands/init.ts
+++ b/packages/eve/src/cli/commands/init.ts
@@ -37,6 +37,7 @@ import {
} from "#setup/scaffold/create/project.js";
import { initAgentDevHandoff, initAgentReplPrompt } from "./agent-instructions.js";
+import { confirmInitInNonEmptyDirectory } from "./init-confirm.js";
import { tryInitializeGit, type GitInitResult } from "./init-git.js";
import { selectInitHandoff, spawnCodingAgentRepl, type InitHandoff } from "./init-repl.js";
@@ -56,6 +57,7 @@ export interface InitCommandOptions {
export interface InitCommandDependencies {
addAgentToProject: typeof addAgentToProject;
+ confirmInitInNonEmptyDirectory: typeof confirmInitInNonEmptyDirectory;
detectInvokingPackageManager: typeof detectInvokingPackageManager;
detectPackageManager: typeof detectPackageManager;
ensureChannel: typeof ensureChannel;
@@ -72,6 +74,7 @@ export interface InitCommandDependencies {
const defaultDependencies: InitCommandDependencies = {
addAgentToProject,
+ confirmInitInNonEmptyDirectory,
detectInvokingPackageManager,
detectPackageManager,
ensureChannel,
@@ -105,20 +108,6 @@ function isCurrentDirectoryTarget(target: string): boolean {
return /^\.(?:[/\\]+\.?)*$/u.test(target.trim());
}
-async function assertCanScaffoldInPlace(targetRoot: string): Promise<void> {
- const entries = await readdir(targetRoot);
- const blocking = blockingCreateInPlaceEntries(entries);
- if (blocking.length === 0) {
- return;
- }
-
- const visible = blocking.slice(0, 5).join(", ");
- const suffix = blocking.length > 5 ? `, and ${blocking.length - 5} more` : "";
- throw new Error(
- `Cannot create project in current directory because it is not empty. Found: ${visible}${suffix}. Use an empty directory.`,
- );
-}
-
async function moveDirectoryContents(sourceRoot: string, targetRoot: string): Promise<void> {
for (const entry of await readdir(sourceRoot)) {
await rename(join(sourceRoot, entry), join(targetRoot, entry));
@@ -207,30 +196,37 @@ async function scaffoldProject(
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);
- if (createInPlace) {
- await assertCanScaffoldInPlace(projectPath);
- } else if (await pathExists(projectPath)) {
+ if (!createInPlace && (await pathExists(projectPath))) {
throw new Error(`Cannot create project because "${projectPath}" already exists.`);
}
- const stagingDirectory = await mkdtemp(join(parentPath, ".eve-init-"));
+ const stagingDirectory =
+ createInPlace && overwriteExisting ? undefined : await mkdtemp(join(parentPath, ".eve-init-"));
const workspaceRootMutations: WorkspaceRootMutation[] = [];
try {
+ const scaffoldDirectory = stagingDirectory ?? projectPath;
if (options.model !== undefined) {
- const rejection = await dependencies.validateModelSlug(stagingDirectory, options.model);
+ const rejection = await dependencies.validateModelSlug(scaffoldDirectory, options.model);
if (rejection !== null) throw new Error(rejection);
}
- const stagedProjectName = createInPlace ? basename(projectPath) : projectName;
+ const stagedProjectName =
+ stagingDirectory === undefined
+ ? CURRENT_DIRECTORY_PROJECT_NAME
+ : createInPlace
+ ? basename(projectPath)
+ : projectName;
const scaffoldOptions = {
projectName: stagedProjectName,
model: options.model ?? DEFAULT_AGENT_MODEL_ID,
reasoning: options.reasoning,
evePackage,
- targetDirectory: stagingDirectory,
+ targetDirectory: scaffoldDirectory,
+ overwriteExisting,
workspaceProbeDirectory: projectPath,
packageManager,
onWorkspaceRootMutation: (mutation: WorkspaceRootMutation) => {
@@ -244,6 +240,7 @@ async function scaffoldProject(
projectRoot: stagedProjectPath,
kind: "web",
packageManager,
+ force: overwriteExisting,
workspaceProbeDirectory: projectPath,
configureVercelServices: false,
onWorkspaceRootMutation: (mutation: WorkspaceRootMutation) => {
@@ -252,17 +249,21 @@ async function scaffoldProject(
});
}
- if (createInPlace) {
- await moveDirectoryContents(stagedProjectPath, projectPath);
- } else {
- await rename(stagedProjectPath, projectPath);
+ if (stagingDirectory !== undefined) {
+ if (createInPlace) {
+ await moveDirectoryContents(stagedProjectPath, projectPath);
+ } else {
+ await rename(stagedProjectPath, projectPath);
+ }
}
return {
projectPath,
workspaceRootMutations: uniqueWorkspaceRootMutations(workspaceRootMutations),
};
} finally {
- await rm(stagingDirectory, { recursive: true, force: true });
+ if (stagingDirectory !== undefined) {
+ await rm(stagingDirectory, { recursive: true, force: true });
+ }
}
}
@@ -329,20 +330,38 @@ async function runInitSteps(input: {
}): Promise<InitResult> {
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 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 agentLaunched = await dependencies.isCodingAgentLaunch();
- const rawTarget = target ?? CURRENT_DIRECTORY_PROJECT_NAME;
- const currentDirectoryTarget = isCurrentDirectoryTarget(rawTarget);
- const existingDirectory = currentDirectoryTarget
- ? (await pathExists(join(resolve(parentDirectory), "package.json")))
- ? resolve(parentDirectory)
- : undefined
- : await resolveTargetDirectory(parentDirectory, rawTarget);
- const evePackage = resolveInitEvePackageOverride();
-
const scaffoldPhase = existingDirectory === undefined ? "creating agent" : "adding agent";
progress.update(existingDirectory === undefined ? "Creating agent" : "Adding agent");
initLog.debug(scaffoldPhase);
@@ -363,6 +382,7 @@ async function runInitSteps(input: {
options,
dependencies,
evePackage,
+ overwriteExisting,
);
project = {
kind: "created",
@@ -454,8 +474,10 @@ async function runInitSteps(input: {
/**
* Creates a new eve agent (`target` is a project name), or adds one to an
- * existing project (`target` is a directory), without prompts or external
- * provisioning.
+ * existing project (`target` is a directory), without external provisioning.
+ * A fresh in-place scaffold asks whether to use the current directory or a new
+ * subdirectory when the current directory is not empty. Coding-agent launches
+ * must pass an explicit subdirectory instead.
*
* Runs launched by a coding agent get the dev command printed instead of
* spawned after scaffolding, since the dev TUI would wedge the launching agent.
@@ -469,7 +491,13 @@ export async function runInitCommand(
options: InitCommandOptions,
dependencies: InitCommandDependencies = defaultDependencies,
): Promise<void> {
- const result = await runInitSteps({ dependencies, logger, options, parentDirectory, target });
+ let result: InitResult;
+ try {
+ result = await runInitSteps({ dependencies, logger, options, parentDirectory, target });
+ } catch (error) {
+ if (error instanceof WizardCancelledError) return;
+ throw error;
+ }
if (result.kind === "created") {
logger.log(