From 5c9573f14d99a092e19a09c577485633d8d96578 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 21:37:24 +1100 Subject: [PATCH 01/28] chore(porch): 1911 init pir --- .../status.yaml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml 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 000000000..0ccc4ea88 --- /dev/null +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -0,0 +1,18 @@ +id: '1911' +title: windows-bare-name-user-tool-sp +protocol: pir +phase: plan +plan_phases: [] +current_plan_phase: null +gates: + plan-approval: + status: pending + dev-approval: + status: pending + pr: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-20T10:37:24.033Z' +updated_at: '2026-11-20T10:37:24.035Z' From b5865fe9fc0c0bff3f2cd6c4e91cc9365fa8ff6e Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 21:52:52 +1100 Subject: [PATCH 02/28] [PIR #1911] Plan draft --- .../1911-windows-bare-name-user-tool-sp.md | 267 ++++++++++++++++++ codev/state/pir-1911_thread.md | 8 + 2 files changed, 275 insertions(+) create mode 100644 codev/plans/1911-windows-bare-name-user-tool-sp.md create mode 100644 codev/state/pir-1911_thread.md 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 000000000..5f446b881 --- /dev/null +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -0,0 +1,267 @@ +# PIR Plan: Windows user-tool lookup hardening (#1911) + +## Understanding + +On Windows, a program started by **bare name** is looked up in the current directory before +`PATH`: libuv does this for `child_process.spawn/execFile*` (`search_path` tries the cwd first), +and `cmd.exe` does it for every `exec`/`execSync` string. Codev runs `git`, `gh`, `npm`, `npx`, +`codev`, `porch` and friends with a builder worktree, a workspace, or a freshly cloned repository +as the cwd, so a `git.exe` committed to that repository runs under Codev instead of Git. +Spec 1658 fixed the system programs (System32 full paths); this issue fixes the user tools, +and with it native Windows leaves preview (README, both `DEPENDENCIES.md`). + +### What the re-grep found (issue inventory is stale) + +I re-inventoried with a TypeScript-AST scan of every non-test `.ts` under `packages/codev/src` +(every `exec/execSync/execFile/execFileSync/spawn/spawnSync`, promisified `execAsync` / +`execFileAsync`, agent-farm `run()`, and `commandLaunch().spawn*` call whose command is a string +literal or template). **72 user-tool sites**, against the issue's 36. The issue missed every +agent-farm `run('git …')` shell string (19, in `cleanup.ts`, `spawn-worktree.ts`, `spawn.ts`, +`utils/git.ts`), `tower-routes.ts`, `tower-instances.ts`, `team-update.ts`, `porch/checks.ts`, +`porch/state.ts`, `team-github.ts`, `import.ts:59`, and the `commandLaunch().spawn` sites. + +**Direct `child_process` sites (67) — must be converted:** + +- `agent-farm/commands/cleanup.ts`: 193, 228, 247, 261, 411, 495 `run(git …)` — **193 runs with the builder worktree as cwd** +- `agent-farm/commands/self-refresh.ts`: 484 `execFileSync(git)` +- `agent-farm/commands/spawn-worktree.ts`: 222, 230, 332, 337, 374, 382, 398, 404, 426, 458, 462 `run(git …)`; 282 `run(gh …)`; 490 `run(porch …)` (cwd = new worktree); 791 `execSync(git …)` (cwd = worktree) +- `agent-farm/commands/spawn.ts`: 958 `run(git …)` +- `agent-farm/commands/team.ts`: 26; `team-update.ts`: 37 `execSync(git …)` +- `agent-farm/servers/tower-routes.ts`: 2912 `execAsync(codev init …)`, 4056 `execAsync(git status …)` (cwd = workspace) +- `agent-farm/servers/tower-instances.ts`: 523 `execAsync(npx codev adopt …)` (cwd = an **arbitrary, not-yet-adopted directory**) +- `agent-farm/utils/config.ts`: 44 `execSync(git …)`; `utils/git.ts`: 33 `run(git …)` +- `commands/consult/index.ts`: 2048, 2049, 2217, 2234, 2249, 2254, 2359, 2753, 2786 `execFileSync(git)`; 2483, 2534, 2649 `execSync(git …)` +- `commands/doctor.ts`: 1154 `spawnSync(git)` +- `commands/import.ts`: 59 `execSync(git clone …)` +- `commands/init.ts`: 176 `execSync(git init)`, 192 `execSync(codev doctor)` (cwd = new project) +- `commands/porch/artifacts.ts`: 397, 421, 434, 466 `execFileSync(git)` +- `commands/porch/checks.ts`: 423; `porch/state.ts`: 205, 206, 209 `execFileAsync(git)` +- `lib/default-branch.ts`: 15 `execSync(git …)` +- `lib/github.ts`: 288 `execFile(gh)` +- `lib/gitignore.ts`: 168, 218 `spawnSync(git)` +- `lib/governance-bootstrap.ts`: 254, 275 `execFileSync(git)` +- `lib/protocol-drift-audit.ts`: 200 `spawnSync(npm)` +- `lib/team-github.ts`: 95 `execFileAsync(git)` +- `lib/tree-snapshot.ts`: 91, 107, 125, 184, 359 `execFileSync(git)` + +**Already routed through the resolver, but not safe (5 + the pty path):** the architect's list — +`commands/import.ts:292` (`claude`), `agent-farm/commands/ide.ts:155/325` (`npm`), +`lib/agent-process.ts:32` — plus `bench.ts:100`, `bootstrap-docs.ts:287` (`consult`), +`porch/index.ts:711` (`afx`), `tower.ts:366` (`npx`/`node`) and `lib/pty-command.ts:26` (every +harness PTY) go through `commandLaunch().spawn*` / `spawnableOnHost` / `resolveSpawnable`. +The root problem there is in the resolver itself: +`packages/sdk/src/node/executable.ts:270-273` — when a name **does not resolve** on `PATH`, +`resolveSpawnable` returns the bare name unchanged, so the spawn falls back to libuv's lookup, +**which checks the cwd first**. "git not on PATH, but `git.exe` in the repo" therefore still runs +the planted file. These sites are **in scope**; they are fixed once, in the resolver, not per +site. `lib/agent-process.ts` itself is already safe when it gets a full path +(`resolveClaudeBin()` returns an absolute path), and is covered by the same fix for other launches. + +A second resolver hole: `findAllExecutables` (`executable.ts:152`) honours **relative** `PATH` +entries (`.`, `bin`), which resolve against the cwd. That is the same attack through `PATH`. + +**POSIX-only tools (out of scope to change; confirmed unreachable on Windows in implement):** +`ps` (cleanup.ts:90, architect-session-holder.ts:94, tower-utils.ts:252, posix/processes.ts:56/80, +session-manager.ts:1150), `pgrep` (tower.ts:470/486), `tail` (tower.ts:603), `lsof` +(posix/processes.ts:139), `sysctl`/`lscpu`/`free` (bench.ts:50/54/72/77), `du` +(migration-backup-audit.ts:79), `command -v` (consult/index.ts:1435), `which` (the five +`commandExists` probes, removed below). Each gets a `// user-tool: posix-only ()` annotation +checked by the guard, so a future refactor that makes one reachable on Windows is visible. + +### Shell-string sites and their shell features (architect point 3) + +Every shell-string user-tool site, and whether it relies on a shell feature. **None uses pipes, +redirects, `||`/`&&`, globbing or variable expansion.** The only shell feature in use is +double-quote quoting of interpolated values (and whitespace word-splitting), which the argv form +replaces exactly — and more safely: today a branch, path or remote containing `"`, `$` or +backticks is shell-interpreted. + +| Site | Command | Shell feature used | argv form | +|---|---|---|---| +| cleanup.ts:193 | `git status --porcelain` | none | `['status','--porcelain']` | +| cleanup.ts:228 | `git push origin --delete "${branch}"` | quoting | `['push','origin','--delete',branch]` | +| cleanup.ts:247 | `git worktree remove "${p}" --force` | quoting | `['worktree','remove',p,'--force']` | +| cleanup.ts:261, 495; spawn.ts:958 | `git worktree prune` | none | `['worktree','prune']` | +| cleanup.ts:411 | `git branch -D "${b}"` | quoting | `['branch','-D',b]` | +| spawn-worktree.ts:222 | `git branch ${branchName}` | word-split (unquoted, single token) | `['branch',branchName]` | +| spawn-worktree.ts:230 | `git worktree add "${p}" ${branchName}` | quoting + word-split | `['worktree','add',p,branchName]` | +| spawn-worktree.ts:282 | `gh pr list --head "${b}" --json … --state open` | quoting | argv | +| spawn-worktree.ts:332 / 337 | `git remote get-url "${n}"` / `git remote add "${n}" "${url}"` | quoting | argv | +| spawn-worktree.ts:374 / 398 | `git fetch "${r}"` [`"${b}"`] | quoting | argv | +| spawn-worktree.ts:382 / 404 | `git ls-remote --heads "${r}" "${b}"` | quoting | argv | +| spawn-worktree.ts:426 | `git worktree list --porcelain` | none | argv | +| spawn-worktree.ts:458 / 462 | `git worktree add "${p}" [-b "${b}" "${r}/${b}"]` | quoting | argv | +| spawn-worktree.ts:490 | `porch init ${proto} ${id} "${name}"` | quoting + word-split (proto/id pre-sanitised to one token) | `['init',proto,id,name]` | +| spawn-worktree.ts:791 | `git update-index --skip-worktree "${rel}"` | quoting | argv | +| team-update.ts:37 | `git log --oneline --since="${since}" --all --grep="spawn" -i` | quoting inside `--opt="…"` | `['log','--oneline',`--since=${since}`,'--all','--grep=spawn','-i']` | +| team.ts:26 | `git config user.name` | none | argv | +| tower-routes.ts:2912 | `codev init --yes "${name}"` | quoting | `['init','--yes',name]` | +| tower-routes.ts:4056; utils/git.ts:33 | `git status --porcelain [--untracked-files=no]` | none | argv | +| tower-instances.ts:523 | `npx codev adopt --yes` | none | `npx` argv | +| config.ts:44 | `git rev-parse --git-common-dir` | none | argv | +| consult 2483 / 2534 / 2649 | `git show HEAD` / `git branch --show-current` | none | argv | +| import.ts:59 | `git clone --depth 1 "${url}" "${dir}"` | quoting | argv | +| init.ts:176 / 192 | `git init` / `codev doctor` | none | argv | +| default-branch.ts:15 | `git symbolic-ref --short refs/remotes/origin/HEAD` | none | argv | + +POSIX regression risk is therefore limited to: (a) the error **message** text (`run()` throws +`Command failed: \n`; I keep that format by joining argv for the message), and +(b) `npx`/`codev`/`porch` resolving from `PATH` the same way `/bin/sh` did — identical on POSIX, +since `execFile` without a shell uses the same `execvp` `PATH` search. + +## Proposed Change + +### 1. Fail closed in the resolver (`packages/sdk/src/node/executable.ts`) + +- `findAllExecutables`: on `win32`, **skip non-absolute `PATH` entries** (they resolve against the + cwd). POSIX unchanged. +- `resolveSpawnable`: add `found: boolean` to `SpawnableCommand`. On `win32`, a **bare** name that + does not resolve returns `found: false` (command still the bare name, for messages). POSIX and + names with a path separator: `found: true` as today (POSIX `execvp` never searches the cwd). + Additive; existing callers that ignore `found` are updated below. + +### 2. One shell-free user-tool API on the platform seam + +`CommandLaunch` (`lib/platform/command-launch.ts`) already has `spawn` / `spawnSync` for bare +commands; add the two missing shapes and make all four fail closed on Windows: + +```ts +spawn(cmd, args, opts): ChildProcess // exists +spawnSync(cmd, args, opts): SpawnSyncReturns // exists +execFileSync(cmd, args, opts): string // new +execFile(cmd, args, opts): Promise<{stdout, stderr}> // new (async, promisified execFile shape) +commandExists(name): boolean // posixProbe parameter removed +``` + +- **POSIX** implementations call `child_process` directly with the same argv and options — + no shell, no lookup change. +- **Windows** implementations run `spawnableOnHost` (PATH-only, `PATHEXT`, `.cmd` shim handling), + set `windowsHide` and `windowsVerbatimArguments`, and when `found === false` produce the + **same ENOENT surface the caller already handles** without ever spawning the bare name: + `execFileSync`/`execFile` throw/reject an `ENOENT` error shaped like Node's + (`code`, `errno`, `syscall: 'spawn '`, `path`, `spawnargs`); `spawnSync` returns + `{ error, status: null, … }`; `spawn` returns a `ChildProcess` that emits that `error` on the + next tick (the async contract callers already listen for). +- `lib/pty-command.ts` (harness PTYs) and `git-bash-launch.ts` get the same `found` check and + throw ENOENT instead of handing node-pty a bare name. + +### 3. `commandExists`: one shell-free implementation (Spec 1658 review A2.9) + +`commandLaunch().commandExists(name)` = `findOnHostPath(name) !== null` on **both** platforms +(the SDK resolver does `X_OK` + `isFile` on POSIX — the `which` semantics). The three `which` +forms go: `doctor.ts:677` (`which ${cmd}` string), `consult/index.ts:419`, `import.ts:324`, +`bench.ts:222`, `agent-farm/utils/shell.ts:139` (its async variant becomes a thin wrapper; its +name sanitising stays). + +### 4. Convert all 67 direct sites + +- `execFileSync('git', …)` → `commandLaunch().execFileSync('git', …)`; `spawnSync` / + `execFile(Async)` likewise. Same argv, same options. +- `execSync('git …')` / `execAsync('…')` strings → argv per the table above. +- agent-farm `run('git …')`: add `runTool(cmd, args, { cwd })` to `utils/shell.ts` (same + `{stdout, stderr}` trimmed result, same `Command failed:` error) built on + `commandLaunch().execFile`. After conversion `run()` has no callers left in `src`; I delete it + rather than leave a shell-string helper behind (grep-confirmed in implement; if a non-tool + caller remains it stays and the guard covers it). +- Tests that mock `node:child_process` and match the old **strings** are updated to the argv + form (6 files today: `spawn-worktree.test.ts`, `spec-1658-cleanup-worktree-removal.test.ts`, + `doctor.test.ts`, `import.test.ts`, `issue-1919-hidden-spawns.test.ts`, + `windows-shell-spawns.test.ts`; more may surface from the 32 files mocking child_process). + +### 5. Static guard (`src/__tests__/user-tool-spawn-guard.test.ts`) + +A vitest AST guard (same technique as `windows-console-spawn-guard.test.ts`, so it runs on every +OS in the existing unit CI job — no new workflow step needed): for every non-test `.ts` under +`packages/codev/src`, any call to a `node:child_process` binding (named, aliased, or +`promisify`-wrapped) or to agent-farm `run`/`runStreaming`/`spawnDetached`, whose command is a +string literal/template whose first token is a **user tool** (`git gh npm npx node pnpm codev +afx porch consult claude codex gemini agy jq`), fails — unless annotated +`// user-tool: ` on the line or the line above. POSIX-only tools (`ps pgrep tail lsof +sysctl lscpu free du which command`) must carry `// user-tool: posix-only (…)`. The allowed path +is `commandLaunch()` (whose Windows half is the resolver). The guard also asserts it found the +known POSIX-only sites, so a broken scanner cannot pass vacuously. + +### 6. Windows behavioural test (`src/__tests__/windows-user-tool-cwd.test.ts`, `win32` only) + +Plants a fake `git.exe` (a copy of `%SystemRoot%\System32\hostname.exe`, which prints the host +name and exits 0) in a temp worktree-shaped cwd, then: +1. **Control:** raw `execFileSync('git', ['--version'], { cwd })` prints the host name — proves + the plant works and the hazard is real on this runner. +2. `commandLaunch().execFileSync('git', ['--version'], { cwd })` prints `git version …` (PATH git). +3. Same for `execFile`, `spawnSync`, `spawn` and `runTool`. +4. With `PATH` stripped of Git: all four fail with `ENOENT`; the planted file never runs. +5. A relative `PATH` entry (`.`) is ignored. + +Plus platform-injected unit tests in `packages/sdk/src/__tests__/executable.test.ts` for +`found: false` and relative-`PATH` skipping (run on every OS). + +### 7. Docs + +Remove the preview wording in `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 a short statement that Codev runs every program by full path or a +`PATH`-only lookup, never from the current folder. + +## Files to Change + +- `packages/sdk/src/node/executable.ts` — `found` flag; skip relative `PATH` entries on win32 +- `packages/sdk/src/__tests__/executable.test.ts` — tests for both +- `packages/codev/src/lib/host-executable.ts` — `spawnableOnHost` passes `found` through; ENOENT error builder +- `packages/codev/src/lib/platform/command-launch.ts` — `execFileSync`, `execFile`; `commandExists(name)` +- `packages/codev/src/lib/platform/{posix,windows}/command-launch.ts` — implementations, fail closed +- `packages/codev/src/lib/pty-command.ts`, `lib/platform/windows/git-bash-launch.ts` — `found` check +- `packages/codev/src/agent-farm/utils/shell.ts` — `runTool`; `commandExists` thin; `run` removed if unused +- The 67 sites listed above (25 files) — argv conversion +- `doctor.ts`, `consult/index.ts`, `import.ts`, `bench.ts` — drop local `which` probes +- POSIX-only sites — `// user-tool: posix-only` annotations +- `packages/codev/src/__tests__/user-tool-spawn-guard.test.ts` — new static guard +- `packages/codev/src/__tests__/windows-user-tool-cwd.test.ts` — new Windows test +- Existing tests mocking the old strings — updated to argv +- `README.md`, `codev/DEPENDENCIES.md`, `codev-skeleton/DEPENDENCIES.md` — preview wording removed +- `codev/state/pir-1911_thread.md` — thread log + +## Risks & Alternatives Considered + +- **Risk: POSIX regression from dropping the shell.** Mitigated by the table above: no site uses + a shell feature beyond quoting. Error messages keep the `Command failed: ` form. +- **Risk: a `.cmd`-shimmed tool (`npx`, `codev`, `porch` installed by npm) behaves differently + under argv than under `cmd.exe`.** `resolveSpawnable` already handles this for the + `commandLaunch().spawn` sites in production today (`consult`, `afx`); same code path. +- **Risk: test-mock churn** across files that match exact `execSync` strings. Mechanical; done + per site with the site. +- **Risk: VS Code extension** (`apps/vscode/src/cli-process.ts`) also uses `resolveSpawnable` and + ignores `found`. The SDK change is additive, so it keeps today's behaviour. It has the same hole + (it runs `codev`/`afx` with the workspace as cwd); the fix is a one-line `found` check there, so + I include it as an adjacent fix-in-place and name it in the PR. If the reviewer wants it out of + scope, drop that one file. +- **Alternative: set `NoDefaultCurrentDirectoryInExePath`.** That env var stops `cmd.exe` from + searching the cwd, but libuv ignores it (it implements its own `search_path`), so it fixes only + half the sites, and it leaks into every child. Rejected. +- **Alternative: convert each site to `spawnableOnHost` inline.** 67 hand-rolled + `windowsHide`/`windowsVerbatimArguments`/ENOENT copies; the guard could only check "uses the + resolver somewhere". Rejected for the seam (single source of truth). +- **Alternative: a script in `scripts/` + CI step, like `tmp-residue-check.mjs`.** The check needs + a TypeScript AST to see through aliases and templates; the vitest guard gets `typescript` for + free and already runs in the unit job. The issue allows "test or script". +- **Out of scope:** the remaining single-site `isWindows()` forks (Spec 1658 A2.5); the IDE-server + capability (#1890); shell strings that run under the resolved **Git Bash** (porch checks, forge + concept scripts, `runStreaming` postSpawn/dev commands) — bash's `PATH` search does not consult + the cwd, and those commands are the user's own configuration. + +## Test Plan + +- **Unit (all OS):** SDK resolver tests (`found`, relative `PATH`); `user-tool-spawn-guard`; + updated site tests; full `packages/codev` unit suite on the Windows host, recording the Tower + PID before and after (and reporting any change), re-running known #1923 load flakes once. +- **Windows behavioural:** `windows-user-tool-cwd.test.ts` (the planted `git.exe` control + + PATH-git + ENOENT cases). +- **Windows CI:** `gh workflow run windows.yml --ref builder/pir-1911 -f purpose='#1911 user-tool PATH-only lookup' -f suites=true`, run linked in the PR. +- **Manual (dev-approval, on this Windows host):** + 1. In a scratch repo, commit a `git.exe` (copy of `hostname.exe`) at the root. + 2. `afx spawn` a builder for it / `afx cleanup` it, and `porch status` inside it: worktree + creation, the clean-check (`git status` in the worktree) and cleanup all behave normally; + nothing prints the host name. + 3. `codev doctor` and `consult` from inside the worktree report the real Git. + 4. Temporarily remove Git from `PATH` in a shell: commands fail with a clear "not found" + error, and the planted `git.exe` still never runs. +- **POSIX:** CI unit + e2e on Linux/macOS unchanged and green. diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md new file mode 100644 index 000000000..fcf3925fe --- /dev/null +++ b/codev/state/pir-1911_thread.md @@ -0,0 +1,8 @@ +# 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. From 740657a98190f8bd03f17268a664fce2d7c476df Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 21:52:59 +1100 Subject: [PATCH 03/28] chore(porch): 1911 plan-approval gate-requested --- codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 0ccc4ea88..088b7c09f 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -7,6 +7,7 @@ current_plan_phase: null gates: plan-approval: status: pending + requested_at: '2026-11-20T10:52:59.449Z' dev-approval: status: pending pr: @@ -15,4 +16,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-20T10:37:24.035Z' +updated_at: '2026-11-20T10:52:59.452Z' From 20606082b70cc14b34483d35a99adcddb8240087 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 21:58:28 +1100 Subject: [PATCH 04/28] [PIR #1911] Plan revised: set NoDefaultCurrentDirectoryInExePath at entry points --- .../1911-windows-bare-name-user-tool-sp.md | 336 ++++++------------ codev/state/pir-1911_thread.md | 6 + 2 files changed, 111 insertions(+), 231 deletions(-) diff --git a/codev/plans/1911-windows-bare-name-user-tool-sp.md b/codev/plans/1911-windows-bare-name-user-tool-sp.md index 5f446b881..d65d6a3b0 100644 --- a/codev/plans/1911-windows-bare-name-user-tool-sp.md +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -1,267 +1,141 @@ # PIR Plan: Windows user-tool lookup hardening (#1911) -## Understanding - -On Windows, a program started by **bare name** is looked up in the current directory before -`PATH`: libuv does this for `child_process.spawn/execFile*` (`search_path` tries the cwd first), -and `cmd.exe` does it for every `exec`/`execSync` string. Codev runs `git`, `gh`, `npm`, `npx`, -`codev`, `porch` and friends with a builder worktree, a workspace, or a freshly cloned repository -as the cwd, so a `git.exe` committed to that repository runs under Codev instead of Git. -Spec 1658 fixed the system programs (System32 full paths); this issue fixes the user tools, -and with it native Windows leaves preview (README, both `DEPENDENCIES.md`). - -### What the re-grep found (issue inventory is stale) - -I re-inventoried with a TypeScript-AST scan of every non-test `.ts` under `packages/codev/src` -(every `exec/execSync/execFile/execFileSync/spawn/spawnSync`, promisified `execAsync` / -`execFileAsync`, agent-farm `run()`, and `commandLaunch().spawn*` call whose command is a string -literal or template). **72 user-tool sites**, against the issue's 36. The issue missed every -agent-farm `run('git …')` shell string (19, in `cleanup.ts`, `spawn-worktree.ts`, `spawn.ts`, -`utils/git.ts`), `tower-routes.ts`, `tower-instances.ts`, `team-update.ts`, `porch/checks.ts`, -`porch/state.ts`, `team-github.ts`, `import.ts:59`, and the `commandLaunch().spawn` sites. - -**Direct `child_process` sites (67) — must be converted:** - -- `agent-farm/commands/cleanup.ts`: 193, 228, 247, 261, 411, 495 `run(git …)` — **193 runs with the builder worktree as cwd** -- `agent-farm/commands/self-refresh.ts`: 484 `execFileSync(git)` -- `agent-farm/commands/spawn-worktree.ts`: 222, 230, 332, 337, 374, 382, 398, 404, 426, 458, 462 `run(git …)`; 282 `run(gh …)`; 490 `run(porch …)` (cwd = new worktree); 791 `execSync(git …)` (cwd = worktree) -- `agent-farm/commands/spawn.ts`: 958 `run(git …)` -- `agent-farm/commands/team.ts`: 26; `team-update.ts`: 37 `execSync(git …)` -- `agent-farm/servers/tower-routes.ts`: 2912 `execAsync(codev init …)`, 4056 `execAsync(git status …)` (cwd = workspace) -- `agent-farm/servers/tower-instances.ts`: 523 `execAsync(npx codev adopt …)` (cwd = an **arbitrary, not-yet-adopted directory**) -- `agent-farm/utils/config.ts`: 44 `execSync(git …)`; `utils/git.ts`: 33 `run(git …)` -- `commands/consult/index.ts`: 2048, 2049, 2217, 2234, 2249, 2254, 2359, 2753, 2786 `execFileSync(git)`; 2483, 2534, 2649 `execSync(git …)` -- `commands/doctor.ts`: 1154 `spawnSync(git)` -- `commands/import.ts`: 59 `execSync(git clone …)` -- `commands/init.ts`: 176 `execSync(git init)`, 192 `execSync(codev doctor)` (cwd = new project) -- `commands/porch/artifacts.ts`: 397, 421, 434, 466 `execFileSync(git)` -- `commands/porch/checks.ts`: 423; `porch/state.ts`: 205, 206, 209 `execFileAsync(git)` -- `lib/default-branch.ts`: 15 `execSync(git …)` -- `lib/github.ts`: 288 `execFile(gh)` -- `lib/gitignore.ts`: 168, 218 `spawnSync(git)` -- `lib/governance-bootstrap.ts`: 254, 275 `execFileSync(git)` -- `lib/protocol-drift-audit.ts`: 200 `spawnSync(npm)` -- `lib/team-github.ts`: 95 `execFileAsync(git)` -- `lib/tree-snapshot.ts`: 91, 107, 125, 184, 359 `execFileSync(git)` +> 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. -**Already routed through the resolver, but not safe (5 + the pty path):** the architect's list — -`commands/import.ts:292` (`claude`), `agent-farm/commands/ide.ts:155/325` (`npm`), -`lib/agent-process.ts:32` — plus `bench.ts:100`, `bootstrap-docs.ts:287` (`consult`), -`porch/index.ts:711` (`afx`), `tower.ts:366` (`npx`/`node`) and `lib/pty-command.ts:26` (every -harness PTY) go through `commandLaunch().spawn*` / `spawnableOnHost` / `resolveSpawnable`. -The root problem there is in the resolver itself: -`packages/sdk/src/node/executable.ts:270-273` — when a name **does not resolve** on `PATH`, -`resolveSpawnable` returns the bare name unchanged, so the spawn falls back to libuv's lookup, -**which checks the cwd first**. "git not on PATH, but `git.exe` in the repo" therefore still runs -the planted file. These sites are **in scope**; they are fixed once, in the resolver, not per -site. `lib/agent-process.ts` itself is already safe when it gets a full path -(`resolveClaudeBin()` returns an absolute path), and is covered by the same fix for other launches. - -A second resolver hole: `findAllExecutables` (`executable.ts:152`) honours **relative** `PATH` -entries (`.`, `bin`), which resolve against the cwd. That is the same attack through `PATH`. - -**POSIX-only tools (out of scope to change; confirmed unreachable on Windows in implement):** -`ps` (cleanup.ts:90, architect-session-holder.ts:94, tower-utils.ts:252, posix/processes.ts:56/80, -session-manager.ts:1150), `pgrep` (tower.ts:470/486), `tail` (tower.ts:603), `lsof` -(posix/processes.ts:139), `sysctl`/`lscpu`/`free` (bench.ts:50/54/72/77), `du` -(migration-backup-audit.ts:79), `command -v` (consult/index.ts:1435), `which` (the five -`commandExists` probes, removed below). Each gets a `// user-tool: posix-only ()` annotation -checked by the guard, so a future refactor that makes one reachable on Windows is visible. +## Understanding -### Shell-string sites and their shell features (architect point 3) +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. -Every shell-string user-tool site, and whether it relies on a shell feature. **None uses pipes, -redirects, `||`/`&&`, globbing or variable expansion.** The only shell feature in use is -double-quote quoting of interpolated values (and whitespace word-splitting), which the argv form -replaces exactly — and more safely: today a branch, path or remote containing `"`, `$` or -backticks is shell-interpreted. +**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`: -| Site | Command | Shell feature used | argv form | +| | `execFileSync('git')` | `spawnSync('git')` | `execSync('git …')` (cmd.exe) | |---|---|---|---| -| cleanup.ts:193 | `git status --porcelain` | none | `['status','--porcelain']` | -| cleanup.ts:228 | `git push origin --delete "${branch}"` | quoting | `['push','origin','--delete',branch]` | -| cleanup.ts:247 | `git worktree remove "${p}" --force` | quoting | `['worktree','remove',p,'--force']` | -| cleanup.ts:261, 495; spawn.ts:958 | `git worktree prune` | none | `['worktree','prune']` | -| cleanup.ts:411 | `git branch -D "${b}"` | quoting | `['branch','-D',b]` | -| spawn-worktree.ts:222 | `git branch ${branchName}` | word-split (unquoted, single token) | `['branch',branchName]` | -| spawn-worktree.ts:230 | `git worktree add "${p}" ${branchName}` | quoting + word-split | `['worktree','add',p,branchName]` | -| spawn-worktree.ts:282 | `gh pr list --head "${b}" --json … --state open` | quoting | argv | -| spawn-worktree.ts:332 / 337 | `git remote get-url "${n}"` / `git remote add "${n}" "${url}"` | quoting | argv | -| spawn-worktree.ts:374 / 398 | `git fetch "${r}"` [`"${b}"`] | quoting | argv | -| spawn-worktree.ts:382 / 404 | `git ls-remote --heads "${r}" "${b}"` | quoting | argv | -| spawn-worktree.ts:426 | `git worktree list --porcelain` | none | argv | -| spawn-worktree.ts:458 / 462 | `git worktree add "${p}" [-b "${b}" "${r}/${b}"]` | quoting | argv | -| spawn-worktree.ts:490 | `porch init ${proto} ${id} "${name}"` | quoting + word-split (proto/id pre-sanitised to one token) | `['init',proto,id,name]` | -| spawn-worktree.ts:791 | `git update-index --skip-worktree "${rel}"` | quoting | argv | -| team-update.ts:37 | `git log --oneline --since="${since}" --all --grep="spawn" -i` | quoting inside `--opt="…"` | `['log','--oneline',`--since=${since}`,'--all','--grep=spawn','-i']` | -| team.ts:26 | `git config user.name` | none | argv | -| tower-routes.ts:2912 | `codev init --yes "${name}"` | quoting | `['init','--yes',name]` | -| tower-routes.ts:4056; utils/git.ts:33 | `git status --porcelain [--untracked-files=no]` | none | argv | -| tower-instances.ts:523 | `npx codev adopt --yes` | none | `npx` argv | -| config.ts:44 | `git rev-parse --git-common-dir` | none | argv | -| consult 2483 / 2534 / 2649 | `git show HEAD` / `git branch --show-current` | none | argv | -| import.ts:59 | `git clone --depth 1 "${url}" "${dir}"` | quoting | argv | -| init.ts:176 / 192 | `git init` / `codev doctor` | none | argv | -| default-branch.ts:15 | `git symbolic-ref --short refs/remotes/origin/HEAD` | none | argv | +| 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" | -POSIX regression risk is therefore limited to: (a) the error **message** text (`run()` throws -`Command failed: \n`; I keep that format by joining argv for the message), and -(b) `npx`/`codev`/`porch` resolving from `PATH` the same way `/bin/sh` did — identical on POSIX, -since `execFile` without a shell uses the same `execvp` `PATH` search. +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. Fail closed in the resolver (`packages/sdk/src/node/executable.ts`) - -- `findAllExecutables`: on `win32`, **skip non-absolute `PATH` entries** (they resolve against the - cwd). POSIX unchanged. -- `resolveSpawnable`: add `found: boolean` to `SpawnableCommand`. On `win32`, a **bare** name that - does not resolve returns `found: false` (command still the bare name, for messages). POSIX and - names with a path separator: `found: true` as today (POSIX `execvp` never searches the cwd). - Additive; existing callers that ignore `found` are updated below. - -### 2. One shell-free user-tool API on the platform seam - -`CommandLaunch` (`lib/platform/command-launch.ts`) already has `spawn` / `spawnSync` for bare -commands; add the two missing shapes and make all four fail closed on Windows: +### 1. One hardening module, set first in every Codev process -```ts -spawn(cmd, args, opts): ChildProcess // exists -spawnSync(cmd, args, opts): SpawnSyncReturns // exists -execFileSync(cmd, args, opts): string // new -execFile(cmd, args, opts): Promise<{stdout, stderr}> // new (async, promisified execFile shape) -commandExists(name): boolean // posixProbe parameter removed -``` +New `packages/codev/src/lib/exe-search-hardening.ts`: a side-effect module that, on `win32` only, +sets `process.env.NoDefaultCurrentDirectoryInExePath = '1'`. It is a no-op on macOS/Linux (POSIX +`execvp` never searches the cwd). It imports nothing, so it can be the first import evaluated. -- **POSIX** implementations call `child_process` directly with the same argv and options — - no shell, no lookup change. -- **Windows** implementations run `spawnableOnHost` (PATH-only, `PATHEXT`, `.cmd` shim handling), - set `windowsHide` and `windowsVerbatimArguments`, and when `found === false` produce the - **same ENOENT surface the caller already handles** without ever spawning the bare name: - `execFileSync`/`execFile` throw/reject an `ENOENT` error shaped like Node's - (`code`, `errno`, `syscall: 'spawn '`, `path`, `spawnargs`); `spawnSync` returns - `{ error, status: null, … }`; `spawn` returns a `ChildProcess` that emits that `error` on the - next tick (the async contract callers already listen for). -- `lib/pty-command.ts` (harness PTYs) and `git-bash-launch.ts` get the same `found` check and - throw ENOENT instead of handing node-pty a bare name. +It is imported **first** (before any other import, so ESM hoisting cannot run a spawn ahead of it) +in each process entry point: -### 3. `commandExists`: one shell-free implementation (Spec 1658 review A2.9) +- `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). -`commandLaunch().commandExists(name)` = `findOnHostPath(name) !== null` on **both** platforms -(the SDK resolver does `X_OK` + `isFile` on POSIX — the `which` semantics). The three `which` -forms go: `doctor.ts:677` (`which ${cmd}` string), `consult/index.ts:419`, `import.ts:324`, -`bench.ts:222`, `agent-farm/utils/shell.ts:139` (its async variant becomes a thin wrapper; its -name sanitising stays). +### 2. Agent/terminal PTYs (node-pty) -### 4. Convert all 67 direct sites +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. -- `execFileSync('git', …)` → `commandLaunch().execFileSync('git', …)`; `spawnSync` / - `execFile(Async)` likewise. Same argv, same options. -- `execSync('git …')` / `execAsync('…')` strings → argv per the table above. -- agent-farm `run('git …')`: add `runTool(cmd, args, { cwd })` to `utils/shell.ts` (same - `{stdout, stderr}` trimmed result, same `Command failed:` error) built on - `commandLaunch().execFile`. After conversion `run()` has no callers left in `src`; I delete it - rather than leave a shell-string helper behind (grep-confirmed in implement; if a non-tool - caller remains it stays and the guard covers it). -- Tests that mock `node:child_process` and match the old **strings** are updated to the argv - form (6 files today: `spawn-worktree.test.ts`, `spec-1658-cleanup-worktree-removal.test.ts`, - `doctor.test.ts`, `import.test.ts`, `issue-1919-hidden-spawns.test.ts`, - `windows-shell-spawns.test.ts`; more may surface from the 32 files mocking child_process). +### 3. VS Code extension -### 5. Static guard (`src/__tests__/user-tool-spawn-guard.test.ts`) +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). -A vitest AST guard (same technique as `windows-console-spawn-guard.test.ts`, so it runs on every -OS in the existing unit CI job — no new workflow step needed): for every non-test `.ts` under -`packages/codev/src`, any call to a `node:child_process` binding (named, aliased, or -`promisify`-wrapped) or to agent-farm `run`/`runStreaming`/`spawnDetached`, whose command is a -string literal/template whose first token is a **user tool** (`git gh npm npx node pnpm codev -afx porch consult claude codex gemini agy jq`), fails — unless annotated -`// user-tool: ` on the line or the line above. POSIX-only tools (`ps pgrep tail lsof -sysctl lscpu free du which command`) must carry `// user-tool: posix-only (…)`. The allowed path -is `commandLaunch()` (whose Windows half is the resolver). The guard also asserts it found the -known POSIX-only sites, so a broken scanner cannot pass vacuously. +### 4. Guard (static, every OS, runs in the existing unit job) -### 6. Windows behavioural test (`src/__tests__/windows-user-tool-cwd.test.ts`, `win32` only) +`packages/codev/src/__tests__/exe-search-hardening.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). -Plants a fake `git.exe` (a copy of `%SystemRoot%\System32\hostname.exe`, which prints the host -name and exits 0) in a temp worktree-shaped cwd, then: -1. **Control:** raw `execFileSync('git', ['--version'], { cwd })` prints the host name — proves - the plant works and the hazard is real on this runner. -2. `commandLaunch().execFileSync('git', ['--version'], { cwd })` prints `git version …` (PATH git). -3. Same for `execFile`, `spawnSync`, `spawn` and `runTool`. -4. With `PATH` stripped of Git: all four fail with `ENOENT`; the planted file never runs. -5. A relative `PATH` entry (`.`) is ignored. +### 5. Windows behavioural test (`win32` only) -Plus platform-injected unit tests in `packages/sdk/src/__tests__/executable.test.ts` for -`found: false` and relative-`PATH` skipping (run on every OS). +`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). -### 7. Docs +### 6. Docs -Remove the preview wording in `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 a short statement that Codev runs every program by full path or a -`PATH`-only lookup, never from the current folder. +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/sdk/src/node/executable.ts` — `found` flag; skip relative `PATH` entries on win32 -- `packages/sdk/src/__tests__/executable.test.ts` — tests for both -- `packages/codev/src/lib/host-executable.ts` — `spawnableOnHost` passes `found` through; ENOENT error builder -- `packages/codev/src/lib/platform/command-launch.ts` — `execFileSync`, `execFile`; `commandExists(name)` -- `packages/codev/src/lib/platform/{posix,windows}/command-launch.ts` — implementations, fail closed -- `packages/codev/src/lib/pty-command.ts`, `lib/platform/windows/git-bash-launch.ts` — `found` check -- `packages/codev/src/agent-farm/utils/shell.ts` — `runTool`; `commandExists` thin; `run` removed if unused -- The 67 sites listed above (25 files) — argv conversion -- `doctor.ts`, `consult/index.ts`, `import.ts`, `bench.ts` — drop local `which` probes -- POSIX-only sites — `// user-tool: posix-only` annotations -- `packages/codev/src/__tests__/user-tool-spawn-guard.test.ts` — new static guard -- `packages/codev/src/__tests__/windows-user-tool-cwd.test.ts` — new Windows test -- Existing tests mocking the old strings — updated to argv +- `packages/codev/src/lib/exe-search-hardening.ts` — new, the side-effect module +- `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__/exe-search-hardening.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: POSIX regression from dropping the shell.** Mitigated by the table above: no site uses - a shell feature beyond quoting. Error messages keep the `Command failed: ` form. -- **Risk: a `.cmd`-shimmed tool (`npx`, `codev`, `porch` installed by npm) behaves differently - under argv than under `cmd.exe`.** `resolveSpawnable` already handles this for the - `commandLaunch().spawn` sites in production today (`consult`, `afx`); same code path. -- **Risk: test-mock churn** across files that match exact `execSync` strings. Mechanical; done - per site with the site. -- **Risk: VS Code extension** (`apps/vscode/src/cli-process.ts`) also uses `resolveSpawnable` and - ignores `found`. The SDK change is additive, so it keeps today's behaviour. It has the same hole - (it runs `codev`/`afx` with the workspace as cwd); the fix is a one-line `found` check there, so - I include it as an adjacent fix-in-place and name it in the PR. If the reviewer wants it out of - scope, drop that one file. -- **Alternative: set `NoDefaultCurrentDirectoryInExePath`.** That env var stops `cmd.exe` from - searching the cwd, but libuv ignores it (it implements its own `search_path`), so it fixes only - half the sites, and it leaks into every child. Rejected. -- **Alternative: convert each site to `spawnableOnHost` inline.** 67 hand-rolled - `windowsHide`/`windowsVerbatimArguments`/ENOENT copies; the guard could only check "uses the - resolver somewhere". Rejected for the seam (single source of truth). -- **Alternative: a script in `scripts/` + CI step, like `tmp-residue-check.mjs`.** The check needs - a TypeScript AST to see through aliases and templates; the vitest guard gets `typescript` for - free and already runs in the unit job. The issue allows "test or script". -- **Out of scope:** the remaining single-site `isWindows()` forks (Spec 1658 A2.5); the IDE-server - capability (#1890); shell strings that run under the resolved **Git Bash** (porch checks, forge - concept scripts, `runStreaming` postSpawn/dev commands) — bash's `PATH` search does not consult - the cwd, and those commands are the user's own configuration. +- **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. Sites that build an env from scratch + (`windowsPtyBaseEnv` for human terminals) only affect that child's own lookups, not Codev's. +- **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):** SDK resolver tests (`found`, relative `PATH`); `user-tool-spawn-guard`; - updated site tests; full `packages/codev` unit suite on the Windows host, recording the Tower - PID before and after (and reporting any change), re-running known #1923 load flakes once. -- **Windows behavioural:** `windows-user-tool-cwd.test.ts` (the planted `git.exe` control + - PATH-git + ENOENT cases). -- **Windows CI:** `gh workflow run windows.yml --ref builder/pir-1911 -f purpose='#1911 user-tool PATH-only lookup' -f suites=true`, run linked in the PR. -- **Manual (dev-approval, on this Windows host):** +- **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 / `afx cleanup` it, and `porch status` inside it: worktree - creation, the clean-check (`git status` in the worktree) and cleanup all behave normally; - nothing prints the host name. - 3. `codev doctor` and `consult` from inside the worktree report the real Git. - 4. Temporarily remove Git from `PATH` in a shell: commands fail with a clear "not found" - error, and the planted `git.exe` still never runs. -- **POSIX:** CI unit + e2e on Linux/macOS unchanged and green. + 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/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index fcf3925fe..20c253ba3 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -6,3 +6,9 @@ - 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. From 57bcccc20806064233d98b434377a4b61dcd81fa Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 21:59:57 +1100 Subject: [PATCH 05/28] chore(porch): 1911 plan-approval gate-approved --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 index 088b7c09f..dc7d1842c 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -6,8 +6,9 @@ plan_phases: [] current_plan_phase: null gates: plan-approval: - status: pending + status: approved requested_at: '2026-11-20T10:52:59.449Z' + approved_at: '2026-11-20T10:59:56.889Z' dev-approval: status: pending pr: @@ -16,4 +17,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-20T10:52:59.452Z' +updated_at: '2026-11-20T10:59:56.890Z' From a032c0139b609738151bc64af6230ec983f04327 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 22:00:01 +1100 Subject: [PATCH 06/28] chore(porch): 1911 implement phase-transition --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index dc7d1842c..568d7692e 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -1,7 +1,7 @@ id: '1911' title: windows-bare-name-user-tool-sp protocol: pir -phase: plan +phase: implement plan_phases: [] current_plan_phase: null gates: @@ -17,4 +17,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-20T10:59:56.890Z' +updated_at: '2026-11-20T11:00:01.201Z' From 7d4d41f7432b501739474da3f666373167b2efd0 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 22:07:07 +1100 Subject: [PATCH 07/28] [PIR #1911] Set NoDefaultCurrentDirectoryInExePath first in every Codev entry point Windows looks a bare program name up in the current folder before PATH, so a git.exe committed to a repository would run under Codev. A side-effect module sets the variable before anything can spawn; a guard test enforces it is the first import of every bin and both server entries, and a Windows test plants a git.exe and proves it never runs. --- packages/codev/bin/afx.js | 2 + packages/codev/bin/codev.js | 2 + packages/codev/bin/consult.js | 2 + packages/codev/bin/generate-image.js | 2 + packages/codev/bin/porch.js | 2 + packages/codev/bin/team.js | 2 + .../__tests__/exe-search-hardening.test.ts | 80 ++++++++++++++++++ .../src/__tests__/windows-exe-search.test.ts | 83 +++++++++++++++++++ .../src/agent-farm/servers/tower-server.ts | 2 + .../codev/src/lib/exe-search-hardening.ts | 32 +++++++ packages/codev/src/terminal/shellper-main.ts | 2 + 11 files changed, 211 insertions(+) create mode 100644 packages/codev/src/__tests__/exe-search-hardening.test.ts create mode 100644 packages/codev/src/__tests__/windows-exe-search.test.ts create mode 100644 packages/codev/src/lib/exe-search-hardening.ts diff --git a/packages/codev/bin/afx.js b/packages/codev/bin/afx.js index 42e9b8e9d..d70f2bfc3 100755 --- a/packages/codev/bin/afx.js +++ b/packages/codev/bin/afx.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.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 fc9510cd0..de98411f6 100755 --- a/packages/codev/bin/codev.js +++ b/packages/codev/bin/codev.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.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 7b689c043..3726c9547 100755 --- a/packages/codev/bin/consult.js +++ b/packages/codev/bin/consult.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.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 f7be92727..1e9ae5003 100755 --- a/packages/codev/bin/generate-image.js +++ b/packages/codev/bin/generate-image.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.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 072034315..03a22ac23 100755 --- a/packages/codev/bin/porch.js +++ b/packages/codev/bin/porch.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.js'; /** * Porch CLI - Protocol Orchestrator diff --git a/packages/codev/bin/team.js b/packages/codev/bin/team.js index 86652a61c..9ddebdb3c 100755 --- a/packages/codev/bin/team.js +++ b/packages/codev/bin/team.js @@ -1,4 +1,6 @@ #!/usr/bin/env node +// First: never run a program from the current folder on Windows (#1911). +import '../dist/lib/exe-search-hardening.js'; // team - Team coordination CLI (standalone command) process.env.CODEV_STANDALONE = 'team'; diff --git a/packages/codev/src/__tests__/exe-search-hardening.test.ts b/packages/codev/src/__tests__/exe-search-hardening.test.ts new file mode 100644 index 000000000..e7d645dee --- /dev/null +++ b/packages/codev/src/__tests__/exe-search-hardening.test.ts @@ -0,0 +1,80 @@ +/** + * Issue #1911: every Codev process turns off Windows' current-folder program + * lookup before anything can spawn. + * + * `lib/exe-search-hardening.ts` sets `NoDefaultCurrentDirectoryInExePath` on + * Windows. It only protects a process that loads it before its first spawn, so + * each process entry point must import it 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 { hardenExeSearch, NO_CWD_EXE_SEARCH_ENV } from '../lib/exe-search-hardening.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. */ +const SERVER_ENTRY_POINTS: Record = { + 'src/agent-farm/servers/tower-server.ts': '../../lib/exe-search-hardening.js', + 'src/terminal/shellper-main.ts': '../lib/exe-search-hardening.js', +}; +const BIN_SPECIFIER = '../dist/lib/exe-search-hardening.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('hardenExeSearch', () => { + it('turns off the current-folder lookup on Windows', () => { + const env: NodeJS.ProcessEnv = {}; + hardenExeSearch('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' }; + hardenExeSearch(platform, env); + expect(env).toEqual({ PATH: '/usr/bin' }); + }); +}); + +describe('every Codev entry point loads the hardening 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__/windows-exe-search.test.ts b/packages/codev/src/__tests__/windows-exe-search.test.ts new file mode 100644 index 000000000..26b3cc997 --- /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/exe-search-hardening.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.platform, 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.platform, 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 8be507f03..f17d25336 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: never run a program from the current folder on Windows (#1911). +import '../../lib/exe-search-hardening.js'; import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/codev/src/lib/exe-search-hardening.ts b/packages/codev/src/lib/exe-search-hardening.ts new file mode 100644 index 000000000..c3b1d6d33 --- /dev/null +++ b/packages/codev/src/lib/exe-search-hardening.ts @@ -0,0 +1,32 @@ +/** + * 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.) + * + * 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 can spawn. It imports nothing for the same reason. + * `exe-search-hardening.test.ts` enforces the import order. + */ + +export const NO_CWD_EXE_SEARCH_ENV = 'NoDefaultCurrentDirectoryInExePath'; + +/** Set the variable on Windows; a no-op elsewhere (POSIX never searches the cwd). */ +export function hardenExeSearch(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): void { + if (platform !== 'win32') { + return; + } + env[NO_CWD_EXE_SEARCH_ENV] = '1'; +} + +hardenExeSearch(process.platform, process.env); diff --git a/packages/codev/src/terminal/shellper-main.ts b/packages/codev/src/terminal/shellper-main.ts index 19e68c73e..5b8e9a2b3 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: never run a program from the current folder on Windows (#1911). +import '../lib/exe-search-hardening.js'; import fs from 'node:fs'; import path from 'node:path'; import { createRequire } from 'node:module'; From 4d54ae89e2236f285eca9408be540ee2cb9cace7 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 22:07:07 +1100 Subject: [PATCH 08/28] [PIR #1911] VS Code: refuse a Codev CLI name that does not resolve on PATH The extension host is shared, so it cannot set the variable process-wide. An unresolved bare name now fails with ENOENT instead of reaching spawn, where Windows would search the workspace folder. --- apps/vscode/src/__tests__/cli-process.test.ts | 46 ++++++++++++++++++- apps/vscode/src/cli-process.ts | 36 ++++++++++++++- 2 files changed, 78 insertions(+), 4 deletions(-) diff --git a/apps/vscode/src/__tests__/cli-process.test.ts b/apps/vscode/src/__tests__/cli-process.test.ts index dbd947178..b4822997a 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/cli-process.ts b/apps/vscode/src/cli-process.ts index 171a31d72..6c050cee8 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, + 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, From 1b16aeecd9afcd26c8da29e9ddbf25414fa6928e Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 22:07:07 +1100 Subject: [PATCH 09/28] [PIR #1911] Docs: native Windows is no longer a preview --- README.md | 2 +- codev-skeleton/DEPENDENCIES.md | 13 ++++++------- codev/DEPENDENCIES.md | 13 ++++++------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 2755b1e19..39c323d7d 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/codev-skeleton/DEPENDENCIES.md b/codev-skeleton/DEPENDENCIES.md index f667ee69a..672f50c94 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,11 @@ 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 in its own processes and the + commands they run (it sets `NoDefaultCurrentDirectoryInExePath`), and runs its own Windows + tools by full system path. Terminal sessions keep the Windows default. - **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 f667ee69a..672f50c94 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,11 @@ 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 in its own processes and the + commands they run (it sets `NoDefaultCurrentDirectoryInExePath`), and runs its own Windows + tools by full system path. Terminal sessions keep the Windows default. - **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. From 1cfb06b92bb0383d5f6ce50f2f74bdc9af2c08b1 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Fri, 20 Nov 2026 22:11:04 +1100 Subject: [PATCH 10/28] [PIR #1911] Thread: implement notes --- codev/state/pir-1911_thread.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 20c253ba3..72a65a15f 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -12,3 +12,10 @@ - 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. From 3bef42211b32eca0dd5057979be4d4e44384b3a2 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 08:15:51 +1100 Subject: [PATCH 11/28] [PIR #1911] Rename to lib/process-bootstrap.ts; move the Windows step to platform/windows/exe-search.ts --- .../1911-windows-bare-name-user-tool-sp.md | 16 +++++++----- codev/state/pir-1911_thread.md | 3 +++ packages/codev/bin/afx.js | 4 +-- packages/codev/bin/codev.js | 4 +-- packages/codev/bin/consult.js | 4 +-- packages/codev/bin/generate-image.js | 4 +-- packages/codev/bin/porch.js | 4 +-- packages/codev/bin/team.js | 4 +-- ...ning.test.ts => process-bootstrap.test.ts} | 26 +++++++++---------- .../src/__tests__/windows-exe-search.test.ts | 6 ++--- .../src/agent-farm/servers/tower-server.ts | 4 +-- .../windows/exe-search.ts} | 15 +++-------- packages/codev/src/lib/process-bootstrap.ts | 24 +++++++++++++++++ packages/codev/src/terminal/shellper-main.ts | 4 +-- 14 files changed, 73 insertions(+), 49 deletions(-) rename packages/codev/src/__tests__/{exe-search-hardening.test.ts => process-bootstrap.test.ts} (76%) rename packages/codev/src/lib/{exe-search-hardening.ts => platform/windows/exe-search.ts} (62%) create mode 100644 packages/codev/src/lib/process-bootstrap.ts diff --git a/codev/plans/1911-windows-bare-name-user-tool-sp.md b/codev/plans/1911-windows-bare-name-user-tool-sp.md index d65d6a3b0..5bbc49d04 100644 --- a/codev/plans/1911-windows-bare-name-user-tool-sp.md +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -32,9 +32,12 @@ on `PATH` the spawn fails closed; the planted file never runs. ### 1. One hardening module, set first in every Codev process -New `packages/codev/src/lib/exe-search-hardening.ts`: a side-effect module that, on `win32` only, -sets `process.env.NoDefaultCurrentDirectoryInExePath = '1'`. It is a no-op on macOS/Linux (POSIX -`execvp` never searches the cwd). It imports nothing, so it can be the first import evaluated. +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: @@ -66,7 +69,7 @@ then set the variable themselves (step 1). ### 4. Guard (static, every OS, runs in the existing unit job) -`packages/codev/src/__tests__/exe-search-hardening.test.ts`: +`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 @@ -93,12 +96,13 @@ system paths or a `PATH`-only lookup. ## Files to Change -- `packages/codev/src/lib/exe-search-hardening.ts` — new, the side-effect module +- `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__/exe-search-hardening.test.ts` — new guard +- `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 diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 72a65a15f..8b30deb23 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -19,3 +19,6 @@ - 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. diff --git a/packages/codev/bin/afx.js b/packages/codev/bin/afx.js index d70f2bfc3..f5cbe0cee 100755 --- a/packages/codev/bin/afx.js +++ b/packages/codev/bin/afx.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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 de98411f6..4e9e45ebb 100755 --- a/packages/codev/bin/codev.js +++ b/packages/codev/bin/codev.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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 3726c9547..268da84ac 100755 --- a/packages/codev/bin/consult.js +++ b/packages/codev/bin/consult.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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 1e9ae5003..30781b3dc 100755 --- a/packages/codev/bin/generate-image.js +++ b/packages/codev/bin/generate-image.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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 03a22ac23..d23cf550a 100755 --- a/packages/codev/bin/porch.js +++ b/packages/codev/bin/porch.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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 9ddebdb3c..cb11f29a4 100755 --- a/packages/codev/bin/team.js +++ b/packages/codev/bin/team.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -// First: never run a program from the current folder on Windows (#1911). -import '../dist/lib/exe-search-hardening.js'; +// 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__/exe-search-hardening.test.ts b/packages/codev/src/__tests__/process-bootstrap.test.ts similarity index 76% rename from packages/codev/src/__tests__/exe-search-hardening.test.ts rename to packages/codev/src/__tests__/process-bootstrap.test.ts index e7d645dee..88079a60a 100644 --- a/packages/codev/src/__tests__/exe-search-hardening.test.ts +++ b/packages/codev/src/__tests__/process-bootstrap.test.ts @@ -1,10 +1,9 @@ /** - * Issue #1911: every Codev process turns off Windows' current-folder program - * lookup before anything can spawn. + * Every Codev process runs `lib/process-bootstrap.ts` before any other code. * - * `lib/exe-search-hardening.ts` sets `NoDefaultCurrentDirectoryInExePath` on - * Windows. It only protects a process that loads it before its first spawn, so - * each process entry point must import it FIRST: every installed command in + * 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`. */ @@ -14,16 +13,17 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import ts from 'typescript'; -import { hardenExeSearch, NO_CWD_EXE_SEARCH_ENV } from '../lib/exe-search-hardening.js'; +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. */ const SERVER_ENTRY_POINTS: Record = { - 'src/agent-farm/servers/tower-server.ts': '../../lib/exe-search-hardening.js', - 'src/terminal/shellper-main.ts': '../lib/exe-search-hardening.js', + '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/exe-search-hardening.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 { @@ -44,21 +44,21 @@ function firstStatementIsImport(file: string): boolean { return source.statements.length > 0 && ts.isImportDeclaration(source.statements[0]); } -describe('hardenExeSearch', () => { +describe('bootstrapProcess', () => { it('turns off the current-folder lookup on Windows', () => { const env: NodeJS.ProcessEnv = {}; - hardenExeSearch('win32', env); + 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' }; - hardenExeSearch(platform, env); + bootstrapProcess(platform, env); expect(env).toEqual({ PATH: '/usr/bin' }); }); }); -describe('every Codev entry point loads the hardening first', () => { +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)); diff --git a/packages/codev/src/__tests__/windows-exe-search.test.ts b/packages/codev/src/__tests__/windows-exe-search.test.ts index 26b3cc997..ce08eae29 100644 --- a/packages/codev/src/__tests__/windows-exe-search.test.ts +++ b/packages/codev/src/__tests__/windows-exe-search.test.ts @@ -15,7 +15,7 @@ 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/exe-search-hardening.js'; +import { hardenExeSearch, NO_CWD_EXE_SEARCH_ENV } from '../lib/platform/windows/exe-search.js'; const isWindows = process.platform === 'win32'; @@ -56,7 +56,7 @@ describe.skipIf(!isWindows)('a planted git.exe in the cwd never runs (Windows)', it('hardened: execFileSync, spawnSync and an execSync string all run the PATH git', () => { delete process.env[NO_CWD_EXE_SEARCH_ENV]; - hardenExeSearch(process.platform, process.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 /); @@ -66,7 +66,7 @@ describe.skipIf(!isWindows)('a planted git.exe in the cwd never runs (Windows)', 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.platform, process.env); + hardenExeSearch(process.env); const pathKey = Object.keys(process.env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH'; const withoutGit = (process.env[pathKey] ?? '') .split(path.delimiter) diff --git a/packages/codev/src/agent-farm/servers/tower-server.ts b/packages/codev/src/agent-farm/servers/tower-server.ts index f17d25336..f9f9fbc63 100644 --- a/packages/codev/src/agent-farm/servers/tower-server.ts +++ b/packages/codev/src/agent-farm/servers/tower-server.ts @@ -8,8 +8,8 @@ * delegates HTTP request handling to tower-routes.ts. */ -// First: never run a program from the current folder on Windows (#1911). -import '../../lib/exe-search-hardening.js'; +// 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/exe-search-hardening.ts b/packages/codev/src/lib/platform/windows/exe-search.ts similarity index 62% rename from packages/codev/src/lib/exe-search-hardening.ts rename to packages/codev/src/lib/platform/windows/exe-search.ts index c3b1d6d33..4fb0d4ba3 100644 --- a/packages/codev/src/lib/exe-search-hardening.ts +++ b/packages/codev/src/lib/platform/windows/exe-search.ts @@ -13,20 +13,13 @@ * ENOENT instead of running the planted file. (node-pty does its own PATH-only * lookup and never searches the terminal's cwd.) * - * 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 can spawn. It imports nothing for the same reason. - * `exe-search-hardening.test.ts` enforces the import order. + * 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'; -/** Set the variable on Windows; a no-op elsewhere (POSIX never searches the cwd). */ -export function hardenExeSearch(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): void { - if (platform !== 'win32') { - return; - } +/** 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'; } - -hardenExeSearch(process.platform, process.env); diff --git a/packages/codev/src/lib/process-bootstrap.ts b/packages/codev/src/lib/process-bootstrap.ts new file mode 100644 index 000000000..4cbbec7de --- /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 5b8e9a2b3..d4f924107 100644 --- a/packages/codev/src/terminal/shellper-main.ts +++ b/packages/codev/src/terminal/shellper-main.ts @@ -23,8 +23,8 @@ * from this process's environment before anything else runs. */ -// First: never run a program from the current folder on Windows (#1911). -import '../lib/exe-search-hardening.js'; +// 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'; From f9d0c8b269e80d9fce7fd6fcc704fd916fe87c06 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 08:53:47 +1100 Subject: [PATCH 12/28] [PIR #1911] Thread: Node 22 runs, waiting on #1946 --- codev/state/pir-1911_thread.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 8b30deb23..9e7af4396 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -22,3 +22,5 @@ - 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. From 875a44b09d729d0948b8a386fbfcbf33b30e3a26 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 09:31:34 +1100 Subject: [PATCH 13/28] chore(porch): 1911 dev-approval gate-requested --- codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index 568d7692e..9ee37767d 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -11,10 +11,11 @@ gates: approved_at: '2026-11-20T10:59:56.889Z' dev-approval: status: pending + requested_at: '2026-11-22T22:31:34.590Z' pr: status: pending iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-20T11:00:01.201Z' +updated_at: '2026-11-22T22:31:34.592Z' From 663603ee9cb828cf6871010363afe61cfb2d7b2d Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 09:31:51 +1100 Subject: [PATCH 14/28] [PIR #1911] Thread: checks pass, at dev-approval --- codev/state/pir-1911_thread.md | 1 + 1 file changed, 1 insertion(+) diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 9e7af4396..a42713193 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -24,3 +24,4 @@ - 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. From 53a1f3cbad474ca0a3f9781b761aae05faa641b2 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 09:41:24 +1100 Subject: [PATCH 15/28] [PIR #1911] Cover every Tower terminal: test it, correct the docs --- codev-skeleton/DEPENDENCIES.md | 8 ++- codev/DEPENDENCIES.md | 8 ++- .../1911-windows-bare-name-user-tool-sp.md | 6 +- codev/state/pir-1911_thread.md | 1 + .../__tests__/tower-lifecycle.windows.test.ts | 57 +++++++++++++++++++ 5 files changed, 72 insertions(+), 8 deletions(-) diff --git a/codev-skeleton/DEPENDENCIES.md b/codev-skeleton/DEPENDENCIES.md index 672f50c94..3309c28c7 100644 --- a/codev-skeleton/DEPENDENCIES.md +++ b/codev-skeleton/DEPENDENCIES.md @@ -261,9 +261,11 @@ How it works and what to know: supported; `codev doctor` and Tower's log report it. - **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 in its own processes and the - commands they run (it sets `NoDefaultCurrentDirectoryInExePath`), and runs its own Windows - tools by full system path. Terminal sessions keep the Windows default. + 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. 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 672f50c94..3309c28c7 100644 --- a/codev/DEPENDENCIES.md +++ b/codev/DEPENDENCIES.md @@ -261,9 +261,11 @@ How it works and what to know: supported; `codev doctor` and Tower's log report it. - **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 in its own processes and the - commands they run (it sets `NoDefaultCurrentDirectoryInExePath`), and runs its own Windows - tools by full system path. Terminal sessions keep the Windows default. + 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. 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 index 5bbc49d04..c9fd0fd9d 100644 --- a/codev/plans/1911-windows-bare-name-user-tool-sp.md +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -112,8 +112,10 @@ system paths or a `PATH`-only lookup. - **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. Sites that build an env from scratch - (`windowsPtyBaseEnv` for human terminals) only affect that child's own lookups, not Codev's. + 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). Only the + non-persistent fallback starts from the `windowsPtyBaseEnv` allowlist. - **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 diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index a42713193..447d2bead 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -25,3 +25,4 @@ - 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). diff --git a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts index 1e34da08a..5c4cf39a3 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,55 @@ 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); + leftovers.push(ownerPid(tower)!); + 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 { + db.close(); + afxRun(tower, ['tower', 'stop']); + for (const pid of shellperPids) 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); From db8577b6789682414b1e1e761e5bbb0270607bb5 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 09:45:06 +1100 Subject: [PATCH 16/28] [PIR #1911] Thread: checks pass, back at dev-approval --- codev/state/pir-1911_thread.md | 1 + 1 file changed, 1 insertion(+) diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 447d2bead..288dcd0d6 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -26,3 +26,4 @@ - 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. From e145f3cb9817fe6a54cd923789b25ffce37bbc54 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 09:55:08 +1100 Subject: [PATCH 17/28] [PIR #1911] Terminal coverage test: end every recorded session in teardown --- codev/state/pir-1911_thread.md | 1 + .../codev/src/__tests__/tower-lifecycle.windows.test.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 288dcd0d6..43030dfc8 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -27,3 +27,4 @@ - 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. diff --git a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts index 5c4cf39a3..42c8895e8 100644 --- a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts +++ b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts @@ -397,9 +397,13 @@ describe.skipIf(!onWindows)('Tower lifecycle on native Windows', () => { }, 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 shellperPids) await endSession(pid); + for (const pid of new Set([...shellperPids, ...recorded])) await endSession(pid); } }, 300_000); From c6179e4154635a3490fd4ea63959528ebffb92bf Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:02:26 +1100 Subject: [PATCH 18/28] chore(porch): 1911 dev-approval gate-approved --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 index 9ee37767d..a93eac508 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -10,12 +10,13 @@ gates: requested_at: '2026-11-20T10:52:59.449Z' approved_at: '2026-11-20T10:59:56.889Z' dev-approval: - status: pending + status: approved requested_at: '2026-11-22T22:31:34.590Z' + approved_at: '2026-11-22T23:02:25.946Z' pr: status: pending iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T22:31:34.592Z' +updated_at: '2026-11-22T23:02:25.947Z' From 145a8b34eaeb308daff85edc64b62a217c7edf1a Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:02:29 +1100 Subject: [PATCH 19/28] chore(porch): 1911 review phase-transition --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index a93eac508..6dbfc8f7b 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -1,7 +1,7 @@ id: '1911' title: windows-bare-name-user-tool-sp protocol: pir -phase: implement +phase: review plan_phases: [] current_plan_phase: null gates: @@ -19,4 +19,4 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:02:25.947Z' +updated_at: '2026-11-22T23:02:29.259Z' From 30d6666820916a150b8082185ba45c432075f41b Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:03:43 +1100 Subject: [PATCH 20/28] [PIR #1911] Review + retrospective --- codev/resources/arch.md | 10 ++ codev/resources/lessons-learned.md | 2 + .../1911-windows-bare-name-user-tool-sp.md | 116 ++++++++++++++++++ 3 files changed, 128 insertions(+) create mode 100644 codev/reviews/1911-windows-bare-name-user-tool-sp.md diff --git a/codev/resources/arch.md b/codev/resources/arch.md index 0014c128b..fd27a1e40 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -1076,6 +1076,16 @@ 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, and every persistent + terminal Tower opens (architect, builder, shell tab) is built from Tower's own environment, so + all of them carry 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 7ce5aa411..9cc4ef4ff 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 000000000..b9f5a1f78 --- /dev/null +++ b/codev/reviews/1911-windows-bare-name-user-tool-sp.md @@ -0,0 +1,116 @@ +# 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 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. + +**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`. + +**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/cli-process.ts` (+34 / -2) +- `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__/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/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. +- 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/45080898387 on the final commit `e145f3cb9`. Earlier green runs: 45079432385 (`53a1f3cba`), 45078247361, 44725012668. + +## 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 + +- **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; 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. From 6fb70fb3a9a4f4a2b0627db0313e2ce9d771c1c8 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:03:58 +1100 Subject: [PATCH 21/28] chore(porch): 1911 record PR #1948 --- .../1911-windows-bare-name-user-tool-sp/status.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 index 6dbfc8f7b..c82af6da2 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -19,4 +19,9 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:02:29.259Z' +updated_at: '2026-11-22T23:03:58.239Z' +pr_history: + - phase: review + pr_number: 1948 + branch: builder/pir-1911 + created_at: '2026-11-22T23:03:58.238Z' From 50bd9f46eed82df70c993942440c120afc614085 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:04:12 +1100 Subject: [PATCH 22/28] chore(porch): 1911 review build-complete --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index c82af6da2..1b5252f6f 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -16,10 +16,10 @@ gates: pr: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:03:58.239Z' +updated_at: '2026-11-22T23:04:12.639Z' pr_history: - phase: review pr_number: 1948 From 70aee8d4a26d426d76f832368ac4798f21a70d4f Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:09:45 +1100 Subject: [PATCH 23/28] chore(porch): 1911 pr gate-requested --- .../1911-windows-bare-name-user-tool-sp/status.yaml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 index 1b5252f6f..2d4d90828 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -15,13 +15,15 @@ gates: approved_at: '2026-11-22T23:02:25.946Z' pr: status: pending + requested_at: '2026-11-22T23:09:45.290Z' iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:04:12.639Z' +updated_at: '2026-11-22T23:09:45.290Z' pr_history: - phase: review pr_number: 1948 branch: builder/pir-1911 created_at: '2026-11-22T23:03:58.238Z' +pr_ready_for_human: true From 199c344d6cc76d3f212017d02997382e184fb909 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:12:34 +1100 Subject: [PATCH 24/28] [PIR #1911] Consultation fixes: cover the fallback terminal, Spawn Builder not-found message, nits, .NET note --- .../__tests__/spawn-builder-not-found.test.ts | 53 +++++++++++++++++++ apps/vscode/src/cli-process.ts | 2 +- apps/vscode/src/commands/spawn.ts | 4 ++ codev-skeleton/DEPENDENCIES.md | 5 +- codev/DEPENDENCIES.md | 5 +- .../1911-windows-bare-name-user-tool-sp.md | 5 +- codev/resources/arch.md | 7 +-- .../1911-windows-bare-name-user-tool-sp.md | 15 ++++-- codev/state/pir-1911_thread.md | 1 + .../src/__tests__/process-bootstrap.test.ts | 6 ++- .../codev/src/__tests__/shell-launch.test.ts | 6 +++ .../__tests__/tower-lifecycle.windows.test.ts | 4 +- .../codev/src/lib/platform/windows/pty-env.ts | 4 ++ 13 files changed, 104 insertions(+), 13 deletions(-) create mode 100644 apps/vscode/src/__tests__/spawn-builder-not-found.test.ts 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 000000000..9844955b9 --- /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 6c050cee8..33080908b 100644 --- a/apps/vscode/src/cli-process.ts +++ b/apps/vscode/src/cli-process.ts @@ -17,7 +17,7 @@ function unresolvedOnWindows(command: string, spawnable: SpawnableCommand): bool function notFoundError(command: string, args: string[]): NodeJS.ErrnoException { return Object.assign(new Error(`spawn ${command} ENOENT (not found on PATH)`), { code: 'ENOENT', - errno: -4058, + errno: -4058, // UV_ENOENT on Windows, the errno a real failed spawn carries syscall: `spawn ${command}`, path: command, spawnargs: args, diff --git a/apps/vscode/src/commands/spawn.ts b/apps/vscode/src/commands/spawn.ts index 5f70953d9..1d44f95af 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 3309c28c7..fa4469513 100644 --- a/codev-skeleton/DEPENDENCIES.md +++ b/codev-skeleton/DEPENDENCIES.md @@ -265,7 +265,10 @@ How it works and what to know: `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. Codev runs its own Windows tools by full system path. + 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 3309c28c7..fa4469513 100644 --- a/codev/DEPENDENCIES.md +++ b/codev/DEPENDENCIES.md @@ -265,7 +265,10 @@ How it works and what to know: `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. Codev runs its own Windows tools by full system path. + 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 index c9fd0fd9d..93daaf1a7 100644 --- a/codev/plans/1911-windows-bare-name-user-tool-sp.md +++ b/codev/plans/1911-windows-bare-name-user-tool-sp.md @@ -114,8 +114,9 @@ system paths or a `PATH`-only lookup. 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). Only the - non-persistent fallback starts from the `windowsPtyBaseEnv` allowlist. + 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 diff --git a/codev/resources/arch.md b/codev/resources/arch.md index fd27a1e40..9b35a4437 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -1081,9 +1081,10 @@ branches are testable on macOS/Linux. 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, and every persistent - terminal Tower opens (architect, builder, shell tab) is built from Tower's own environment, so - all of them carry it: in a `cmd.exe` terminal a current-folder program runs only as `.\name`. + 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 diff --git a/codev/reviews/1911-windows-bare-name-user-tool-sp.md b/codev/reviews/1911-windows-bare-name-user-tool-sp.md index b9f5a1f78..4a168d1f9 100644 --- a/codev/reviews/1911-windows-bare-name-user-tool-sp.md +++ b/codev/reviews/1911-windows-bare-name-user-tool-sp.md @@ -10,18 +10,22 @@ On Windows, a program started by bare name (`git`, `gh`, `npm`, `codev`) is look - 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 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. +- **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) @@ -36,10 +40,12 @@ On Windows, a program started by bare name (`git`, `gh`, `npm`, `codev`) is look - `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) @@ -70,6 +76,8 @@ On Windows, a program started by bare name (`git`, `gh`, `npm`, `codev`) is look - `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). @@ -88,7 +96,8 @@ Routed to COLD `codev/resources/lessons-learned.md`, Testing: ## Things to Look At During PR Review -- **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; 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. +- **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. diff --git a/codev/state/pir-1911_thread.md b/codev/state/pir-1911_thread.md index 43030dfc8..48340bd6e 100644 --- a/codev/state/pir-1911_thread.md +++ b/codev/state/pir-1911_thread.md @@ -28,3 +28,4 @@ - 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/src/__tests__/process-bootstrap.test.ts b/packages/codev/src/__tests__/process-bootstrap.test.ts index 88079a60a..13699fe64 100644 --- a/packages/codev/src/__tests__/process-bootstrap.test.ts +++ b/packages/codev/src/__tests__/process-bootstrap.test.ts @@ -18,7 +18,11 @@ 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. */ +/** + * 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', diff --git a/packages/codev/src/__tests__/shell-launch.test.ts b/packages/codev/src/__tests__/shell-launch.test.ts index 0107508b2..2c7db27a4 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 42c8895e8..ace64c008 100644 --- a/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts +++ b/packages/codev/src/__tests__/tower-lifecycle.windows.test.ts @@ -362,7 +362,9 @@ describe.skipIf(!onWindows)('Tower lifecycle on native Windows', () => { if (key.toLowerCase() === 'nodefaultcurrentdirectoryinexepath') delete tower.env[key]; } expect(afxRun(tower, ['tower', 'start']).code).toBe(0); - leftovers.push(ownerPid(tower)!); + 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; diff --git a/packages/codev/src/lib/platform/windows/pty-env.ts b/packages/codev/src/lib/platform/windows/pty-env.ts index f6eb8826a..fbb18681b 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; } From 2b09e30bb63547889470e47bf0e089b94cf10e36 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:12:45 +1100 Subject: [PATCH 25/28] chore(porch): 1911 review build-complete --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index 2d4d90828..e8d8c612f 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -17,10 +17,10 @@ gates: status: pending requested_at: '2026-11-22T23:09:45.290Z' iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:09:45.290Z' +updated_at: '2026-11-22T23:12:44.938Z' pr_history: - phase: review pr_number: 1948 From 57d2ec597831f1a1127d229cb2439efc0843ca86 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:16:15 +1100 Subject: [PATCH 26/28] [PIR #1911] Review: final CI run and test counts --- codev/reviews/1911-windows-bare-name-user-tool-sp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/reviews/1911-windows-bare-name-user-tool-sp.md b/codev/reviews/1911-windows-bare-name-user-tool-sp.md index 4a168d1f9..71fc18813 100644 --- a/codev/reviews/1911-windows-bare-name-user-tool-sp.md +++ b/codev/reviews/1911-windows-bare-name-user-tool-sp.md @@ -81,7 +81,8 @@ On Windows, a program started by bare name (`git`, `gh`, `npm`, `codev`) is look - 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/45080898387 on the final commit `e145f3cb9`. Earlier green runs: 45079432385 (`53a1f3cba`), 45078247361, 44725012668. +- 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 From 600cfbaef47c2248731dca23d4bf8d3c5cb8e84e Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:25:16 +1100 Subject: [PATCH 27/28] chore(porch): 1911 pr gate-approved --- .../1911-windows-bare-name-user-tool-sp/status.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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 index e8d8c612f..0af3e88d1 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -14,16 +14,17 @@ gates: requested_at: '2026-11-22T22:31:34.590Z' approved_at: '2026-11-22T23:02:25.946Z' pr: - status: pending + 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:12:44.938Z' +updated_at: '2026-11-22T23:25:16.299Z' pr_history: - phase: review pr_number: 1948 branch: builder/pir-1911 created_at: '2026-11-22T23:03:58.238Z' -pr_ready_for_human: true +pr_ready_for_human: false From 016450dc474a9333c255890fa493bcb600c42589 Mon Sep 17 00:00:00 2001 From: Amr Elsayed Date: Mon, 23 Nov 2026 10:25:19 +1100 Subject: [PATCH 28/28] chore(porch): 1911 protocol complete --- .../projects/1911-windows-bare-name-user-tool-sp/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index 0af3e88d1..91a0a8cab 100644 --- a/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml +++ b/codev/projects/1911-windows-bare-name-user-tool-sp/status.yaml @@ -1,7 +1,7 @@ id: '1911' title: windows-bare-name-user-tool-sp protocol: pir -phase: review +phase: verified plan_phases: [] current_plan_phase: null gates: @@ -21,7 +21,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-20T10:37:24.033Z' -updated_at: '2026-11-22T23:25:16.299Z' +updated_at: '2026-11-22T23:25:19.529Z' pr_history: - phase: review pr_number: 1948