diff --git a/README.md b/README.md index 2755b1e19a..39c323d7da 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ If Tower is running during an upgrade, restart it afterwards so it picks up the On Linux and WSL, also install `build-essential` and `python3` (node-pty compiles from source). -**Windows:** two paths. **Native** (preview): Node.js 22 or 24 (x64 or ARM64), [Git for Windows](https://git-scm.com/download/win) and `jq`, no admin rights or Developer Mode needed. **WSL 2**: follow the Linux instructions inside your distribution. See [DEPENDENCIES.md](codev-skeleton/DEPENDENCIES.md#windows) for setup and limitations, including why native support is a preview (#1911). +**Windows:** two paths. **Native**: Node.js 22 or 24 (x64 or ARM64), [Git for Windows](https://git-scm.com/download/win) and `jq`, no admin rights or Developer Mode needed. **WSL 2**: follow the Linux instructions inside your distribution. See [DEPENDENCIES.md](codev-skeleton/DEPENDENCIES.md#windows) for setup and limitations. **AI CLIs** (install all three for multi-model consultation): - Claude Code: `npm install -g @anthropic-ai/claude-code` diff --git a/apps/vscode/src/__tests__/cli-process.test.ts b/apps/vscode/src/__tests__/cli-process.test.ts index dbd9471786..b4822997a2 100644 --- a/apps/vscode/src/__tests__/cli-process.test.ts +++ b/apps/vscode/src/__tests__/cli-process.test.ts @@ -4,22 +4,35 @@ * pass through unchanged. */ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; const childProcess = vi.hoisted(() => ({ spawn: vi.fn(() => ({ unref: vi.fn() })), execFile: vi.fn() })); -vi.mock('node:child_process', () => ({ spawn: childProcess.spawn, execFile: childProcess.execFile })); +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal(); + return { ChildProcess: actual.ChildProcess, spawn: childProcess.spawn, execFile: childProcess.execFile }; +}); const sdk = vi.hoisted(() => ({ resolveSpawnable: vi.fn() })); vi.mock('@cluesmith/codev-sdk/node/executable', () => ({ resolveSpawnable: sdk.resolveSpawnable })); import { spawnCodevCli, execCodevCli } from '../cli-process.js'; +const realPlatform = process.platform; + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); +} + beforeEach(() => { childProcess.spawn.mockClear(); childProcess.execFile.mockReset(); sdk.resolveSpawnable.mockReset(); }); +afterEach(() => { + setPlatform(realPlatform); +}); + describe('spawnCodevCli', () => { it('spawns the resolver output with its verbatim flag, hidden', () => { sdk.resolveSpawnable.mockReturnValue({ @@ -57,6 +70,7 @@ describe('spawnCodevCli', () => { }); it('execCodevCli rejects on a failing exit, carrying its output', async () => { + setPlatform('linux'); sdk.resolveSpawnable.mockImplementation((command: string, args: string[]) => ({ command, args, windowsVerbatimArguments: false })); childProcess.execFile.mockImplementation((_file: string, _args: string[], _opts: unknown, cb: (e: Error | null, o: string, e2: string) => void) => { cb(new Error('exit 1'), '', 'no such builder'); @@ -65,6 +79,7 @@ describe('spawnCodevCli', () => { }); it('passes a POSIX command through unchanged', () => { + setPlatform('linux'); sdk.resolveSpawnable.mockImplementation((command: string, args: string[]) => ({ command, args, windowsVerbatimArguments: false })); spawnCodevCli('codev', ['--version'], { cwd: '/repo' }); expect(childProcess.spawn).toHaveBeenCalledWith('codev', ['--version'], { @@ -74,3 +89,30 @@ describe('spawnCodevCli', () => { }); }); }); + +describe('a bare name not on PATH on Windows (#1911)', () => { + // The resolver hands an unresolved name back unchanged; spawning it would let + // Windows run a same-named program from the workspace folder instead. + beforeEach(() => { + setPlatform('win32'); + sdk.resolveSpawnable.mockImplementation((command: string, args: string[]) => ({ command, args, windowsVerbatimArguments: false })); + }); + + it('spawnCodevCli never spawns it and emits ENOENT asynchronously', async () => { + const child = spawnCodevCli('afx', ['tower', 'start'], { cwd: 'C:\\ws' }); + expect(childProcess.spawn).not.toHaveBeenCalled(); + const error = await new Promise((resolve) => child.on('error', resolve)); + expect(error).toMatchObject({ code: 'ENOENT', path: 'afx', syscall: 'spawn afx', spawnargs: ['tower', 'start'] }); + }); + + it('execCodevCli never runs it and rejects with ENOENT', async () => { + await expect(execCodevCli('porch', ['approve', '42', 'pr'], { cwd: 'C:\\ws' })).rejects.toMatchObject({ code: 'ENOENT', path: 'porch' }); + expect(childProcess.execFile).not.toHaveBeenCalled(); + }); + + it('still spawns a name the resolver found', () => { + sdk.resolveSpawnable.mockReturnValue({ command: 'C:\\npm\\codev.exe', args: ['--version'], windowsVerbatimArguments: false }); + spawnCodevCli('codev', ['--version'], {}); + expect(childProcess.spawn).toHaveBeenCalledWith('C:\\npm\\codev.exe', ['--version'], { windowsHide: true, windowsVerbatimArguments: false }); + }); +}); diff --git a/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts b/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts new file mode 100644 index 0000000000..9844955b92 --- /dev/null +++ b/apps/vscode/src/__tests__/spawn-builder-not-found.test.ts @@ -0,0 +1,53 @@ +/** + * #1911: when `afx` cannot be started (on Windows, `cli-process.ts` refuses a + * name that does not resolve on PATH and emits ENOENT), Spawn Builder shows a + * readable error instead of leaving an unhandled 'error' event. + */ + +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { EventEmitter } from 'node:events'; + +const vscodeMock = vi.hoisted(() => ({ + window: { + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showInputBox: vi.fn(), + showQuickPick: vi.fn(), + }, +})); +vi.mock('vscode', () => vscodeMock); + +const cli = vi.hoisted(() => ({ spawnCodevCli: vi.fn() })); +vi.mock('../cli-process.js', () => cli); + +import { spawnBuilder } from '../commands/spawn.js'; + +function fakeChild(): EventEmitter & { unref: () => void } { + return Object.assign(new EventEmitter(), { unref: vi.fn() }); +} + +beforeEach(() => { + vi.clearAllMocks(); + vscodeMock.window.showQuickPick.mockResolvedValue('pir'); +}); + +describe('Spawn Builder when afx cannot start', () => { + it('says afx was not found on PATH for ENOENT', async () => { + const child = fakeChild(); + cli.spawnCodevCli.mockReturnValue(child); + await spawnBuilder('42'); + expect(cli.spawnCodevCli).toHaveBeenCalledWith('afx', ['spawn', '42', '--protocol', 'pir'], { detached: true, stdio: 'ignore' }); + + child.emit('error', Object.assign(new Error('spawn afx ENOENT'), { code: 'ENOENT' })); + expect(vscodeMock.window.showErrorMessage).toHaveBeenCalledWith(expect.stringContaining('afx was not found on PATH')); + }); + + it('shows the error message for any other failure', async () => { + const child = fakeChild(); + cli.spawnCodevCli.mockReturnValue(child); + await spawnBuilder('42'); + + child.emit('error', Object.assign(new Error('spawn EACCES'), { code: 'EACCES' })); + expect(vscodeMock.window.showErrorMessage).toHaveBeenCalledWith('Codev: could not run afx: spawn EACCES'); + }); +}); diff --git a/apps/vscode/src/cli-process.ts b/apps/vscode/src/cli-process.ts index 171a31d724..33080908bf 100644 --- a/apps/vscode/src/cli-process.ts +++ b/apps/vscode/src/cli-process.ts @@ -1,5 +1,28 @@ -import { execFile, spawn, type ChildProcess, type ExecFileOptions, type SpawnOptions } from 'node:child_process'; -import { resolveSpawnable } from '@cluesmith/codev-sdk/node/executable'; +import { ChildProcess, execFile, spawn, type ExecFileOptions, type SpawnOptions } from 'node:child_process'; +import { resolveSpawnable, type SpawnableCommand } from '@cluesmith/codev-sdk/node/executable'; + +/** + * Windows looks a bare name up in the current folder before `PATH` (#1911), so + * a `codev.exe` in the open workspace would run in place of Codev. The + * resolver searches `PATH` only and hands the name back unchanged when it is + * not there; that case must fail here rather than reach `spawn`. The extension + * host is shared with other extensions, so it does not set + * `NoDefaultCurrentDirectoryInExePath` process-wide as the Codev CLIs do. + */ +function unresolvedOnWindows(command: string, spawnable: SpawnableCommand): boolean { + return process.platform === 'win32' && spawnable.command === command && !/[\\/]/.test(command); +} + +/** The ENOENT error `spawn` raises for a missing program. */ +function notFoundError(command: string, args: string[]): NodeJS.ErrnoException { + return Object.assign(new Error(`spawn ${command} ENOENT (not found on PATH)`), { + code: 'ENOENT', + errno: -4058, // UV_ENOENT on Windows, the errno a real failed spawn carries + syscall: `spawn ${command}`, + path: command, + spawnargs: args, + }); +} /** * Spawn a Codev CLI (`afx`, `codev`). On Windows each is an npm `.cmd` shim, @@ -9,6 +32,12 @@ import { resolveSpawnable } from '@cluesmith/codev-sdk/node/executable'; */ export function spawnCodevCli(command: string, args: string[], options: SpawnOptions): ChildProcess { const spawnable = resolveSpawnable(command, args); + if (unresolvedOnWindows(command, spawnable)) { + // The async contract callers already handle: an 'error' event, never a throw. + const child = new ChildProcess(); + process.nextTick(() => child.emit('error', notFoundError(command, args))); + return child; + } return spawn(spawnable.command, spawnable.args, { ...options, windowsHide: true, @@ -28,6 +57,9 @@ export function execCodevCli( options: ExecFileOptions, ): Promise<{ stdout: string; stderr: string }> { const spawnable = resolveSpawnable(command, args); + if (unresolvedOnWindows(command, spawnable)) { + return Promise.reject(notFoundError(command, args)); + } return new Promise((resolve, reject) => { execFile(spawnable.command, spawnable.args, { ...options, diff --git a/apps/vscode/src/commands/spawn.ts b/apps/vscode/src/commands/spawn.ts index 5f70953d92..1d44f95afe 100644 --- a/apps/vscode/src/commands/spawn.ts +++ b/apps/vscode/src/commands/spawn.ts @@ -44,6 +44,10 @@ export async function spawnBuilder(issueArg?: string): Promise { function runAfxCommand(args: string[]): void { const child = spawnCodevCli('afx', args, { detached: true, stdio: 'ignore' }); + child.on('error', (err: NodeJS.ErrnoException) => { + const reason = err.code === 'ENOENT' ? 'afx was not found on PATH (install @cluesmith/codev)' : err.message; + vscode.window.showErrorMessage(`Codev: could not run afx: ${reason}`); + }); child.unref(); vscode.window.showInformationMessage(`Codev: Running afx ${args.join(' ')}`); } diff --git a/codev-skeleton/DEPENDENCIES.md b/codev-skeleton/DEPENDENCIES.md index f667ee69a1..fa4469513b 100644 --- a/codev-skeleton/DEPENDENCIES.md +++ b/codev-skeleton/DEPENDENCIES.md @@ -210,7 +210,7 @@ sudo apt install nodejs npm git build-essential python3 ### Windows -Codev supports two paths on Windows: native, with Git for Windows (a preview), and WSL 2. +Codev supports two paths on Windows: native, with Git for Windows, and WSL 2. #### Native Windows (Git for Windows) @@ -259,12 +259,16 @@ How it works and what to know: - **PowerShell.** Tower uses the built-in `powershell.exe` (CIM) to list and stop the processes each session starts. A machine policy that blocks it, or Constrained Language Mode, is not supported; `codev doctor` and Tower's log report it. -- **Preview: only work in repositories you trust.** On Windows, a program started by bare name - (`git`, `gh`, `npm`, `node`) is looked up in the current folder before `PATH`, and Codev runs - many of those commands with a builder worktree or a cloned repository as the current folder. - A repository that contains, say, a `git.exe` would have that file run instead of Git. Codev's - own Windows tools (`powershell.exe`, `taskkill`, `cmd.exe`) already run by full system path; - the user tools follow (#1911), and native Windows support leaves preview with that fix. +- **Programs never run from the current folder.** Windows normally looks a program started by + bare name (`git`, `npm`) up in the current folder before `PATH`, so a `git.exe` inside a + repository could run in place of Git. Codev turns that lookup off (it sets + `NoDefaultCurrentDirectoryInExePath`) in its own processes, the commands they run, and every + terminal Tower opens: architect and builder sessions and shell tabs alike. In a `cmd.exe` + shell, a program in the current folder then runs only when you name its folder (`.\name`); + PowerShell already works this way. One known effect: a .NET 10 NativeAOT `dotnet publish` fails + inside a Codev terminal, because Visual Studio's `vcvarsall.bat` does not support the setting + (fixed in .NET 11; [dotnet/runtime#129340](https://github.com/dotnet/runtime/issues/129340)). + Codev runs its own Windows tools by full system path. - **Known limitations.** Doctor cannot show Tower's environment on Windows (the process table does not expose it). Building this repository from source on ARM64 fails in one bundler; installing the published package on ARM64 works. diff --git a/codev/DEPENDENCIES.md b/codev/DEPENDENCIES.md index f667ee69a1..fa4469513b 100644 --- a/codev/DEPENDENCIES.md +++ b/codev/DEPENDENCIES.md @@ -210,7 +210,7 @@ sudo apt install nodejs npm git build-essential python3 ### Windows -Codev supports two paths on Windows: native, with Git for Windows (a preview), and WSL 2. +Codev supports two paths on Windows: native, with Git for Windows, and WSL 2. #### Native Windows (Git for Windows) @@ -259,12 +259,16 @@ How it works and what to know: - **PowerShell.** Tower uses the built-in `powershell.exe` (CIM) to list and stop the processes each session starts. A machine policy that blocks it, or Constrained Language Mode, is not supported; `codev doctor` and Tower's log report it. -- **Preview: only work in repositories you trust.** On Windows, a program started by bare name - (`git`, `gh`, `npm`, `node`) is looked up in the current folder before `PATH`, and Codev runs - many of those commands with a builder worktree or a cloned repository as the current folder. - A repository that contains, say, a `git.exe` would have that file run instead of Git. Codev's - own Windows tools (`powershell.exe`, `taskkill`, `cmd.exe`) already run by full system path; - the user tools follow (#1911), and native Windows support leaves preview with that fix. +- **Programs never run from the current folder.** Windows normally looks a program started by + bare name (`git`, `npm`) up in the current folder before `PATH`, so a `git.exe` inside a + repository could run in place of Git. Codev turns that lookup off (it sets + `NoDefaultCurrentDirectoryInExePath`) in its own processes, the commands they run, and every + terminal Tower opens: architect and builder sessions and shell tabs alike. In a `cmd.exe` + shell, a program in the current folder then runs only when you name its folder (`.\name`); + PowerShell already works this way. One known effect: a .NET 10 NativeAOT `dotnet publish` fails + inside a Codev terminal, because Visual Studio's `vcvarsall.bat` does not support the setting + (fixed in .NET 11; [dotnet/runtime#129340](https://github.com/dotnet/runtime/issues/129340)). + Codev runs its own Windows tools by full system path. - **Known limitations.** Doctor cannot show Tower's environment on Windows (the process table does not expose it). Building this repository from source on ARM64 fails in one bundler; installing the published package on ARM64 works. diff --git a/codev/plans/1911-windows-bare-name-user-tool-sp.md b/codev/plans/1911-windows-bare-name-user-tool-sp.md new file mode 100644 index 0000000000..93daaf1a78 --- /dev/null +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -0,0 +1,148 @@ +# PIR Plan: Windows user-tool lookup hardening (#1911) + +> Revised 2026-11-20 at the owner's direction: the small version. The first draft (route all +> ~72 bare-name sites through the resolver) rested on an untested claim that libuv ignores +> `NoDefaultCurrentDirectoryInExePath`. Measured below: it does not. + +## Understanding + +On Windows, a program started by **bare name** (`git`, `gh`, `npm`, `npx`, `codev`) is looked up in +the current directory before `PATH`. Codev runs those commands with a builder worktree, a +workspace, or a freshly cloned repository as the current directory, so a `git.exe` committed to a +repository runs under Codev, as the user, on routine commands (`afx spawn`, `afx cleanup`, porch, +consult, `codev doctor`, `codev import`). Spec 1658 fixed the system programs by full System32 +path; this issue covers the user tools, and with it native Windows leaves preview. + +**Measured on this host (Node 24.13.0, libuv 1.51.0):** a copy of `hostname.exe` planted as +`git.exe` in a temp directory, `git --version` run with that directory as `cwd`: + +| | `execFileSync('git')` | `spawnSync('git')` | `execSync('git …')` (cmd.exe) | +|---|---|---|---| +| variable unset | planted file ran | planted file ran | planted file ran | +| `process.env.NoDefaultCurrentDirectoryInExePath = '1'` set in-process first | PATH git | PATH git | PATH git | +| same, Git removed from `PATH` | ENOENT | ENOENT | "not recognized" | + +libuv's `search_path` honours the variable (via `NeedCurrentDirectoryForExePathW`, read from the +calling process's environment), and `cmd.exe` honours it from its inherited environment. Setting +it in our own process at startup closes the hole for every spawn that process makes, and for +every child that inherits our environment, with no change to any call site. When the tool is not +on `PATH` the spawn fails closed; the planted file never runs. + +## Proposed Change + +### 1. One hardening module, set first in every Codev process + +New `packages/codev/src/lib/process-bootstrap.ts`: a general side-effect module for setup every +Codev process runs first. Its one step, on `win32` only, calls `hardenExeSearch` from the new +`packages/codev/src/lib/platform/windows/exe-search.ts`, which sets +`process.env.NoDefaultCurrentDirectoryInExePath = '1'`. It is a no-op on macOS/Linux (POSIX +`execvp` never searches the cwd). Neither file imports anything else, so the bootstrap can be the +first import evaluated. + +It is imported **first** (before any other import, so ESM hoisting cannot run a spawn ahead of it) +in each process entry point: + +- `packages/codev/bin/{codev,afx,porch,consult,team,generate-image}.js` — every installed command. + Child Codev processes started via `process.execPath ` (porch `notify.ts`, + `workspace-recover.ts`) go through these too. +- `packages/codev/src/agent-farm/servers/tower-server.ts` and + `packages/codev/src/terminal/shellper-main.ts` — node scripts launched by path, not via a bin. + They would inherit the variable from the `afx` that starts them; the explicit import makes each + process safe on its own (e.g. a Tower started by a dev script). + +### 2. Agent/terminal PTYs (node-pty) + +Harness PTYs go through `lib/pty-command.ts`, which already resolves a found command to its full +path. The open case is a command that does **not** resolve: node-pty then hands the bare name to +`CreateProcess`, and I have not yet verified that `CreateProcess`'s own search honours the +variable. In implement I test it with the same planted-file setup. If it does not, the fix is a +three-line check in `pty-command.ts`: an unresolved bare name throws ENOENT instead of reaching +node-pty. + +### 3. VS Code extension + +The extension host is shared with other extensions, so the extension must not set a process-wide +variable there. `apps/vscode/src/cli-process.ts` already resolves `codev`/`afx` with +`resolveSpawnable`; the only gap is the unresolved case, where it passes the bare name on. Fix: +on `win32`, refuse (ENOENT) when the name does not resolve on `PATH`. The `codev`/`afx` it starts +then set the variable themselves (step 1). + +### 4. Guard (static, every OS, runs in the existing unit job) + +`packages/codev/src/__tests__/process-bootstrap.test.ts`: +- every file in `packages/codev/bin/` and the two server entries has the hardening import as its + **first** import (so a new bin or a reordered import fails CI); +- the module sets the variable on `win32` and leaves `process.env` untouched elsewhere + (platform-injected). + +### 5. Windows behavioural test (`win32` only) + +`packages/codev/src/__tests__/windows-exe-search.test.ts` plants a `git.exe` (copy of +`%SystemRoot%\System32\hostname.exe`) in a temp worktree-shaped directory and runs a child +`node` process that does `execFileSync('git', …)`, `spawnSync` and `execSync('git --version')` +with that `cwd`: +1. **Control:** without the variable, the planted file runs (proves the plant works on the runner). +2. With the hardening module imported: `git version …` from `PATH`. +3. With Git removed from `PATH`: ENOENT; the planted file still never runs. +The child-process form keeps the test independent of the vitest worker's own environment (this +host's Claude Code shell already exports the variable, which hid the hazard in my first probe). + +### 6. Docs + +Remove the preview wording: `README.md:123` and `DEPENDENCIES.md:213, 262-267` in **both** +`codev/` and `codev-skeleton/` (kept byte-identical). The "only work in repositories you trust" +bullet becomes one sentence: Codev never runs a program from the current folder; it uses full +system paths or a `PATH`-only lookup. + +## Files to Change + +- `packages/codev/src/lib/process-bootstrap.ts` — new, the side-effect module +- `packages/codev/src/lib/platform/windows/exe-search.ts` — new, the Windows step it runs +- `packages/codev/bin/codev.js`, `afx.js`, `porch.js`, `consult.js`, `team.js`, `generate-image.js` — first import +- `packages/codev/src/agent-farm/servers/tower-server.ts`, `packages/codev/src/terminal/shellper-main.ts` — first import +- `packages/codev/src/lib/pty-command.ts` — only if the node-pty test shows it is needed +- `apps/vscode/src/cli-process.ts` — refuse an unresolved bare name on Windows +- `packages/codev/src/__tests__/process-bootstrap.test.ts` — new guard +- `packages/codev/src/__tests__/windows-exe-search.test.ts` — new Windows test +- `README.md`, `codev/DEPENDENCIES.md`, `codev-skeleton/DEPENDENCIES.md` — preview wording removed +- `codev/state/pir-1911_thread.md` — thread log + +## Risks & Alternatives Considered + +- **Risk: a Codev process that never loads an entry point** (e.g. a script run with `node + dist/…` directly, or a future server entry). Mitigated by the guard over `bin/` and the server + entries, and by inheritance: anything started from a hardened process inherits the variable + unless it is given a hand-built environment. Every persistent terminal Tower opens (architect, + builder, shell tab) is built from Tower's own environment, so all of them inherit it (owner + decision: no carve-out for human shells; `tower-lifecycle.windows.test.ts` covers it). The + non-persistent fallback starts from the `windowsPtyBaseEnv` allowlist, which sets the variable + explicitly (found by the PR consultation). +- **Risk: user-visible change in children.** Programs Codev starts inherit the variable, so a + `cmd.exe` session inside a Codev terminal would no longer run `foo.exe` from its current + folder by bare name (`.\foo` still works). PowerShell already behaves this way. Accepted as the + safer default; named in the PR. +- **Not covered:** a relative entry such as `.` in the user's own `PATH` is still searched. That is + the user's configuration and `cmd.exe` behaves the same. +- **Alternative: route every bare-name spawn through the host resolver** (the issue's stated fix, + and this plan's first draft): ~72 sites, a new spawn API, SDK changes, test-mock churn across + six or more files. Same protection; rejected by the owner as disproportionate. +- **Deferred, not dropped:** the issue's `commandExists` unification (three `which` forms, + including `doctor.ts`'s `which ${cmd}` string) and converting quoted `execSync`/`run()` shell + strings to argv. Neither is needed to close this hole; both are hygiene. Proposed as a + follow-up issue. +- **Out of scope:** the remaining single-site `isWindows()` forks (Spec 1658 A2.5) and the + IDE-server capability (#1890). + +## Test Plan + +- **Unit (all OS):** the guard; full `packages/codev` unit suite on this Windows host, recording + the Tower PID before and after and reporting any change; known #1923 load flakes re-run once. +- **Windows behavioural:** `windows-exe-search.test.ts` (control, PATH git, ENOENT). +- **node-pty check:** the planted-file probe for an unresolved PTY command (decides step 2). +- **Windows CI:** `gh workflow run windows.yml --ref builder/pir-1911 -f purpose='#1911 exe search hardening' -f suites=true`, run linked in the PR. +- **Manual (dev-approval, this host), from a shell with the variable unset:** + 1. In a scratch repo, commit a `git.exe` (copy of `hostname.exe`) at the root. + 2. `afx spawn` a builder for it, run `porch status` and `codev doctor` inside the worktree, then + `afx cleanup` it: everything behaves normally and nothing prints the host name. + 3. Same commands with Git removed from `PATH`: a clear "not found" error; the planted file never runs. +- **POSIX:** CI unit + e2e on Linux/macOS unchanged and green (the module is a no-op there). diff --git a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml new file mode 100644 index 0000000000..91a0a8cabe --- /dev/null +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -0,0 +1,30 @@ +id: '1911' +title: windows-bare-name-user-tool-sp +protocol: pir +phase: verified +plan_phases: [] +current_plan_phase: null +gates: + plan-approval: + status: approved + requested_at: '2026-11-20T10:52:59.449Z' + approved_at: '2026-11-20T10:59:56.889Z' + dev-approval: + status: approved + requested_at: '2026-11-22T22:31:34.590Z' + approved_at: '2026-11-22T23:02:25.946Z' + pr: + status: approved + requested_at: '2026-11-22T23:09:45.290Z' + approved_at: '2026-11-22T23:25:16.298Z' +iteration: 1 +build_complete: true +history: [] +started_at: '2026-11-20T10:37:24.033Z' +updated_at: '2026-11-22T23:25:19.529Z' +pr_history: + - phase: review + pr_number: 1948 + branch: builder/pir-1911 + created_at: '2026-11-22T23:03:58.238Z' +pr_ready_for_human: false diff --git a/codev/resources/arch.md b/codev/resources/arch.md index 0014c128b9..9b35a4437f 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -1076,6 +1076,17 @@ branches are testable on macOS/Linux. prompt (a `git fetch` / `git push` needing credentials) must be made non-interactive and fail instead, as `GitRefResolver`'s fetch (`GIT_TERMINAL_PROMPT=0`, a timeout) and porch's status push now are. +- **Process bootstrap and current-folder lookup** (#1911): every Codev process entry point (each + `bin/*.js`, `tower-server.ts`, `shellper-main.ts`) imports `lib/process-bootstrap.ts` as its + FIRST import; `process-bootstrap.test.ts` enforces it. Its one step today, on Windows, sets + `NoDefaultCurrentDirectoryInExePath=1` (`lib/platform/windows/exe-search.ts`), so a bare-name + spawn (`git`, `npm`) never resolves to a same-named file in the cwd (libuv and `cmd.exe` both + honor it; node-pty already searches `PATH` only). Children inherit it: every persistent + terminal Tower opens (architect, builder, shell tab) is built from Tower's own environment, and + the non-persistent fallback's `windowsPtyBaseEnv` allowlist sets it explicitly, so every + terminal carries it: in a `cmd.exe` terminal a current-folder program runs only as `.\name`. + The VS Code extension host is shared, so it does not set the variable; `cli-process.ts` + refuses an unresolved bare `codev`/`afx` name instead. - **Resolvers**: `lib/platform/windows/git-bash.ts` (Git Bash: override, then install paths, then `PATH`; never the System32 WSL launcher), `codev-sdk/node/executable` (`findExecutable` with `PATHEXT`, `resolveSpawnable` turns `.cmd` shims into `node ` or `%COMSPEC% /d /s /c`), diff --git a/codev/resources/lessons-learned.md b/codev/resources/lessons-learned.md index 7ce5aa4113..9cc4ef4ffa 100644 --- a/codev/resources/lessons-learned.md +++ b/codev/resources/lessons-learned.md @@ -480,6 +480,8 @@ Generalizable wisdom extracted from review documents, ordered by impact. Updated - [From #1869] **The browser run found what 65 unit and integration tests could not.** Every test passed while the workbench's sockets bypassed Tower and the IDE token sat in the cookie jar. Only a Playwright pass that recorded the actual WebSocket URLs and read `context.cookies()` exposed it. For a proxy feature, make "where does traffic really go" and "what lands in the jar" explicit acceptance assertions. - [From #1869] A user npm config with a SCOPED registry (`@cluesmith:registry=…`) makes `protocol-drift-audit.test.ts` ("registry unreachable") fail deterministically: a scoped registry overrides the test's `npm_config_registry` for `@cluesmith/*`, so `npm view` reaches the real registry. It is environmental (the cache is not the cause, and CI passes). Run with `NPM_CONFIG_USERCONFIG=`; never edit the user's `~/.npmrc`. - [From 1912] **When porch hides a failed check's output (#1801), vitest's own results cache names the failing files.** `packages/codev/node_modules/.vite/vitest/*/results.json` records each file's last pass/fail and duration, with no re-run, which matters under the machine-load rule. It identified three load-sensitive timeouts (agy-auth-cache, the pir-1233 and bugfix-1267 launch loops) that porch showed only as npm warnings. +- [From #1911] **A security control test must fail without the fix; run that control before trusting a pass.** Claude Code's shell already exports `NoDefaultCurrentDirectoryInExePath`, which hid the hazard from a naive probe; and a test that deleted it from a `{ ...process.env }` copy still passed with the fix removed, because the inherited key was `NODEFAULTCURRENTDIRECTORYINEXEPATH`. On Windows `process.env` is case-insensitive but a spread copy is not: delete by `key.toLowerCase()`. Both mistakes surfaced only by running the test with the fix taken out. +- [From #1911] **Persistent terminals outlive `tower stop` by design, so a test that opens them must end them in `finally`.** Three throwaway probe runs left ten shellper trees running after their isolated Towers exited. End every session the test Tower recorded in its `global.db` (not only the ones the test noted before an assertion failed), and confirm with a before/after count of the worktree's `shellper-main.js` processes. - [From 1912] A file-wide `vi.mock('node:child_process')` whose `spawn` is given `mockImplementation(actual.spawn)` in one test keeps that implementation for every later test in the file. Later lanes then spawn real binaries (EACCES here). Call `mockReset()` in `afterEach`, not just `mockClear()`. - [From #1920] **A fixture recorder that adds environment production does not add records a screen production never shows.** Spec 1658's ConPTY recorder set `TERM=xterm-256color` itself, so every capture drew claude's Unicode `❯` marker, while real architects (launched as bare `claude` with Tower's env and no `TERM`) drew the ASCII fallback `>`, and the gate held all their mail. The suite stayed green for exactly that reason. Record with the env the production launch path builds, and when a recorder must deviate, make it a named switch (`--bare-env`) so the production-shaped capture can still be taken. The quickest diagnosis was a read-only viewer attach to the held session: the replay frame IS the gate's mirror. diff --git a/codev/reviews/1911-windows-bare-name-user-tool-sp.md b/codev/reviews/1911-windows-bare-name-user-tool-sp.md new file mode 100644 index 0000000000..71fc18813c --- /dev/null +++ b/codev/reviews/1911-windows-bare-name-user-tool-sp.md @@ -0,0 +1,126 @@ +# PIR Review: Windows never runs a program from the current folder + +Fixes #1911 + +## Summary + +On Windows, a program started by bare name (`git`, `gh`, `npm`, `codev`) is looked up in the current folder before `PATH`, so a `git.exe` committed to a repository ran in place of Git whenever Codev ran `git` there. Every Codev process now imports `lib/process-bootstrap.ts` first, which on Windows sets `NoDefaultCurrentDirectoryInExePath=1` (`lib/platform/windows/exe-search.ts`); libuv and `cmd.exe` both honor it, and everything Codev starts inherits it, including every terminal Tower opens. With the hole closed, the native-Windows "preview" wording is removed from the README and both `DEPENDENCIES.md` copies. + +**What is covered:** + +- Every Codev process: the six commands (`codev`, `afx`, `porch`, `consult`, `team`, `generate-image`), the Tower server and shellper. A guard test fails if a new command does not import the bootstrap first. +- Everything those processes run, through inheritance (`child_process` spawns and `execSync` strings through `cmd.exe`). +- **Every terminal Tower opens**: architect and builder sessions (Claude Code, Codex, agy) and human shell tabs alike (owner decision: no carve-out). Persistent terminals are built from Tower's own environment; the non-persistent fallback (used only when shellper is unavailable) starts from the `windowsPtyBaseEnv` allowlist, which now sets the variable explicitly. +- The VS Code extension: its host is shared with other extensions, so it does not set the variable; instead `cli-process.ts` refuses a `codev`/`afx`/`porch` name that does not resolve on `PATH`, rather than letting Windows find a same-named file in the workspace. Spawn Builder then shows "afx was not found on PATH" instead of an unhandled error. + +**User-visible change (`cmd.exe`):** in a `cmd.exe` session inside a Codev terminal, a program in the current folder no longer runs by bare name; `.\name` still runs it. PowerShell, the default Windows shell, already works this way. Verified on the host: `cmd.exe` runs a planted `git.exe` by default, the real Git with the variable set, and the planted file again as `.\git`. + +**Known effect on other tools:** a .NET 10 NativeAOT `dotnet publish` fails inside a Codev terminal, because Visual Studio's `vcvarsall.bat` does not support the setting ([dotnet/runtime#129340](https://github.com/dotnet/runtime/issues/129340), closed as fixed in .NET 11; confirmed by reading the issue, not reproduced here). Documented in `DEPENDENCIES.md`; nothing else is done about it. + +**Not changed:** node-pty does its own `PATH`-only lookup and never searches the terminal's folder, so the PTY launch path needed nothing (measured: a bare unresolvable name fails with "File not found"). A relative `.` entry in the user's own `PATH` is still searched; that is the user's configuration. + +## Files Changed + +- `README.md` (+1 / -1) +- `apps/vscode/src/__tests__/cli-process.test.ts` (+44 / -2) +- `apps/vscode/src/__tests__/spawn-builder-not-found.test.ts` (new) +- `apps/vscode/src/cli-process.ts` (+34 / -2) +- `apps/vscode/src/commands/spawn.ts` ('error' listener) +- `codev-skeleton/DEPENDENCIES.md` (+8 / -7) +- `codev/DEPENDENCIES.md` (+8 / -7) +- `codev/plans/1911-windows-bare-name-user-tool-sp.md` (+147 / -0) +- `codev/resources/arch.md` (Platform Layer: process bootstrap) +- `codev/resources/lessons-learned.md` (Testing: two lessons) +- `codev/reviews/1911-windows-bare-name-user-tool-sp.md` (this file) +- `codev/state/pir-1911_thread.md` (+30 / -0) +- `packages/codev/bin/afx.js` (+2 / -0) +- `packages/codev/bin/codev.js` (+2 / -0) +- `packages/codev/bin/consult.js` (+2 / -0) +- `packages/codev/bin/generate-image.js` (+2 / -0) +- `packages/codev/bin/porch.js` (+2 / -0) +- `packages/codev/bin/team.js` (+2 / -0) +- `packages/codev/src/__tests__/process-bootstrap.test.ts` (+80 / -0) +- `packages/codev/src/__tests__/shell-launch.test.ts` (one assertion) +- `packages/codev/src/__tests__/tower-lifecycle.windows.test.ts` (+61 / -0) +- `packages/codev/src/__tests__/windows-exe-search.test.ts` (+83 / -0) +- `packages/codev/src/agent-farm/servers/tower-server.ts` (+2 / -0) +- `packages/codev/src/lib/platform/windows/exe-search.ts` (+25 / -0) +- `packages/codev/src/lib/platform/windows/pty-env.ts` (sets the variable in the fallback allowlist) +- `packages/codev/src/lib/process-bootstrap.ts` (+24 / -0) +- `packages/codev/src/terminal/shellper-main.ts` (+2 / -0) + +## Commits + +- `e145f3cb9` [PIR #1911] Terminal coverage test: end every recorded session in teardown +- `db8577b67` [PIR #1911] Thread: checks pass, back at dev-approval +- `53a1f3cba` [PIR #1911] Cover every Tower terminal: test it, correct the docs +- `663603ee9` [PIR #1911] Thread: checks pass, at dev-approval +- `f9d0c8b26` [PIR #1911] Thread: Node 22 runs, waiting on #1946 +- `3bef42211` [PIR #1911] Rename to lib/process-bootstrap.ts; move the Windows step to platform/windows/exe-search.ts +- `1cfb06b92` [PIR #1911] Thread: implement notes +- `1b16aeecd` [PIR #1911] Docs: native Windows is no longer a preview +- `4d54ae89e` [PIR #1911] VS Code: refuse a Codev CLI name that does not resolve on PATH +- `7d4d41f74` [PIR #1911] Set NoDefaultCurrentDirectoryInExePath first in every Codev entry point +- `20606082b` [PIR #1911] Plan revised: set NoDefaultCurrentDirectoryInExePath at entry points +- `b5865fe9f` [PIR #1911] Plan draft + +(Plus a merge of `main` for #1947 and porch's own `chore(porch)` commits.) + +## Test Results + +- `npm run build`: ✓ pass +- `npm test` (porch `tests` check, run alone on the host): ✓ pass. A direct run of the same suite after the `main` merge: 8123 passed, 247 skipped, plus the two #1923 flakes below, which pass on their own. +- VS Code suite: 1282 passed. +- New tests: + - `process-bootstrap.test.ts`: the bootstrap sets the variable on `win32` only; every `bin/` command and both server entries import it first. + - `windows-exe-search.test.ts` (Windows): plants a copy of `hostname.exe` as `git.exe`. Control: with the variable removed, `git` runs the planted file. Hardened: `execFileSync`, `spawnSync` and an `execSync` string all run the real Git. With Git off `PATH`: ENOENT, and the planted file still never runs. + - `tower-lifecycle.windows.test.ts`, new scenario: an isolated Tower started WITHOUT the variable opens a persistent builder terminal, a persistent API shell terminal and the dashboard's PowerShell shell tab; all three carry `NoDefaultCurrentDirectoryInExePath=1`. With the bootstrap import removed from `afx`, Tower and shellper, it fails (`unset`). Its teardown ends every session the test Tower recorded, pass or fail. + - `cli-process.test.ts`: an unresolved bare name on Windows is never spawned and fails as ENOENT; a resolved one still spawns. + - `spawn-builder-not-found.test.ts`: Spawn Builder turns that ENOENT into "afx was not found on PATH". + - `shell-launch.test.ts`: `windowsPtyBaseEnv` sets the variable even when the parent did not. +- Real user path: `porch init` in a repository containing a planted `git.exe`. Without the bootstrap the planted file ran (`Command failed: git add`, no commit); with it, the real Git made the commit. +- **Local verification ran on Node 24.13.0 (the implementation and first suite runs) and Node 22.23.4 (all runs after the owner switched to nvm-windows, including the final porch checks).** node-pty and better-sqlite3 were confirmed to load and work under 22 before the re-runs. +- Tower PID: unchanged across every full-suite run (37868 on the first session, 53132 after the Node switch). +- Windows CI (on-demand `windows.yml`): https://github.com/cluesmith/codev/actions/runs/45082298979 on the final commit (consultation fixes, `199c344d6` + porch state). Earlier green runs: 45080898387 (`e145f3cb9`), 45079432385 (`53a1f3cba`), 45078247361, 44725012668. +- Final local run after the consultation fixes (alone, Node 22.23.4): `npm run build` pass; `npm test` 8127 passed, 247 skipped, 0 failed; VS Code `cli-process` + Spawn Builder tests pass. No shellper left running afterwards. + +## Architecture Updates + +Routed to COLD `codev/resources/arch.md`, Platform Layer: a "Process bootstrap and current-folder lookup" bullet (every entry point imports `lib/process-bootstrap.ts` first; on Windows it sets `NoDefaultCurrentDirectoryInExePath`; children and every Tower terminal inherit it; the VS Code host refuses unresolved names instead). Not HOT: it changes behavior on one platform and is enforced by a guard test, so it does not need to be in every prompt. + +## Lessons Learned Updates + +Routed to COLD `codev/resources/lessons-learned.md`, Testing: + +- A security control test must fail without the fix; run that control before trusting a pass. Two traps hid the hazard here: Claude Code's shell already exports the variable, and on Windows a `{ ...process.env }` copy has case-sensitive keys, so deleting `NoDefaultCurrentDirectoryInExePath` missed the inherited `NODEFAULTCURRENTDIRECTORYINEXEPATH`. +- Persistent terminals outlive `tower stop`, so a test that opens them must end every session its Tower recorded, in `finally`, and confirm with a before/after process count. + +## Things to Look At During PR Review + +- **Consultation** (single pass): codex=COMMENT, claude=COMMENT. **Gemini did not run** (the `agy` CLI was not found on this host; porch recorded the skip as COMMENT). Acted on, with the architect's go-ahead: Claude found that the non-persistent fallback's `windowsPtyBaseEnv` allowlist lacked the variable, so a builder terminal created while shellper is unavailable kept the Windows default, contradicting "every terminal" in the docs (architect and shell-tab fallbacks pass Tower's full env and were covered). Fixed in `pty-env.ts` with a unit assertion. Also from Claude: Spawn Builder had no `'error'` listener, now shows "afx was not found on PATH"; nits (errno comment, the hand-listed `SERVER_ENTRY_POINTS` comment, a null check in the new scenario). Codex's .NET NativeAOT note was checked against dotnet/runtime#129340 and documented. +- **Every Tower terminal is covered, human shells included.** Earlier in the project I said terminals were built from the `windowsPtyBaseEnv` allowlist and would keep the Windows default. That was wrong: only the non-persistent fallback uses the allowlist (and it now sets the variable too); persistent terminals (architect, builder, shell tab) are built from Tower's environment. The owner chose to keep every terminal covered. Docs and plan now say so. +- **The `cmd.exe` behavior change** above is the one user-visible effect. PowerShell is unaffected. +- **Import order is the whole mechanism.** ESM evaluates imports before the module body, so the bootstrap must be the first import in each entry point. `process-bootstrap.test.ts` checks the first statement of each `bin/*.js` and both server entries; the bootstrap and `exe-search.ts` import nothing. +- **Tower and shellper imports are belt-and-braces.** Tower started by `afx` would inherit the variable anyway; the direct imports cover a Tower or shellper started some other way. +- **VS Code (`apps/vscode/src/cli-process.ts`)** returns a `ChildProcess` that emits an ENOENT-shaped error on the next tick (and `execCodevCli` rejects) when the resolver hands back an unresolved bare name. Callers already handle spawn errors. +- **Shell-string to argv conversion and `commandExists` unification were deliberately left out** of this PR (the plan's first draft proposed converting ~70 sites). With the variable set process-wide they are no longer needed to close the hole; they can be a follow-up if wanted. + +## How to Test Locally + +- **View diff**: VSCode sidebar → right-click builder pir-1911 → **View Diff** (auto-detects the repo's default branch) +- **Run dev**: VSCode sidebar → **Run Dev**, or `afx dev pir-1911` +- **What to verify** (native Windows): + - `npx vitest run src/__tests__/windows-exe-search.test.ts src/__tests__/process-bootstrap.test.ts` in `packages/codev`. + - `npx vitest run src/__tests__/tower-lifecycle.windows.test.ts -t 1911` (isolated Tower; leaves no shellpers behind). + - Real path: in a scratch repo, copy `C:\Windows\System32\hostname.exe` to `git.exe`, then run a Codev command that runs `git` there (e.g. `porch init`); the real Git runs. + - In a Codev `cmd.exe` terminal: `set NoDefaultCurrentDirectoryInExePath` prints `1`; a program in the folder runs only as `.\name`. + - Run your test shell with the variable removed (`env -u NoDefaultCurrentDirectoryInExePath` in Git Bash), since Claude Code's shell already exports it. + +## Flaky Tests (if any) + +All are recorded on #1923; each was left running, not skipped, and passed on its own or on re-run: + +- `packages/codev/src/commands/porch/__tests__/bugfix-1814-check-timeout.test.ts` ("a protocol.json timeout_ms reaches the runner and kills the check at that value"): 2574–3271 ms against a 2500 ms bound under load; blocked porch twice. Fixed on `main` by #1947 (#1946) and merged into this branch. +- `packages/codev/src/agent-farm/__tests__/launch-loop-exit-code.test.ts:49` ("still auto-restarts after a crash"): EBUSY / EPERM removing its temp folder in `afterEach`. +- `packages/codev/src/__tests__/tower-lifecycle.windows.test.ts`, scenario 4 ("a session survives tower stop/start", agent pid not alive after restart, under full-suite load) and scenario 5 (`read ECONNRESET` on Windows CI Node 22, run 44725012668; also failed on another branch before this change). +- One Vitest "Worker exited unexpectedly" unhandled error in a Node 22 full run, not tied to any test file. diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md new file mode 100644 index 0000000000..48340bd6ee --- /dev/null +++ b/codev/state/pir-1911_thread.md @@ -0,0 +1,31 @@ +# pir-1911 thread + +## 2026-11-20 — plan +- Re-inventoried with a TS-AST scan: 72 user-tool sites, not 36. The issue missed every agent-farm `run('git …')` shell string (19), tower-routes/tower-instances, porch checks/state, team-update, team-github, import.ts:59. +- Root hole beyond the sites: `resolveSpawnable` returns the bare name when it does not resolve on PATH, so libuv falls back to a cwd-first lookup. Same for relative PATH entries. Fix in the SDK resolver (fail closed, `found` flag), then every caller through `commandLaunch()`. +- No shell-string site uses pipes/redirects/||; only quoting. argv conversion is a straight swap. +- Static guard as a vitest AST test (like windows-console-spawn-guard), not a script. +- Plan at codev/plans/1911-windows-bare-name-user-tool-sp.md; waiting at plan-approval. + +## 2026-11-20 — plan revised (small version, owner direction) +- Measured: libuv and cmd.exe both honour `NoDefaultCurrentDirectoryInExePath` set in-process. My first draft's claim that libuv ignores it was untested and wrong. +- Gotcha: the Claude Code shell on this host already exports that variable, which masks the hazard in any naive probe. Tests must spawn a child with it unset as a control. +- New approach: a side-effect module imported first in every bin + tower-server + shellper-main; VS Code cli-process refuses unresolved bare names; node-pty unresolved case to be tested. +- Deferred to a follow-up: commandExists unification and shell-string-to-argv conversion. + +## 2026-11-20 — implement +- node-pty: does its own C++ lookup (path_util::get_shell_path), PATH only, no PATHEXT, never the terminal cwd. Unresolved bare names fail "File not found". pty-command.ts unchanged. +- Terminals get a hand-built env (windowsPtyBaseEnv allowlist), so they do NOT inherit the variable. Docs say so; told the architect. +- Real-path proof: `porch init` in a repo with a planted git.exe (variable unset). Without the hardening import: "Command failed: git add" and no commit, so the planted file ran. With it: real commit. `codev doctor` is NOT a good probe: it never runs bare git in the cwd. +- Windows CI dispatched: https://github.com/cluesmith/codev/actions/runs/44725012668 +- Full codev suite on this host: 8123 passed, 2 failed (load flakes, pass on re-run: launch-loop-exit-code EPERM temp cleanup; bugfix-1814-check-timeout 2574ms > 2500ms). Tower PID 37868 before and after. VS Code suite 1282 passed. +- Windows CI 44725012668: all green except Unit Node 22, tower-lifecycle scenario 5 ECONNRESET (also failed on pir-1919 run 44258108002 before this change; passes 3/3 locally). Re-ran the failed job. +- porch tests check blocked twice by bugfix-1814-check-timeout under load (2574/3271/2690ms vs 2500); asked the architect. +- Owner asked for a generic name: renamed to lib/process-bootstrap.ts (general first-run setup); the Windows step moved to lib/platform/windows/exe-search.ts. Guard test renamed process-bootstrap.test.ts. Build, tsc and both tests pass. +- Node switched to nvm (22.23.4). Commands run with PATH prefix C:\nvm4w\nodejs and npm_config_script_shell=Git Bash (architect ruling, my commands only). node-pty and better-sqlite3 load and work on 22. +- porch done x2 alone on Node 22: build pass; tests fail only on bugfix-1814 (2767ms); one Vitest worker-exit unhandled error. Tower PID 53132 unchanged. Owner: test fixed in #1946; wait, then merge main and re-run porch done. +- Merged origin/main (#1947 timing-test fix). porch done #1: build pass, tests fail on 2 known #1923 flakes (tower-lifecycle scenario 4: agent pid not alive after restart; launch-loop-exit-code EBUSY on temp rmdir); both pass alone (5/5, 3/3). porch done #2: build + tests pass. Tower PID 53132 before and after. Gate dev-approval pending. +- Owner decision (option A): every Tower terminal carries the variable. Earlier claim that terminals use the windowsPtyBaseEnv allowlist was wrong: persistent terminals get Tower's env. New test in tower-lifecycle.windows.test.ts (builder, API shell, dashboard shell tab); control with the bootstrap removed fails ('unset'), with it passes. Gotcha: the test env had the variable as NODEFAULTCURRENTDIRECTORYINEXEPATH, so a plain delete missed it; the test removes it case-insensitively. Docs and plan corrected; cmd.exe change named (.\name still works; PowerShell already behaves so). +- porch done alone after terminal-coverage change: build + tests pass. Tower PID 53132 before/after. Windows CI 45078247361 green (pre-terminal-test); new run dispatched on 53a1f3cba. At dev-approval. +- Architect: 10 leaked shellpers (3 trees per run) from my worktree dist. Cause: my temporary probe tests (09:34-09:40) never ended their sessions. Verified each (my dist, codev-1658-tower test socket, parent gone) and ended all 10 trees (3 processes each); 0 left. Hardened the scenario teardown: end every shellper the isolated Tower recorded in its DB plus those seen, in finally. Counts after a passing run and a forced-failure run: 0 shellpers, 0 probes. +- PR #1948 consultation: codex/claude COMMENT, gemini skipped (agy not found). Architect go-ahead: windowsPtyBaseEnv now sets the variable (non-persistent fallback covered) + unit assertion; VS Code Spawn Builder 'error' listener ('afx was not found on PATH') + test; nits. dotnet/runtime#129340 confirmed real (closed, fixed in .NET 11): one sentence in docs and PR. diff --git a/packages/codev/bin/afx.js b/packages/codev/bin/afx.js index 42e9b8e9dc..f5cbe0cee3 100755 --- a/packages/codev/bin/afx.js +++ b/packages/codev/bin/afx.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; // afx - Agent Farm CLI (standalone command) // Issue #846: imports runAgentFarm directly. The `codev afx` / `codev agent-farm` diff --git a/packages/codev/bin/codev.js b/packages/codev/bin/codev.js index fc9510cd05..4e9e45ebba 100755 --- a/packages/codev/bin/codev.js +++ b/packages/codev/bin/codev.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; // Main codev CLI entry point import('../dist/cli.js'); diff --git a/packages/codev/bin/consult.js b/packages/codev/bin/consult.js index 7b689c043d..268da84ac4 100755 --- a/packages/codev/bin/consult.js +++ b/packages/codev/bin/consult.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; // consult - AI consultation CLI (standalone command) process.env.CODEV_STANDALONE = 'consult'; diff --git a/packages/codev/bin/generate-image.js b/packages/codev/bin/generate-image.js index f7be92727a..30781b3dcf 100755 --- a/packages/codev/bin/generate-image.js +++ b/packages/codev/bin/generate-image.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; // generate-image is shorthand for codev generate-image import { run } from '../dist/cli.js'; diff --git a/packages/codev/bin/porch.js b/packages/codev/bin/porch.js index 0720343158..d23cf550ac 100755 --- a/packages/codev/bin/porch.js +++ b/packages/codev/bin/porch.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; /** * Porch CLI - Protocol Orchestrator diff --git a/packages/codev/bin/team.js b/packages/codev/bin/team.js index 86652a61c9..cb11f29a4b 100755 --- a/packages/codev/bin/team.js +++ b/packages/codev/bin/team.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: per-process setup that must run before anything else (#1911). +import '../dist/lib/process-bootstrap.js'; // team - Team coordination CLI (standalone command) process.env.CODEV_STANDALONE = 'team'; diff --git a/packages/codev/src/__tests__/process-bootstrap.test.ts b/packages/codev/src/__tests__/process-bootstrap.test.ts new file mode 100644 index 0000000000..13699fe646 --- /dev/null +++ b/packages/codev/src/__tests__/process-bootstrap.test.ts @@ -0,0 +1,84 @@ +/** + * Every Codev process runs `lib/process-bootstrap.ts` before any other code. + * + * Its one step today (#1911) sets `NoDefaultCurrentDirectoryInExePath` on + * Windows, which only protects a process that loads it before its first spawn, + * so each process entry point must import the bootstrap FIRST: every installed command in + * `bin/` and the two scripts Tower starts by path. Static, so it runs on every OS. + * The behaviour itself is proven on Windows by `windows-exe-search.test.ts`. + */ + +import { describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; +import { bootstrapProcess } from '../lib/process-bootstrap.js'; +import { NO_CWD_EXE_SEARCH_ENV } from '../lib/platform/windows/exe-search.js'; + +const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); + +/** + * Process entry points that are not `bin/` commands, with the specifier each must import first. + * Hand-listed (the bins are derived from package.json): add any new script Codev starts by path. + * A process started from a hardened one is covered anyway, because it inherits the variable. + */ +const SERVER_ENTRY_POINTS: Record = { + 'src/agent-farm/servers/tower-server.ts': '../../lib/process-bootstrap.js', + 'src/terminal/shellper-main.ts': '../lib/process-bootstrap.js', +}; +const BIN_SPECIFIER = '../dist/lib/process-bootstrap.js'; + +/** The module specifier of the first `import` declaration in a file, or null. */ +function firstImport(file: string): string | null { + const text = fs.readFileSync(path.join(PACKAGE_ROOT, file), 'utf8'); + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); + for (const statement of source.statements) { + if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { + return statement.moduleSpecifier.text; + } + } + return null; +} + +/** The first top-level statement, so nothing (even a side effect) runs ahead of the import. */ +function firstStatementIsImport(file: string): boolean { + const text = fs.readFileSync(path.join(PACKAGE_ROOT, file), 'utf8'); + const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); + return source.statements.length > 0 && ts.isImportDeclaration(source.statements[0]); +} + +describe('bootstrapProcess', () => { + it('turns off the current-folder lookup on Windows', () => { + const env: NodeJS.ProcessEnv = {}; + bootstrapProcess('win32', env); + expect(env).toEqual({ [NO_CWD_EXE_SEARCH_ENV]: '1' }); + }); + + it.each(['linux', 'darwin'] as const)('leaves the environment alone on %s', (platform) => { + const env: NodeJS.ProcessEnv = { PATH: '/usr/bin' }; + bootstrapProcess(platform, env); + expect(env).toEqual({ PATH: '/usr/bin' }); + }); +}); + +describe('every Codev entry point loads the bootstrap first', () => { + const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')) as { bin: Record }; + const bins = Object.values(pkg.bin).map((p) => path.posix.normalize(p)); + + it('covers every installed command', () => { + const onDisk = fs.readdirSync(path.join(PACKAGE_ROOT, 'bin')).filter((f) => f.endsWith('.js')).map((f) => `bin/${f}`); + expect(bins.sort()).toEqual(onDisk.sort()); + expect(bins.length).toBeGreaterThanOrEqual(6); + }); + + it.each(bins)('%s', (bin) => { + expect(firstStatementIsImport(bin)).toBe(true); + expect(firstImport(bin)).toBe(BIN_SPECIFIER); + }); + + it.each(Object.entries(SERVER_ENTRY_POINTS))('%s', (file, specifier) => { + expect(firstStatementIsImport(file)).toBe(true); + expect(firstImport(file)).toBe(specifier); + }); +}); diff --git a/packages/codev/src/__tests__/shell-launch.test.ts b/packages/codev/src/__tests__/shell-launch.test.ts index 0107508b22..2c7db27a42 100644 --- a/packages/codev/src/__tests__/shell-launch.test.ts +++ b/packages/codev/src/__tests__/shell-launch.test.ts @@ -34,6 +34,7 @@ import { import { windowsPowerShellPath } from '../lib/platform.js'; import { ptyCommand } from '../lib/pty-command.js'; import { windowsPtyBaseEnv } from '../lib/platform/windows/pty-env.js'; +import { NO_CWD_EXE_SEARCH_ENV } from '../lib/platform/windows/exe-search.js'; import { defaultInteractiveShell, windowsSystem32Path } from '../lib/platform.js'; import { getDefaultConfig } from '../lib/config.js'; import { forceHostPlatform } from './helpers/host-platform.js'; @@ -227,6 +228,11 @@ describe('windowsPtyBaseEnv', () => { expect(base.SECRET_TOKEN).toBeUndefined(); }); + it('turns off the current-folder program lookup even when the parent did not (#1911)', () => { + const base = windowsPtyBaseEnv({ Path: 'C:\\Windows\\system32' }); + expect(base[NO_CWD_EXE_SEARCH_ENV]).toBe('1'); + }); + it('keeps an explicit HOME', () => { expect(windowsPtyBaseEnv({ USERPROFILE: 'C:\\Users\\dev', HOME: 'D:\\home' }).HOME).toBe('D:\\home'); }); diff --git a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts index 1e34da08a8..ace64c0083 100644 --- a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts +++ b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts @@ -24,6 +24,7 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import Database from 'better-sqlite3'; import { TOWER_KEY_HEADER } from '@cluesmith/codev-types'; +import { encodeWorkspacePath } from '@cluesmith/codev-sdk/workspace'; import { WindowsJobHelper, sessionJobName } from '../lib/platform/windows/job-objects.js'; import { killSessionTree } from '../lib/process-tree.js'; @@ -47,6 +48,13 @@ process.stdin.on('data', (d) => process.stdout.write('ECHO:' + d.trim() + '\\r\\ setInterval(() => {}, 1000); `); +/** Prints whether the terminal's environment carries the #1911 variable, then idles. */ +const envProbeScript = path.join(workDir, 'env-probe.cjs'); +fs.writeFileSync(envProbeScript, ` +process.stdout.write('NDC[' + (process.env.NoDefaultCurrentDirectoryInExePath ?? 'unset') + ']\\r\\n'); +setInterval(() => {}, 1000); +`); + interface IsolatedTower { stateDir: string; port: number; @@ -346,6 +354,61 @@ describe.skipIf(!onWindows)('Tower lifecycle on native Windows', () => { await endSession(shellperPid); }, 300_000); + it('#1911: every persistent terminal, agent and human shell, runs with the current-folder program lookup off', async () => { + const tower = await isolatedTower(); + // Tower must set it itself: some launching shells (Claude Code's) already export it, + // possibly in another case (`tower.env` is a plain copy, so its keys are case-sensitive). + for (const key of Object.keys(tower.env)) { + if (key.toLowerCase() === 'nodefaultcurrentdirectoryinexepath') delete tower.env[key]; + } + expect(afxRun(tower, ['tower', 'start']).code).toBe(0); + const towerPid = ownerPid(tower); + expect(towerPid).not.toBeNull(); + leftovers.push(towerPid!); + const shellperPids: number[] = []; + const db = new Database(path.join(tower.stateDir, 'global.db'), { readonly: true }); + const shellperOf = (id: string) => (db.prepare('SELECT shellper_pid FROM terminal_sessions WHERE id = ?').get(id) as { shellper_pid: number }).shellper_pid; + + try { + // An agent terminal and an API-created shell terminal, each running the probe. + for (const type of ['builder', 'shell'] as const) { + const created = await api(tower, 'POST', '/api/terminals', { + command: process.execPath, args: [envProbeScript], cwd: workDir, persistent: true, + workspacePath: workDir, type, roleId: `ndc-${type}`, label: `ndc-${type}`, + }); + expect(created.status, JSON.stringify(created.json)).toBe(201); + expect(created.json.persistent).toBe(true); + const id = created.json.id as string; + shellperPids.push(shellperOf(id)); + await waitFor(async () => /NDC\[/.test(await output(tower, id)), 30_000, `the ${type} probe`); + expect((await output(tower, id)).match(/NDC\[([^\]]*)\]/)?.[1], type).toBe('1'); + } + + // The dashboard's shell tab (Windows PowerShell by default): ask the shell itself. + const tab = await api(tower, 'POST', `/workspace/${encodeWorkspacePath(workDir)}/api/tabs/shell`); + expect(tab.status, JSON.stringify(tab.json)).toBe(200); + expect(tab.json.persistent).toBe(true); + const tabId = tab.json.terminalId as string; + shellperPids.push(shellperOf(tabId)); + // The typed line echoes as `'NDC=' + ...`; only the shell's answer reads `NDC=1=END`. + const ask = "Write-Output ('NDC=' + $env:NoDefaultCurrentDirectoryInExePath + '=END')\r"; + await waitFor(async () => { + await api(tower, 'POST', `/api/terminals/${tabId}/write`, { data: ask }); + await new Promise((r) => setTimeout(r, 1000)); + return /NDC=[^=']*=END/.test(await output(tower, tabId)); + }, 60_000, 'the shell tab to answer'); + expect((await output(tower, tabId)).match(/NDC=([^=']*)=END/)?.[1]).toBe('1'); + } finally { + // Persistent sessions outlive `tower stop` by design: end every one this Tower + // recorded, plus any seen before an assertion failed, with their process trees. + const recorded = (db.prepare('SELECT shellper_pid FROM terminal_sessions WHERE shellper_pid IS NOT NULL').all() as Array<{ shellper_pid: number }>) + .map((row) => row.shellper_pid); + db.close(); + afxRun(tower, ['tower', 'stop']); + for (const pid of new Set([...shellperPids, ...recorded])) await endSession(pid); + } + }, 300_000); + it('scenario 5: a row whose shellper pid was reused is refused and removed, and the pid is never signaled', async () => { const tower = await isolatedTower(); expect(afxRun(tower, ['tower', 'start']).code).toBe(0); diff --git a/packages/codev/src/__tests__/windows-exe-search.test.ts b/packages/codev/src/__tests__/windows-exe-search.test.ts new file mode 100644 index 0000000000..ce08eae298 --- /dev/null +++ b/packages/codev/src/__tests__/windows-exe-search.test.ts @@ -0,0 +1,83 @@ +/** + * Issue #1911, on Windows: a `git.exe` planted in the folder Codev runs `git` + * from must never run. + * + * Plants a copy of `hostname.exe` named `git.exe` in a worktree-shaped temp + * folder and runs `git` there the three ways Codev does (`execFileSync`, + * `spawnSync`, an `execSync` string through `cmd.exe`). The control case runs + * with the protection off and must hit the planted file, so the test proves the + * hazard is real on the runner before proving the fix. (Some shells, Claude + * Code's among them, already export the variable; the control removes it.) + */ + +import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest'; +import { execFileSync, execSync, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { hardenExeSearch, NO_CWD_EXE_SEARCH_ENV } from '../lib/platform/windows/exe-search.js'; + +const isWindows = process.platform === 'win32'; + +describe.skipIf(!isWindows)('a planted git.exe in the cwd never runs (Windows)', () => { + let worktree: string; + let saved: string | undefined; + const hostname = os.hostname().toLowerCase(); + + /** What `git` printed when run with no arguments in the planted folder. */ + function bareGitOutput(env: NodeJS.ProcessEnv = process.env): string { + const result = spawnSync('git', [], { cwd: worktree, env, encoding: 'utf8', windowsHide: true }); + return `${result.stdout ?? ''}${result.stderr ?? ''}`.trim().toLowerCase(); + } + + beforeAll(() => { + saved = process.env[NO_CWD_EXE_SEARCH_ENV]; + worktree = fs.mkdtempSync(path.join(os.tmpdir(), 'codev-1911-')); + fs.mkdirSync(path.join(worktree, '.git')); + const hostnameExe = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'hostname.exe'); + fs.copyFileSync(hostnameExe, path.join(worktree, 'git.exe')); + }); + + afterEach(() => { + delete process.env[NO_CWD_EXE_SEARCH_ENV]; + if (saved !== undefined) { + process.env[NO_CWD_EXE_SEARCH_ENV] = saved; + } + }); + + afterAll(() => { + fs.rmSync(worktree, { recursive: true, force: true }); + }); + + it('control: with the protection off, Windows runs the planted file', () => { + delete process.env[NO_CWD_EXE_SEARCH_ENV]; + expect(bareGitOutput()).toBe(hostname); + }); + + it('hardened: execFileSync, spawnSync and an execSync string all run the PATH git', () => { + delete process.env[NO_CWD_EXE_SEARCH_ENV]; + hardenExeSearch(process.env); + const options = { cwd: worktree, encoding: 'utf8' as const, windowsHide: true }; + expect(execFileSync('git', ['--version'], options)).toMatch(/^git version /); + expect(spawnSync('git', ['--version'], options).stdout).toMatch(/^git version /); + expect(execSync('git --version', options)).toMatch(/^git version /); + expect(bareGitOutput()).not.toBe(hostname); + }); + + it('hardened, Git missing from PATH: the spawn fails and the planted file still never runs', () => { + delete process.env[NO_CWD_EXE_SEARCH_ENV]; + hardenExeSearch(process.env); + const pathKey = Object.keys(process.env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH'; + const withoutGit = (process.env[pathKey] ?? '') + .split(path.delimiter) + .filter((dir) => !fs.existsSync(path.join(dir, 'git.exe'))) + .join(path.delimiter); + const env = { ...process.env, [pathKey]: withoutGit }; + + const result = spawnSync('git', ['--version'], { cwd: worktree, env, encoding: 'utf8', windowsHide: true }); + expect((result.error as NodeJS.ErrnoException | undefined)?.code).toBe('ENOENT'); + expect(() => execFileSync('git', ['--version'], { cwd: worktree, env, windowsHide: true, stdio: 'pipe' })) + .toThrow(expect.objectContaining({ code: 'ENOENT' })); + expect(bareGitOutput(env)).not.toBe(hostname); + }); +}); diff --git a/packages/codev/src/agent-farm/servers/tower-server.ts b/packages/codev/src/agent-farm/servers/tower-server.ts index 8be507f037..f9f9fbc633 100644 --- a/packages/codev/src/agent-farm/servers/tower-server.ts +++ b/packages/codev/src/agent-farm/servers/tower-server.ts @@ -8,6 +8,8 @@ * delegates HTTP request handling to tower-routes.ts. */ +// First: per-process setup that must run before anything else (#1911). +import '../../lib/process-bootstrap.js'; import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/codev/src/lib/platform/windows/exe-search.ts b/packages/codev/src/lib/platform/windows/exe-search.ts new file mode 100644 index 0000000000..4fb0d4ba3e --- /dev/null +++ b/packages/codev/src/lib/platform/windows/exe-search.ts @@ -0,0 +1,25 @@ +/** + * Windows: never run a program from the current folder (#1911). + * + * On Windows a program started by bare name (`git`, `gh`, `npm`, `codev`) is + * looked up in the current directory before `PATH`, by libuv for + * `child_process` spawns and by `cmd.exe` for `exec` strings. Codev runs those + * commands with a builder worktree or a cloned repository as the cwd, so a + * `git.exe` committed to a repository would run instead of Git. + * + * `NoDefaultCurrentDirectoryInExePath` turns that lookup off: libuv reads it + * from the calling process's environment, `cmd.exe` from its inherited one, + * and every child inherits it. A tool missing from `PATH` then fails with + * ENOENT instead of running the planted file. (node-pty does its own PATH-only + * lookup and never searches the terminal's cwd.) + * + * Applied once per process by `lib/process-bootstrap.ts`, which every Codev + * entry point imports first. Imports nothing, so loading it spawns nothing. + */ + +export const NO_CWD_EXE_SEARCH_ENV = 'NoDefaultCurrentDirectoryInExePath'; + +/** Turn off the current-folder program lookup for this process and its children. */ +export function hardenExeSearch(env: NodeJS.ProcessEnv): void { + env[NO_CWD_EXE_SEARCH_ENV] = '1'; +} diff --git a/packages/codev/src/lib/platform/windows/pty-env.ts b/packages/codev/src/lib/platform/windows/pty-env.ts index f6eb8826a0..fbb18681ba 100644 --- a/packages/codev/src/lib/platform/windows/pty-env.ts +++ b/packages/codev/src/lib/platform/windows/pty-env.ts @@ -39,5 +39,9 @@ export function windowsPtyBaseEnv(env: Record): Reco if (home !== undefined) { base.HOME = home; } + // #1911: never run a program from the current folder, also in a terminal built + // from this allowlist (the non-persistent fallback when shellper is unavailable). + // The name is NO_CWD_EXE_SEARCH_ENV in `exe-search.ts`; spelled out to stay a leaf. + base.NoDefaultCurrentDirectoryInExePath = '1'; return base; } diff --git a/packages/codev/src/lib/process-bootstrap.ts b/packages/codev/src/lib/process-bootstrap.ts new file mode 100644 index 0000000000..4cbbec7def --- /dev/null +++ b/packages/codev/src/lib/process-bootstrap.ts @@ -0,0 +1,24 @@ +/** + * Process bootstrap: setup that must run in every Codev process before any + * other code. + * + * This is a side-effect module. Every Codev process entry point (each + * `bin/*.js`, `tower-server.ts`, `shellper-main.ts`) imports it FIRST, so it + * runs before any other module loads; `process-bootstrap.test.ts` enforces the + * import order. Keep it, and everything it imports, free of other imports and + * of anything that spawns, so nothing can run ahead of it. + * + * Today it holds one step: on Windows, never run a program from the current + * folder (#1911, `platform/windows/exe-search.ts`). + */ + +import { hardenExeSearch } from './platform/windows/exe-search.js'; + +/** Apply every bootstrap step for the given platform to the given environment. */ +export function bootstrapProcess(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): void { + if (platform === 'win32') { + hardenExeSearch(env); + } +} + +bootstrapProcess(process.platform, process.env); diff --git a/packages/codev/src/terminal/shellper-main.ts b/packages/codev/src/terminal/shellper-main.ts index 19e68c73ee..d4f9241072 100644 --- a/packages/codev/src/terminal/shellper-main.ts +++ b/packages/codev/src/terminal/shellper-main.ts @@ -23,6 +23,8 @@ * from this process's environment before anything else runs. */ +// First: per-process setup that must run before anything else (#1911). +import '../lib/process-bootstrap.js'; import fs from 'node:fs'; import path from 'node:path'; import { createRequire } from 'node:module';