Files
Codeman/test/cli-executable-resolver.test.ts
DevvynandClaude Opus 5.5 0a52a99ca9 feat(cli-registry): CLI management write API + Settings UI (Phases 1-6) (#476)
* feat(cli-registry): add cliManagementEnabled flag and GET /api/clis

Phases 1-2 of docs/cli-enable-disable-plan.md ("PR C" from the #343
review): a synced, default-OFF master flag gating the upcoming CLI
management surface, plus a read-only GET /api/clis endpoint listing
every registry entry (stock + custom, enabled or not) for the
Settings UI. Non-admins in multi-user mode see an empty list rather
than a 403. Write endpoints, auto-install, custom entry CRUD and the
Settings UI list itself land in later phases.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* feat(cli-registry): Phases 3-6 - write API + custom entries + Settings UI

Completes docs/cli-enable-disable-plan.md ("PR C" from the #343 review).

Phase 3: PUT /api/clis/:id toggles enabled for any EXISTING entry (stock or
custom) via a shallow merge onto its clis.json override; shell/claude are
structurally un-disableable (Decision 4), an unknown id 404s rather than
becoming a creation backdoor.

Phase 4: POST /api/clis/:id/install runs a STOCK entry's already-vetted
install command (shell:true, bounded by timeout, process-group killed on
expiry, output captured, audit-logged). A custom entry's id is refused
outright, independent of anything Phase 5 does (Decision 3: a custom
entry's install text is display-only, never executed).

Phase 5: POST /api/clis (create) / PUT /api/clis/custom/:id (update) /
DELETE /api/clis/:id (custom only) — a deliberately minimal request shape
(id/label/shortBadge/binaries/a simple launch variant), assembled into a
full CliEntry with conservative capability defaults and re-validated
through CliEntrySchema before writing, never a relaxed path for
UI-originated entries. Stock-id collisions, duplicate custom ids, and
edits/deletes against a stock id are all rejected explicitly.

Phase 6: the Settings UI section (App Settings -> Agents & CLIs), gated
independently on cliManagementEnabled AND admin-in-multi-user-mode
(Decision 5), fetching/rendering GET /api/clis and wiring every write
endpoint above.

Every write endpoint answers the same way when the feature is off: 403
FORBIDDEN via one shared requireCliManagementGate() (Phase 1's own
checklist item). registry-writer.ts is a new, deliberately separate write
module so registry.ts itself stays import-side-effect-free, same tmp+
rename+0600 shape as custom-model-hosts.ts.

27 new/updated route tests covering every gate, collision, and cleanup
path; full CI gate green (415/416 files, 7854 tests).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* fix(cli-registry): toggling a CLI off in Settings never hid it anywhere else

window.__codemanCliAvailable — the flag isCliAvailable() reads client-side
to gate the welcome-screen buttons, the Run-menu dropdown and the mobile
overview — was built purely from each CLI's own installed-on-PATH resolver
(isClaudeAvailable() etc.), with no reference to the registry's `enabled`
flag at all. So disabling a CLI via the new Settings UI (or a hand-edited
clis.json) updated the settings row and nothing else: every launch surface
kept offering it, both live and after a full page reload, since even a
fresh render never consulted the registry.

Fixed in two places:

- server.ts: after building `available`, intersect the nine real
  SessionMode ids against `enabledClis()`. git/cloudflared (utility
  binaries, not CLI registry entries) and deepseekBinary (a secondary
  installed-only flag for the "add a profile" affordance) are deliberately
  left alone.
- settings-ui.js: `toggleCliEnabled()` now patches
  `window.__codemanCliAvailable` in place and refreshes the welcome screen,
  the mobile overview and an already-open Run menu, mirroring the existing
  `installDeepSeekProfile()` pattern for the same "injected once, needs an
  explicit patch" reason — without this half, the server-side fix alone
  still left every surface stale until the next reload.

New test in test/render-index-html.test.ts: an installed-but-disabled CLI
(codex, forced via clis.json + reloadCliRegistry()) reads as unavailable,
while an installed-and-enabled one (claude) is unaffected by the override.

Verified on the Debian devbox (codeman-devbox, real tmux — this sandbox has
none and WebServer's constructor hard-requires it): typecheck clean, the
new test passes (17/17 in render-index-html.test.ts), the CLI-registry
suites pass (86/86), and the full CI gate is green (415 test files, 7855
tests, 0 failures).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD

* docs(cli-registry): update the CLI-management plan with status, gotchas, and the Run-menu gap

Phases 1-6 were implemented across two commits (da07b38c, db4557d9) with no
corresponding update to the plan doc itself — every checklist still read
Status: TODO and every box unchecked. Brings the doc in line with the tree:

- A new "Status as of 2026-09-22" section up top: what's actually
  implemented (verified by grepping the routes/schema/UI, not just trusting
  the commit messages), the availability-flag staleness bug found and fixed
  in this session (commit 0c77dd0a) with its devbox verification record, and
  one real outstanding gap.

- The outstanding gap: a custom CLI created via Phase 5's write API has no
  way to actually be launched. The Run menu is static per-mode markup with
  no consumer of window.__codemanCliCatalog, so Phase 6's own "create a
  custom entry, confirm it can be launched" verify step was never actually
  exercised against this. Documented with two candidate fixes, neither
  started.

- Each phase's checklist flipped to [x] where confirmed present in the tree,
  Status lines updated from TODO to DONE, and the two originally-open
  questions (Phase 2's installed source, Phase 5's PUT endpoint shape)
  marked resolved against what actually shipped.

No code changes in this commit — documentation only, so a future session
(or the one already mid-flight on a separate checkout of this same branch)
picks up accurate status instead of a stale plan.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD

* docs: add the CLI-registry deployment plan and the parked Copilot plan

Both were sitting as untracked scratch files in the master checkout,
never committed to any branch. Moving them here rather than leaving them
loose:

- DEPLOYMENT_PLAN.md is the live tracker for the CLI-registry follow-up
  series (PR A #347 merged, PR B #380 merged, PR B2 merged as #458) and
  is where PR C (this branch's own CLI-management work) belongs.
- docs/copilot-integration-plan.md is explicitly PARKED, referenced by
  name in docs/cli-enable-disable-plan.md's own header as a sibling plan
  tracked separately — kept for continuity, not active on this branch.

The other scratch files found alongside these (PRA.md, PRB.md, PR-B2.md
and their review-response counterparts) described PR A/B/B2, all now
merged — deleted from the master checkout as stale rather than committed
anywhere, since their content is superseded by the real merged PRs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N6eadpRyqpA9PD3i139cSD

* fix(cli-registry): render enabled CLIs in launch surfaces

* test(cli-registry): update frontend branch guard

* fix(test): isolate suite from deployment environment

* fix(cli-registry): revise Decision 4 - claude is toggleable, shell stays permanent

shell/claude were both structurally un-disableable in the original plan
(Decision 4). Revised: shell keeps the hard backend guarantee (it is the
one non-agent mode several code paths assume always exists as a raw-
terminal fallback), but claude is now a normal toggleable entry like any
other CLI.

Safe to do because internal session creation (tmux-manager.ts, session.ts,
Ralph, plan-orchestrator) resolves a CLI via getCli(), which does not
check `enabled` at all - only the Run menu and the HTTP-facing
sessionModeSchema() (new session requests through the normal API) key off
it. Disabling claude therefore behaves identically in kind to disabling
any other CLI: no internal fallback path breaks, it just stops being
offered for new sessions until re-enabled.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* fix(cli-registry): hide shell's toggle entirely instead of greying it out

A permanently-disabled switch next to every other row's working toggle
read as broken rather than intentional. shell now renders no switch at
all - a plain "Always available" label - so there is nothing to click
that could look like it should work but doesn't. Backend guard is
unchanged (UNDISABLEABLE_IDS still refuses shell unconditionally); this
is UI-only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* fix(cli-registry): sort the Installed CLIs list, installed-first then alphabetical

renderCliList() previously rendered in registry order (each entry's fixed
order field). Now sorts installed CLIs first, then not-installed, each
group alphabetical by label - matches how a user actually scans the list
(what's ready to use, then what needs installing).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* style: prettier fixes from the master merge

* fix(cli-registry): install/edit take effect immediately, confirm before install, phone labels

Four gaps found verifying #476 against the #343 review trail:

- Installed or edited CLIs kept reading as missing/stale. Every binary lookup
  (the nine per-CLI resolvers and the generic registry one) caches in its own
  closure, with a negative-cache backoff of up to 5 minutes, and nothing
  cleared them. invalidateCliExecutableResolvers(binaries) now drops those
  caches per binary; install (success or failure), create, edit and delete
  call it plus invalidateCliResolverCache(id). Before this, a CLI installed
  from Settings could fail to launch for minutes, and an edited custom entry
  kept launching its old binary until a restart.
- The Settings "installed" badge for a custom entry used a private `which`,
  ignoring the entry's searchDirs and the login-shell lookup that spawn and
  the Run menu use; it now asks the same generic resolver they do.
- Install ran on a single click. The #343 review asked for auto-install to
  sit behind an explicit confirm; the confirm now names the exact command,
  which GET /api/clis returns for stock entries only (installCommand).
- The phone Run button showed the two-letter tab badge ("CC", "CX") instead
  of the word ("Claude", "Codex"). It uses the registry label again, which is
  identical to the old static table for every stock CLI (now pinned).

14 new tests; 9 of them fail against the previous head and pass here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* fix(cli-registry): address #476 review — safe serialized writes, no id branches, docs

Must-fix:
- registry-writer: start fresh only on ENOENT; refuse (409) a clis.json that
  does not parse or has group/world permission bits instead of overwriting it
  (isUnsafePermissions now exported from registry.ts)
- mutateRegistryFile(): one promise chain for every mutation, with the
  existence/duplicate checks inside the serialized step, plus a unique tmp
  name per write
- docs: CLAUDE.md, architecture-invariants, cli-registry (new Settings
  section) and api-reference (the six /api/clis routes)
- drop DEPLOYMENT_PLAN.md and docs/copilot-integration-plan.md

Smaller:
- PUT /api/clis/custom/:id keeps the entry's current enabled state when the
  body omits it
- runMode setter falls back to the first enabled catalogue entry, not 'claude'
- shell guard keyed on kind === 'shell' (routes + Settings list); stock probe
  map shared with server.ts via utils/cli-installed-probes.ts
- stock claude label is now 'Claude Code', so the Run menu / phone overview
  label rewrites are gone (doctor row keeps "Claude CLI" via its override)
- welcome buttons are translatable again and read "Run Claude Code" /
  "Run Shell"; zh-CN gains "Run Codex" / "Run OMP"
- install: per-id in-flight guard (409) and CODEMAN_* stripped from its env
- fileoverview / CliEnableSchema comments no longer say stock-only
- test-env isolation changes moved to their own PR

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

* test(cli-registry): pin the #343/#347 findings #476 makes reachable

A CLI toggled or created through the routes is accepted or rejected by
CreateSessionSchema with no restart (#343 finding 2), and a custom CLI created
through the API renders a real local, remote and docker launch command
(#347 finding 5: no more `cd <path> && undefined`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GuHtuPiHXdykq9T6rKQJ9n

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-24 01:48:26 +02:00

445 lines
18 KiB
TypeScript

import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { EXEC_TIMEOUT_MS } from '../src/config/exec-timeout.js';
import {
cliResolveRetryDelayMs,
createCliExecutableResolver,
createProductionCliResolverHost,
formatCliNotFoundMessage,
invalidateCliExecutableResolvers,
type CliResolverHost,
} from '../src/utils/cli-executable-resolver.js';
// Pass-through spy on execFileSync so the vitest-hermeticity test below can
// PROVE the un-injected production host never spawns anything.
const { execFileSyncSpy } = vi.hoisted(() => ({ execFileSyncSpy: vi.fn() }));
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
execFileSyncSpy.mockImplementation(actual.execFileSync as (...args: unknown[]) => unknown);
return { ...actual, execFileSync: execFileSyncSpy };
});
const BEGIN_MARKER = '__CODEMAN_CLI_RESOLVE_BEGIN__';
const END_MARKER = '__CODEMAN_CLI_RESOLVE_END__';
const temporaryDirectories: string[] = [];
afterEach(() => {
for (const directory of temporaryDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
function host(overrides: Partial<CliResolverHost> = {}): CliResolverHost {
return {
processPath: '/usr/bin:/bin',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
findOnProcessPath: vi.fn(() => null),
findInLoginShell: vi.fn(() => null),
exists: vi.fn(() => false),
...overrides,
};
}
describe('createCliExecutableResolver', () => {
it('prefers the server process PATH over common directories and the login shell', () => {
const h = host({
findOnProcessPath: vi.fn(() => '/process/bin/codex'),
findInLoginShell: vi.fn(() => '/shell/bin/codex'),
exists: vi.fn(() => true),
});
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: ['/known/bin'] }, h);
expect(resolver.resolve()).toMatchObject({ binaryPath: '/process/bin/codex', source: 'process-path' });
expect(h.exists).toHaveBeenCalledTimes(1);
expect(h.findInLoginShell).not.toHaveBeenCalled();
});
it('prefers common directories in order over the login shell', () => {
const h = host({
findInLoginShell: vi.fn(() => '/shell/bin/codex'),
exists: vi.fn((path) => path === '/second/bin/codex' || path === '/shell/bin/codex'),
});
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: ['/first/bin', '/second/bin'] }, h);
expect(resolver.resolve()).toMatchObject({ binaryPath: '/second/bin/codex', source: 'common-directory' });
expect(h.exists).toHaveBeenNthCalledWith(1, '/first/bin/codex');
expect(h.exists).toHaveBeenNthCalledWith(2, '/second/bin/codex');
expect(h.findInLoginShell).not.toHaveBeenCalled();
});
it('finds an executable exposed only by the interactive login shell', () => {
const h = host({
findInLoginShell: vi.fn(() => '/home/u/.nvm/versions/node/v22/bin/codex'),
exists: vi.fn((path) => path === '/home/u/.nvm/versions/node/v22/bin/codex'),
});
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: ['/known/bin'] }, h);
expect(resolver.resolve()).toMatchObject({
binaryPath: '/home/u/.nvm/versions/node/v22/bin/codex',
directory: '/home/u/.nvm/versions/node/v22/bin',
source: 'login-shell',
});
});
it('continues after a validator rejects an earlier candidate', () => {
const h = host({
findOnProcessPath: vi.fn(() => '/usr/bin/pi'),
findInLoginShell: vi.fn(() => '/home/u/.npm/bin/pi'),
exists: vi.fn(() => true),
});
const resolver = createCliExecutableResolver(
{
binary: 'pi',
searchDirs: [],
validateCandidate: (path) =>
path.includes('.npm') ? { accepted: true, metadata: '0.84.1' } : { accepted: false },
},
h
);
expect(resolver.resolve()).toMatchObject({
binaryPath: '/home/u/.npm/bin/pi',
source: 'login-shell',
metadata: '0.84.1',
});
});
it('caches success, and retries a miss only after the backoff elapses', () => {
let now = 0;
const findInLoginShell = vi.fn<() => string | null>().mockReturnValueOnce(null).mockReturnValue('/new/bin/codex');
const h = host({ findInLoginShell, exists: vi.fn((path) => path === '/new/bin/codex') });
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: [], now: () => now }, h);
expect(resolver.resolve()).toBeNull();
// Within the backoff window the miss is answered from the negative cache:
// the chain — whose login-shell tail is a synchronous 5s-bounded spawn —
// must NOT re-run per call, or a missing CLI stalls every status request.
now = cliResolveRetryDelayMs(1) - 1;
expect(resolver.resolve()).toBeNull();
expect(findInLoginShell).toHaveBeenCalledTimes(1);
// Once the backoff elapses the retry runs, so installing a CLI while the
// server is up is still picked up without a restart.
now = cliResolveRetryDelayMs(1);
expect(resolver.resolve()?.binaryPath).toBe('/new/bin/codex');
expect(resolver.resolve()?.binaryPath).toBe('/new/bin/codex');
expect(findInLoginShell).toHaveBeenCalledTimes(2);
});
it('invalidation drops a negative-cache backoff immediately (a CLI installed from Settings)', () => {
let now = 0;
const findInLoginShell = vi.fn<() => string | null>().mockReturnValueOnce(null).mockReturnValue('/new/bin/grokx');
const h = host({ findInLoginShell, exists: vi.fn((path) => path === '/new/bin/grokx') });
const resolver = createCliExecutableResolver({ binary: 'grokx', searchDirs: [], now: () => now }, h);
expect(resolver.resolve()).toBeNull();
// Still inside the backoff window: without invalidation this answers from the
// negative cache for up to five minutes after a successful install.
now = 1;
invalidateCliExecutableResolvers(['grokx']);
expect(resolver.resolve()?.binaryPath).toBe('/new/bin/grokx');
expect(findInLoginShell).toHaveBeenCalledTimes(2);
});
it('invalidation drops a cached success too, so an edited binary is re-resolved', () => {
const findOnProcessPath = vi
.fn<() => string | null>()
.mockReturnValueOnce('/old/bin/editedx')
.mockReturnValue('/new/bin/editedx');
const h = host({ findOnProcessPath, exists: vi.fn(() => true) });
const resolver = createCliExecutableResolver({ binary: 'editedx', searchDirs: [] }, h);
expect(resolver.resolve()?.binaryPath).toBe('/old/bin/editedx');
expect(resolver.resolve()?.binaryPath).toBe('/old/bin/editedx');
invalidateCliExecutableResolvers(['editedx']);
expect(resolver.resolve()?.binaryPath).toBe('/new/bin/editedx');
// And the fresh result is cached again rather than re-probed every call.
expect(resolver.resolve()?.binaryPath).toBe('/new/bin/editedx');
expect(findOnProcessPath).toHaveBeenCalledTimes(2);
});
it('invalidation is scoped to the named binaries and leaves every other cache alone', () => {
const findOnProcessPath = vi.fn(() => '/bin/untouchedx');
const h = host({ findOnProcessPath, exists: vi.fn(() => true) });
const resolver = createCliExecutableResolver({ binary: 'untouchedx', searchDirs: [] }, h);
resolver.resolve();
invalidateCliExecutableResolvers(['some-other-binary']);
resolver.resolve();
expect(findOnProcessPath).toHaveBeenCalledTimes(1);
});
it('doubles the retry delay per consecutive miss and caps it at five minutes', () => {
let now = 0;
const findInLoginShell = vi.fn(() => null);
const resolver = createCliExecutableResolver(
{ binary: 'codex', searchDirs: [], now: () => now },
host({ findInLoginShell })
);
expect(cliResolveRetryDelayMs(0)).toBe(0);
expect(cliResolveRetryDelayMs(1)).toBe(60_000);
expect(cliResolveRetryDelayMs(2)).toBe(120_000);
expect(cliResolveRetryDelayMs(3)).toBe(240_000);
expect(cliResolveRetryDelayMs(4)).toBe(300_000);
expect(cliResolveRetryDelayMs(60)).toBe(300_000);
// Consecutive misses stack: after the second miss the SECOND delay applies.
expect(resolver.resolve()).toBeNull();
now += cliResolveRetryDelayMs(1);
expect(resolver.resolve()).toBeNull();
expect(findInLoginShell).toHaveBeenCalledTimes(2);
now += cliResolveRetryDelayMs(2) - 1;
expect(resolver.resolve()).toBeNull();
expect(findInLoginShell).toHaveBeenCalledTimes(2);
now += 1;
expect(resolver.resolve()).toBeNull();
expect(findInLoginShell).toHaveBeenCalledTimes(3);
});
it('rejects unsafe binary names', () => {
const h = host();
expect(() => createCliExecutableResolver({ binary: 'codex;id', searchDirs: [] }, h)).toThrow(
'Unsafe CLI binary name'
);
expect(() => createCliExecutableResolver({ binary: '../codex', searchDirs: [] }, h)).toThrow(
'Unsafe CLI binary name'
);
});
it('rejects relative and nonexistent candidates', () => {
let now = 0;
const findInLoginShell = vi
.fn<() => string | null>()
.mockReturnValueOnce('relative/codex')
.mockReturnValue('/missing/codex');
const h = host({ findInLoginShell, exists: vi.fn(() => false) });
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: [], now: () => now }, h);
expect(resolver.resolve()).toBeNull();
now = cliResolveRetryDelayMs(1);
expect(resolver.resolve()).toBeNull();
expect(h.exists).toHaveBeenCalledTimes(1);
expect(h.exists).toHaveBeenCalledWith('/missing/codex');
});
});
describe('formatCliNotFoundMessage', () => {
it('includes only the base install hint and bounded resolution diagnostics', () => {
const base = 'Codex CLI not found. Install with: npm install -g @openai/codex';
const diagnostics = {
binary: 'codex',
processPath: '/usr/bin:/bin',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
searchDirs: ['/home/u/.local/bin', '/usr/local/bin'],
API_KEY: 'super-secret',
};
const message = formatCliNotFoundMessage(base, diagnostics);
expect(message).toContain(base);
expect(message).toContain('Server PATH: /usr/bin:/bin');
expect(message).toContain('Login shell: /bin/bash -i -l');
expect(message).toContain('Checked directories: /home/u/.local/bin, /usr/local/bin');
expect(message).not.toContain('API_KEY');
expect(message).not.toContain('super-secret');
});
it('marks empty diagnostic values without dumping arbitrary environment data', () => {
const message = formatCliNotFoundMessage('Missing CLI', {
binary: 'codex',
processPath: '',
shellPath: '',
shellArgs: [],
searchDirs: [],
});
expect(message).toBe('Missing CLI\nServer PATH: (empty)\nLogin shell: (none)\nChecked directories: (none)');
expect(message).not.toContain('HOME=');
expect(message).not.toContain('TOKEN=');
});
it('flattens control characters and bounds every diagnostic field', () => {
const pathological = `first\r\nforged label: value\u0000${'x'.repeat(10_000)}`;
const message = formatCliNotFoundMessage('Missing CLI', {
binary: 'codex',
processPath: pathological,
shellPath: pathological,
shellArgs: [pathological],
searchDirs: [pathological, pathological],
});
const lines = message.split('\n');
expect(lines).toHaveLength(4);
expect(lines[1]).toMatch(/^Server PATH: first forged label: value x+…$/);
expect(lines[2]).toMatch(/^Login shell: first forged label: value x+…$/);
expect(lines[3]).toMatch(/^Checked directories: first forged label: value x+…$/);
expect(lines.slice(1).every((line) => line.length <= 1_050)).toBe(true);
});
});
describe('createProductionCliResolverHost', () => {
// Hermeticity gate (the guards PR #329 deleted, restored shared): under
// vitest an un-injected host must neither scan the machine nor spawn a login
// shell — route tests hitting the per-CLI status endpoints would otherwise
// walk the real PATH and execute real binaries on whatever box runs the suite.
it('never scans the machine or spawns a login shell under vitest without injected IO', () => {
const root = mkdtempSync(join(tmpdir(), 'codeman-cli-vitest-gate-'));
temporaryDirectories.push(root);
writeFileSync(join(root, 'codex'), '#!/bin/sh\n');
chmodSync(join(root, 'codex'), 0o755);
execFileSyncSpy.mockClear();
const gatedHost = createProductionCliResolverHost({
processPath: root,
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
});
// The real, executable candidate is invisible: the filesystem predicate is inert.
expect(gatedHost.findOnProcessPath('codex')).toBeNull();
expect(gatedHost.exists(join(root, 'codex'))).toBe(false);
// The login-shell step yields nothing and never reaches execFileSync.
expect(gatedHost.findInLoginShell('codex')).toBeNull();
expect(execFileSyncSpy).not.toHaveBeenCalled();
// The same fixture through the test-only real-IO opt-in IS found, proving
// the nulls above come from the vitest gate rather than from the fixture.
const optedInHost = createProductionCliResolverHost({
processPath: root,
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
runCommand: () => '',
allowRealIoUnderVitest: true,
});
expect(optedInHost.findOnProcessPath('codex')).toBe(join(root, 'codex'));
});
it('resolves through injected IO hooks under vitest (injection is the opt-in)', () => {
const runCommand = vi.fn(() => `${BEGIN_MARKER}\n/home/u/.nvm/bin/codex\n${END_MARKER}`);
const productionHost = createProductionCliResolverHost({
processPath: '',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
runCommand,
isExecutableFile: () => true,
});
const resolver = createCliExecutableResolver({ binary: 'codex', searchDirs: [] }, productionHost);
expect(resolver.resolve()).toMatchObject({
binaryPath: '/home/u/.nvm/bin/codex',
source: 'login-shell',
});
expect(runCommand).toHaveBeenCalledTimes(1);
});
it('searches the captured process PATH directly in directory order without running a command', () => {
const runCommand = vi.fn(() => '');
const isExecutableFile = vi.fn((path: string) => path === '/second/bin/codex');
const productionHost = createProductionCliResolverHost({
processPath: '/first/bin:/second/bin:/third/bin',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
runCommand,
isExecutableFile,
});
expect(productionHost.findOnProcessPath('codex')).toBe('/second/bin/codex');
expect(isExecutableFile).toHaveBeenNthCalledWith(1, '/first/bin/codex');
expect(isExecutableFile).toHaveBeenNthCalledWith(2, '/second/bin/codex');
expect(runCommand).not.toHaveBeenCalled();
});
it('accepts only executable regular files with the production predicate', () => {
const root = mkdtempSync(join(tmpdir(), 'codeman-cli-resolver-'));
temporaryDirectories.push(root);
const executableDirectory = join(root, 'executable');
const plainDirectory = join(root, 'plain');
const directoryCandidate = join(root, 'directory');
mkdirSync(executableDirectory);
mkdirSync(plainDirectory);
mkdirSync(directoryCandidate);
writeFileSync(join(executableDirectory, 'codex'), '#!/bin/sh\n');
chmodSync(join(executableDirectory, 'codex'), 0o755);
writeFileSync(join(plainDirectory, 'codex'), '#!/bin/sh\n');
mkdirSync(join(directoryCandidate, 'codex'));
const productionHost = createProductionCliResolverHost({
processPath: [directoryCandidate, plainDirectory, executableDirectory].join(':'),
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
// This test exists to exercise the REAL executable-regular-file predicate
// against its own temp fixtures, so it opts out of the vitest inert-IO
// gate; the stubbed runCommand keeps the login-shell path inert anyway.
runCommand: () => '',
allowRealIoUnderVitest: true,
});
expect(productionHost.findOnProcessPath('codex')).toBe(join(executableDirectory, 'codex'));
});
it('uses the resolved shell, allowlisted args, tagged command, and bounded timeout', () => {
const runCommand = vi.fn(() =>
['/profile/absolute-noise', BEGIN_MARKER, '/home/u/.nvm/bin/codex', END_MARKER, '/exit-trap/absolute-noise'].join(
'\n'
)
);
const productionHost = createProductionCliResolverHost({
processPath: '',
shellPath: '/usr/bin/fish',
shellArgs: ['-i', '-l'],
runCommand,
isExecutableFile: () => true,
});
expect(productionHost.findInLoginShell('codex')).toBe('/home/u/.nvm/bin/codex');
expect(runCommand).toHaveBeenCalledWith(
'/usr/bin/fish',
['-i', '-l', '-c', `printf '%s\\n' '${BEGIN_MARKER}'; command -v -- codex; printf '%s\\n' '${END_MARKER}'`],
{
encoding: 'utf8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
// SIGKILL is load-bearing: interactive bash ignores SIGTERM, and
// execFileSync's timeout only sends the signal, then keeps waiting.
killSignal: 'SIGKILL',
}
);
});
it.each([
['mismatched basename', `${BEGIN_MARKER}\n/opt/bin/not-codex\n${END_MARKER}`],
['missing begin marker', `/opt/bin/codex\n${END_MARKER}`],
['missing end marker', `${BEGIN_MARKER}\n/opt/bin/codex`],
['absolute output outside markers', `/profile/codex\n${BEGIN_MARKER}\nrelative/codex\n${END_MARKER}\n/exit/codex`],
])('rejects malformed tagged shell output: %s', (_name, output) => {
const productionHost = createProductionCliResolverHost({
processPath: '',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
runCommand: () => output,
isExecutableFile: () => true,
});
expect(productionHost.findInLoginShell('codex')).toBeNull();
});
it('returns null when the shell command throws', () => {
const productionHost = createProductionCliResolverHost({
processPath: '',
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'],
runCommand: () => {
throw new Error('exit 1');
},
isExecutableFile: () => true,
});
expect(productionHost.findInLoginShell('codex')).toBeNull();
});
});