Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix Windows Desktop GitHub connect/clone spawn EINVAL (PRD-7998) (#4339)
mike-inkeepab6d38a28e2c
diff --git a/.changeset/windows-local-op-spawn-einval.md b/.changeset/windows-local-op-spawn-einval.mdnew file mode 100644index 000000000..db1b82036--- /dev/null+++ b/.changeset/windows-local-op-spawn-einval.md@@ -0,0 +1,13 @@+---+"@inkeep/open-knowledge": patch+---++Connect GitHub and Clone repository work again on Windows Desktop.++Both failed instantly with `spawn EINVAL` on every packaged Windows install since 0.47.0, the first release to ship Windows installers. The Navigator window ran its GitHub sign-in, sign-in status, repository list, and clone helpers by spawning the bundled `ok.cmd` batch wrapper directly, and Node refuses to spawn a `.cmd` or `.bat` file without a shell (its CVE-2024-27980 mitigation). The same operations from a project window went through the detached server, which already spawned the Electron binary as Node, so they worked.++Desktop now hands those helpers what the wrapper would have run: `OpenKnowledge.exe` with `ELECTRON_RUN_AS_NODE=1` on the bundled `cli.mjs`, with `NODE_OPTIONS` moved aside to `OK_NODE_OPTIONS` exactly as `ok.cmd` does. No shell is involved, so clone URLs and target paths are never interpreted by `cmd.exe`. macOS and Linux keep spawning their executable `ok.sh` wrapper.++A helper spawn that throws synchronously now resolves as a normal failed run with the error text in stderr instead of escaping the IPC handler, so a future failure of this shape lands in the desktop log rather than only in the renderer console.++Three of these changes reach every platform, not just Windows. Cancelling a GitHub sign-in or a repository clone now ends the run quietly instead of reporting it as a failure. Error text from a failed sign-in or clone is scrubbed before it is shown or written to the log: a GitHub token is redacted, and a home directory inside a path is shortened to `~`, so a clone that stops because the folder already exists now reads `~/Documents/repo` rather than your full home path. And if a second sign-in starts while one is already running, the first one now ends with a message saying it was replaced, instead of leaving its dialog counting down a device code that is no longer being polled.diff --git a/knip.config.ts b/knip.config.tsindex 11f947931..3fb895477 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -152,6 +152,7 @@ export default {'src/utility/server-entry.ts','src/utility/pty-host.ts','src/**/*.test.ts',+ 'src/**/*.typelock.ts','scripts/*.mjs','tests/**/*.test.ts','tests/**/*.test.mjs',diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 59d7c01b0..9da728126 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -692,7 +692,7 @@ export interface OkLocalOpRepoEntry {export type OkLocalOpAuthReposResponse =| { ok: true; host: string; repos: OkLocalOpRepoEntry[] }- | { ok: false; error: string };+ | { ok: false; error: string; authenticated?: false };export type OkEditorActiveTargetSnapshot =| { readonly kind: 'doc'; readonly identifier: string }diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 33a739ab5..7e228939c 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -82,6 +82,7 @@ import {getMeter,initContent,isProcessAlive,+ type LocalOpCliInvocation,normalizeFsPath,ONBOARDING_BUNDLE_IDS,prepareSingleFileOpen,@@ -316,6 +317,7 @@ import {detectGraphicalAuthCommand,runManualInstallFallbackDialog,} from './linux-install-fallback.ts';+import { resolveLocalOpCliInvocation } from './local-op-cli-invocation.ts';import { createMenuTranslator, resolveMenuCatalogDir } from './main-i18n.ts';import { createMainThreadWatchdog } from './main-thread-watchdog.ts';import {@@ -1145,11 +1147,14 @@ function isDebugKeyringSmokeAllowed(): boolean {return !app.isPackaged || process.env.OK_DEBUG_KEYRING_SMOKE === '1';}-function resolveLocalOpCliArgs(): string[] {- if (app.isPackaged) {- return [wrapperPathInBundle(app.getPath('exe'))];- }- return ['open-knowledge'];+function resolveLocalOpCli(): LocalOpCliInvocation {+ return resolveLocalOpCliInvocation({+ platform: process.platform,+ isPackaged: app.isPackaged,+ execPath: app.getPath('exe'),+ resourcesPath: process.resourcesPath,+ parentEnv: process.env,+ });}function runDriverBootSmokeInProduction(): void {@@ -1937,7 +1942,7 @@ async function openProject(pendingShareBranchSwitch,didEnsureGit,consentVersion: 1,- localOpCliArgs: resolveLocalOpCliArgs(),+ localOpCliInvocation: resolveLocalOpCli(),freshlyCreated: entryPoint === 'create-new',});getLogger('project').info(@@ -4885,7 +4890,7 @@ function registerIpcHandlers() {try {const senderWindow = BrowserWindow.fromWebContents(event.sender);const outcome = await wm.restartServerForWindow(senderWindow, projectPath, {- localOpCliArgs: resolveLocalOpCliArgs(),+ localOpCliInvocation: resolveLocalOpCli(),});if (outcome.ok === false) {logIpcError({@@ -5153,7 +5158,8 @@ function registerIpcHandlers() {});const localOpDeps: LocalOpDeps = {- resolveCliArgs: resolveLocalOpCliArgs,+ resolveCliInvocation: resolveLocalOpCli,+ logFailure: logIpcError,state: createLocalOpState(),};handle('ok:local-op:auth:start', async (event) => {@@ -5918,7 +5924,7 @@ function bootPrimaryInstance(): void {let authenticated = false;try {const status = await runAuthStatusSubprocess({- cliArgs: resolveLocalOpCliArgs(),+ ...resolveLocalOpCli(),host,});authenticated = status.authenticated;diff --git a/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts b/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.tsindex f4f5fee4d..da82b5d5b 100644--- a/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts+++ b/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts@@ -70,7 +70,8 @@ function makeSender() {function makeDeps() {return {- resolveCliArgs: () => ['open-knowledge'],+ resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ logFailure: vi.fn(),state: createLocalOpState(),};}diff --git a/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts b/packages/desktop/src/main/ipc/local-op-clone-branch.test.tsindex 872e89332..6fe3ec3e4 100644--- a/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts+++ b/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts@@ -49,7 +49,8 @@ function makeSender(captured: CapturedSend[]) {function makeDeps() {return {- resolveCliArgs: () => ['open-knowledge'],+ resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ logFailure: vi.fn(),state: createLocalOpState(),};}diff --git a/packages/desktop/src/main/ipc/local-op-failure-logging.test.ts b/packages/desktop/src/main/ipc/local-op-failure-logging.test.tsnew file mode 100644index 000000000..d7ad19e8b--- /dev/null+++ b/packages/desktop/src/main/ipc/local-op-failure-logging.test.ts@@ -0,0 +1,304 @@+import type {+ AuthEvent,+ AuthReposResponse,+ AuthStatusResponse,+ CloneEvent,+} from '@inkeep/open-knowledge-server';+import { beforeEach, describe, expect, test, vi } from 'vitest';++interface StreamEntry<E> {+ resolve: () => void;+ onEvent: (event: E) => void;+}++const deviceFlowControllers: StreamEntry<AuthEvent>[] = [];+const cloneControllers: StreamEntry<CloneEvent>[] = [];++let statusResponse: AuthStatusResponse = { authenticated: false, host: 'github.com' };+let reposResponse: AuthReposResponse = { ok: true, host: 'github.com', repos: [] };++function pushController<E>(+ registry: StreamEntry<E>[],+ onEvent: (event: E) => void,+): { done: Promise<void>; cancel: () => void } {+ let resolveDone: () => void = () => {};+ const done = new Promise<void>((resolve) => {+ resolveDone = resolve;+ });+ registry.push({ resolve: resolveDone, onEvent });+ return { done, cancel: () => {} };+}++vi.doMock('@inkeep/open-knowledge-server', () => ({+ runAuthStatusSubprocess: () => Promise.resolve(statusResponse),+ runAuthReposSubprocess: () => Promise.resolve(reposResponse),+ runDeviceFlowSubprocess: ({ onEvent }: { onEvent: (event: AuthEvent) => void }) =>+ pushController(deviceFlowControllers, onEvent),+ runCloneSubprocess: ({ onEvent }: { onEvent: (event: CloneEvent) => void }) =>+ pushController(cloneControllers, onEvent),+ validateCloneInputs: () => ({ ok: true }),+}));++const {+ createLocalOpState,+ handleAuthCancel,+ handleAuthRepos,+ handleAuthStart,+ handleAuthStatus,+ handleCloneCancel,+ handleCloneStart,+} = await import('./local-op.ts');++function makeSender() {+ return {+ isDestroyed: () => false,+ send: () => {},+ };+}++function makeDeps() {+ return {+ resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ logFailure: vi.fn(),+ state: createLocalOpState(),+ };+}++const CLONE_REQ = { url: 'https://example.test/r.git', dir: '/tmp/r' };++async function settle(): Promise<void> {+ await new Promise<void>((resolve) => setImmediate(resolve));+}++beforeEach(() => {+ deviceFlowControllers.length = 0;+ cloneControllers.length = 0;+ statusResponse = { authenticated: false, host: 'github.com' };+ reposResponse = { ok: true, host: 'github.com', repos: [] };+});++describe('handleAuthStart — terminal failure reaches the desktop log', () => {+ test('a terminal error event logs the spawn failure once the run settles', async () => {+ const deps = makeDeps();+ const result = handleAuthStart(deps, makeSender());+ expect(result.ok).toBe(true);++ deviceFlowControllers[0]?.onEvent({+ type: 'error',+ message: 'auth login exited with code -1 — spawn EINVAL',+ });+ expect(deps.logFailure).not.toHaveBeenCalled();++ deviceFlowControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:start',+ reason: 'auth login exited with code -1 — spawn EINVAL',+ handler: 'handleAuthStart',+ });+ });++ test('cancelling a sign-in that emitted no error clears the in-flight slot and logs nothing', async () => {+ const deps = makeDeps();+ const result = handleAuthStart(deps, makeSender());+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(deps.state.authInFlight).not.toBeNull();++ handleAuthCancel(deps, result.streamId);+ expect(deps.state.authInFlight).toBeNull();++ deviceFlowControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('a sign-in that emitted a terminal error before the user cancelled still logs it once', async () => {+ const deps = makeDeps();+ const result = handleAuthStart(deps, makeSender());+ expect(result.ok).toBe(true);+ if (!result.ok) return;++ deviceFlowControllers[0]?.onEvent({+ type: 'error',+ message: 'auth login exited with code -1 — spawn EINVAL',+ });+ handleAuthCancel(deps, result.streamId);+ deviceFlowControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:start',+ reason: 'auth login exited with code -1 — spawn EINVAL',+ handler: 'handleAuthStart',+ });+ });++ test('a successful sign-in logs nothing', async () => {+ const deps = makeDeps();+ handleAuthStart(deps, makeSender());++ deviceFlowControllers[0]?.onEvent({+ type: 'verification',+ user_code: 'ABCD',+ verification_uri: 'https://example.test/login',+ expires_in: 60,+ });+ deviceFlowControllers[0]?.onEvent({ type: 'complete', host: 'github.com', login: 'octocat' });+ deviceFlowControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).not.toHaveBeenCalled();+ });+});++describe('handleCloneStart — terminal failure reaches the desktop log', () => {+ test('a terminal error event logs the clone failure once the run settles', async () => {+ const deps = makeDeps();+ const result = handleCloneStart(deps, makeSender(), CLONE_REQ);+ expect(result.ok).toBe(true);++ cloneControllers[0]?.onEvent({+ type: 'error',+ message: 'Clone process exited with code -1 — spawn EINVAL',+ });+ cloneControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:clone:start',+ reason: 'Clone process exited with code -1 — spawn EINVAL',+ handler: 'handleCloneStart',+ });+ });++ test('cancelling a clone that emitted no error clears the in-flight slot and logs nothing', async () => {+ const deps = makeDeps();+ const result = handleCloneStart(deps, makeSender(), CLONE_REQ);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(deps.state.cloneInFlight).not.toBeNull();++ handleCloneCancel(deps, result.streamId);+ expect(deps.state.cloneInFlight).toBeNull();++ cloneControllers[0]?.onEvent({ type: 'progress', phase: 'receiving', pct: 12 });+ cloneControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('a clone that emitted a terminal error before the user cancelled still logs it once', async () => {+ const deps = makeDeps();+ const result = handleCloneStart(deps, makeSender(), CLONE_REQ);+ expect(result.ok).toBe(true);+ if (!result.ok) return;++ cloneControllers[0]?.onEvent({+ type: 'error',+ message: 'Clone process exited with code -1 — spawn EINVAL',+ });+ handleCloneCancel(deps, result.streamId);+ cloneControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:clone:start',+ reason: 'Clone process exited with code -1 — spawn EINVAL',+ handler: 'handleCloneStart',+ });+ });++ test('a successful clone logs nothing', async () => {+ const deps = makeDeps();+ handleCloneStart(deps, makeSender(), CLONE_REQ);++ cloneControllers[0]?.onEvent({ type: 'progress', phase: 'receiving', pct: 50 });+ cloneControllers[0]?.onEvent({ type: 'complete', port: 0, dir: '/tmp/r' });+ cloneControllers[0]?.resolve();+ await settle();++ expect(deps.logFailure).not.toHaveBeenCalled();+ });+});++describe('handleAuthStatus / handleAuthRepos — query failures reach the desktop log', () => {+ test('an unauthenticated status carrying no error does not log (benign poll)', async () => {+ statusResponse = { authenticated: false, host: 'github.com' };+ const deps = makeDeps();+ await handleAuthStatus(deps, { host: 'github.com' });+ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('an authenticated status does not log', async () => {+ statusResponse = { authenticated: true, host: 'github.com', login: 'octocat' };+ const deps = makeDeps();+ await handleAuthStatus(deps, { host: 'github.com' });+ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('a status carrying the subprocess stderr logs it', async () => {+ statusResponse = { authenticated: false, host: 'github.com', error: 'spawn EINVAL' };+ const deps = makeDeps();+ await handleAuthStatus(deps, { host: 'github.com' });+ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:status',+ reason: 'spawn EINVAL',+ handler: 'handleAuthStatus',+ });+ });++ test('two coalesced status callers produce a single log line', async () => {+ statusResponse = { authenticated: false, host: 'github.com', error: 'spawn EINVAL' };+ const deps = makeDeps();+ await Promise.all([+ handleAuthStatus(deps, { host: 'github.com' }),+ handleAuthStatus(deps, { host: 'github.com' }),+ ]);+ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ });++ test('a successful repos listing does not log', async () => {+ reposResponse = { ok: true, host: 'github.com', repos: [] };+ const deps = makeDeps();+ await handleAuthRepos(deps, { host: 'github.com' });+ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('a signed-out repos response does not log (first-run state, not a failure)', async () => {+ reposResponse = {+ ok: false,+ error: '[auth] token storage: OS keychain\nNot logged in to github.com',+ authenticated: false,+ };+ const deps = makeDeps();+ await handleAuthRepos(deps, { host: 'github.com' });+ expect(deps.logFailure).not.toHaveBeenCalled();+ });++ test('a failed repos listing logs the subprocess error', async () => {+ reposResponse = { ok: false, error: 'auth repos exited with code -1' };+ const deps = makeDeps();+ await handleAuthRepos(deps, { host: 'github.com' });+ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:repos',+ reason: 'auth repos exited with code -1',+ handler: 'handleAuthRepos',+ });+ });+});diff --git a/packages/desktop/src/main/ipc/local-op.test.ts b/packages/desktop/src/main/ipc/local-op.test.tsindex ae931f6c2..114f9b21e 100644--- a/packages/desktop/src/main/ipc/local-op.test.ts+++ b/packages/desktop/src/main/ipc/local-op.test.ts@@ -23,7 +23,8 @@ const { createLocalOpState, handleAuthRepos, handleAuthStatus } = await import('function makeDeps() {return {- resolveCliArgs: () => ['open-knowledge'],+ resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ logFailure: vi.fn(),state: createLocalOpState(),};}@@ -69,6 +70,13 @@ describe('handleAuthStatus — coalescing + concurrency cap', () => {host: 'h5',error: 'too many concurrent auth status queries',});+ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:status',+ reason: 'too many concurrent auth status queries',+ handler: 'handleAuthStatus',+ });for (const call of statusCalls) {call.resolve({ authenticated: false, host: call.host ?? 'github.com' });@@ -122,6 +130,13 @@ describe('handleAuthRepos — coalescing + concurrency cap', () => {ok: false,error: 'too many concurrent auth repos queries',});+ expect(deps.logFailure).toHaveBeenCalledTimes(1);+ expect(deps.logFailure).toHaveBeenCalledWith({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:repos',+ reason: 'too many concurrent auth repos queries',+ handler: 'handleAuthRepos',+ });for (const call of reposCalls) {call.resolve({ ok: true, host: call.host ?? 'github.com', repos: [] });diff --git a/packages/desktop/src/main/ipc/local-op.ts b/packages/desktop/src/main/ipc/local-op.tsindex 6d1d1ec80..898cb27e1 100644--- a/packages/desktop/src/main/ipc/local-op.ts+++ b/packages/desktop/src/main/ipc/local-op.ts@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto';import {type AuthReposResponse,type AuthStatusResponse,+ type LocalOpCliInvocation,type RunCloneController,type RunDeviceFlowController,runAuthReposSubprocess,@@ -40,8 +41,16 @@ export function createLocalOpState(): LocalOpHandlerState {};}+interface LocalOpFailure {+ readonly event: 'ipc.error';+ readonly channel: string;+ readonly reason: string;+ readonly handler: string;+}+export interface LocalOpDeps {- resolveCliArgs: () => readonly string[];+ resolveCliInvocation: () => LocalOpCliInvocation;+ logFailure: (failure: LocalOpFailure) => void;state: LocalOpHandlerState;}@@ -63,9 +72,11 @@ export function handleAuthStart(}),);}+ let terminalError: string | null = null;const controller = runDeviceFlowSubprocess({- cliArgs: deps.resolveCliArgs(),+ ...deps.resolveCliInvocation(),onEvent: (event) => {+ if (event.type === 'error') terminalError = event.message;if (!sender.isDestroyed?.()) {sendToRenderer(sender, 'ok:local-op:auth:event', { streamId, event });}@@ -76,6 +87,14 @@ export function handleAuthStart(if (deps.state.authInFlight?.streamId === streamId) {deps.state.authInFlight = null;}+ if (terminalError !== null) {+ deps.logFailure({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:start',+ reason: terminalError,+ handler: 'handleAuthStart',+ });+ }});return { ok: true, streamId };}@@ -116,12 +135,14 @@ export function handleCloneStart(}),);}+ let terminalError: string | null = null;const controller = runCloneSubprocess({- cliArgs: deps.resolveCliArgs(),+ ...deps.resolveCliInvocation(),url: request.url,dir: request.dir,branch: request.branch,onEvent: (event) => {+ if (event.type === 'error') terminalError = event.message;if (sender.isDestroyed?.()) return;sendToRenderer(sender, 'ok:local-op:clone:event', { streamId, event });},@@ -131,6 +152,14 @@ export function handleCloneStart(if (deps.state.cloneInFlight?.streamId === streamId) {deps.state.cloneInFlight = null;}+ if (terminalError !== null) {+ deps.logFailure({+ event: 'ipc.error',+ channel: 'ok:local-op:clone:start',+ reason: terminalError,+ handler: 'handleCloneStart',+ });+ }});return { ok: true, streamId };}@@ -172,19 +201,31 @@ export function handleAuthStatus(request?: { host?: string },): Promise<AuthStatusResponse> {const host = request?.host ?? DEFAULT_AUTH_QUERY_HOST;+ const logged = (response: AuthStatusResponse): AuthStatusResponse => {+ if (!response.authenticated && response.error !== undefined) {+ deps.logFailure({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:status',+ reason: response.error,+ handler: 'handleAuthStatus',+ });+ }+ return response;+ };return runCoalescedAuthQuery(deps.state.authStatusInFlight,host,() =>runAuthStatusSubprocess({- cliArgs: deps.resolveCliArgs(),+ ...deps.resolveCliInvocation(),host: request?.host,+ }).then(logged),+ (h) =>+ logged({+ authenticated: false,+ host: h,+ error: 'too many concurrent auth status queries',}),- (h) => ({- authenticated: false,- host: h,- error: 'too many concurrent auth status queries',- }),);}@@ -193,17 +234,29 @@ export function handleAuthRepos(request?: { host?: string },): Promise<AuthReposResponse> {const host = request?.host ?? DEFAULT_AUTH_QUERY_HOST;+ const logged = (response: AuthReposResponse): AuthReposResponse => {+ if (!response.ok && response.authenticated !== false) {+ deps.logFailure({+ event: 'ipc.error',+ channel: 'ok:local-op:auth:repos',+ reason: response.error,+ handler: 'handleAuthRepos',+ });+ }+ return response;+ };return runCoalescedAuthQuery(deps.state.authReposInFlight,host,() =>runAuthReposSubprocess({- cliArgs: deps.resolveCliArgs(),+ ...deps.resolveCliInvocation(),host: request?.host,+ }).then(logged),+ () =>+ logged({+ ok: false,+ error: 'too many concurrent auth repos queries',}),- () => ({- ok: false,- error: 'too many concurrent auth repos queries',- }),);}diff --git a/packages/desktop/src/main/local-op-cli-invocation.test.ts b/packages/desktop/src/main/local-op-cli-invocation.test.tsnew file mode 100644index 000000000..0f43291c8--- /dev/null+++ b/packages/desktop/src/main/local-op-cli-invocation.test.ts@@ -0,0 +1,150 @@+import { describe, expect, test } from 'vitest';+import {+ resolveLocalOpCliArgsForUtilityFork,+ resolveLocalOpCliInvocation,+} from './local-op-cli-invocation.ts';++const WIN_EXE =+ 'C:\\Users\\q\\AppData\\Local\\Programs\\@inkeepopen-knowledge-desktop\\OpenKnowledge.exe';+const WIN_RESOURCES =+ 'C:\\Users\\q\\AppData\\Local\\Programs\\@inkeepopen-knowledge-desktop\\resources';++const isWindowsBatchFile = (file: string): boolean => /\.(cmd|bat)$/i.test(file);++describe('resolveLocalOpCliInvocation', () => {+ test('dev builds resolve the CLI from PATH with no env overlay', () => {+ expect(+ resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: false,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ }),+ ).toEqual({ cliArgs: ['open-knowledge'] });+ });++ test('packaged win32 spawns OpenKnowledge.exe as Node on the bundled CLI, never the .cmd wrapper', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ });+ expect(invocation.cliArgs).toEqual([WIN_EXE, `${WIN_RESOURCES}\\cli\\dist\\cli.mjs`]);+ expect(isWindowsBatchFile(invocation.cliArgs[0] ?? '')).toBe(false);+ expect(invocation.cliEnv).toMatchObject({ ELECTRON_RUN_AS_NODE: '1' });+ });++ test('packaged win32 targets the keyring-resolvable cli/dist copy, not the app.asar.unpacked one', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ });+ const entry = invocation.cliArgs[1] ?? '';+ expect(entry).toBe(`${WIN_RESOURCES}\\cli\\dist\\cli.mjs`);+ expect(entry).not.toContain('app.asar.unpacked');+ });++ test('packaged win32 moves NODE_OPTIONS aside the way ok.cmd does', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: { NODE_OPTIONS: '--require ./hook.js' },+ });+ expect(invocation.cliEnv).toEqual({+ ELECTRON_RUN_AS_NODE: '1',+ NODE_OPTIONS: undefined,+ OK_NODE_OPTIONS: '--require ./hook.js',+ });+ expect(Object.hasOwn(invocation.cliEnv ?? {}, 'NODE_OPTIONS')).toBe(true);+ });++ test('packaged win32 without NODE_OPTIONS still clears it and sets no OK_NODE_OPTIONS', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: { PATH: 'C:\\Windows' },+ });+ expect(invocation.cliEnv).toEqual({ ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: undefined });+ });++ test('packaged darwin and linux keep the executable shell wrapper', () => {+ expect(+ resolveLocalOpCliInvocation({+ platform: 'darwin',+ isPackaged: true,+ execPath: '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',+ resourcesPath: '/Applications/OpenKnowledge.app/Contents/Resources',+ parentEnv: {},+ }),+ ).toEqual({ cliArgs: ['/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh'] });+ expect(+ resolveLocalOpCliInvocation({+ platform: 'linux',+ isPackaged: true,+ execPath: '/opt/OpenKnowledge/openknowledge',+ resourcesPath: '/opt/OpenKnowledge/resources',+ parentEnv: {},+ }),+ ).toEqual({ cliArgs: ['/opt/OpenKnowledge/resources/cli/bin/ok.sh'] });+ });+});++describe('resolveLocalOpCliArgsForUtilityFork', () => {+ test('returns a detached copy of cliArgs when the invocation carries no env overlay', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: false,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ });+ const args = resolveLocalOpCliArgsForUtilityFork(invocation);+ expect(args).toEqual(['open-knowledge']);+ expect(args).not.toBe(invocation.cliArgs);+ });++ test('returns the darwin wrapper path, which is runnable without an env overlay', () => {+ expect(+ resolveLocalOpCliArgsForUtilityFork(+ resolveLocalOpCliInvocation({+ platform: 'darwin',+ isPackaged: true,+ execPath: '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',+ resourcesPath: '/Applications/OpenKnowledge.app/Contents/Resources',+ parentEnv: {},+ }),+ ),+ ).toEqual(['/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh']);+ });++ test('throws on a packaged win32 invocation rather than silently dropping its cliEnv', () => {+ const invocation = resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ });+ expect(invocation.cliEnv).toBeDefined();+ expect(() => resolveLocalOpCliArgsForUtilityFork(invocation)).toThrow(/cliEnv/);+ });++ test('throws for any invocation carrying a cliEnv overlay, not just the win32 shape', () => {+ expect(() =>+ resolveLocalOpCliArgsForUtilityFork({+ cliArgs: ['open-knowledge'],+ cliEnv: { ELECTRON_RUN_AS_NODE: '1' },+ }),+ ).toThrow(/cliEnv/);+ });+});diff --git a/packages/desktop/src/main/local-op-cli-invocation.ts b/packages/desktop/src/main/local-op-cli-invocation.tsnew file mode 100644index 000000000..d5ff961c5--- /dev/null+++ b/packages/desktop/src/main/local-op-cli-invocation.ts@@ -0,0 +1,44 @@+import { win32 } from 'node:path';+import type { LocalOpCliInvocation } from '@inkeep/open-knowledge-server';+import { wrapperPathInBundle } from './bundle-paths.ts';++export interface ResolveLocalOpCliInvocationInput {+ readonly platform: NodeJS.Platform;+ readonly isPackaged: boolean;+ readonly execPath: string;+ readonly resourcesPath: string;+ readonly parentEnv: Readonly<Record<string, string | undefined>>;+}++function bundledCliEntryOnWindows(resourcesPath: string): string {+ return win32.join(resourcesPath, 'cli', 'dist', 'cli.mjs');+}++export function resolveLocalOpCliInvocation(+ input: ResolveLocalOpCliInvocationInput,+): LocalOpCliInvocation {+ if (!input.isPackaged) {+ return { cliArgs: ['open-knowledge'] };+ }+ if (input.platform === 'win32') {+ const nodeOptions = input.parentEnv.NODE_OPTIONS;+ return {+ cliArgs: [input.execPath, bundledCliEntryOnWindows(input.resourcesPath)],+ cliEnv: {+ ELECTRON_RUN_AS_NODE: '1',+ NODE_OPTIONS: undefined,+ ...(nodeOptions ? { OK_NODE_OPTIONS: nodeOptions } : {}),+ },+ };+ }+ return { cliArgs: [wrapperPathInBundle(input.execPath, input.platform)] };+}++export function resolveLocalOpCliArgsForUtilityFork(invocation: LocalOpCliInvocation): string[] {+ if (invocation.cliEnv !== undefined) {+ throw new Error(+ 'local-op CLI invocation carries a cliEnv overlay that bare argv would drop; the utility-fork path cannot run this invocation',+ );+ }+ return [...invocation.cliArgs];+}diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 37e437234..915463831 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -8,7 +8,7 @@ import {sliceLastSpawnAttempt,} from '@inkeep/open-knowledge-core';import type { KeepaliveHandle } from '@inkeep/open-knowledge-core/keepalive';-import { getLocalDir } from '@inkeep/open-knowledge-server';+import { getLocalDir, type LocalOpCliInvocation } from '@inkeep/open-knowledge-server';import {BOOT_HEARTBEAT_EVENTS,SPAWN_STARTUP_DEADLINE_MS,@@ -21,6 +21,7 @@ import { registerPendingDelivery } from '../shared/ipc-send.ts';import type { AssetOpenResult } from './asset-allowlist.ts';import { attachAssetSafetyNet } from './asset-safety-net.ts';import { startBootHeartbeat } from './boot-heartbeat.ts';+import { resolveLocalOpCliArgsForUtilityFork } from './local-op-cli-invocation.ts';import type { ServerExitInfo } from './server-exit-record.ts';import type { ShowGateRegistry } from './show-gate.ts';import type { RestoredWindow } from './state-store.ts';@@ -213,7 +214,7 @@ interface CreateProjectWindowOpts {pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload;didEnsureGit?: boolean;consentVersion?: number;- localOpCliArgs?: string[];+ localOpCliInvocation?: LocalOpCliInvocation;pendingServerRestartedToast?: boolean;freshlyCreated?: boolean;}@@ -696,7 +697,7 @@ export class WindowManager {async restartAttachedServer(projectPath: string,- opts?: { localOpCliArgs?: string[] },+ opts?: { localOpCliInvocation?: LocalOpCliInvocation },): Promise<OkServerRestartOutcome> {const resolved = resolve(projectPath);const canonicalKey = this.canonicalizeKey(resolved);@@ -751,7 +752,7 @@ export class WindowManager {recreated = await this.createProjectWindow({projectPath: resolved,pendingServerRestartedToast: true,- localOpCliArgs: opts?.localOpCliArgs,+ localOpCliInvocation: opts?.localOpCliInvocation,});} catch (err) {this.deps.log?.warn(@@ -861,7 +862,7 @@ export class WindowManager {async restartServerForWindow(sender: BrowserWindowLike | null,projectPath: string,- opts: { localOpCliArgs?: string[] },+ opts: { localOpCliInvocation?: LocalOpCliInvocation },): Promise<OkServerRestartOutcome> {if (sender !== null) {const ephemeralIdentity = this.getEphemeralIdentityForWindow(sender);@@ -1204,6 +1205,9 @@ export class WindowManager {}const INIT_TIMEOUT_MS = this.deps.utilityInitTimeoutMs ?? UTILITY_INIT_TIMEOUT_MS;+ const localOpCliArgs = opts.localOpCliInvocation+ ? resolveLocalOpCliArgsForUtilityFork(opts.localOpCliInvocation)+ : null;const utility = this.deps.forkUtility(this.deps.utilityEntryPath,@@ -1276,7 +1280,7 @@ export class WindowManager {didEnsureGit: opts.didEnsureGit === true,consentVersion: opts.consentVersion ?? 1,...(reactShellDistDir !== null ? { reactShellDistDir } : {}),- ...(opts.localOpCliArgs ? { localOpCliArgs: opts.localOpCliArgs } : {}),+ ...(localOpCliArgs ? { localOpCliArgs } : {}),},});diff --git a/packages/desktop/src/shared/local-op-types.typelock.ts b/packages/desktop/src/shared/local-op-types.typelock.tsnew file mode 100644index 000000000..3ab061a20--- /dev/null+++ b/packages/desktop/src/shared/local-op-types.typelock.ts@@ -0,0 +1,34 @@+import type {+ AuthEvent,+ AuthReposResponse,+ AuthStatusResponse,+ RawCloneEvent,+} from '@inkeep/open-knowledge-server';+import type {+ OkLocalOpAuthEvent,+ OkLocalOpAuthReposResponse,+ OkLocalOpAuthStatusResponse,+ OkLocalOpCloneEvent,+} from './bridge-contract.ts';++type Equal<A, B> =+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;+type Expect<T extends true> = T;+type AssignableTo<A, B> = [A] extends [B] ? true : false;+type WithoutGhAvailable<T> = T extends unknown ? Omit<T, 'ghAvailable'> : never;++export type PinAuthEventIdenticalToBridge = Expect<Equal<AuthEvent, OkLocalOpAuthEvent>>;++export type PinCloneEventIdenticalToBridge = Expect<Equal<RawCloneEvent, OkLocalOpCloneEvent>>;++export type PinAuthReposResponseIdenticalToBridge = Expect<+ Equal<AuthReposResponse, OkLocalOpAuthReposResponse>+>;++export type PinAuthStatusResponseAssignableToBridge = Expect<+ AssignableTo<AuthStatusResponse, OkLocalOpAuthStatusResponse>+>;++export type PinAuthStatusResponseWidenedOnlyByGhAvailable = Expect<+ Equal<AuthStatusResponse, WithoutGhAvailable<OkLocalOpAuthStatusResponse>>+>;diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.tsindex cd9cd7f96..2fe5d780c 100644--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts@@ -1093,10 +1093,12 @@ describe('restartServerForWindow (IPC routing seam)', () => {.mockResolvedValue({ ok: false, reason: 'eperm' });const outcome = await wm.restartServerForWindow(projectWindow, '/some/project', {- localOpCliArgs: ['--y'],+ localOpCliInvocation: { cliArgs: ['--y'] },});- expect(attached).toHaveBeenCalledWith('/some/project', { localOpCliArgs: ['--y'] });+ expect(attached).toHaveBeenCalledWith('/some/project', {+ localOpCliInvocation: { cliArgs: ['--y'] },+ });expect(outcome).toEqual({ ok: false, reason: 'eperm' });});diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 7a91b0f2e..2c28e946f 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -4,6 +4,7 @@ import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import { DEFAULT_SERVER_HOST, formatSpawnAttemptHeader } from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { resolveLocalOpCliInvocation } from '../../src/main/local-op-cli-invocation.ts';import { breakServerLockHeldBy } from '../../src/main/server-lock-break.ts';import type { ShowGateRegistry } from '../../src/main/show-gate.ts';import {@@ -278,12 +279,12 @@ describe('WindowManager', () => {await promise;});- test('createProjectWindow forwards localOpCliArgs into the utility init IPC payload', async () => {+ test('createProjectWindow forwards the resolved local-op CLI argv into the utility init IPC payload', async () => {const wm = new WindowManager(env.deps);const expectedCliArgs = ['/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh'];const promise = wm.createProjectWindow({projectPath: '/tmp/cli-args-plumbed',- localOpCliArgs: expectedCliArgs,+ localOpCliInvocation: { cliArgs: expectedCliArgs },});const utility = env.utilities[0];@@ -3915,3 +3916,100 @@ describe('boot heartbeats (the unpackaged path CI runs)', () => {expect(intervals.every((i) => i.cleared)).toBe(true);});});++describe('WindowManager — local-op CLI invocation threading', () => {+ const WIN_EXE = 'C:\\Program Files\\OpenKnowledge\\OpenKnowledge.exe';+ const WIN_RESOURCES = 'C:\\Program Files\\OpenKnowledge\\resources';++ const spawnedLock: ServerLockMetadataLike = {+ pid: 88001,+ hostname: 'my-host',+ port: 60111,+ startedAt: '2026-05-21T00:00:00.000Z',+ worktreeRoot: '/tmp/spawned-project',+ kind: 'interactive',+ capabilities: ['http', 'ws'],+ };++ function packagedWin32Invocation() {+ return resolveLocalOpCliInvocation({+ platform: 'win32',+ isPackaged: true,+ execPath: WIN_EXE,+ resourcesPath: WIN_RESOURCES,+ parentEnv: {},+ });+ }++ let env: TestEnv;++ beforeEach(() => {+ env = buildEnv();+ });++ function enableDetachedSpawn(): void {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ let readCount = 0;+ env.deps.readServerLock = () => {+ readCount++;+ return readCount === 1 ? null : spawnedLock;+ };+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001 });+ }++ test('a packaged win32 host opens a project window on the detached-spawn path it actually takes', async () => {+ enableDetachedSpawn();+ const wm = new WindowManager(env.deps);++ const ctx = await wm.createProjectWindow({+ projectPath: '/tmp/spawned-project',+ localOpCliInvocation: packagedWin32Invocation(),+ });++ expect(ctx.ownsServer).toBe(false);+ expect(env.utilities.length).toBe(0);+ expect(env.windows.length).toBe(1);+ });++ test('an invocation carrying a cliEnv overlay fails loudly when it reaches the utility fork', async () => {+ const wm = new WindowManager(env.deps);++ await expect(+ wm.createProjectWindow({+ projectPath: '/tmp/fork-with-overlay',+ localOpCliInvocation: packagedWin32Invocation(),+ }),+ ).rejects.toThrow(/cliEnv/);+ });++ test('the cliEnv overlay rejection acquires no utility child, heartbeat, or init timer', async () => {+ const intervals: { ms: number; cleared: boolean }[] = [];+ env.deps.setInterval = ((_cb: () => void, ms: number) => {+ const rec = { ms, cleared: false };+ intervals.push(rec);+ return rec;+ }) as unknown as WindowManagerDeps['setInterval'];+ env.deps.clearInterval = ((handle: unknown) => {+ (handle as { cleared: boolean }).cleared = true;+ }) as unknown as WindowManagerDeps['clearInterval'];+ const wm = new WindowManager(env.deps);++ await expect(+ wm.createProjectWindow({+ projectPath: '/tmp/fork-with-overlay-clean',+ localOpCliInvocation: packagedWin32Invocation(),+ }),+ ).rejects.toThrow(/cliEnv/);++ expect(env.utilities).toEqual([]);+ expect(env.forkUtilityArgs).toEqual([]);+ expect(env.timers).toEqual([]);+ expect(intervals.filter((rec) => !rec.cleared)).toEqual([]);+ });+});diff --git a/packages/desktop/tests/unit/local-op-types-drift.test.ts b/packages/desktop/tests/unit/local-op-types-drift.test.tsdeleted file mode 100644index 104c60bc5..000000000--- a/packages/desktop/tests/unit/local-op-types-drift.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import type {- AuthEvent,- AuthReposResponse,- AuthStatusResponse,- RawCloneEvent,-} from '@inkeep/open-knowledge-server';-import { describe, expect, test } from 'vitest';-import type {- OkLocalOpAuthEvent,- OkLocalOpAuthReposResponse,- OkLocalOpAuthStatusResponse,- OkLocalOpCloneEvent,-} from '../../src/shared/bridge-contract.ts';--type Eq<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;--describe('local-op type drift (server runner ↔ desktop bridge contract)', () => {- test('AuthEvent ≡ OkLocalOpAuthEvent (device-flow streaming events)', () => {- const _eq: Eq<AuthEvent, OkLocalOpAuthEvent> = true;- expect(_eq).toBe(true);- });-- test('RawCloneEvent ≡ OkLocalOpCloneEvent (clone streaming events)', () => {- const _eq: Eq<RawCloneEvent, OkLocalOpCloneEvent> = true;- expect(_eq).toBe(true);- });-- test('AuthStatusResponse ≡ OkLocalOpAuthStatusResponse (one-shot auth status)', () => {- const _eq: Eq<AuthStatusResponse, OkLocalOpAuthStatusResponse> = true;- expect(_eq).toBe(true);- });-- test('AuthReposResponse ≡ OkLocalOpAuthReposResponse (one-shot repos list)', () => {- const _eq: Eq<AuthReposResponse, OkLocalOpAuthReposResponse> = true;- expect(_eq).toBe(true);- });-});diff --git a/packages/server/src/http/local-op-routes.test.ts b/packages/server/src/http/local-op-routes.test.tsindex 74ae823d7..e71c63c40 100644--- a/packages/server/src/http/local-op-routes.test.ts+++ b/packages/server/src/http/local-op-routes.test.ts@@ -1,7 +1,9 @@-import { describe, expect, test } from 'vitest';+import { createServer, type Server as HttpServer } from 'node:http';+import { afterEach, describe, expect, test } from 'vitest';import { createConcurrencyGuard } from '../local-op-security.ts';import type { AuthEvent } from '../local-ops/types.ts';import { loggerFactory } from '../logger.ts';+import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';import type { SyncEngine } from '../sync-engine.ts';import { createLocalOpRoutes, resumeSyncOnAuthEvent } from './local-op-routes.ts';@@ -21,7 +23,9 @@ const LOCAL_OP_PATHS = ['/api/local-op/embeddings/test',];-function buildGroup() {+type LocalOpRouteDeps = Parameters<typeof createLocalOpRoutes>[0];++function buildGroup(overrides: Partial<LocalOpRouteDeps> = {}) {return createLocalOpRoutes({projectDir: undefined,contentDir: '/tmp/ok-local-op-routes-test',@@ -34,6 +38,7 @@ function buildGroup() {embeddingsSecretsFile: undefined,readSemanticProviderConfig: undefined,semanticSearch: undefined,+ ...overrides,});}@@ -127,3 +132,119 @@ describe('resumeSyncOnAuthEvent (reconnect → resume wiring)', () => {await Promise.resolve();});});++const DEVICE_FLOW_BACKSTOP_MS = 20_000;++function parkedDeviceFlowCli(): string[] {+ return [+ process.execPath,+ '-e',+ `+ console.log(+ JSON.stringify({+ type: 'verification',+ user_code: 'WDJB-MJHT',+ verification_uri: 'https://github.com/login/device',+ expires_in: 900,+ }),+ );+ setTimeout(() => process.exit(1), ${DEVICE_FLOW_BACKSTOP_MS});+ `,+ ];+}++type StreamLine = Record<string, unknown>;++async function* ndjsonLines(body: ReadableStream<Uint8Array>): AsyncGenerator<StreamLine> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ for (;;) {+ const { done, value } = await reader.read();+ if (done) {+ const trailing = buffer.trim();+ if (trailing) yield JSON.parse(trailing) as StreamLine;+ return;+ }+ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop() ?? '';+ for (const line of lines) {+ if (!line.trim()) continue;+ yield JSON.parse(line) as StreamLine;+ }+ }+}++describe('auth-login stream displacement (a second start orphans the first client)', () => {+ let servers: HttpServer[] = [];++ afterEach(async () => {+ const active = servers;+ servers = [];+ await Promise.allSettled(+ active.map(+ (server) =>+ new Promise<void>((resolve) => {+ server.closeAllConnections();+ server.close(() => resolve());+ }),+ ),+ );+ });++ async function serveLocalOpGroup(overrides: Partial<LocalOpRouteDeps> = {}): Promise<string> {+ const group = buildGroup(overrides);+ const server = createServer((req, res) => {+ const pathname = new URL(req.url ?? '/', 'http://127.0.0.1').pathname;+ const dispatch = group.table.resolve(pathname)?.dispatch;+ if (!dispatch) {+ res.writeHead(404).end();+ return;+ }+ void dispatch(req, res);+ });+ const { baseUrl } = await listenOnLoopback(server);+ servers.push(server);+ return baseUrl;+ }++ const postJson = (baseUrl: string, path: string, body: unknown): Promise<Response> =>+ fetch(`${baseUrl}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++ test('the displaced stream is told it was replaced before the server ends it', async () => {+ const baseUrl = await serveLocalOpGroup({ localOpCliArgs: parkedDeviceFlowCli() });++ const first = await postJson(baseUrl, '/api/local-op/auth/login', { host: 'github.com' });+ expect(first.status).toBe(200);+ if (!first.body) throw new Error('first login stream has no body');+ const firstLines = ndjsonLines(first.body);+ expect((await firstLines.next()).value).toMatchObject({ type: 'verification' });++ const second = await postJson(baseUrl, '/api/local-op/auth/login', { host: 'github.com' });+ expect(second.status).toBe(200);+ if (!second.body) throw new Error('second login stream has no body');++ const remainder: StreamLine[] = [];+ for await (const line of firstLines) remainder.push(line);++ const terminal = remainder.filter((line) => line.type !== 'ping').at(-1);+ expect(terminal).toMatchObject({+ type: 'error',+ problem: {+ type: 'urn:ok:error:concurrent-operation',+ status: 409,+ title: 'Sign-in was replaced by a newer sign-in attempt.',+ },+ });++ await postJson(baseUrl, '/api/local-op/auth/cancel', {});+ const secondLines: StreamLine[] = [];+ for await (const line of ndjsonLines(second.body)) secondLines.push(line);+ expect(secondLines.some((line) => line.type === 'verification')).toBe(true);+ }, 30_000);+});diff --git a/packages/server/src/http/local-op-routes.ts b/packages/server/src/http/local-op-routes.tsindex 92cf58521..ecf4084c4 100644--- a/packages/server/src/http/local-op-routes.ts+++ b/packages/server/src/http/local-op-routes.ts@@ -497,14 +497,17 @@ export function createLocalOpRoutes(deps: LocalOpRouteDeps): ApiRouteGroup {const defaultAuthHost = (): string => originGitHubHost(projectDir ?? contentDir);type StreamingAuthController = { done: Promise<void>; cancel(): void };- const authLoginInFlight: { current: StreamingAuthController | null } = { current: null };- const authGhLoginInFlight: { current: StreamingAuthController | null } = { current: null };+ type InFlightAuthStream = { cancel(): void; notifyDisplaced(): void };+ const authLoginInFlight: { current: InFlightAuthStream | null } = { current: null };+ const authGhLoginInFlight: { current: InFlightAuthStream | null } = { current: null };++ const DISPLACED_STREAM_MESSAGE = 'Sign-in was replaced by a newer sign-in attempt.';function streamAuthFlow(cfg: {res: ServerResponse;handler: string;guardKey: string;- inFlight: { current: StreamingAuthController | null };+ inFlight: { current: InFlightAuthStream | null };concurrentMessage: string;streamErrorMessage: string;makeFlow: (onEvent: (event: AuthEvent) => void) => StreamingAuthController;@@ -529,6 +532,7 @@ export function createLocalOpRoutes(deps: LocalOpRouteDeps): ApiRouteGroup {});return;}+ stale.notifyDisplaced();stale.cancel();inFlight.current = null;console.warn(@@ -576,11 +580,21 @@ export function createLocalOpRoutes(deps: LocalOpRouteDeps): ApiRouteGroup {resumeSyncOnAuthEvent(event, getSyncEngine);writeLine(`${JSON.stringify(event)}\n`);});- inFlight.current = flow;+ const slot: InFlightAuthStream = {+ cancel: () => {+ flow.cancel();+ },+ notifyDisplaced: () => {+ stopHeartbeat();+ if (res.writableEnded || res.destroyed) return;+ writeStreamError(409, 'urn:ok:error:concurrent-operation', DISPLACED_STREAM_MESSAGE);+ },+ };+ inFlight.current = slot;const onClientClose = () => {stopHeartbeat();- if (inFlight.current !== flow) return;+ if (inFlight.current !== slot) return;console.warn(JSON.stringify({event: 'ok-local-op:auth-stream-detached',@@ -600,7 +614,7 @@ export function createLocalOpRoutes(deps: LocalOpRouteDeps): ApiRouteGroup {res.end();} catch {}}- if (inFlight.current === flow) {+ if (inFlight.current === slot) {inFlight.current = null;localOpGuard.release(guardKey);}diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 20f831931..927310173 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -314,6 +314,7 @@ export {type DeviceCompleteEvent,type DeviceErrorEvent,type DeviceVerificationEvent,+ type LocalOpCliInvocation,type RawCloneEvent,type RepoEntry,type RunAuthQueryOptions,diff --git a/packages/server/src/local-ops/auth-flow.test.ts b/packages/server/src/local-ops/auth-flow.test.tsindex 620fd6abe..68bd49cce 100644--- a/packages/server/src/local-ops/auth-flow.test.ts+++ b/packages/server/src/local-ops/auth-flow.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { runDeviceFlowSubprocess } from './auth-flow.ts';+import { type RunDeviceFlowController, runDeviceFlowSubprocess } from './auth-flow.ts';import type { AuthEvent } from './types.ts';const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];@@ -83,7 +83,7 @@ describe('runDeviceFlowSubprocess', () => {}});- test('CLI-emitted error event is forwarded as-is and counts as terminal', async () => {+ test('CLI-emitted error event is forwarded and counts as terminal', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({cliArgs: fixtureCli(`@@ -97,6 +97,62 @@ describe('runDeviceFlowSubprocess', () => {expect(events[0]).toEqual({ type: 'error', message: 'bad code' });});+ test('CLI-emitted error message is redacted and capped before it reaches the consumer', async () => {+ const events: AuthEvent[] = [];+ const token = `ghp_${'c'.repeat(36)}`;+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ const message = "[auth] Failed to parse auth.yml at line 2:\\n token: ${token} " + "z".repeat(3000);+ console.log(JSON.stringify({type:'error', message}));+ `),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toHaveLength(1);+ expect(events[0].type).toBe('error');+ if (events[0].type === 'error') {+ expect(events[0].message).not.toContain(token);+ expect(events[0].message).toContain('[REDACTED-GH-PAT]');+ expect(events[0].message.length).toBeLessThanOrEqual(500);+ }+ });++ test('CLI-emitted error message that redacts to nothing falls back to "Unknown error"', async () => {+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'error', message:' \\n '}));+ `),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toEqual([{ type: 'error', message: 'Unknown error' }]);+ });++ test('a cancel landing after the timeout still reports the timeout', async () => {+ const events: AuthEvent[] = [];+ const ctrl: RunDeviceFlowController = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ process.on('SIGTERM', () => {+ console.log(JSON.stringify({type:'verification', user_code:'TERM', verification_uri:'https://e.com/login', expires_in:60}));+ setTimeout(() => process.exit(7), 200);+ });+ setInterval(() => {}, 1000);+ `),+ timeoutMs: 800,+ onEvent: (e) => {+ events.push(e);+ if (e.type === 'verification') ctrl.cancel();+ },+ });+ await ctrl.done;+ const errEvent = events.find((e) => e.type === 'error');+ expect(errEvent).toBeDefined();+ if (errEvent?.type === 'error') {+ expect(errEvent.message).toMatch(/timed out/i);+ }+ });+test('malformed JSON lines are silently dropped, not forwarded as errors', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({@@ -137,7 +193,77 @@ describe('runDeviceFlowSubprocess', () => {expect(events.map((e) => e.type)).toEqual(['complete']);});- test('cancel terminates the subprocess', async () => {+ test('non-zero exit folds the child stderr into the error message', async () => {+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('spawn EINVAL');+ process.exitCode = 2;+ `),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toHaveLength(1);+ expect(events[0].type).toBe('error');+ if (events[0].type === 'error') {+ expect(events[0].message).toContain('exited with code 2');+ expect(events[0].message).toContain('spawn EINVAL');+ }+ });++ test('credentialed stderr is redacted before it reaches the error message', async () => {+ const token = `ghp_${'a'.repeat(36)}`;+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("fatal: unable to access 'https://x-access-token:${token}@github.com/o/r.git/'");+ process.exitCode = 2;+ `),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events[0]?.type).toBe('error');+ if (events[0]?.type === 'error') {+ expect(events[0].message).not.toContain(token);+ expect(events[0].message).toContain('https://[REDACTED]@github.com');+ }+ });++ test('a bare PAT in stderr is redacted before it reaches the error message', async () => {+ const token = `ghp_${'f'.repeat(36)}`;+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${token}");+ process.exitCode = 2;+ `),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events[0]?.type).toBe('error');+ if (events[0]?.type === 'error') {+ expect(events[0].message).not.toContain(token);+ expect(events[0].message).toContain('[REDACTED-GH-PAT]');+ }+ });++ test('forwards cliEnv through to the spawned CLI', async () => {+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'complete', host:'github.com', login: process.env.OK_AUTH_FLOW_ENV_MARKER || 'unset'}));+ `),+ cliEnv: { OK_AUTH_FLOW_ENV_MARKER: 'marker-from-cli-env' },+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events[0]?.type).toBe('complete');+ if (events[0]?.type === 'complete') {+ expect(events[0].login).toBe('marker-from-cli-env');+ }+ });++ test('cancel terminates the subprocess without synthesizing an error event', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),@@ -145,7 +271,6 @@ describe('runDeviceFlowSubprocess', () => {});setTimeout(() => ctrl.cancel(), 50);await ctrl.done;- expect(events.length).toBe(1);- expect(events[0].type).toBe('error');+ expect(events).toEqual([]);});});diff --git a/packages/server/src/local-ops/auth-flow.ts b/packages/server/src/local-ops/auth-flow.tsindex d9a1109ed..156e4ff1e 100644--- a/packages/server/src/local-ops/auth-flow.ts+++ b/packages/server/src/local-ops/auth-flow.ts@@ -1,8 +1,8 @@-import { runSubprocess } from './subprocess.ts';+import { redactedStderrDetail, stderrDetailSuffix } from './clone-error-classify.ts';+import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';import type { AuthEvent } from './types.ts';-export interface RunDeviceFlowOptions {- cliArgs: readonly string[];+export interface RunDeviceFlowOptions extends LocalOpCliInvocation {host?: string;timeoutMs?: number;onEvent: (event: AuthEvent) => void;@@ -43,10 +43,8 @@ function asAuthEvent(parsed: Record<string, unknown>): AuthEvent | null {};}if (type === 'error') {- return {- type: 'error',- message: typeof parsed.message === 'string' ? parsed.message : 'Unknown error',- };+ const message = typeof parsed.message === 'string' ? redactedStderrDetail(parsed.message) : '';+ return { type: 'error', message: message || 'Unknown error' };}return null;}@@ -59,6 +57,7 @@ export function runDeviceFlowSubprocess(opts: RunDeviceFlowOptions): RunDeviceFlconst proc = runSubprocess({cliArgs: opts.cliArgs,+ cliEnv: opts.cliEnv,trailingArgs: ['auth', 'login', '--json', '--host', host],timeoutMs,onLine: ({ parsed }) => {@@ -74,16 +73,19 @@ export function runDeviceFlowSubprocess(opts: RunDeviceFlowOptions): RunDeviceFlconst done = proc.done.then((result) => {if (sawTerminal) return;+ if (result.timedOut) {+ opts.onEvent({ type: 'error', message: 'Sign-in timed out' });+ return;+ }+ if (result.cancelled) return;if (result.code === 0) {opts.onEvent({ type: 'complete', host, login: '' });- } else {- opts.onEvent({- type: 'error',- message: result.timedOut- ? 'Sign-in timed out'- : `auth login exited with code ${result.code ?? -1}`,- });+ return;}+ opts.onEvent({+ type: 'error',+ message: `auth login exited with code ${result.code ?? -1}${stderrDetailSuffix(result.stderr)}`,+ });});return { done, cancel: proc.cancel };diff --git a/packages/server/src/local-ops/auth-pat.test.ts b/packages/server/src/local-ops/auth-pat.test.tsindex c9a26cb2c..681eab58d 100644--- a/packages/server/src/local-ops/auth-pat.test.ts+++ b/packages/server/src/local-ops/auth-pat.test.ts@@ -46,4 +46,71 @@ describe('runPatSubprocess', () => {expect(result.error).toBe('Token validation failed.');}});++ test('folds the child stderr into the generic fallback error', async () => {+ const result = await runPatSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('spawn EINVAL');+ process.exitCode = 3;+ `),+ host: 'ghes.test',+ token: 'x',+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain('Token validation failed.');+ expect(result.error).toContain('spawn EINVAL');+ }+ });++ test('redacts credentialed stderr before it reaches the fallback error', async () => {+ const token = `ghp_${'b'.repeat(36)}`;+ const result = await runPatSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("fatal: unable to access 'https://x-access-token:${token}@ghes.test/o/r.git/'");+ process.exitCode = 3;+ `),+ host: 'ghes.test',+ token,+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).not.toContain(token);+ expect(result.error).toContain('https://[REDACTED]@ghes.test');+ }+ });++ test('redacts a bare PAT in stderr before it reaches the fallback error', async () => {+ const token = `ghp_${'g'.repeat(36)}`;+ const result = await runPatSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${token}");+ process.exitCode = 3;+ `),+ host: 'ghes.test',+ token,+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).not.toContain(token);+ expect(result.error).toContain('[REDACTED-GH-PAT]');+ }+ });++ test('forwards cliEnv through to the spawned CLI', async () => {+ const result = await runPatSubprocess({+ cliArgs: fixtureCli(`+ let d='';+ process.stdin.on('data', c => { d += c; });+ process.stdin.on('end', () => {+ process.stdout.write(JSON.stringify({ type: 'complete', host: 'ghes.test', login: process.env.OK_AUTH_PAT_ENV_MARKER || 'unset' }) + '\\n');+ process.exit(0);+ });+ `),+ cliEnv: { OK_AUTH_PAT_ENV_MARKER: 'marker-from-cli-env' },+ host: 'ghes.test',+ token: 'good-token',+ });+ expect(result).toEqual({ ok: true, host: 'ghes.test', login: 'marker-from-cli-env' });+ });});diff --git a/packages/server/src/local-ops/auth-pat.ts b/packages/server/src/local-ops/auth-pat.tsindex 026284347..a81b01145 100644--- a/packages/server/src/local-ops/auth-pat.ts+++ b/packages/server/src/local-ops/auth-pat.ts@@ -1,7 +1,7 @@-import { runSubprocess } from './subprocess.ts';+import { stderrDetailSuffix } from './clone-error-classify.ts';+import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';-export interface RunPatOptions {- cliArgs: readonly string[];+export interface RunPatOptions extends LocalOpCliInvocation {host?: string;token: string;timeoutMs?: number;@@ -19,6 +19,7 @@ export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResulconst proc = runSubprocess({cliArgs: opts.cliArgs,+ cliEnv: opts.cliEnv,trailingArgs: ['auth', 'pat', '--json', '--host', host, '--token-stdin'],stdinData: opts.token,timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,@@ -42,9 +43,6 @@ export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResulconst result = await proc.done;if (terminal) return terminal;- return {- ok: false,- host,- error: result.timedOut ? 'Token validation timed out.' : 'Token validation failed.',- };+ if (result.timedOut) return { ok: false, host, error: 'Token validation timed out.' };+ return { ok: false, host, error: `Token validation failed.${stderrDetailSuffix(result.stderr)}` };}diff --git a/packages/server/src/local-ops/auth-query.test.ts b/packages/server/src/local-ops/auth-query.test.tsindex a432f21fc..688b241d1 100644--- a/packages/server/src/local-ops/auth-query.test.ts+++ b/packages/server/src/local-ops/auth-query.test.ts@@ -94,6 +94,34 @@ describe('runAuthStatusSubprocess', () => {}});+ test('redacts a bare PAT out of the status error before it is persisted', async () => {+ const token = `ghp_${'c'.repeat(36)}`;+ const result = await runAuthStatusSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${token}\\n");+ process.exit(1);+ `),+ });+ expect(result.authenticated).toBe(false);+ if (!result.authenticated) {+ expect(result.error).not.toContain(token);+ expect(result.error).toContain('[REDACTED-GH-PAT]');+ }+ });++ test('caps an overlong status stderr at the shared detail cap', async () => {+ const result = await runAuthStatusSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('x'.repeat(3000));+ process.exit(1);+ `),+ });+ expect(result.authenticated).toBe(false);+ if (!result.authenticated) {+ expect(result.error?.length).toBe(500);+ }+ });+test('reports a timeout-marker error when the subprocess hangs past timeoutMs', async () => {const result = await runAuthStatusSubprocess({cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),@@ -129,6 +157,19 @@ describe('runAuthStatusSubprocess', () => {}});+ test('forwards cliEnv through to the spawned CLI', async () => {+ const result = await runAuthStatusSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'status', host:'github.com', authenticated:true, login: process.env.OK_AUTH_STATUS_ENV_MARKER || 'unset'}));+ `),+ cliEnv: { OK_AUTH_STATUS_ENV_MARKER: 'marker-from-cli-env' },+ });+ expect(result.authenticated).toBe(true);+ if (result.authenticated) {+ expect(result.login).toBe('marker-from-cli-env');+ }+ });+test('uses a custom host when provided', async () => {const result = await runAuthStatusSubprocess({cliArgs: fixtureCli(`@@ -196,6 +237,96 @@ describe('runAuthReposSubprocess', () => {}});+ test('flags the signed-out CLI exit as unauthenticated, not a command failure', async () => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('[auth] token storage: OS keychain\\nNot logged in to github.com\\n');+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.authenticated).toBe(false);+ expect(result.error).toContain('Not logged in to github.com');+ }+ });++ test.each([+ ['a bare signed-out sentence', 'Not logged in to github.com\\n'],+ [+ 'a file-backend storage banner ahead of the signed-out sentence',+ '[auth] token storage: file (~/.ok/auth.yml) — OS keychain unavailable: keyring init failed\\nNot logged in to github.com\\n',+ ],+ ])('still flags %s as unauthenticated', async (_label, stderr) => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('${stderr}');+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.authenticated).toBe(false);+ expect(result.error).toContain('Not logged in to github.com');+ }+ });++ test('an auth.yml parse error beside the signed-out sentence stays a loggable failure', async () => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('[auth] token storage: file (~/.ok/auth.yml) — OS keychain unavailable: keyring init failed\\n[auth] Failed to parse ~/.ok/auth.yml: bad indentation at line 2. Starting with empty credentials.\\nNot logged in to github.com\\n');+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.authenticated).toBeUndefined();+ expect(result.error).toContain('Failed to parse ~/.ok/auth.yml');+ }+ });++ test('a genuine command failure carries no unauthenticated flag', async () => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('spawn EINVAL\\n');+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.authenticated).toBeUndefined();+ expect(result.error).toContain('spawn EINVAL');+ }+ });++ test('redacts a bare PAT out of the repos error before it is persisted', async () => {+ const token = `ghp_${'d'.repeat(36)}`;+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${token}\\n");+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).not.toContain(token);+ expect(result.error).toContain('[REDACTED-GH-PAT]');+ }+ });++ test('caps an overlong repos stderr at the shared detail cap', async () => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ process.stderr.write('x'.repeat(3000));+ process.exit(1);+ `),+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error.length).toBe(500);+ }+ });+test('returns an error when the CLI emits no repos line on clean exit', async () => {const result = await runAuthReposSubprocess({cliArgs: fixtureCli(`process.exit(0)`),@@ -216,4 +347,19 @@ describe('runAuthReposSubprocess', () => {expect(result.error).toMatch(/timed out/i);}});++ test('forwards cliEnv through to the spawned CLI', async () => {+ const result = await runAuthReposSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'repos', host:'github.com', repos:[+ {full_name: process.env.OK_AUTH_REPOS_ENV_MARKER || 'unset', clone_url:'https://github.com/octo/repo1.git', private:false},+ ]}));+ `),+ cliEnv: { OK_AUTH_REPOS_ENV_MARKER: 'marker/from-cli-env' },+ });+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.repos.map((r) => r.full_name)).toEqual(['marker/from-cli-env']);+ }+ });});diff --git a/packages/server/src/local-ops/auth-query.ts b/packages/server/src/local-ops/auth-query.tsindex c9bbc94a1..adf6215f8 100644--- a/packages/server/src/local-ops/auth-query.ts+++ b/packages/server/src/local-ops/auth-query.ts@@ -1,7 +1,22 @@-import { runSubprocess } from './subprocess.ts';+import { redactedStderrDetail } from './clone-error-classify.ts';+import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';const DEFAULT_TIMEOUT_MS = 30_000;+const SIGNED_OUT_SENTENCE = /^not logged in to /i;+const BENIGN_TOKEN_STORAGE_BANNER = /^\[auth\] token storage: /;++function isSignedOutOnlyStderr(stderr: string): boolean {+ const lines = stderr+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ return (+ lines.some((line) => SIGNED_OUT_SENTENCE.test(line)) &&+ lines.every((line) => SIGNED_OUT_SENTENCE.test(line) || BENIGN_TOKEN_STORAGE_BANNER.test(line))+ );+}+export type AuthStatusResponse =| {authenticated: true;@@ -21,10 +36,9 @@ export interface RepoEntry {export type AuthReposResponse =| { ok: true; host: string; repos: RepoEntry[] }- | { ok: false; error: string };+ | { ok: false; error: string; authenticated?: false };-export interface RunAuthQueryOptions {- cliArgs: readonly string[];+export interface RunAuthQueryOptions extends LocalOpCliInvocation {host?: string;timeoutMs?: number;}@@ -36,6 +50,7 @@ export async function runAuthStatusSubprocess(const lines: Record<string, unknown>[] = [];const proc = runSubprocess({cliArgs: opts.cliArgs,+ cliEnv: opts.cliEnv,trailingArgs: ['auth', 'status', '--json', '--host', host],timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,onLine: ({ parsed }) => {@@ -71,7 +86,7 @@ export async function runAuthStatusSubprocess(error: result.timedOut? 'auth status timed out': result.code !== 0- ? result.stderr || `auth status exited with code ${result.code ?? -1}`+ ? redactedStderrDetail(result.stderr) || `auth status exited with code ${result.code ?? -1}`: undefined,};}@@ -83,6 +98,7 @@ export async function runAuthReposSubprocess(const lines: Record<string, unknown>[] = [];const proc = runSubprocess({cliArgs: opts.cliArgs,+ cliEnv: opts.cliEnv,trailingArgs: ['auth', 'repos', '--json', '--host', host],timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,onLine: ({ parsed }) => {@@ -92,9 +108,13 @@ export async function runAuthReposSubprocess(const result = await proc.done;if (result.timedOut) return { ok: false, error: 'auth repos timed out' };if (result.code !== 0) {+ const detail = redactedStderrDetail(result.stderr);+ if (isSignedOutOnlyStderr(result.stderr)) {+ return { ok: false, error: detail, authenticated: false };+ }return {ok: false,- error: result.stderr || `auth repos exited with code ${result.code ?? -1}`,+ error: detail || `auth repos exited with code ${result.code ?? -1}`,};}for (let i = lines.length - 1; i >= 0; i--) {diff --git a/packages/server/src/local-ops/clone-error-classify.test.ts b/packages/server/src/local-ops/clone-error-classify.test.tsindex ac63ef70d..27e791662 100644--- a/packages/server/src/local-ops/clone-error-classify.test.ts+++ b/packages/server/src/local-ops/clone-error-classify.test.ts@@ -87,14 +87,30 @@ describe('classifyCloneError', () => {"fatal: unable to access 'https://x-access-token:[email protected]/acme/x.git/': 404";const result = classifyCloneError(stderr);expect(result.detail).not.toContain('ghp_abc123XYZ');- expect(result.detail).toContain('***');+ expect(result.detail).toContain('https://[REDACTED]@github.com');});test('bare basic-auth credentials in URL are redacted', () => {const stderr = "fatal: unable to access 'https://alice:[email protected]/x.git/': 403";const result = classifyCloneError(stderr);expect(result.detail).not.toContain('s3cret');- expect(result.detail).toContain('***');+ expect(result.detail).not.toContain('alice');+ expect(result.detail).toContain('https://[REDACTED]@github.com');+ });++ test('a bare PAT outside a URL is redacted (auth.yml parse errors echo the token line)', () => {+ const token = `ghp_${'e'.repeat(36)}`;+ const stderr = `[auth] Failed to parse auth.yml: bad indentation at line 2:\n token: ${token}`;+ const result = classifyCloneError(stderr);+ expect(result.detail).not.toContain(token);+ expect(result.detail).toContain('[REDACTED-GH-PAT]');+ });++ test('a bare fine-grained PAT outside a URL is redacted', () => {+ const token = `github_pat_${'F'.repeat(24)}`;+ const result = classifyCloneError(`fatal: bad credentials: ${token}`);+ expect(result.detail).not.toContain(token);+ expect(result.detail).toContain('[REDACTED-GH-PAT]');});});diff --git a/packages/server/src/local-ops/clone-error-classify.ts b/packages/server/src/local-ops/clone-error-classify.tsindex ebf99972e..5e4ff516b 100644--- a/packages/server/src/local-ops/clone-error-classify.ts+++ b/packages/server/src/local-ops/clone-error-classify.ts@@ -1,3 +1,4 @@+import { scrubSecrets } from '@inkeep/open-knowledge-core';import { redactShareSubprocessStderr } from '../share/publish.ts';export interface CloneErrorClassification {@@ -7,10 +8,19 @@ export interface CloneErrorClassification {const GENERIC_TITLE = 'Clone subprocess reported an error.';-export const MAX_DETAIL_LEN = 500;+const MAX_DETAIL_LEN = 500;++export function redactedStderrDetail(rawStderr: string): string {+ return scrubSecrets(redactShareSubprocessStderr(rawStderr)).trim().slice(0, MAX_DETAIL_LEN);+}++export function stderrDetailSuffix(rawStderr: string): string {+ const detail = redactedStderrDetail(rawStderr);+ return detail.length > 0 ? ` — ${detail}` : '';+}export function classifyCloneError(rawStderr: string): CloneErrorClassification {- const detail = redactShareSubprocessStderr(rawStderr).trim().slice(0, MAX_DETAIL_LEN);+ const detail = redactedStderrDetail(rawStderr);if (detail.length === 0) {return { title: GENERIC_TITLE, detail: '' };diff --git a/packages/server/src/local-ops/clone-flow.test.ts b/packages/server/src/local-ops/clone-flow.test.tsindex f7292267a..0b279bf23 100644--- a/packages/server/src/local-ops/clone-flow.test.ts+++ b/packages/server/src/local-ops/clone-flow.test.ts@@ -1,7 +1,12 @@import { homedir } from 'node:os';import { join } from 'node:path';import { describe, expect, test } from 'vitest';-import { type RawCloneEvent, runCloneSubprocess, validateCloneInputs } from './clone-flow.ts';+import {+ type RawCloneEvent,+ type RunCloneController,+ runCloneSubprocess,+ validateCloneInputs,+} from './clone-flow.ts';const HOME_PATH = join(homedir(), 'open-knowledge-test-clone');@@ -142,6 +147,68 @@ describe('runCloneSubprocess', () => {expect(events[0]).toEqual({ type: 'error', message: 'permission denied' });});+ test('CLI-emitted error message is redacted and capped before it reaches the consumer', async () => {+ const events: RawCloneEvent[] = [];+ const token = `ghp_${'b'.repeat(36)}`;+ const ctrl = runCloneSubprocess({+ cliArgs: fixtureCli(`+ const message = "[auth] Failed to parse auth.yml at line 2:\\n token: ${token} " + "y".repeat(3000);+ console.log(JSON.stringify({type:'error', message}));+ `),+ url: 'https://github.com/octocat/locked.git',+ dir: '/tmp/locked',+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toHaveLength(1);+ expect(events[0].type).toBe('error');+ if (events[0].type === 'error') {+ expect(events[0].message).not.toContain(token);+ expect(events[0].message).toContain('[REDACTED-GH-PAT]');+ expect(events[0].message.length).toBeLessThanOrEqual(500);+ }+ });++ test('CLI-emitted error message that redacts to nothing falls back to "Unknown error"', async () => {+ const events: RawCloneEvent[] = [];+ const ctrl = runCloneSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'error', message:' \\n '}));+ `),+ url: 'https://github.com/octocat/blank-msg.git',+ dir: '/tmp/blank-msg',+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toEqual([{ type: 'error', message: 'Unknown error' }]);+ });++ test('a cancel landing after the timeout still reports the timeout', async () => {+ const events: RawCloneEvent[] = [];+ const ctrl: RunCloneController = runCloneSubprocess({+ cliArgs: fixtureCli(`+ process.on('SIGTERM', () => {+ console.log(JSON.stringify({type:'progress', phase:'terminating', pct:99}));+ setTimeout(() => process.exit(7), 200);+ });+ setInterval(() => {}, 1000);+ `),+ url: 'https://github.com/octocat/slow.git',+ dir: '/tmp/slow',+ timeoutMs: 800,+ onEvent: (e) => {+ events.push(e);+ if (e.type === 'progress') ctrl.cancel();+ },+ });+ await ctrl.done;+ const errEvent = events.find((e) => e.type === 'error');+ expect(errEvent).toBeDefined();+ if (errEvent?.type === 'error') {+ expect(errEvent.message).toMatch(/timed out/i);+ }+ });+test('progress events with missing fields are dropped', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({@@ -191,7 +258,7 @@ describe('runCloneSubprocess', () => {expect(events.map((e) => e.type)).toEqual(['complete']);});- test('cancel SIGTERMs the subprocess', async () => {+ test('cancel SIGTERMs the subprocess without synthesizing an error event', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),@@ -201,8 +268,22 @@ describe('runCloneSubprocess', () => {});setTimeout(() => ctrl.cancel(), 50);await ctrl.done;- const errEvent = events.find((e) => e.type === 'error');- expect(errEvent).toBeDefined();+ expect(events).toEqual([]);+ });++ test('forwards cliEnv through to the spawned CLI', async () => {+ const events: RawCloneEvent[] = [];+ const ctrl = runCloneSubprocess({+ cliArgs: fixtureCli(`+ console.log(JSON.stringify({type:'complete', dir: process.env.OK_CLONE_ENV_MARKER || 'unset'}));+ `),+ cliEnv: { OK_CLONE_ENV_MARKER: '/tmp/marker-from-cli-env' },+ url: 'https://github.com/octocat/hello.git',+ dir: '/tmp/cloned-repo',+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toEqual([{ type: 'complete', dir: '/tmp/marker-from-cli-env' }]);});test('handles a chunked stream that splits a JSON line across writes', async () => {diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.tsindex 4a15bb89f..9540687c3 100644--- a/packages/server/src/local-ops/clone-flow.ts+++ b/packages/server/src/local-ops/clone-flow.ts@@ -8,9 +8,8 @@ import {import { emitPreflightFailureSpan } from '../git-preflight-telemetry.ts';import { expandTilde, isAllowedGitUrl, isSafeLocalPath } from '../local-op-security.ts';import { getLogger } from '../logger.ts';-import { redactShareSubprocessStderr } from '../share/publish.ts';-import { MAX_DETAIL_LEN } from './clone-error-classify.ts';-import { runSubprocess } from './subprocess.ts';+import { redactedStderrDetail, stderrDetailSuffix } from './clone-error-classify.ts';+import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';const log = getLogger('clone-flow');@@ -20,8 +19,7 @@ export type RawCloneEvent =| { type: 'branch-fallback'; branch: string }| { type: 'error'; message: string };-export interface RunCloneOptions {- cliArgs: readonly string[];+export interface RunCloneOptions extends LocalOpCliInvocation {url: string;dir: string;branch?: string | null;@@ -65,10 +63,8 @@ function asRawCloneEvent(parsed: Record<string, unknown>): RawCloneEvent | nullreturn null;}if (type === 'error') {- return {- type: 'error',- message: typeof parsed.message === 'string' ? parsed.message : 'Unknown error',- };+ const message = typeof parsed.message === 'string' ? redactedStderrDetail(parsed.message) : '';+ return { type: 'error', message: message || 'Unknown error' };}return null;}@@ -116,6 +112,7 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {typeof opts.branch === 'string' && opts.branch.length > 0 ? ['-b', opts.branch] : [];const proc = runSubprocess({cliArgs: opts.cliArgs,+ cliEnv: opts.cliEnv,trailingArgs: ['clone', '--json', ...branchArgs, opts.url, targetDir],extraPathDirs,timeoutMs,@@ -136,14 +133,11 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {opts.onEvent({ type: 'error', message: 'Clone timed out after 10 minutes' });return;}+ if (result.cancelled) return;if (result.code !== 0) {- const redacted = redactShareSubprocessStderr(result.stderr ?? '')- .trim()- .slice(0, MAX_DETAIL_LEN);- const detail = redacted.length > 0 ? ` — ${redacted}` : '';opts.onEvent({type: 'error',- message: `Clone process exited with code ${result.code ?? -1}${detail}`,+ message: `Clone process exited with code ${result.code ?? -1}${stderrDetailSuffix(result.stderr)}`,});return;}diff --git a/packages/server/src/local-ops/gh-login.test.ts b/packages/server/src/local-ops/gh-login.test.tsindex 3eb008bbb..04f761624 100644--- a/packages/server/src/local-ops/gh-login.test.ts+++ b/packages/server/src/local-ops/gh-login.test.ts@@ -2,7 +2,11 @@ import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { describe, expect, test } from 'vitest';-import { resolveGhBinaryPath, runGhDeviceLoginSubprocess } from './gh-login.ts';+import {+ type RunGhDeviceLoginController,+ resolveGhBinaryPath,+ runGhDeviceLoginSubprocess,+} from './gh-login.ts';import type { AuthEvent } from './types.ts';const dir = mkdtempSync(join(tmpdir(), 'gh-login-test-'));@@ -54,6 +58,63 @@ describe('runGhDeviceLoginSubprocess', () => {if (terminal?.type === 'error') expect(terminal.message).toContain('gh sign-in failed');});+ test('cancel terminates the gh subprocess without synthesizing a failure event', async () => {+ const cancelGh = join(dir, 'gh-cancel');+ writeFileSync(+ cancelGh,+ `#!/bin/bash+echo "! First copy your one-time code: TEST-1234" >&2+echo "Open this URL to continue in your web browser: https://ghes.test/login/device" >&2+exec sleep 60 1>/dev/null 2>/dev/null+`,+ );+ chmodSync(cancelGh, 0o755);+ const events: AuthEvent[] = [];+ const ctl = runGhDeviceLoginSubprocess({+ host: 'ghes.test',+ ghPath: cancelGh,+ verificationDeadlineMs: 10_000,+ onEvent: (e) => events.push(e),+ });+ setTimeout(() => ctl.cancel(), 300);+ await ctl.done;+ expect(events).toEqual([+ {+ type: 'verification',+ user_code: 'TEST-1234',+ verification_uri: 'https://ghes.test/login/device',+ expires_in: 900,+ },+ ]);+ });++ test('a cancel landing after the timeout still reports the timeout', async () => {+ const trapGh = join(dir, 'gh-trap');+ writeFileSync(+ trapGh,+ `#!/bin/bash+trap 'echo "! First copy your one-time code: TERM-9999" >&2; echo "Open this URL to continue in your web browser: https://ghes.test/login/device" >&2; sleep 0.2; exit 7' TERM+while true; do sleep 0.05; done+`,+ );+ chmodSync(trapGh, 0o755);+ const events: AuthEvent[] = [];+ const ctl: RunGhDeviceLoginController = runGhDeviceLoginSubprocess({+ host: 'ghes.test',+ ghPath: trapGh,+ timeoutMs: 500,+ verificationDeadlineMs: 10_000,+ onEvent: (e) => {+ events.push(e);+ if (e.type === 'verification') ctl.cancel();+ },+ });+ await ctl.done;+ const terminal = events[events.length - 1];+ expect(terminal?.type).toBe('error');+ if (terminal?.type === 'error') expect(terminal.message).toContain('gh sign-in timed out');+ });+test('unrecognizable stderr trips the verification deadline with a single actionable error', async () => {const stallGh = join(dir, 'gh-stall');writeFileSync(diff --git a/packages/server/src/local-ops/gh-login.ts b/packages/server/src/local-ops/gh-login.tsindex 78fffc9a0..e65590d20 100644--- a/packages/server/src/local-ops/gh-login.ts+++ b/packages/server/src/local-ops/gh-login.ts@@ -142,17 +142,17 @@ export function runGhDeviceLoginSubprocess(const done = proc.done.then(async (result) => {clearTimeout(verificationDeadline);if (deadlineExpired) return;+ if (result.timedOut) {+ opts.onEvent({ type: 'error', message: 'gh sign-in timed out — please try again' });+ return;+ }+ if (result.cancelled) return;if (result.code === 0) {const login = await resolveGhLogin(opts.ghPath, opts.host);opts.onEvent({ type: 'complete', host: opts.host, login });- } else {- opts.onEvent({- type: 'error',- message: result.timedOut- ? 'gh sign-in timed out — please try again'- : 'gh sign-in failed — please try again',- });+ return;}+ opts.onEvent({ type: 'error', message: 'gh sign-in failed — please try again' });});return { done, cancel: proc.cancel };diff --git a/packages/server/src/local-ops/index.ts b/packages/server/src/local-ops/index.tsindex 2f79f1749..101ab9aa2 100644--- a/packages/server/src/local-ops/index.ts+++ b/packages/server/src/local-ops/index.ts@@ -21,6 +21,7 @@ export {validateCloneInputs,} from './clone-flow.ts';export { cachedGhBinaryPath, runGhDeviceLoginSubprocess } from './gh-login.ts';+export type { LocalOpCliInvocation } from './subprocess.ts';export type {AuthEvent,CloneCompleteEvent,diff --git a/packages/server/src/local-ops/subprocess.test.ts b/packages/server/src/local-ops/subprocess.test.tsindex c3af4bafb..2ee6586b5 100644--- a/packages/server/src/local-ops/subprocess.test.ts+++ b/packages/server/src/local-ops/subprocess.test.ts@@ -1,6 +1,6 @@import { delimiter as PATH_DELIMITER } from 'node:path';import { describe, expect, test } from 'vitest';-import { runSubprocess } from './subprocess.ts';+import { buildOverlaidEnv, runSubprocess } from './subprocess.ts';const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];@@ -179,6 +179,21 @@ describe('runSubprocess', () => {expect(childPathFrom(lines)).toBe(process.env.PATH ?? '');});+ test('extraPathDirs composes the child PATH from a cliEnv PATH overlay, not the parent PATH', async () => {+ const overlaidPath = `/opt/overlay${PATH_DELIMITER}${process.env.PATH ?? ''}`;+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: echoPathCli,+ cliEnv: { PATH: overlaidPath },+ trailingArgs: [],+ extraPathDirs: ['/opt/one'],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ await proc.done;+ expect(childPathFrom(lines)).toBe(`/opt/one${PATH_DELIMITER}${overlaidPath}`);+ });+test('extraPathDirs drops empty segments when composing the child PATH', async () => {const lines: { parsed: Record<string, unknown> | null }[] = [];const proc = runSubprocess({@@ -193,3 +208,261 @@ describe('runSubprocess', () => {expect(childPath.split(PATH_DELIMITER)[0]).toBe('/opt/only');});});++describe('runSubprocess — cliEnv overlay', () => {+ const printEnvCli = fixtureCli(+ `process.stdout.write(JSON.stringify({ a: process.env.OK_TEST_A ?? null, b: process.env.OK_TEST_B ?? null }))`,+ );++ const withInheritedB = async (run: () => Promise<void>): Promise<void> => {+ const previous = process.env.OK_TEST_B;+ process.env.OK_TEST_B = 'inherited';+ try {+ await run();+ } finally {+ if (previous === undefined) delete process.env.OK_TEST_B;+ else process.env.OK_TEST_B = previous;+ }+ };++ test('overlay values reach the child and undefined removes an inherited key', async () => {+ await withInheritedB(async () => {+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: printEnvCli,+ cliEnv: { OK_TEST_A: 'overlay', OK_TEST_B: undefined },+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ const result = await proc.done;+ expect(result.code).toBe(0);+ expect(lines[0]?.parsed).toEqual({ a: 'overlay', b: null });+ });+ });++ test('no overlay leaves the inherited environment untouched', async () => {+ await withInheritedB(async () => {+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: printEnvCli,+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ await proc.done;+ expect(lines[0]?.parsed).toEqual({ a: null, b: 'inherited' });+ });+ });+});++describe('buildOverlaidEnv — case handling across the overlay and the PATH composition', () => {+ const NODE_OPTIONS_VARIANTS = { Node_Options: '--require ./hook.js', node_options: '--inspect' };++ test('win32 deletion removes every inherited casing variant of the key', () => {+ expect(+ buildOverlaidEnv(+ { ...NODE_OPTIONS_VARIANTS },+ { NODE_OPTIONS: undefined },+ undefined,+ 'win32',+ ),+ ).toEqual({});+ });++ test('non-win32 deletion leaves differently-cased POSIX variables intact', () => {+ expect(+ buildOverlaidEnv(+ { ...NODE_OPTIONS_VARIANTS },+ { NODE_OPTIONS: undefined },+ undefined,+ 'linux',+ ),+ ).toEqual(NODE_OPTIONS_VARIANTS);+ });++ test('win32 assignment replaces a differently-cased inherited key instead of leaving a stale twin', () => {+ expect(+ buildOverlaidEnv({ Ok_Marker: 'inherited' }, { OK_MARKER: 'overlay' }, undefined, 'win32'),+ ).toEqual({ OK_MARKER: 'overlay' });+ });++ test('non-win32 assignment keeps a differently-cased POSIX variable as a distinct entry', () => {+ expect(+ buildOverlaidEnv({ Ok_Marker: 'inherited' }, { OK_MARKER: 'overlay' }, undefined, 'linux'),+ ).toEqual({ Ok_Marker: 'inherited', OK_MARKER: 'overlay' });+ });++ test('win32 extraPathDirs folds an inherited Path into one PATH entry and keeps its value', () => {+ expect(+ buildOverlaidEnv({ Path: 'C:\\Windows\\System32' }, undefined, ['C:\\git\\cmd'], 'win32'),+ ).toEqual({ PATH: 'C:\\git\\cmd;C:\\Windows\\System32' });+ });++ test('non-win32 extraPathDirs reads the exact PATH and leaves a differently-cased Path alone', () => {+ expect(+ buildOverlaidEnv({ Path: '/decoy', PATH: '/usr/bin' }, undefined, ['/opt/one'], 'linux'),+ ).toEqual({ Path: '/decoy', PATH: '/opt/one:/usr/bin' });+ });++ test('extraPathDirs composes from the overlaid PATH, not the base PATH', () => {+ expect(+ buildOverlaidEnv({ PATH: '/base' }, { PATH: '/from/overlay' }, ['/opt/one'], 'linux'),+ ).toEqual({ PATH: '/opt/one:/from/overlay' });+ });++ test('win32 extraPathDirs composes from an overlay PATH that folded an inherited Path away', () => {+ expect(+ buildOverlaidEnv({ Path: '/base' }, { PATH: '/from/overlay' }, ['/opt/one'], 'win32'),+ ).toEqual({ PATH: '/opt/one;/from/overlay' });+ });++ test('extraPathDirs drops empty segments, including an absent base PATH', () => {+ expect(buildOverlaidEnv({}, undefined, ['', '/opt/only'], 'linux')).toEqual({+ PATH: '/opt/only',+ });+ });++ test('the base environment is copied, not mutated', () => {+ const base = { PATH: '/base', Ok_Marker: 'inherited' };+ buildOverlaidEnv(base, { OK_MARKER: 'overlay' }, ['/opt/one'], 'win32');+ expect(base).toEqual({ PATH: '/base', Ok_Marker: 'inherited' });+ });+});++describe('runSubprocess — the win32-folded environment reaches the child', () => {+ const caseVariantsCli = fixtureCli(+ `process.stdout.write(JSON.stringify(Object.fromEntries(Object.entries(process.env).filter(([k]) => k.toLowerCase() === 'ok_test_case_marker'))))`,+ );++ test('win32 assignment hands the child one folded key, not a stale twin', async () => {+ const previous = process.env.Ok_Test_Case_Marker;+ process.env.Ok_Test_Case_Marker = 'inherited';+ try {+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: caseVariantsCli,+ cliEnv: { OK_TEST_CASE_MARKER: 'overlay' },+ platform: 'win32',+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ await proc.done;+ expect(lines[0]?.parsed).toEqual({ OK_TEST_CASE_MARKER: 'overlay' });+ } finally {+ if (previous === undefined) delete process.env.Ok_Test_Case_Marker;+ else process.env.Ok_Test_Case_Marker = previous;+ }+ });++ test.runIf(process.platform !== 'win32')(+ 'POSIX: the default platform keeps both inherited casings, so the overlay adds rather than folds',+ async () => {+ const previous = process.env.Ok_Test_Case_Marker;+ process.env.Ok_Test_Case_Marker = 'inherited';+ try {+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: caseVariantsCli,+ cliEnv: { OK_TEST_CASE_MARKER: 'overlay' },+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ await proc.done;+ expect(lines[0]?.parsed).toEqual({+ Ok_Test_Case_Marker: 'inherited',+ OK_TEST_CASE_MARKER: 'overlay',+ });+ } finally {+ if (previous === undefined) delete process.env.Ok_Test_Case_Marker;+ else process.env.Ok_Test_Case_Marker = previous;+ }+ },+ );+});++describe('runSubprocess — synchronous spawn failure', () => {+ const NUL_BEARING_ARG = '--marker\u0000injected';++ test('an argument shape spawn() rejects synchronously resolves done with code -1 and the thrown message', async () => {+ const lines: { raw: string }[] = [];+ const stderrChunks: Buffer[] = [];+ const proc = runSubprocess({+ cliArgs: fixtureCli('process.exit(0)'),+ trailingArgs: [NUL_BEARING_ARG],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ onStderr: (chunk) => stderrChunks.push(chunk),+ });+ const result = await proc.done;+ expect(result).toEqual({+ code: -1,+ stderr: expect.stringContaining('must be a string without null bytes'),+ timedOut: false,+ cancelled: false,+ });+ expect(lines).toEqual([]);+ expect(stderrChunks).toEqual([]);+ expect(() => proc.cancel()).not.toThrow();+ });++ test('the synchronous-throw result is already settled, so no async error event was routed', async () => {+ const ASYNC_ROUTE = Symbol('async-error-event');+ const proc = runSubprocess({+ cliArgs: fixtureCli('process.exit(0)'),+ trailingArgs: [NUL_BEARING_ARG],+ timeoutMs: 5000,+ onLine: () => {},+ });+ const first = await Promise.race([proc.done, Promise.resolve(ASYNC_ROUTE)]);+ expect(first).not.toBe(ASYNC_ROUTE);+ expect(first).toMatchObject({ code: -1 });+ });++ test('the synchronous-throw stderr carries the structured error facts, not just the message', async () => {+ const proc = runSubprocess({+ cliArgs: fixtureCli('process.exit(0)'),+ trailingArgs: [NUL_BEARING_ARG],+ timeoutMs: 5000,+ onLine: () => {},+ });+ const result = await proc.done;+ expect(result.stderr).toContain('code=ERR_INVALID_ARG_VALUE');+ });++ test('an asynchronous spawn failure reports the same shape with the structured facts', async () => {+ const proc = runSubprocess({+ cliArgs: ['ok-local-op-no-such-binary'],+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: () => {},+ });+ const result = await proc.done;+ expect(result.code).toBe(-1);+ expect(result.timedOut).toBe(false);+ expect(result.cancelled).toBe(false);+ expect(result.stderr).toContain('code=ENOENT');+ expect(result.stderr).toContain('syscall=spawn');+ });++ test.runIf(process.platform !== 'win32')(+ 'POSIX: a cwd that is a file makes spawn() throw ENOTDIR synchronously',+ async () => {+ const proc = runSubprocess({+ cliArgs: fixtureCli('process.exit(0)'),+ cwd: new URL(import.meta.url).pathname,+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: () => {},+ });+ const result = await proc.done;+ expect(result.code).toBe(-1);+ expect(result.stderr).toMatch(/spawn ENOTDIR/);+ expect(result.timedOut).toBe(false);+ expect(result.cancelled).toBe(false);+ expect(() => proc.cancel()).not.toThrow();+ },+ );+});diff --git a/packages/server/src/local-ops/subprocess.ts b/packages/server/src/local-ops/subprocess.tsindex 8771ffa95..bdd476c67 100644--- a/packages/server/src/local-ops/subprocess.ts+++ b/packages/server/src/local-ops/subprocess.ts@@ -1,5 +1,5 @@import { spawn } from 'node:child_process';-import { delimiter as PATH_DELIMITER } from 'node:path';+import { posix, win32 } from 'node:path';import { withHiddenWindowsConsole } from '../child-process-windows-hide.ts';interface ParsedLine {@@ -7,8 +7,14 @@ interface ParsedLine {parsed: Record<string, unknown> | null;}-interface SubprocessRunOptions {- cliArgs: readonly string[];+type LocalOpCliEnv = Readonly<Record<string, string | undefined>>;++export interface LocalOpCliInvocation {+ readonly cliArgs: readonly string[];+ readonly cliEnv?: LocalOpCliEnv;+}++interface SubprocessRunOptions extends LocalOpCliInvocation {trailingArgs: readonly string[];cwd?: string;extraPathDirs?: readonly string[];@@ -16,6 +22,7 @@ interface SubprocessRunOptions {onLine: (line: ParsedLine) => void;onStderr?: (chunk: Buffer) => void;stdinData?: string;+ platform?: NodeJS.Platform;}interface SubprocessRunResult {@@ -30,6 +37,74 @@ interface SubprocessController {cancel(): void;}+function overlayEnvEntry(+ env: NodeJS.ProcessEnv,+ key: string,+ value: string | undefined,+ platform: NodeJS.Platform,+): void {+ if (platform === 'win32') {+ const folded = key.toLowerCase();+ for (const existing of Object.keys(env)) {+ if (existing !== key && existing.toLowerCase() === folded) delete env[existing];+ }+ }+ if (value === undefined) delete env[key];+ else env[key] = value;+}++function pathDelimiterFor(platform: NodeJS.Platform): string {+ return platform === 'win32' ? win32.delimiter : posix.delimiter;+}++function readPathEntry(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): string {+ if (env.PATH !== undefined) return env.PATH;+ if (platform === 'win32') {+ for (const key of Object.keys(env)) {+ if (key.toLowerCase() === 'path') return env[key] ?? '';+ }+ }+ return '';+}++export function buildOverlaidEnv(+ baseEnv: NodeJS.ProcessEnv,+ overlay: LocalOpCliEnv | undefined,+ extraPathDirs: readonly string[] | undefined,+ platform: NodeJS.Platform,+): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = { ...baseEnv };+ for (const [key, value] of Object.entries(overlay ?? {})) {+ overlayEnvEntry(env, key, value, platform);+ }+ if (extraPathDirs && extraPathDirs.length > 0) {+ overlayEnvEntry(+ env,+ 'PATH',+ [...extraPathDirs, readPathEntry(env, platform)]+ .filter(Boolean)+ .join(pathDelimiterFor(platform)),+ platform,+ );+ }+ return env;+}++const SPAWN_ERROR_FACT_KEYS = ['code', 'errno', 'syscall'] as const;++function describeSpawnError(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ if (err === null || typeof err !== 'object') return message;+ const facts: string[] = [];+ for (const key of SPAWN_ERROR_FACT_KEYS) {+ const value = (err as Record<string, unknown>)[key];+ if (typeof value === 'number' || (typeof value === 'string' && value !== '')) {+ facts.push(`${key}=${value}`);+ }+ }+ return facts.length === 0 ? message : `${message} (${facts.join(' ')})`;+}+export function runSubprocess(opts: SubprocessRunOptions): SubprocessController {const [cmd, ...baseArgs] = opts.cliArgs;if (!cmd) {@@ -50,24 +125,33 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessControllerlet stdoutBuffer = '';const stderrChunks: Buffer[] = [];- const childEnv: NodeJS.ProcessEnv = { ...process.env };- if (opts.extraPathDirs && opts.extraPathDirs.length > 0) {- childEnv.PATH = [...opts.extraPathDirs, process.env.PATH ?? '']- .filter(Boolean)- .join(PATH_DELIMITER);- }+ const platform = opts.platform ?? process.platform;+ const childEnv = buildOverlaidEnv(process.env, opts.cliEnv, opts.extraPathDirs, platform);const stdio: ['ignore' | 'pipe', 'pipe', 'pipe'] =opts.stdinData !== undefined ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'];- const child = spawn(- cmd,- argv,- withHiddenWindowsConsole({- stdio,- cwd: opts.cwd,- env: childEnv,- }),- );+ let child: ReturnType<typeof spawn>;+ try {+ child = spawn(+ cmd,+ argv,+ withHiddenWindowsConsole({+ stdio,+ cwd: opts.cwd,+ env: childEnv,+ }),+ );+ } catch (err) {+ return {+ done: Promise.resolve({+ code: -1,+ stderr: describeSpawnError(err),+ timedOut: false,+ cancelled: false,+ }),+ cancel: () => {},+ };+ }if (opts.stdinData !== undefined && child.stdin) {child.stdin.on('error', () => {});@@ -118,7 +202,7 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessController});child.on('error', (err) => {clearTimeout(killTimer);- stderrChunks.push(Buffer.from(err.message, 'utf-8'));+ stderrChunks.push(Buffer.from(describeSpawnError(err), 'utf-8'));resolve({code: -1,stderr: Buffer.concat(stderrChunks).toString('utf-8').trim(),