Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Give dev builds their own OpenKnowledge channel (PRD-9401) (#6397)
Andrew Mikofalvy24d4465a7b2a
diff --git a/.changeset/dev-build-own-channel.md b/.changeset/dev-build-own-channel.mdnew file mode 100644index 000000000..3294858ee--- /dev/null+++ b/.changeset/dev-build-own-channel.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The desktop app and dev server run from source now use their own `dev` channel, with separate home folder, credentials, MCP entry and link scheme, so they no longer share or take over an installed app's state and projects.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 5f689c9ae..831e9f737 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -144,7 +144,7 @@ Each project runs its own local server. These commands let you see and stop them| --- | --- || `ok status` | Show whether a server and UI are running for the current project || `ok ps` | List every running OpenKnowledge server on your machine |-| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when the server's lock records a different OpenKnowledge app (Stable or Beta) than [the CLI's own](/docs/reference/what-open-knowledge-writes#beta-uses-its-own-entry), naming that app, and when something is still connected to the target, naming how many clients are attached. Either way it exits `1`; pass `--force` to stop it anyway. A lock with no recorded app is stopped as before, and a server it cannot reach is stopped without the connected-clients check |+| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when the server's lock records a different OpenKnowledge app (Stable, Beta, or a `dev` build run from source) than [the CLI's own](/docs/reference/what-open-knowledge-writes#beta-uses-its-own-entry), naming that app, and when something is still connected to the target, naming how many clients are attached. Either way it exits `1`; pass `--force` to stop it anyway. A lock with no recorded app is stopped as before, and a server it cannot reach is stopped without the connected-clients check || `ok clean` | Remove a stale lock file left behind by a crash (never touches live servers) |`ok clean` retains a lock and exits `1` if it cannot read it, it records another machine, or it has no recorded owner and its PID is still running locally. A PID that has exited is not running even while it lingers as a defunct entry in the process table, so `ok clean` prunes the lock naming it. The error names the lock and explains what to check. For an unverified owner, inspect the named local PID and stop it if it is an OpenKnowledge server; do not delete the lock while that process is running.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex b5cc3e819..4f022b8a9 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -32,6 +32,8 @@ Every `~/.ok/` path on this page belongs to Stable, except the shared entries liNo product's uninstall removes `~/.ok/machine-id`, and Stable's `ok uninstall` keeps every entry in this list. See [the uninstall notes](#opt-outs-in-one-place) for how `--purge-content` treats the shared skills store.+If you run the desktop app or the `packages/app` dev server from source, it runs as a third product, `dev`, which keeps its files under `~/.ok-dev/` and its credentials under the service `open-knowledge-dev`, and shares the entries above. A CLI run from source stays Stable unless you set `OK_CHANNEL=dev`. See [how a process picks its product](#beta-uses-its-own-entry).+OpenKnowledge installs one of two ways, and the footprint differs a little between them. Pick yours below — each tab lists the complete set of writes for that path. The [opt-outs](#opt-outs-in-one-place) and [what leaves your machine](#what-leaves-your-machine) at the end apply to both.<Tabs groupId="ok-install" persist className="ok-flush-tabs ok-tabs-h2" items={['Desktop app', 'CLI']}>@@ -130,7 +132,9 @@ Each product registers under its own name, so Stable and Beta can both be connecEarlier releases of the separately installed `OpenKnowledge Beta` app registered under `open-knowledge`, and updating does not move that entry. If an editor's config has no `open-knowledge-beta` entry, reconnect that editor from **Settings → Agent connections** in OpenKnowledge Beta, then remove the old `open-knowledge` entry from the file listed under [`ok init`](#ok-init) if you don't also run Stable. An older Beta install still named `OpenKnowledge` keeps using `open-knowledge`; leave that entry in place.-A CLI process decides which product it belongs to in this order: the `OK_CHANNEL` environment variable (`stable` or `beta`; any other value is an error), then the name of the executable it runs as, and otherwise Stable. The CLI bundled in OpenKnowledge Beta resolves as Beta from its executable name, and Beta's launcher sets `OK_CHANNEL=beta` before it falls back to npx. A CLI run under plain Node, such as `npx @inkeep/open-knowledge@beta init` typed by hand, resolves as Stable and writes the `open-knowledge` entry unless you set `OK_CHANNEL=beta`.+A CLI process decides which product it belongs to in this order: the `OK_CHANNEL` environment variable (`stable`, `beta`, or `dev`; any other value is an error), then the name of the executable it runs as, and otherwise Stable. The CLI bundled in OpenKnowledge Beta resolves as Beta from its executable name, and Beta's launcher sets `OK_CHANNEL=beta` before it falls back to npx. A CLI run under plain Node, such as `npx @inkeep/open-knowledge@beta init` typed by hand, resolves as Stable and writes the `open-knowledge` entry unless you set `OK_CHANNEL=beta`.++`dev` is the product for building OpenKnowledge from source. An unpackaged desktop build and the `packages/app` dev server select it when `OK_CHANNEL` is unset, and `ok init --dev-mcp` does too. It registers as `open-knowledge-dev`, in project config only, never in your user-level editor config. A dev build claims the `openknowledge-dev://` link scheme only when you set `OK_DEV_PROTOCOL=1`. Set `OK_CHANNEL=stable` to run a source build as Stable on purpose. A dev build never writes an MCP launcher for an installed product, and never hands `OK_CHANNEL=dev` to a CLI it does not control: its own CLI calls run the checkout's `packages/cli/dist/cli.mjs`, while terminals and agents it starts get no `OK_CHANNEL`. Build the checkout first: without `packages/cli/dist/cli.mjs`, those calls run the `open-knowledge` on your PATH as Stable, and the dev build refuses anything that would change Stable: signing in or out, storing a token, and cloning a project. Run `pnpm build` in the checkout, then restart the dev build. `ok uninstall` from an installed product leaves the dev footprint in place; delete `~/.ok-dev/` and the `open-knowledge-dev` credential yourself.#### Upgrading Beta to its own home folder@@ -144,7 +148,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable` or `beta`); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored |+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable`, `beta`, or `dev` for a source build); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |@@ -173,7 +177,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite#### Stable and Beta on the same project-Only one OpenKnowledge app serves a project at a time. `server.lock` records which product started the server, resolved the same way a [CLI process picks its product](#beta-uses-its-own-entry). When OpenKnowledge Beta opens a project that Stable is serving, or the other way round, it does not connect to that server, take it over, or stop it on its own. It shows **This project is open in another OpenKnowledge app**, naming the app that holds it (for example **OpenKnowledge (Stable)**), and **Restart server** reports that the other app keeps the project. A lock that names a product this app does not know gets the same treatment. The same dialog appears when another app's lock blocks the open in other ways too: its server is not answering, a server of this app collided with that lock, or a new server timed out because that lock was already held. This dialog is the only way the app stops another app's server.+Only one OpenKnowledge app serves a project at a time. `server.lock` records which product started the server, resolved the same way a [CLI process picks its product](#beta-uses-its-own-entry). When OpenKnowledge Beta opens a project that Stable is serving, or the other way round, it does not connect to that server, take it over, or stop it on its own. It shows **This project is open in another OpenKnowledge app**, naming the app that holds it (for example **OpenKnowledge (Stable)**), and **Restart server** reports that the other app keeps the project. A lock that names a product this app does not know gets the same treatment. A server started by an unpackaged desktop build or the `packages/app` dev server names `dev`, so installed Stable and Beta treat it as another app too. The same dialog appears when another app's lock blocks the open in other ways too: its server is not answering, a server of this app collided with that lock, or a new server timed out because that lock was already held. This dialog is the only way the app stops another app's server.Closing the other app's window does not free the project, because its server keeps running in the background. To move the project, choose the dialog's **Stop … Server & Open Here** button (for example **Stop OpenKnowledge (Stable) Server & Open Here**). Every window, editor, or agent connected to that server loses its connection to the project. Cancel is the default and stops nothing. From a terminal, `ok stop --force` in the project folder does the same. Without `--force`, `ok stop` declines, and exits `1`, when the lock names a different app than the one its CLI resolves to.@@ -286,7 +290,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable` or `beta`); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored |+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable`, `beta`, or `dev` for a source build); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |diff --git a/packages/app/src/lib/transports/auth-query-transport.test.ts b/packages/app/src/lib/transports/auth-query-transport.test.tsindex dd0c3bb0c..7ea769a7c 100644--- a/packages/app/src/lib/transports/auth-query-transport.test.ts+++ b/packages/app/src/lib/transports/auth-query-transport.test.ts@@ -1,3 +1,4 @@+import { DEV_FALLBACK_CLI_REFUSAL } from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { httpAuthQueryTransport } from './auth-query-transport';@@ -221,6 +222,25 @@ describe('httpAuthQueryTransport().signout', () => {expect(result).toEqual({ ok: false, error: 'Auth signout failed.' });});+ it('surfaces the problem detail over the title, so a refusal keeps its remedy', async () => {+ stubFetch(+ () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:auth-failed',+ title: 'This dev build has no built CLI.',+ status: 409,+ detail: DEV_FALLBACK_CLI_REFUSAL,+ }),+ { status: 409, headers: { 'content-type': 'application/problem+json' } },+ ),+ );+ const transport = httpAuthQueryTransport();+ if (!transport.signout) throw new Error('http transport must implement signout');++ expect(await transport.signout()).toEqual({ ok: false, error: DEV_FALLBACK_CLI_REFUSAL });+ });+it('returns failure with no error title when the body is not problem+json', async () => {stubFetch(() => new Response('upstream boom', { status: 502 }));const transport = httpAuthQueryTransport();diff --git a/packages/app/src/lib/transports/auth-query-transport.ts b/packages/app/src/lib/transports/auth-query-transport.tsindex 4d87dfa77..cd4008271 100644--- a/packages/app/src/lib/transports/auth-query-transport.ts+++ b/packages/app/src/lib/transports/auth-query-transport.ts@@ -151,8 +151,8 @@ export function httpAuthQueryTransport(): AuthQueryTransport {async signout(request) {const res = await postJson('/api/local-op/auth/signout', request);if (!res.ok) {- const error = (await extractProblem(res))?.title;- return { ok: false, error };+ const problem = await extractProblem(res);+ return { ok: false, error: problem?.detail || problem?.title };}return { ok: true };},diff --git a/packages/app/src/lib/transports/auth-transport.test.ts b/packages/app/src/lib/transports/auth-transport.test.tsindex ec5385f2c..5752b3e8a 100644--- a/packages/app/src/lib/transports/auth-transport.test.ts+++ b/packages/app/src/lib/transports/auth-transport.test.ts@@ -1,3 +1,4 @@+import { DEV_FALLBACK_CLI_REFUSAL } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test, vi } from 'vitest';import { httpAuthTransport } from './auth-transport';@@ -158,6 +159,24 @@ describe('httpAuthTransport().start / ghLogin (streamAuthEndpoint)', () => {]);});+ test('a dev build without its workspace CLI shows the build-and-restart refusal as the sign-in error', async () => {+ globalThis.fetch = vi.fn(+ async () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:auth-failed',+ title: 'This dev build has no built CLI.',+ status: 409,+ detail: DEV_FALLBACK_CLI_REFUSAL,+ }),+ { status: 409, headers: { 'Content-Type': 'application/problem+json' } },+ ),+ ) as unknown as typeof fetch;+ expect(await collectEvents(httpAuthTransport().start())).toEqual([+ { type: 'error', message: DEV_FALLBACK_CLI_REFUSAL },+ ]);+ });+test('a pre-stream failure with an unparseable body falls back to the generic message', async () => {globalThis.fetch = vi.fn(async () => new Response('<html>gateway error</html>', { status: 502 }),diff --git a/packages/app/src/lib/transports/clone-transport.test.ts b/packages/app/src/lib/transports/clone-transport.test.tsindex b84127d5a..735036c00 100644--- a/packages/app/src/lib/transports/clone-transport.test.ts+++ b/packages/app/src/lib/transports/clone-transport.test.ts@@ -1,6 +1,7 @@-import { describe, expect, test } from 'vitest';+import { DEV_FALLBACK_CLI_REFUSAL } from '@inkeep/open-knowledge-core';+import { afterEach, describe, expect, test, vi } from 'vitest';import type { OkDesktopBridge, OkLocalOpCloneEvent } from '@/lib/desktop-bridge-types';-import { ipcCloneTransport } from './clone-transport';+import { httpCloneTransport, ipcCloneTransport } from './clone-transport';interface CapturedStart {url: string;@@ -116,3 +117,41 @@ describe('CloneTransport contract — shape symmetry between HTTP + IPC', () =>expect(captured[0]?.branch).toBe('feat/foo');});});++describe('httpCloneTransport — a refused request', () => {+ const realFetch = globalThis.fetch;+ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ async function firstEventFor(problem: Record<string, unknown>, status: number) {+ globalThis.fetch = vi.fn(+ async () => new Response(JSON.stringify({ status, ...problem }), { status }),+ ) as unknown as typeof fetch;+ const handle = httpCloneTransport().start({ url: 'https://github.com/o/r.git', dir: '/tmp/r' });+ for await (const event of handle.events) return event;+ return undefined;+ }++ test('shows the problem detail, so the dev-build refusal keeps its remedy', async () => {+ expect(+ await firstEventFor(+ {+ type: 'urn:ok:error:clone-failed',+ title: 'This dev build has no built CLI.',+ detail: DEV_FALLBACK_CLI_REFUSAL,+ },+ 409,+ ),+ ).toEqual({ type: 'error', message: `Clone failed: ${DEV_FALLBACK_CLI_REFUSAL}` });+ });++ test('keeps the title when the problem carries no detail', async () => {+ expect(+ await firstEventFor(+ { type: 'urn:ok:error:url-not-allowed', title: 'URL protocol is not allowed for clone.' },+ 400,+ ),+ ).toEqual({ type: 'error', message: 'Clone failed: URL protocol is not allowed for clone.' });+ });+});diff --git a/packages/app/src/lib/transports/clone-transport.ts b/packages/app/src/lib/transports/clone-transport.tsindex 8a30b97d3..ae784939d 100644--- a/packages/app/src/lib/transports/clone-transport.ts+++ b/packages/app/src/lib/transports/clone-transport.ts@@ -44,7 +44,7 @@ export function httpCloneTransport(): CloneTransport {const body = (await res.json()) as unknown;const result = ProblemDetailsSchema.safeParse(body);if (result.success) {- const title = result.data.title;+ const title = result.data.detail || result.data.title;message = t`Clone failed: ${title}`;}} catch {}diff --git a/packages/app/src/server/dev-server-channel.test.ts b/packages/app/src/server/dev-server-channel.test.tsnew file mode 100644index 000000000..9cc435ee8--- /dev/null+++ b/packages/app/src/server/dev-server-channel.test.ts@@ -0,0 +1,55 @@+import { resolveDesktopProductName } from '@inkeep/open-knowledge-core/constants/product';+import { describe, expect, test } from 'vitest';+import {+ applyDevServerChannel,+ devServerCliArgs,+ workspaceCliEntry,+} from './dev-server-channel.ts';++describe('applyDevServerChannel', () => {+ test('pnpm dev serves as the dev channel', () => {+ const env: Record<string, string | undefined> = {};+ applyDevServerChannel(env);+ expect(resolveDesktopProductName(env, '/usr/local/bin/node')).toBe('dev');+ });++ test('an explicit OK_CHANNEL still wins', () => {+ const env: Record<string, string | undefined> = { OK_CHANNEL: 'stable' };+ applyDevServerChannel(env);+ expect(resolveDesktopProductName(env, '/usr/local/bin/node')).toBe('stable');+ });++ test('a test-isolated run keeps the shipped identity', () => {+ const env: Record<string, string | undefined> = { OK_TEST_CONTENT_DIR: '/tmp/content' };+ applyDevServerChannel(env);+ expect(env.OK_CHANNEL).toBeUndefined();+ });+});++describe('devServerCliArgs', () => {+ const root = '/src/open-knowledge';+ const entry = workspaceCliEntry(root);++ test('a dev server runs its CLI children on the workspace build, which knows the dev channel', () => {+ expect(+ devServerCliArgs(+ root,+ { OK_CHANNEL: 'dev' },+ { nodePath: '/usr/local/bin/node', entryExists: () => true },+ ),+ ).toEqual(['/usr/local/bin/node', entry]);+ expect(entry).toBe('/src/open-knowledge/packages/cli/dist/cli.mjs');+ });++ test('falls back to the CLI on PATH when the workspace CLI is not built', () => {+ expect(+ devServerCliArgs(root, { OK_CHANNEL: 'dev' }, { entryExists: () => false }),+ ).toBeUndefined();+ });++ test('a dev server pinned to a shipped channel keeps the CLI on PATH', () => {+ expect(+ devServerCliArgs(root, { OK_CHANNEL: 'stable' }, { entryExists: () => true }),+ ).toBeUndefined();+ });+});diff --git a/packages/app/src/server/dev-server-channel.ts b/packages/app/src/server/dev-server-channel.tsnew file mode 100644index 000000000..5155c94d6--- /dev/null+++ b/packages/app/src/server/dev-server-channel.ts@@ -0,0 +1,23 @@+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { defaultToDevChannel, isDevChannel } from '@inkeep/open-knowledge-core/constants/product';++export function applyDevServerChannel(env: Record<string, string | undefined>): void {+ if (env.OK_TEST_CONTENT_DIR) return;+ defaultToDevChannel(env);+}++export function workspaceCliEntry(projectRoot: string): string {+ return join(projectRoot, 'packages', 'cli', 'dist', 'cli.mjs');+}++export function devServerCliArgs(+ projectRoot: string,+ env: Readonly<Record<string, string | undefined>>,+ deps: { nodePath?: string; entryExists?: (path: string) => boolean } = {},+): string[] | undefined {+ if (!isDevChannel(env)) return undefined;+ const entry = workspaceCliEntry(projectRoot);+ if (!(deps.entryExists ?? existsSync)(entry)) return undefined;+ return [deps.nodePath ?? process.execPath, entry];+}diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex cea0e1d7c..533ab1255 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -1,5 +1,6 @@import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';import { relative, resolve } from 'node:path';+import { isDevChannel } from '@inkeep/open-knowledge-core/constants/product';import {ASSET_EXTENSIONS,EXECUTABLE_BLOCKLIST_EXTENSIONS,@@ -25,6 +26,11 @@ import type { WebSocketServer } from 'ws';import { parse as parseYaml } from 'yaml';import { computeDevApiConfigResponse } from './api-config-handler.ts';import { type AssetRouting, routeAssets } from './asset-routing.ts';+import {+ applyDevServerChannel,+ devServerCliArgs,+ workspaceCliEntry,+} from './dev-server-channel.ts';let configureServerInvocations = 0;@@ -170,6 +176,14 @@ async function attachOkServer(assetRouting: AssetRouting,activeRuntimeTeardowns: RuntimeTeardowns,): Promise<() => Promise<void>> {+ applyDevServerChannel(process.env);+ const localOpCliArgs = devServerCliArgs(PROJECT_ROOT, process.env);+ if (localOpCliArgs === undefined && isDevChannel(process.env)) {+ getLogger('hocuspocus').warn(+ { entry: workspaceCliEntry(PROJECT_ROOT) },+ 'The workspace CLI is not built, so this dev server runs the open-knowledge on PATH as Stable for MCP, git credentials and local operations, and refuses sign-in, sign-out, token storage and clone. Run pnpm build in the checkout, then restart pnpm dev.',+ );+ }configureServerInvocations += 1;if (configureServerInvocations > 1) {console.warn(@@ -189,6 +203,7 @@ async function attachOkServer(quiet: true,embeddingsKeyStore: makeLazyEmbeddingsKeyStore(),capabilities: ['http', 'ws', 'ui'],+ ...(localOpCliArgs === undefined ? {} : { localOpCliArgs }),...(isEphemeralTest ? { ephemeral: true, singleDocRelPath: SINGLE_DOC_REL_PATH } : {}),});@@ -240,7 +255,7 @@ async function attachOkServer(getMcpStdioCommand: () => {const addr = server.httpServer?.address();const port = typeof addr === 'object' && addr !== null ? addr.port : 5173;- return buildOkMcpStdioCommand(undefined, port, { log: getLogger('acp-threads') });+ return buildOkMcpStdioCommand(localOpCliArgs, port, { log: getLogger('acp-threads') });},agentBrowserTools: () =>!isTestIsolated &&diff --git a/packages/cli/src/commands/auth/dev-fallback-classification.test.ts b/packages/cli/src/commands/auth/dev-fallback-classification.test.tsnew file mode 100644index 000000000..ebac68c9b--- /dev/null+++ b/packages/cli/src/commands/auth/dev-fallback-classification.test.ts@@ -0,0 +1,19 @@+import { OkCliCommand } from '@inkeep/open-knowledge-core';+import { describe, expect, test } from 'vitest';+import { authCommand } from './index.ts';++const STABLE_READS = new Set(['status', 'repos', 'git-credential']);++describe('auth verbs on a dev build that falls back to the installed CLI', () => {+ test('every registered verb is refused unless it is a declared read of Stable', () => {+ const cli = OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } });+ const verbs = authCommand().commands.map((command) => command.name());+ expect(verbs.length).toBeGreaterThan(STABLE_READS.size);+ for (const verb of verbs) {+ expect({ verb, refused: cli.refusalFor(['auth', verb]) !== undefined }).toEqual({+ verb,+ refused: !STABLE_READS.has(verb),+ });+ }+ });+});diff --git a/packages/cli/src/commands/channel-mcp-key.test.ts b/packages/cli/src/commands/channel-mcp-key.test.tsindex 6301f10fd..0519ae129 100644--- a/packages/cli/src/commands/channel-mcp-key.test.ts+++ b/packages/cli/src/commands/channel-mcp-key.test.ts@@ -11,11 +11,12 @@ import {buildManagedServerEntry,CHAIN_V2,CHAIN_WIN_V1,+ DEV_CHANNEL_LAUNCHER_REFUSAL,EDITOR_TARGETS,isEntryUpToDate,isOwnManagedEntry,} from './editors.ts';-import { writeEditorMcpConfig } from './init.ts';+import { writeEditorMcpConfig, writeUserMcpConfigs } from './init.ts';const STABLE_UNIX_CHAIN = `# ok-mcp-v2USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"@@ -230,4 +231,59 @@ describe('per-channel MCP registration', () => {expect(isOwnPiExtensionSource(betaSource)).toBe(false);expect(isPiExtensionSourceUpToDate(betaSource)).toBe(false);});++ it('the dev channel never claims a Stable dev-mode bridge, and Stable never claims a dev bridge', () => {+ const stableDevBridge = '// ok-pi-bridge-dev\nbody';+ const devPublishedBridge = '// ok-pi-bridge-dev-v1\nbody';+ const devDevBridge = '// ok-pi-bridge-dev-dev\nbody';++ vi.stubEnv('OK_CHANNEL', 'stable');+ expect(isOwnPiExtensionSource(stableDevBridge)).toBe(true);+ expect(isOwnPiExtensionSource(devPublishedBridge)).toBe(false);+ expect(isOwnPiExtensionSource(devDevBridge)).toBe(false);++ vi.stubEnv('OK_CHANNEL', 'dev');+ expect(EDITOR_TARGETS.pi.projectConfigPath('/p')).toBe(+ join('/p', '.pi', 'extensions', 'open-knowledge-dev.ts'),+ );+ expect(isOwnPiExtensionSource(devPublishedBridge)).toBe(true);+ expect(isOwnPiExtensionSource(devDevBridge)).toBe(true);+ expect(isOwnPiExtensionSource(stableDevBridge)).toBe(false);+ });++ it('a dev-channel process builds no launcher for an installed channel and owns none', () => {+ const stableEntry = buildManagedServerEntry({ mode: 'published', platformName: 'darwin' });+ vi.stubEnv('OK_CHANNEL', 'dev');+ expect(() => buildManagedServerEntry({ mode: 'published', platformName: 'darwin' })).toThrow(+ DEV_CHANNEL_LAUNCHER_REFUSAL,+ );+ expect(() => buildManagedServerEntry({ mode: 'published', platformName: 'win32' })).toThrow(+ DEV_CHANNEL_LAUNCHER_REFUSAL,+ );+ expect(() => buildPiExtensionSource({ mode: 'published' })).toThrow(+ DEV_CHANNEL_LAUNCHER_REFUSAL,+ );+ const opencode = writeEditorMcpConfig(+ EDITOR_TARGETS.opencode,+ home,+ { mode: 'published', skipAvailabilityCheck: true },+ home,+ join(home, 'opencode.json'),+ );+ expect([opencode.action, opencode.error]).toEqual(['failed', DEV_CHANNEL_LAUNCHER_REFUSAL]);+ expect(isOwnManagedEntry(stableEntry)).toBe(false);+ });++ it('a dev-channel process writes no user-global MCP config, and says why', async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ const results = await writeUserMcpConfigs({ editors: ['claude'], home });+ expect(results.map((r) => [r.serverName, r.action, r.error])).toEqual([+ [+ 'open-knowledge-dev',+ 'failed',+ 'A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run `node <checkout>/packages/cli/dist/cli.mjs init --dev-mcp` in the project, or set OK_CHANNEL=stable.',+ ],+ ]);+ expect(() => readFileSync(join(home, '.claude.json'), 'utf-8')).toThrow();+ });});diff --git a/packages/cli/src/commands/desktop-dispatch.test.ts b/packages/cli/src/commands/desktop-dispatch.test.tsindex efdd68bb4..8ce2b593b 100644--- a/packages/cli/src/commands/desktop-dispatch.test.ts+++ b/packages/cli/src/commands/desktop-dispatch.test.ts@@ -327,7 +327,7 @@ describe('detectDesktop — unsupported channel override', () => {});expect(warn).toHaveBeenCalledTimes(1);expect(warn).toHaveBeenCalledWith(- `Treating this CLI as OpenKnowledge (Stable) for this command: Unsupported ${OK_CHANNEL_ENV}="nightly". Expected stable or beta.`,+ `Treating this CLI as OpenKnowledge (Stable) for this command: Unsupported ${OK_CHANNEL_ENV}="nightly". Expected stable or beta or dev.`,);});@@ -349,7 +349,7 @@ describe('detectDesktop — unsupported channel override', () => {cliProduct: 'beta',});expect(warn).toHaveBeenCalledWith(- `Treating this CLI as OpenKnowledge Beta for this command: Unsupported ${OK_CHANNEL_ENV}="nightly". Expected stable or beta.`,+ `Treating this CLI as OpenKnowledge Beta for this command: Unsupported ${OK_CHANNEL_ENV}="nightly". Expected stable or beta or dev.`,);});@@ -361,6 +361,23 @@ describe('detectDesktop — unsupported channel override', () => {});});+describe('detectDesktop — dev channel', () => {+ test('a dev-channel CLI never probes for a dev app, which is never packaged', () => {+ const probed: string[] = [];+ const result = detectDesktop(+ baseDeps({+ env: { [OK_CHANNEL_ENV]: 'dev' },+ statSync: (p) => {+ probed.push(p);+ return p === APP_EXEC ? { isFile: () => true, isDirectory: () => false } : null;+ },+ }),+ );+ expect(result).toMatchObject({ available: true, product: 'stable', cliProduct: 'dev' });+ expect(probed.filter((p) => p.includes('OpenKnowledge Dev'))).toEqual([]);+ });+});+describe('detectDesktop — headless gate (FR9 — CI is intentionally NOT a trigger)', () => {const WIN_EXE ='C:\\Users\\u\\AppData\\Local\\Programs\\@inkeepopen-knowledge-desktop\\OpenKnowledge.exe';diff --git a/packages/cli/src/commands/desktop-dispatch.ts b/packages/cli/src/commands/desktop-dispatch.tsindex 18e03f6b9..ddb716213 100644--- a/packages/cli/src/commands/desktop-dispatch.ts+++ b/packages/cli/src/commands/desktop-dispatch.ts@@ -10,13 +10,14 @@ import {desktopWindowsExecutableName,desktopWindowsInstallDirNames,OK_CHANNEL_ENV,+ PACKAGED_DESKTOP_PRODUCT_NAMES,resolveDesktopProductName,} from '@inkeep/open-knowledge-core';import { spawnDetachedScrubbed } from '../utils/detached-spawn.ts';export const DESKTOP_BUNDLE_ID = DESKTOP_PRODUCTS.stable.appId;-const ALL_DESKTOP_PRODUCTS = Object.keys(DESKTOP_PRODUCTS) as readonly DesktopProductName[];+const PACKAGED_DESKTOP_PRODUCTS: readonly DesktopProductName[] = PACKAGED_DESKTOP_PRODUCT_NAMES;const PUBLIC_DESKTOP_PRODUCTS: readonly DesktopProductName[] = ['stable', 'beta'];@@ -44,7 +45,8 @@ export function runningDesktopProduct(export function desktopProductsVisibleTo(cliProduct: DesktopProductName,): readonly DesktopProductName[] {- return PUBLIC_DESKTOP_PRODUCTS.includes(cliProduct)+ return PUBLIC_DESKTOP_PRODUCTS.includes(cliProduct) ||+ !PACKAGED_DESKTOP_PRODUCTS.includes(cliProduct)? PUBLIC_DESKTOP_PRODUCTS: [cliProduct, ...PUBLIC_DESKTOP_PRODUCTS];}@@ -118,7 +120,7 @@ function resolveBundlePath(if (m?.[1]) {const bundle = m[1];const product =- ALL_DESKTOP_PRODUCTS.find((name) =>+ PACKAGED_DESKTOP_PRODUCTS.find((name) =>bundle.endsWith(`/${DESKTOP_PRODUCTS[name].productName}.app`),) ?? cliProduct;return { path: bundle, product };@@ -154,7 +156,7 @@ function resolveWindowsExecutable(cliProduct: DesktopProductName,): ResolvedDesktop | null {if (deps.env.ELECTRON_RUN_AS_NODE === '1') {- const bundledProduct = ALL_DESKTOP_PRODUCTS.find((name) =>+ const bundledProduct = PACKAGED_DESKTOP_PRODUCTS.find((name) =>deps.execPath.toLowerCase().endsWith(`\\${desktopWindowsExecutableName(DESKTOP_PRODUCTS[name]).toLowerCase()}`),@@ -183,7 +185,7 @@ function resolveLinuxExecutable(cliProduct: DesktopProductName,): ResolvedDesktop | null {if (deps.env.ELECTRON_RUN_AS_NODE === '1') {- const bundledProduct = ALL_DESKTOP_PRODUCTS.find((name) =>+ const bundledProduct = PACKAGED_DESKTOP_PRODUCTS.find((name) =>deps.execPath.endsWith(`/${DESKTOP_PRODUCTS[name].linuxExecutableName}`),);if (bundledProduct) return { path: deps.execPath, product: bundledProduct };diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.tsindex 1ef149250..4e1b59fb6 100644--- a/packages/cli/src/commands/editors.ts+++ b/packages/cli/src/commands/editors.ts@@ -2,6 +2,7 @@ import { existsSync, readdirSync } from 'node:fs';import { homedir } from 'node:os';import { basename, dirname, join, posix, resolve, sep, win32 } from 'node:path';import {+ CHECKOUT_CLI_COMMAND,ALL_EDITOR_IDS as CORE_ALL_EDITOR_IDS,EDITOR_LABELS as CORE_EDITOR_LABELS,HOSTS_WITH_USER_SKILL_DIR as CORE_HOSTS_WITH_USER_SKILL_DIR,@@ -11,9 +12,10 @@ import {currentMcpServerName,DESKTOP_PRODUCTS,type DesktopProduct,- type DesktopProductName,+ isDevChannel,mcpChainMarkerPrefix,OK_CHANNEL_ENV,+ type PackagedDesktopProductName,piExtensionProjectPath,resolveDesktopProductName,} from '@inkeep/open-knowledge-core';@@ -30,6 +32,11 @@ const DEV_MCP_ENV = {OK_LOG_FILE: '/tmp/ok-mcp.log',} as const;+function devMcpEnv(): Record<string, string> {+ const channel = resolveDesktopProductName();+ return channel === 'stable' ? { ...DEV_MCP_ENV } : { ...DEV_MCP_ENV, [OK_CHANNEL_ENV]: channel };+}+const UNIX_CHAIN_REVISION = 2;const WIN_CHAIN_REVISION = 1;@@ -45,7 +52,7 @@ function winChainSentinel(product: DesktopProduct): string {return `${mcpChainMarkerPrefix('windows-chain', product.mcpChainTag)}${WIN_CHAIN_REVISION}`;}-function buildUnixChain(name: DesktopProductName): string {+function buildUnixChain(name: PackagedDesktopProductName): string {const product = DESKTOP_PRODUCTS[name];const npxSpec = `${OK_PACKAGE_SPEC}@${product.npmDistTag}`;const channelLine = name === 'stable' ? '' : `\nexport ${OK_CHANNEL_ENV}=${name}`;@@ -64,7 +71,7 @@ echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editorexit 127`;}-function buildWinChain(name: DesktopProductName): string {+function buildWinChain(name: PackagedDesktopProductName): string {const product = DESKTOP_PRODUCTS[name];const npxSpec = `${OK_PACKAGE_SPEC}@${product.npmDistTag}`;const cmd = `${product.cliCommandNames[0]}.cmd`;@@ -97,6 +104,14 @@ foreach ($d in $dirs) {exit 127`;}+export const DEV_CHANNEL_LAUNCHER_REFUSAL = `A dev build writes no MCP launcher for an installed OpenKnowledge channel, because that launcher runs a released CLI. Register this checkout by running \`${CHECKOUT_CLI_COMMAND} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;++function launcherChannel(): PackagedDesktopProductName {+ const channel = resolveDesktopProductName();+ if (channel === 'dev') throw new Error(DEV_CHANNEL_LAUNCHER_REFUSAL);+ return channel;+}+export const CHAIN_VERSION_SENTINEL = unixChainSentinel(DESKTOP_PRODUCTS.stable);export const CHAIN_V2 = buildUnixChain('stable');@@ -113,6 +128,10 @@ export function piExtensionVersionSentinel(product: DesktopProduct): string {return `${piExtensionOwnershipMarker(product)}-v1`;}+export function piExtensionDevHeader(product: DesktopProduct): string {+ return `${piExtensionOwnershipMarker(product)}-dev`;+}+export const PI_EXTENSION_OWNERSHIP_MARKER = piExtensionOwnershipMarker(DESKTOP_PRODUCTS.stable);export const PI_EXTENSION_VERSION_SENTINEL = piExtensionVersionSentinel(DESKTOP_PRODUCTS.stable);@@ -210,7 +229,7 @@ export function buildManagedServerEntry(options: McpInstallOptions = {}): Recordreturn {command: DEV_MCP_SERVER_COMMAND,args: [resolveDevCliDistPath(), 'mcp'],- env: { ...DEV_MCP_ENV },+ env: devMcpEnv(),};}@@ -218,17 +237,12 @@ export function buildManagedServerEntry(options: McpInstallOptions = {}): Recordif (platformName === 'win32') {return {command: 'powershell',- args: [- '-NoProfile',- '-NonInteractive',- '-Command',- buildWinChain(resolveDesktopProductName()),- ],+ args: ['-NoProfile', '-NonInteractive', '-Command', buildWinChain(launcherChannel())],};}return {command: '/bin/sh',- args: ['-l', '-c', buildUnixChain(resolveDesktopProductName())],+ args: ['-l', '-c', buildUnixChain(launcherChannel())],};}@@ -238,7 +252,7 @@ function buildOpenCodeEntry(options: McpInstallOptions = {}): Record<string, unktype: 'local',enabled: true,command: [DEV_MCP_SERVER_COMMAND, resolveDevCliDistPath(), 'mcp'],- environment: { ...DEV_MCP_ENV },+ environment: devMcpEnv(),};}@@ -252,19 +266,19 @@ function buildOpenCodeEntry(options: McpInstallOptions = {}): Record<string, unk'-NoProfile','-NonInteractive','-Command',- buildWinChain(resolveDesktopProductName()),+ buildWinChain(launcherChannel()),],};}return {type: 'local',enabled: true,- command: ['/bin/sh', '-l', '-c', buildUnixChain(resolveDesktopProductName())],+ command: ['/bin/sh', '-l', '-c', buildUnixChain(launcherChannel())],};}export function isOwnManagedEntry(entry: unknown): boolean {- if (typeof entry !== 'object' || entry === null) return false;+ if (typeof entry !== 'object' || entry === null || isDevChannel()) return false;const e = entry as Record<string, unknown>;return (matchesCanonicalExactly(@@ -370,20 +384,18 @@ type ManagedEntry = ReturnType<NonNullable<EditorMcpTarget['buildEntry']>>;export function droppedManagedKeys(existing: object | null | undefined,- canonical: ManagedEntry,+ canonical: ManagedEntry | null,): readonly string[] {- if (typeof existing !== 'object' || existing === null) return [];+ if (canonical === null || typeof existing !== 'object' || existing === null) return [];const e = existing as Record<string, unknown>;return managedEntryKeys(canonical).filter((key) => canonical[key] === undefined && e[key] !== undefined,);}-export function canonicalEntryFor(- target: EditorMcpTarget,- cwd: string,-): Record<string, unknown> | null {- return target.format === 'file' ? null : target.buildEntry(cwd, {});+export function canonicalEntryFor(target: EditorMcpTarget, cwd: string): ManagedEntry | null {+ if (target.format === 'file' || isDevChannel()) return null;+ return target.buildEntry(cwd, {});}export function entryCarriesDroppedManagedKey(diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex 97c0c96d1..eaf3cfa15 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -50,6 +50,7 @@ import {buildInitJsonSummary,ContentDirError,classifyExistingMcpEntry,+ DevMcpScopeError,detectInstalledEditors,type EditorMcpResult,formatInitResult,@@ -106,8 +107,13 @@ describe('runInit', () => {env: {MCP_DEBUG: '1',OK_LOG_FILE: '/tmp/ok-mcp.log',+ OK_CHANNEL: 'dev',},});+ const enableDevChannelMcp = () => {+ enableDevMcp();+ vi.stubEnv('OK_CHANNEL', 'dev');+ };const defaultInstallUserSkill = async () => 'installed' as const;const runInitForTest = async (options: Parameters<typeof runInit>[0] = {}) =>runInit({@@ -149,6 +155,7 @@ describe('runInit', () => {process.env.XDG_CONFIG_HOME = originalXdgConfigHome;}process.argv[1] = originalArgv1;+ vi.unstubAllEnvs();rmSync(testDir, { recursive: true, force: true });});@@ -218,14 +225,70 @@ describe('runInit', () => {expect(config.mcpServers[result.editors[0].serverName]).toBeDefined();});- it('writes a local dev MCP entry when --dev-mcp is enabled', async () => {- enableDevMcp();- const result = await runInitForTest({ devMcp: true });+ it('writes the dev MCP entry under the open-knowledge-dev key in project config only', async () => {+ enableDevChannelMcp();+ const result = await runInitForTest({ devMcp: true, scope: undefined });- expect(result.mcpAction).toBe('written');+ expect(result.editors).toEqual([+ expect.objectContaining({+ editorId: 'claude',+ action: 'written',+ serverName: 'open-knowledge-dev',+ configScope: 'project',+ }),+ ]);+ const config = JSON.parse(readFileSync(join(testDir, '.mcp.json'), 'utf-8'));+ expect(config.mcpServers).toEqual({ 'open-knowledge-dev': expectedDevMcpEntry() });+ expect(existsSync(claudeConfigPath())).toBe(false);+ expect(formatInitResult(result, testDir)).toContain(+ 'The open-knowledge-dev entry runs this checkout on this machine only; keep it out of commits.',+ );+ });- const config = JSON.parse(readFileSync(claudeConfigPath(), 'utf-8'));- expect(config.mcpServers[result.editors[0].serverName]).toEqual(expectedDevMcpEntry());+ it.each(['user', 'both'] as const)('refuses --dev-mcp with --scope %s', async (scope) => {+ enableDevChannelMcp();+ await expect(runInitForTest({ devMcp: true, scope })).rejects.toBeInstanceOf(DevMcpScopeError);+ expect(existsSync(claudeConfigPath())).toBe(false);+ expect(existsSync(join(testDir, '.mcp.json'))).toBe(false);+ });++ it('the command action selects the dev channel for --dev-mcp and exits 64 on a user scope', async () => {+ vi.stubEnv('OK_CHANNEL', undefined);+ const savedCwd = process.cwd();+ const savedExitCode = process.exitCode;+ const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ process.chdir(testDir);+ await initCommand().parseAsync(['--dev-mcp', '--scope', 'user', '--no-skills'], {+ from: 'user',+ });++ expect(process.env.OK_CHANNEL).toBe('dev');+ expect(process.exitCode).toBe(64);+ const printed = stderrSpy.mock.calls.map((call) => String(call[0])).join('');+ expect(printed).toContain('A dev MCP entry is written to project config only');+ expect(existsSync(claudeConfigPath())).toBe(false);+ } finally {+ process.chdir(savedCwd);+ process.exitCode = savedExitCode;+ stderrSpy.mockRestore();+ }+ });++ it('refuses a launcher for an installed channel on a dev-channel run without --dev-mcp', async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ const result = await runInitForTest({ scope: undefined });++ expect(result.editors.map((e) => [e.serverName, e.configScope, e.action, e.error])).toEqual([+ [+ 'open-knowledge-dev',+ 'project',+ 'failed',+ 'A dev build writes no MCP launcher for an installed OpenKnowledge channel, because that launcher runs a released CLI. Register this checkout by running `node <checkout>/packages/cli/dist/cli.mjs init --dev-mcp` in the project, or set OK_CHANNEL=stable.',+ ],+ ]);+ expect(existsSync(join(testDir, '.mcp.json'))).toBe(false);+ expect(existsSync(claudeConfigPath())).toBe(false);});it('overwrites a differing open-knowledge entry by default', async () => {@@ -283,30 +346,27 @@ describe('runInit', () => {});});- it('updates only the managed launcher when switching a published entry to dev mode', async () => {+ it('leaves the installed Stable entry alone when registering dev MCP', async () => {+ const stableUserConfig = `${JSON.stringify(+ { mcpServers: { 'open-knowledge': PUBLISHED_CHAIN_ENTRY } },+ null,+ 2,+ )}\n`;+ writeFileSync(claudeConfigPath(), stableUserConfig);writeFileSync(- claudeConfigPath(),- JSON.stringify(- {- mcpServers: {- 'open-knowledge': {- command: 'npx',- args: ['-y', '@inkeep/open-knowledge@latest', 'mcp'],- },- },- },- null,- 2,- ),+ join(testDir, '.mcp.json'),+ JSON.stringify({ mcpServers: { 'open-knowledge': PUBLISHED_CHAIN_ENTRY } }, null, 2),);- enableDevMcp();- const result = await runInitForTest({ devMcp: true });- expect(result.mcpAction).toBe('overwritten');- expect(result.editors[0].action).toBe('overwritten');+ enableDevChannelMcp();+ await runInitForTest({ devMcp: true, scope: undefined });- const config = JSON.parse(readFileSync(claudeConfigPath(), 'utf-8'));- expect(config.mcpServers['open-knowledge']).toEqual(expectedDevMcpEntry());+ expect(readFileSync(claudeConfigPath(), 'utf-8')).toBe(stableUserConfig);+ const project = JSON.parse(readFileSync(join(testDir, '.mcp.json'), 'utf-8'));+ expect(project.mcpServers).toEqual({+ 'open-knowledge': PUBLISHED_CHAIN_ENTRY,+ 'open-knowledge-dev': expectedDevMcpEntry(),+ });});it('does not touch ~/.claude.json when --no-mcp is passed', async () => {@@ -447,19 +507,21 @@ describe('runInit', () => {expect(config.mcp_servers[result.editors[0].serverName]).toEqual(PUBLISHED_CHAIN_ENTRY);});- it('writes the dev MCP env block to Codex TOML configs', async () => {+ it('writes the dev MCP env block to the project Codex TOML config', async () => {mkdirSync(dirname(codexConfigPath()), { recursive: true });- enableDevMcp();+ enableDevChannelMcp();const result = await runInitForTest({editors: ['codex'],devMcp: true,+ scope: undefined,});expect(result.editors).toHaveLength(1);expect(result.editors[0].action).toBe('written');- const config = Bun.TOML.parse(readFileSync(codexConfigPath(), 'utf-8'));- expect(config.mcp_servers[result.editors[0].serverName]).toEqual(expectedDevMcpEntry());+ const config = Bun.TOML.parse(readFileSync(join(testDir, '.codex', 'config.toml'), 'utf-8'));+ expect(config.mcp_servers['open-knowledge-dev']).toEqual(expectedDevMcpEntry());+ expect(existsSync(codexConfigPath())).toBe(false);});it.skipIf(!NATIVE_TOML_AVAILABLE)('preserves existing Codex MCP entries', async () => {@@ -510,21 +572,26 @@ describe('runInit', () => {expect(config.mcp['open-knowledge']).toEqual(PUBLISHED_OPENCODE_ENTRY);});- it('writes the dev MCP entry with an environment block', async () => {+ it('writes the dev MCP entry with an environment block to project opencode.json', async () => {mkdirSync(dirname(opencodeConfigPath()), { recursive: true });- enableDevMcp();- const result = await runInitForTest({ editors: ['opencode'], devMcp: true });+ enableDevChannelMcp();+ const result = await runInitForTest({+ editors: ['opencode'],+ devMcp: true,+ scope: undefined,+ });expect(result.editors).toHaveLength(1);expect(result.editors[0].action).toBe('written');- const config = JSON.parse(readFileSync(opencodeConfigPath(), 'utf-8'));- expect(config.mcp[result.editors[0].serverName]).toEqual({+ const config = JSON.parse(readFileSync(join(testDir, 'opencode.json'), 'utf-8'));+ expect(config.mcp['open-knowledge-dev']).toEqual({type: 'local',enabled: true,command: ['node', join(devRepoRoot(), 'packages', 'cli', 'dist', 'cli.mjs'), 'mcp'],- environment: { MCP_DEBUG: '1', OK_LOG_FILE: '/tmp/ok-mcp.log' },+ environment: { MCP_DEBUG: '1', OK_LOG_FILE: '/tmp/ok-mcp.log', OK_CHANNEL: 'dev' },});+ expect(existsSync(opencodeConfigPath())).toBe(false);});it('preserves existing OpenCode mcp entries', async () => {diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 91874a9d3..76b322837 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -3,8 +3,12 @@ import { homedir } from 'node:os';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { inspect } from 'node:util';import {+ CHECKOUT_CLI_COMMAND,currentCliCommandName,currentMcpServerName,+ DESKTOP_PRODUCTS,+ defaultToDevChannel,+ isDevChannel,type McpLauncherDeclineReason,OPENKNOWLEDGE_SKILLS_REPO,okUserHomeDisplayPath,@@ -594,6 +598,17 @@ export class ContentDirError extends Error {}}+export class DevMcpScopeError extends Error {+ constructor(scope: McpScope) {+ super(+ `A dev MCP entry is written to project config only, never to user-level editor config, so --scope ${scope} is not supported with --dev-mcp or OK_CHANNEL=dev. Re-run with --scope project or without --scope.`,+ );+ this.name = 'DevMcpScopeError';+ }+}++const DEV_CHANNEL_USER_MCP_REFUSAL = `A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run \`${CHECKOUT_CLI_COMMAND} init --dev-mcp\` in the project, or set OK_CHANNEL=stable.`;+export { FilesystemRootProjectError, HomeProjectRootError };export function resolveInitSkillEnablement(skills: string | boolean | undefined): Set<BundleId> {@@ -1021,6 +1036,16 @@ export interface UserMcpConfigsOptions {export async function writeUserMcpConfigs(opts: UserMcpConfigsOptions): Promise<EditorMcpResult[]> {const targets = resolveEditorTargets(opts.editors).filter((t) => t.scope === 'global');+ if (isDevChannel()) {+ return targets.map((target) => ({+ editorId: target.id,+ label: target.label,+ action: 'failed',+ configPath: target.configPath('', opts.home),+ serverName: target.serverName(''),+ error: DEV_CHANNEL_USER_MCP_REFUSAL,+ }));+ }const installOptions: McpInstallOptions = {mode: 'published',skipAvailabilityCheck: true,@@ -1168,6 +1193,10 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitComconst installOptions: McpInstallOptions = {mode: options.devMcp ? 'dev' : 'published',};+ const projectOnlyMcp = options.devMcp === true || isDevChannel();+ if (projectOnlyMcp && options.mcp !== false && options.scope && options.scope !== 'project') {+ throw new DevMcpScopeError(options.scope);+ }const gitResult = await ensureProjectGit(projectRoot);@@ -1223,7 +1252,7 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom}const scope = await resolveMcpScope({- scope: options.scope,+ scope: projectOnlyMcp ? 'project' : options.scope,mcp: options.mcp,isTTY: options.isTTY,promptFn: options.promptFn,@@ -1653,6 +1682,17 @@ export function formatInitResult(result: InitCommandResult, cwd: string): stringconst verb = result.projectScopeUnsupportedLabels.length === 1 ? 'does' : 'do';lines.push(` ${names} ${verb} not support project-level config; skipped`);}+ const devServerName = DESKTOP_PRODUCTS.dev.mcpServerName;+ if (+ result.editors.some(+ (e) =>+ e.serverName === devServerName && (e.action === 'written' || e.action === 'overwritten'),+ )+ ) {+ lines.push(+ ` The ${devServerName} entry runs this checkout on this machine only; keep it out of commits.`,+ );+ }}if (result.projectSkills.length > 0) {@@ -1933,7 +1973,7 @@ export function initCommand(): Command {.option('--no-mcp', `Scaffold the ${OK_DIR}/ directory but do not touch MCP config`).option('--dev-mcp',- 'Register a local dev MCP entry using node + packages/cli/dist/cli.mjs with debug logging',+ 'Register a local dev MCP entry (node + packages/cli/dist/cli.mjs, debug logging) in project config only, as the dev channel unless OK_CHANNEL is set',).option('--content-dir <dir>',@@ -1975,6 +2015,7 @@ export function initCommand(): Command {skills?: string | boolean;}) => {const cwd = process.cwd();+ if (opts.devMcp) defaultToDevChannel(process.env);const sharing: 'shared' | 'local-only' | undefined = opts.shared? 'shared'@@ -1997,6 +2038,7 @@ export function initCommand(): Command {} catch (err) {if (err instanceof ContentDirError ||+ err instanceof DevMcpScopeError ||err instanceof HomeProjectRootError ||err instanceof FilesystemRootProjectError) {diff --git a/packages/cli/src/commands/repair-mcp-configs.test.ts b/packages/cli/src/commands/repair-mcp-configs.test.tsindex a3d4890d5..5fce05702 100644--- a/packages/cli/src/commands/repair-mcp-configs.test.ts+++ b/packages/cli/src/commands/repair-mcp-configs.test.ts@@ -179,6 +179,37 @@ describe('repairMcpConfigs', () => {expect(readFileSync(configPath, 'utf-8')).toBe(before);});+ it('reads a recognized project launcher on the dev channel without building a launcher for it', () => {+ const previous = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'dev';+ try {+ const path = join(projectDir, '.mcp.json');+ writeFileSync(+ path,+ JSON.stringify({+ mcpServers: {+ 'open-knowledge-dev': {+ command: '/bin/sh',+ args: ['-l', '-c', '# ok-mcp-dev-v99\nfuture launcher body'],+ },+ },+ }),+ );+ const before = readFileSync(path, 'utf-8');++ const result = repairMcpConfigs({ projectDir, home: fakeHome });+ const outcome = result.outcomes.find(+ (item) => item.scope === 'project' && item.editorId === 'claude',+ );++ expect(outcome?.outcome).toBe('canonical');+ expect(readFileSync(path, 'utf-8')).toBe(before);+ } finally {+ if (previous === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = previous;+ }+ });+it('declines a foreign project entry without writing it', () => {const configPath = writeProjectClaude({ command: '/usr/bin/foreign', args: ['server.js'] });const before = readFileSync(configPath, 'utf-8');diff --git a/packages/cli/src/commands/repair-mcp-configs.ts b/packages/cli/src/commands/repair-mcp-configs.tsindex 5b6d52e16..410dbc07a 100644--- a/packages/cli/src/commands/repair-mcp-configs.ts+++ b/packages/cli/src/commands/repair-mcp-configs.ts@@ -2,6 +2,7 @@ import { homedir } from 'node:os';import { classifyMcpLauncherEntry } from '@inkeep/open-knowledge-core';import {ALL_EDITOR_IDS,+ canonicalEntryFor,droppedManagedKeys,EDITOR_TARGETS,type EditorId,@@ -143,7 +144,7 @@ function repairOne(opts: RepairOneOptions): RepairOutcome {} else {const launcher = classifyMcpLauncherEntry(existing);if (launcher.kind === 'recognized' && launcher.disposition === 'keep') {- const dropped = droppedManagedKeys(existing, opts.target.buildEntry(opts.cwd, {}));+ const dropped = droppedManagedKeys(existing, canonicalEntryFor(opts.target, opts.cwd));if (dropped.length === 0) return { ...base, outcome: 'canonical' };const pruned = finishRepairWrite(opts,diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.tsindex 509dffe29..7653f956b 100644--- a/packages/cli/src/commands/stop.test.ts+++ b/packages/cli/src/commands/stop.test.ts@@ -253,6 +253,32 @@ describe('runStop channel guard', () => {expect(warnings.some((msg) => msg.includes('Unsupported OK_CHANNEL'))).toBe(true);});+ test("installed Stable refuses a dev build's server without --force", async () => {+ vi.stubEnv('OK_CHANNEL', '');+ const { outcome, killed, errors } = run('dev', { selfChannel: undefined });+ expect((await outcome).declined).toEqual({ otherChannel: 'dev' });+ expect(killed).toEqual([]);+ expect(errors[0]).toContain('OpenKnowledge Dev');+ expect(errors[0]).toContain(+ '`node <checkout>/packages/cli/dist/cli.mjs stop` with OK_CHANNEL=dev set',+ );+ expect(errors[0]).toContain('--force');+ });++ test("a dev-channel CLI stops the dev build's server", async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ const { outcome, killed } = run('dev', { selfChannel: undefined });+ expect((await outcome).declined).toBeUndefined();+ expect(killed).toEqual([[100, 'SIGTERM']]);+ });++ test("a dev-channel CLI refuses installed Stable's server", async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ const { outcome, killed } = run('stable', { selfChannel: undefined });+ expect((await outcome).declined).toEqual({ otherChannel: 'stable' });+ expect(killed).toEqual([]);+ });+test('refuses a foreign-host lock of another channel whose pid is alive here', async () => {const { outcome, killed } = run('stable', {inspect: () => lockOf('stable', foreign(100, 3001)),diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex c2f5554c2..63e2253a5 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -1,6 +1,8 @@import { resolve } from 'node:path';import {+ CHECKOUT_CLI_COMMAND,currentCliCommandName,+ DEV_CHANNEL,desktopChannelLabel,resolveDesktopProductName,} from '@inkeep/open-knowledge-core';@@ -95,7 +97,7 @@ interface RunStopDeps {error?: (msg: string) => void;probeClients?: (lockDir: string, logger?: PinoLoggerInstance) => Promise<number | null>;logger?: PinoLoggerInstance;- selfChannel?: 'stable' | 'beta';+ selfChannel?: 'stable' | 'beta' | 'dev';}interface StopOutcome {@@ -143,7 +145,9 @@ export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {if (self !== undefined && holder !== self) {error(`Not stopping: the server at ${deps.lockDir} belongs to ${desktopChannelLabel(holder)}. ` +- 'Stop it from that app or its CLI, or re-run with --force to terminate anyway.',+ (holder === DEV_CHANNEL+ ? `Stop it from that dev build, or run \`${CHECKOUT_CLI_COMMAND} stop\` with OK_CHANNEL=dev set, or re-run with --force to terminate anyway.`+ : 'Stop it from that app or its CLI, or re-run with --force to terminate anyway.'),);logger?.warn({@@ -278,7 +282,7 @@ export function stopCommand(getConfig: () => Config): Command {.argument('[target...]', 'port number, directory path (spaces OK), or "all"').option('--force',- 'Stop even when the server belongs to another OpenKnowledge app (Stable or Beta) or editor windows or agents are still connected to it',+ 'Stop even when the server belongs to another OpenKnowledge app (Stable, Beta or a dev build run from source) or editor windows or agents are still connected to it',).action(async (parts: string[], options: { force?: boolean }) => {const force = options.force === true;diff --git a/packages/cli/src/diagnose/os-termination-evidence.ts b/packages/cli/src/diagnose/os-termination-evidence.tsindex efde22e1a..a925a86fb 100644--- a/packages/cli/src/diagnose/os-termination-evidence.ts+++ b/packages/cli/src/diagnose/os-termination-evidence.ts@@ -2,7 +2,11 @@ import { type ExecFileException, execFile } from 'node:child_process';import { readdirSync, readFileSync, statSync } from 'node:fs';import { readdir, readFile, stat } from 'node:fs/promises';import { join, win32 } from 'node:path';-import { DESKTOP_PRODUCTS, desktopWindowsExecutableName } from '@inkeep/open-knowledge-core';+import {+ DESKTOP_PRODUCTS,+ desktopWindowsExecutableName,+ PACKAGED_DESKTOP_PRODUCT_NAMES,+} from '@inkeep/open-knowledge-core';import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';import {DIAGNOSTIC_REPORT_WINDOW_DAYS,@@ -22,7 +26,9 @@ const MACOS_SYSTEM_DIAGNOSTIC_REPORTS_DIR = '/Library/Logs/DiagnosticReports';const OWNED_NAME = /openknowledge/i;-const WINDOWS_EXECUTABLES = Object.values(DESKTOP_PRODUCTS).map(desktopWindowsExecutableName);+const WINDOWS_EXECUTABLES = PACKAGED_DESKTOP_PRODUCT_NAMES.map((name) =>+ desktopWindowsExecutableName(DESKTOP_PRODUCTS[name]),+);type OsTerminationSource = 'macos-jetsam' | 'linux-journal' | 'windows-event-log';diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex ce07d6294..f85985546 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -23,6 +23,7 @@ export { redactContent } from './commands/bug-report-redact.ts';export {ALL_EDITOR_IDS,buildManagedServerEntry,+ canonicalEntryFor,droppedManagedKeys,EDITOR_LABELS,EDITOR_TARGETS,diff --git a/packages/cli/src/integrations/pi-extension.ts b/packages/cli/src/integrations/pi-extension.tsindex d248d9021..6b0601547 100644--- a/packages/cli/src/integrations/pi-extension.ts+++ b/packages/cli/src/integrations/pi-extension.ts@@ -1,23 +1,23 @@import {currentCliCommandName,currentDesktopProduct,- DESKTOP_PRODUCTS,piToolNamespace,} from '@inkeep/open-knowledge-core';import {buildManagedServerEntry,type McpInstallOptions,PI_MANAGED_FILE_ENTRY_COMMAND,+ piExtensionDevHeader,piExtensionOwnershipMarker,piExtensionVersionSentinel,} from '../commands/editors.ts';export function isOwnPiExtensionSource(text: string): boolean {- const marker = piExtensionOwnershipMarker(currentDesktopProduct());- if (!text.startsWith(marker)) return false;- return Object.values(DESKTOP_PRODUCTS)- .map(piExtensionOwnershipMarker)- .every((other) => other.length <= marker.length || !text.startsWith(other));+ const product = currentDesktopProduct();+ const firstLine = text.split(/\r?\n/, 1)[0] ?? '';+ if (firstLine === piExtensionDevHeader(product)) return true;+ const marker = piExtensionOwnershipMarker(product);+ return firstLine.startsWith(marker) && /^-v\d+$/.test(firstLine.slice(marker.length));}export function isPiExtensionSourceUpToDate(text: string): boolean {@@ -39,9 +39,7 @@ export function makePiManagedFileEntry(text: string): Record<string, unknown> {export function buildPiExtensionSource(options: McpInstallOptions = {}): string {const dev = options.mode === 'dev';const product = currentDesktopProduct();- const header = dev- ? `${piExtensionOwnershipMarker(product)}-dev`- : piExtensionVersionSentinel(product);+ const header = dev ? piExtensionDevHeader(product) : piExtensionVersionSentinel(product);const toolPrefix = `${piToolNamespace(product)}_`;const launchers = {unix: buildManagedServerEntry({ ...options, platformName: 'darwin' }),diff --git a/packages/cli/src/integrations/registry-probes.test.ts b/packages/cli/src/integrations/registry-probes.test.tsindex 9c00eb8da..ac1a20de8 100644--- a/packages/cli/src/integrations/registry-probes.test.ts+++ b/packages/cli/src/integrations/registry-probes.test.ts@@ -300,6 +300,22 @@ describe('an MCP entry', () => {expect(answer?.state).toBe('satisfied');});+ it('reads a present launcher on the dev channel as satisfied, never as unprobed', async () => {+ const previous = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'dev';+ try {+ writeProjectMcpJson({+ command: '/bin/sh',+ args: ['-l', '-c', '# ok-mcp-v99\nfuture launcher body'],+ });+ const answer = await answerFor('claude/mcp/project/config-entry');+ expect(answer?.state).toBe('satisfied');+ } finally {+ if (previous === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = previous;+ }+ });+it('reads a config it cannot parse as unprobed, never as absent', async () => {writeFileSync(join(ctx.cwd, '.mcp.json'), '{ this is not json');expect(await answerFor('claude/mcp/project/config-entry')).toEqual({ state: 'unprobed' });diff --git a/packages/core/src/acp/tool-call-input.test.ts b/packages/core/src/acp/tool-call-input.test.tsindex a0feb95f5..fcdf3d0d0 100644--- a/packages/core/src/acp/tool-call-input.test.ts+++ b/packages/core/src/acp/tool-call-input.test.ts@@ -62,7 +62,7 @@ describe('identifyOpenKnowledgeToolCall', () => {expect(openKnowledgeToolName({ title: 'write', rawInput: { tool: 'write' } })).toBe('write');});- test('known-server matching needs the server we inject, its dev alias, or the Pi bridge prefix', () => {+ test('known-server matching needs a channel server we inject or its Pi bridge prefix', () => {for (const title of ['mcp__open-knowledge__write','mcp__open-knowledge-dev__write',@@ -70,6 +70,7 @@ describe('identifyOpenKnowledgeToolCall', () => {'mcp.open_knowledge.write','ok_write','ok-beta_write',+ 'ok-dev_write',]) {expect(identifyOpenKnowledgeToolCall({ title, rawInput: {} }, 'known')?.tool).toBe('write');}@@ -77,7 +78,6 @@ describe('identifyOpenKnowledgeToolCall', () => {'mcp__ok__write','mcp__ok-dev__write','mcp.ok.write',- 'ok-dev_write','mcp__open-knowledge-payments__write',]) {expect(identifyOpenKnowledgeToolCall({ title, rawInput: {} }, 'known')).toBeNull();diff --git a/packages/core/src/acp/tool-call-input.ts b/packages/core/src/acp/tool-call-input.tsindex 47b294131..bd7696e97 100644--- a/packages/core/src/acp/tool-call-input.ts+++ b/packages/core/src/acp/tool-call-input.ts@@ -56,12 +56,9 @@ const OPEN_KNOWLEDGE_TOOLS: ReadonlySet<string> = new Set(OPEN_KNOWLEDGE_MCP_TOOconst ANY_OPEN_KNOWLEDGE_SERVER = /^(?:open[-_ ]?knowledge|ok)(?:[-_][a-z]+)*$/;-const KNOWN_SERVER_SUFFIXES = [- '-dev',- ...Object.values(DESKTOP_PRODUCTS)- .map((product) => product.mcpServerName.slice(MCP_SERVER_NAME.length))- .filter((suffix) => suffix !== ''),-];+const KNOWN_SERVER_SUFFIXES = Object.values(DESKTOP_PRODUCTS)+ .map((product) => product.mcpServerName.slice(MCP_SERVER_NAME.length))+ .filter((suffix) => suffix !== '');const KNOWN_OPEN_KNOWLEDGE_SERVER = new RegExp(`^open[-_ ]?knowledge(?:${KNOWN_SERVER_SUFFIXES.join('|')})?$`,diff --git a/packages/core/src/constants/pi-docs.uncached.test.ts b/packages/core/src/constants/pi-docs.uncached.test.tsindex e28dc34a9..243892ce5 100644--- a/packages/core/src/constants/pi-docs.uncached.test.ts+++ b/packages/core/src/constants/pi-docs.uncached.test.ts@@ -3,7 +3,7 @@ import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';import { piToolNamespace } from './editors.ts';-import { DESKTOP_PRODUCTS } from './product.ts';+import { DESKTOP_PRODUCTS, PACKAGED_DESKTOP_PRODUCT_NAMES } from './product.ts';const PI_PAGE = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../../../../docs/content/integrations/pi.mdx'),@@ -18,7 +18,7 @@ function verifySection(): string {}describe('Pi integration page', () => {- test.each(Object.values(DESKTOP_PRODUCTS))(+ test.each(PACKAGED_DESKTOP_PRODUCT_NAMES.map((name) => DESKTOP_PRODUCTS[name]))('Verify names the $productName tool and prefix',(product) => {const namespace = piToolNamespace(product);diff --git a/packages/core/src/constants/product.test.ts b/packages/core/src/constants/product.test.tsindex 6b9ccb632..8565ae98b 100644--- a/packages/core/src/constants/product.test.ts+++ b/packages/core/src/constants/product.test.ts@@ -2,8 +2,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import {currentCliCommandName,DESKTOP_PRODUCTS,+ DEV_FALLBACK_CLI_REFUSAL,+ defaultToDevChannel,desktopChannelLabel,desktopProductForCliCommand,+ envWithoutDevChannel,+ isDevChannel,+ OkCliCommand,+ PACKAGED_DESKTOP_PRODUCT_NAMES,resolveDesktopProductName,userHomeDisplayPath,} from './product.ts';@@ -65,6 +71,7 @@ describe('resolveDesktopProductName', () => {).toEqual({stable: { deb: 'openknowledge', rpm: 'openknowledge' },beta: { deb: 'openknowledge-beta', rpm: 'openknowledge-beta' },+ dev: { deb: 'openknowledge-dev', rpm: 'openknowledge-dev' },});for (const product of Object.values(DESKTOP_PRODUCTS)) {expect(product.linuxPackageNames.deb).toBe(product.linuxExecutableName);@@ -104,14 +111,62 @@ describe('resolveDesktopProductName', () => {).toEqual({stable: 'openknowledge',beta: 'openknowledge-beta',+ dev: 'openknowledge-dev',});});++ it('gives the dev channel its own home, keychain, MCP key and lock channel', () => {+ const dev = resolveDesktopProductName({ OK_CHANNEL: 'dev' }, '/usr/local/bin/node');+ expect(dev).toBe('dev');+ expect(DESKTOP_PRODUCTS[dev]).toMatchObject({+ userHomeDirName: '.ok-dev',+ keyringService: 'open-knowledge-dev',+ mcpServerName: 'open-knowledge-dev',+ protocolScheme: 'openknowledge-dev',+ });+ });++ it('never resolves an executable to dev, which ships no app', () => {+ const dev = DESKTOP_PRODUCTS.dev;+ for (const execPath of [+ `/Applications/${dev.productName}.app/Contents/MacOS/${dev.productName}`,+ `/opt/${dev.productName}/${dev.linuxExecutableName}`,+ `C:\\Programs\\${dev.productName}\\${dev.productName}.exe`,+ ]) {+ expect(resolveDesktopProductName({}, execPath)).toBe('stable');+ }+ expect(PACKAGED_DESKTOP_PRODUCT_NAMES).toEqual(['stable', 'beta']);+ });+});++describe('defaultToDevChannel', () => {+ it('selects dev when no channel is set', () => {+ const env: Record<string, string | undefined> = {};+ defaultToDevChannel(env);+ expect(env.OK_CHANNEL).toBe('dev');+ expect(isDevChannel(env)).toBe(true);+ expect(resolveDesktopProductName(env, '/usr/local/bin/node')).toBe('dev');+ });++ it.each(['stable', 'beta', 'Beta'])('keeps an explicit OK_CHANNEL=%s', (channel) => {+ const env: Record<string, string | undefined> = { OK_CHANNEL: channel };+ defaultToDevChannel(env);+ expect(env.OK_CHANNEL).toBe(channel);+ expect(isDevChannel(env)).toBe(false);+ });++ it('treats a blank OK_CHANNEL as unset', () => {+ const env: Record<string, string | undefined> = { OK_CHANNEL: ' ' };+ defaultToDevChannel(env);+ expect(env.OK_CHANNEL).toBe('dev');+ });});describe('desktopChannelLabel', () => {it.each([['stable', 'OpenKnowledge (Stable)'],['beta', 'OpenKnowledge Beta'],+ ['dev', 'OpenKnowledge Dev'],['cloud', 'OpenKnowledge (cloud)'],])('%s is named %s', (channel, expected) => {expect(desktopChannelLabel(channel)).toBe(expected);@@ -133,6 +188,12 @@ describe('channel CLI command name', () => {expect(currentCliCommandName()).toBe('ok-beta');});+ it('names ok-dev on the dev channel, a bare command name like every other channel', () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ expect(currentCliCommandName()).toBe('ok-dev');+ expect(desktopProductForCliCommand('ok-dev')).toBe(DESKTOP_PRODUCTS.dev);+ });+it('maps a command name back to its product, and anything else to Stable', () => {expect(desktopProductForCliCommand('ok-beta')).toBe(DESKTOP_PRODUCTS.beta);expect(desktopProductForCliCommand('ok')).toBe(DESKTOP_PRODUCTS.stable);@@ -147,3 +208,133 @@ describe('channel CLI command name', () => {);});});++describe('envWithoutDevChannel', () => {+ it('drops the dev channel and keeps everything else', () => {+ expect(envWithoutDevChannel({ PATH: '/usr/bin', OK_CHANNEL: 'dev', EMPTY: undefined })).toEqual(+ {+ PATH: '/usr/bin',+ },+ );+ });++ it('drops the dev channel under any key casing, as a Windows environment can carry it', () => {+ expect(envWithoutDevChannel({ Path: 'C:\\Windows', ok_channel: ' Dev ' })).toEqual({+ Path: 'C:\\Windows',+ });+ });++ it('keeps a shipped channel, which every released CLI knows', () => {+ expect(envWithoutDevChannel({ OK_CHANNEL: 'beta' })).toEqual({ OK_CHANNEL: 'beta' });+ });+});++describe('OkCliCommand', () => {+ const checkoutCli = ['node', '/src/cli.mjs'];++ it('pins dev only on a CLI the host supplies', () => {+ const cli = OkCliCommand.resolve({+ host: { cliArgs: checkoutCli },+ env: { OK_CHANNEL: 'dev' },+ });+ expect(cli.runnerInvocation(['auth', 'login'])).toEqual({+ cliArgs: [...checkoutCli, 'auth', 'login'],+ cliEnv: { OK_CHANNEL: 'dev' },+ });+ expect(cli.refusalFor(['auth', 'login'])).toBeUndefined();+ });++ it('never hands dev to the CLI on PATH, which a released build may be', () => {+ const cli = OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } });+ expect(cli.runnerInvocation(['auth', 'status'])).toEqual({+ cliArgs: ['open-knowledge', 'auth', 'status'],+ cliEnv: {},+ });+ expect(cli.spawn(['status'], { PATH: '/usr/bin', OK_CHANNEL: 'dev' })).toEqual({+ command: 'open-knowledge',+ args: ['status'],+ env: { PATH: '/usr/bin' },+ });+ });++ it.each([+ [['auth', 'login', '--json']],+ [['auth', 'pat', '--token-stdin']],+ [['auth', 'token']],+ [['auth', 'signout', '--host', 'github.com']],+ [['clone', '--json', 'https://github.com/o/r.git', '/tmp/r']],+ [['start', '--port', '0']],+ ])('refuses %j on every path when a dev build falls back to the CLI on PATH', (args) => {+ const cli = OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } });+ expect(cli.refusalFor(args)).toBe(DEV_FALLBACK_CLI_REFUSAL);+ expect(cli.runnerInvocation(args)).toEqual({ refused: DEV_FALLBACK_CLI_REFUSAL });+ expect(cli.spawn(args, {})).toEqual({ refused: DEV_FALLBACK_CLI_REFUSAL });+ expect(() => cli.stdioServer(args)).toThrow(DEV_FALLBACK_CLI_REFUSAL);+ expect(() => cli.shellCommand(args, (part) => part)).toThrow(DEV_FALLBACK_CLI_REFUSAL);+ });++ it('tells the developer to build and restart, since the CLI is resolved once per launch', () => {+ expect(DEV_FALLBACK_CLI_REFUSAL).toContain('pnpm build');+ expect(DEV_FALLBACK_CLI_REFUSAL).toContain('restart this dev build');+ expect(DEV_FALLBACK_CLI_REFUSAL).not.toMatch(/retry/i);+ });++ it('lets a fallback dev build read through the CLI on PATH', () => {+ const cli = OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } });+ expect(cli.refusalFor(['auth', 'status'])).toBeUndefined();+ expect(cli.refusalFor(['auth', 'git-credential'])).toBeUndefined();+ expect(cli.refusalFor(['share', 'owners', '--json'])).toBeUndefined();+ });++ it('pins a shipped non-Stable channel on any CLI', () => {+ expect(+ OkCliCommand.resolve({ host: { cliArgs: [] }, env: { OK_CHANNEL: 'beta' } }).runnerInvocation(+ [],+ ),+ ).toEqual({+ cliArgs: ['open-knowledge'],+ cliEnv: { OK_CHANNEL: 'beta' },+ });+ });++ it('pins nothing on Stable and refuses nothing', () => {+ const cli = OkCliCommand.resolve({ host: { cliArgs: ['ok'] }, env: { OK_CHANNEL: 'stable' } });+ expect(cli.runnerInvocation(['start'])).toEqual({ cliArgs: ['ok', 'start'], cliEnv: {} });+ expect(cli.refusalFor(['auth', 'login'])).toBeUndefined();+ });++ it('carries the channel with the argv into every form a caller can take', () => {+ const cli = OkCliCommand.resolve({+ host: { cliArgs: checkoutCli },+ env: { OK_CHANNEL: 'dev' },+ });+ expect(cli.spawn(['mcp'], { OK_CHANNEL: 'dev', HOME: '/h' })).toEqual({+ command: 'node',+ args: ['/src/cli.mjs', 'mcp'],+ env: { HOME: '/h', OK_CHANNEL: 'dev' },+ });+ expect(cli.stdioServer(['mcp'])).toEqual({+ command: 'node',+ args: ['/src/cli.mjs', 'mcp'],+ env: { OK_CHANNEL: 'dev' },+ });+ expect(cli.shellCommand(['auth', 'git-credential'], (part) => part)).toBe(+ 'OK_CHANNEL=dev node /src/cli.mjs auth git-credential',+ );+ });++ it('applies a host overlay, where undefined removes an inherited key', () => {+ const cli = OkCliCommand.resolve({+ host: {+ cliArgs: ['/app/OpenKnowledge.exe', 'cli.mjs'],+ cliEnv: { ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: undefined },+ },+ env: { OK_CHANNEL: 'stable' },+ });+ const spawn = cli.spawn([], { NODE_OPTIONS: '--inspect', PATH: 'C:\\Windows' });+ expect('env' in spawn && spawn.env).toEqual({+ PATH: 'C:\\Windows',+ ELECTRON_RUN_AS_NODE: '1',+ });+ });+});diff --git a/packages/core/src/constants/product.ts b/packages/core/src/constants/product.tsindex 3974a2b6a..e96dcc093 100644--- a/packages/core/src/constants/product.ts+++ b/packages/core/src/constants/product.ts@@ -41,11 +41,41 @@ export const DESKTOP_PRODUCTS = {userHomeDirName: '.ok-beta',keyringService: 'open-knowledge-beta',},+ dev: {+ appId: 'com.inkeep.open-knowledge.dev',+ productName: 'OpenKnowledge Dev',+ packageName: 'openknowledge-dev-desktop',+ linuxExecutableName: 'openknowledge-dev',+ protocolScheme: 'openknowledge-dev',+ linuxPackageNames: {+ deb: 'openknowledge-dev',+ rpm: 'openknowledge-dev',+ },+ retiredLinuxPackageNames: {+ deb: [],+ rpm: [],+ },+ cliCommandNames: ['ok-dev', 'open-knowledge-dev'],+ mcpServerName: 'open-knowledge-dev',+ mcpChainTag: '-dev',+ npmDistTag: 'latest',+ userHomeDirName: '.ok-dev',+ keyringService: 'open-knowledge-dev',+ },} as const;export type DesktopProductName = keyof typeof DESKTOP_PRODUCTS;export type DesktopProduct = (typeof DESKTOP_PRODUCTS)[DesktopProductName];+export const PACKAGED_DESKTOP_PRODUCT_NAMES = [+ 'stable',+ 'beta',+] as const satisfies readonly DesktopProductName[];++export type PackagedDesktopProductName = (typeof PACKAGED_DESKTOP_PRODUCT_NAMES)[number];++export const DEV_CHANNEL = 'dev' satisfies DesktopProductName;+export function desktopWindowsExecutableName(product: DesktopProduct): string {return `${product.productName}.exe`;}@@ -62,6 +92,20 @@ function isDesktopProductName(value: string): value is DesktopProductName {return Object.hasOwn(DESKTOP_PRODUCTS, value);}+function channelOverride(env: Record<string, string | undefined>): string | undefined {+ return env[OK_CHANNEL_ENV]?.trim().toLowerCase() || undefined;+}++export function isDevChannel(+ env: Record<string, string | undefined> = globalThis.process?.env ?? {},+): boolean {+ return channelOverride(env) === DEV_CHANNEL;+}++export function defaultToDevChannel(env: Record<string, string | undefined>): void {+ if (channelOverride(env) === undefined) env[OK_CHANNEL_ENV] = DEV_CHANNEL;+}+export function desktopChannelLabel(channel: string): string {if (channel === 'stable') return `${PRODUCT_NAME} (Stable)`;return isDesktopProductName(channel)@@ -77,7 +121,7 @@ export function resolveDesktopProductName(env: Record<string, string | undefined> = globalThis.process?.env ?? {},execPath: string = globalThis.process?.execPath ?? '',): DesktopProductName {- const override = env[OK_CHANNEL_ENV]?.trim().toLowerCase();+ const override = channelOverride(env);if (override) {if (isDesktopProductName(override)) return override;throw new Error(@@ -85,7 +129,7 @@ export function resolveDesktopProductName();}const exe = executableBaseName(execPath);- for (const name of Object.keys(DESKTOP_PRODUCTS) as DesktopProductName[]) {+ for (const name of PACKAGED_DESKTOP_PRODUCT_NAMES) {if (name === 'stable') continue;const product = DESKTOP_PRODUCTS[name];if (@@ -118,6 +162,153 @@ export function desktopProductForCliCommand(command: string | null | undefined):return DESKTOP_PRODUCTS.stable;}+export const CHECKOUT_CLI_COMMAND = 'node <checkout>/packages/cli/dist/cli.mjs';++export const DEV_FALLBACK_CLI_REFUSAL = `This dev build has no built CLI, so it will not sign in, sign out, store a token, clone a project or start a project server through the installed OpenKnowledge (Stable) CLI. Run pnpm build in the checkout, then restart this dev build.`;++function isChannelKey(key: string): boolean {+ return key.toUpperCase() === OK_CHANNEL_ENV;+}++function carriesDevChannel(env: Readonly<Record<string, string | undefined>>): boolean {+ return Object.entries(env).some(+ ([key, value]) => isChannelKey(key) && value?.trim().toLowerCase() === DEV_CHANNEL,+ );+}++export function envWithoutDevChannel(+ env: Readonly<Record<string, string | undefined>>,+): Record<string, string> {+ const dropChannel = carriesDevChannel(env);+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(env)) {+ if (value === undefined || (dropChannel && isChannelKey(key))) continue;+ out[key] = value;+ }+ return out;+}++type EnvOverlay = Readonly<Record<string, string | undefined>>;++const STABLE_FALLBACK_REFUSED_COMMANDS: readonly (readonly string[])[] = [+ ['auth', 'login'],+ ['auth', 'pat'],+ ['auth', 'token'],+ ['auth', 'signout'],+ ['clone'],+ ['start'],+];++export interface HostCliInvocation {+ readonly cliArgs: readonly string[];+ readonly cliEnv?: EnvOverlay | undefined;+}++export interface OkCliSpawn {+ readonly command: string;+ readonly args: string[];+ readonly env: Record<string, string>;+}++export interface OkCliRunnerInvocation {+ readonly cliArgs: readonly string[];+ readonly cliEnv: EnvOverlay;+}++export interface OkCliRefusal {+ readonly refused: string;+}++export interface ResolveOkCliCommandInput {+ readonly host?: HostCliInvocation | undefined;+ readonly env?: Readonly<Record<string, string | undefined>>;+}++export class OkCliCommand {+ readonly #argv: readonly [string, ...string[]];+ readonly #overlay: EnvOverlay;+ readonly #fallsBackToStable: boolean;++ private constructor(+ argv: readonly [string, ...string[]],+ overlay: EnvOverlay,+ fallsBackToStable: boolean,+ ) {+ this.#argv = argv;+ this.#overlay = overlay;+ this.#fallsBackToStable = fallsBackToStable;+ }++ static resolve(input: ResolveOkCliCommandInput = {}): OkCliCommand {+ const env = input.env ?? globalThis.process?.env ?? {};+ const [first, ...rest] = input.host?.cliArgs ?? [];+ const channel = resolveDesktopProductName(env);+ const released = (PACKAGED_DESKTOP_PRODUCT_NAMES as readonly DesktopProductName[]).includes(+ channel,+ );+ const hostCli = first !== undefined;+ const pinned = channel !== 'stable' && (hostCli || released);+ return new OkCliCommand(+ hostCli ? [first, ...rest] : ['open-knowledge'],+ { ...input.host?.cliEnv, ...(pinned ? { [OK_CHANNEL_ENV]: channel } : {}) },+ channel === DEV_CHANNEL && !hostCli,+ );+ }++ refusalFor(trailingArgs: readonly string[]): string | undefined {+ if (!this.#fallsBackToStable) return undefined;+ const refused = STABLE_FALLBACK_REFUSED_COMMANDS.some((prefix) =>+ prefix.every((part, index) => trailingArgs[index] === part),+ );+ return refused ? DEV_FALLBACK_CLI_REFUSAL : undefined;+ }++ runnerInvocation(trailingArgs: readonly string[]): OkCliRunnerInvocation | OkCliRefusal {+ const refused = this.refusalFor(trailingArgs);+ if (refused !== undefined) return { refused };+ return { cliArgs: [...this.#argv, ...trailingArgs], cliEnv: { ...this.#overlay } };+ }++ spawn(trailingArgs: readonly string[], baseEnv: EnvOverlay): OkCliSpawn | OkCliRefusal {+ const refused = this.refusalFor(trailingArgs);+ if (refused !== undefined) return { refused };+ const [command, ...args] = this.#argv;+ const env = envWithoutDevChannel(baseEnv);+ for (const [key, value] of Object.entries(this.#overlay)) {+ if (value === undefined) delete env[key];+ else env[key] = value;+ }+ return { command, args: [...args, ...trailingArgs], env };+ }++ stdioServer(trailingArgs: readonly string[]): OkCliSpawn {+ this.#assertNotRefused(trailingArgs);+ const [command, ...args] = this.#argv;+ return { command, args: [...args, ...trailingArgs], env: definedEntries(this.#overlay) };+ }++ shellCommand(trailingArgs: readonly string[], quote: (part: string) => string): string {+ this.#assertNotRefused(trailingArgs);+ const assignments = Object.entries(definedEntries(this.#overlay)).map(+ ([key, value]) => `${key}=${quote(value)}`,+ );+ return [...assignments, ...[...this.#argv, ...trailingArgs].map(quote)].join(' ');+ }++ #assertNotRefused(trailingArgs: readonly string[]): void {+ const refused = this.refusalFor(trailingArgs);+ if (refused !== undefined) throw new Error(refused);+ }+}++function definedEntries(overlay: EnvOverlay): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(overlay)) {+ if (value !== undefined) out[key] = value;+ }+ return out;+}+export function userHomeDisplayPath(product: DesktopProduct, ...segments: string[]): string {return ['~', product.userHomeDirName, ...segments].join('/');}diff --git a/packages/core/src/helper-bundle.test.ts b/packages/core/src/helper-bundle.test.tsindex 9a7133b94..88936b1be 100644--- a/packages/core/src/helper-bundle.test.ts+++ b/packages/core/src/helper-bundle.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { DESKTOP_PRODUCTS } from './constants/product.ts';+import { DESKTOP_PRODUCTS, PACKAGED_DESKTOP_PRODUCT_NAMES } from './constants/product.ts';import {HELPER_BUNDLE_NAME,HELPER_EXECUTABLE_NAME,@@ -30,7 +30,7 @@ describe('resolveHelperBundleBinary', () => {);});- test.each(Object.values(DESKTOP_PRODUCTS))(+ test.each(PACKAGED_DESKTOP_PRODUCT_NAMES.map((name) => DESKTOP_PRODUCTS[name]))('matches the layout afterPack writes for $productName',({ productName }) => {const app = `/Applications/${productName}.app`;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 6befc30bf..b72c2977f 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -558,17 +558,31 @@ export {type PreviewThemeToken,} from './constants/preview-theme-tokens.ts';export {+ CHECKOUT_CLI_COMMAND,currentCliCommandName,currentDesktopProduct,currentMcpServerName,DESKTOP_PRODUCTS,+ DEV_CHANNEL,+ DEV_FALLBACK_CLI_REFUSAL,type DesktopProduct,type DesktopProductName,+ defaultToDevChannel,desktopChannelLabel,desktopWindowsExecutableName,desktopWindowsInstallDirNames,+ envWithoutDevChannel,+ type HostCliInvocation,+ isDevChannel,OK_CHANNEL_ENV,+ OkCliCommand,+ type OkCliRefusal,+ type OkCliRunnerInvocation,+ type OkCliSpawn,+ PACKAGED_DESKTOP_PRODUCT_NAMES,+ type PackagedDesktopProductName,PRODUCT_NAME,+ type ResolveOkCliCommandInput,resolveDesktopProductName,} from './constants/product.ts';export { isReservedLogDoc } from './constants/reserved-docs.ts';diff --git a/packages/desktop/src/main/dev-channel.test.ts b/packages/desktop/src/main/dev-channel.test.tsnew file mode 100644index 000000000..287317a5f--- /dev/null+++ b/packages/desktop/src/main/dev-channel.test.ts@@ -0,0 +1,48 @@+import { describe, expect, test } from 'vitest';+import { applyUnpackagedDevChannel, desktopProtocolScheme } from './dev-channel.ts';++describe('applyUnpackagedDevChannel', () => {+ test('an unpackaged build runs as the dev channel', () => {+ const env: Record<string, string | undefined> = {};+ applyUnpackagedDevChannel(env, false);+ expect(env.OK_CHANNEL).toBe('dev');+ });++ test.each(['stable', 'beta'])('an explicit OK_CHANNEL=%s still wins', (channel) => {+ const env: Record<string, string | undefined> = { OK_CHANNEL: channel };+ applyUnpackagedDevChannel(env, false);+ expect(env.OK_CHANNEL).toBe(channel);+ });++ test('a packaged app keeps resolving by its executable', () => {+ const env: Record<string, string | undefined> = {};+ applyUnpackagedDevChannel(env, true);+ expect(env.OK_CHANNEL).toBeUndefined();+ });++ test('the desktop smoke harness keeps the shipped identity', () => {+ const env: Record<string, string | undefined> = { OK_DESKTOP_E2E_SMOKE: '1' };+ applyUnpackagedDevChannel(env, false);+ expect(env.OK_CHANNEL).toBeUndefined();+ });+});++describe('desktopProtocolScheme', () => {+ test('a dev build claims openknowledge-dev, never Stable', () => {+ expect(desktopProtocolScheme(false, 'openknowledge', { OK_CHANNEL: 'dev' })).toBe(+ 'openknowledge-dev',+ );+ });++ test('an unpackaged build pinned to a channel uses that channel', () => {+ expect(desktopProtocolScheme(false, 'openknowledge', { OK_CHANNEL: 'beta' })).toBe(+ 'openknowledge-beta',+ );+ });++ test('a packaged build keeps its variant scheme whatever the env says', () => {+ expect(desktopProtocolScheme(true, 'openknowledge-beta', { OK_CHANNEL: 'dev' })).toBe(+ 'openknowledge-beta',+ );+ });+});diff --git a/packages/desktop/src/main/dev-channel.ts b/packages/desktop/src/main/dev-channel.tsnew file mode 100644index 000000000..0446b7a32--- /dev/null+++ b/packages/desktop/src/main/dev-channel.ts@@ -0,0 +1,23 @@+import {+ DESKTOP_PRODUCTS,+ defaultToDevChannel,+ resolveDesktopProductName,+} from '@inkeep/open-knowledge-core/constants/product';++export function applyUnpackagedDevChannel(+ env: Record<string, string | undefined>,+ isPackaged: boolean,+): void {+ if (isPackaged || env.OK_DESKTOP_E2E_SMOKE === '1') return;+ defaultToDevChannel(env);+}++export function desktopProtocolScheme(+ isPackaged: boolean,+ variantScheme: string,+ env: Record<string, string | undefined> = process.env,+): string {+ return isPackaged+ ? variantScheme+ : DESKTOP_PRODUCTS[resolveDesktopProductName(env)].protocolScheme;+}diff --git a/packages/desktop/src/main/entry.ts b/packages/desktop/src/main/entry.tsindex 54724bb07..bc1070736 100644--- a/packages/desktop/src/main/entry.ts+++ b/packages/desktop/src/main/entry.ts@@ -5,6 +5,7 @@ import {UNINSTALL_PROGRESS_ARG,UNINSTALL_RESULT_ARG,} from './desktop-uninstall-result.ts';+import { applyUnpackagedDevChannel } from './dev-channel.ts';import { isExecutableFileSync } from './executable-file.ts';import { clearAmbientCapsBeforeBoot } from './linux-ambient-caps.ts';@@ -37,5 +38,6 @@ if (process.argv.includes(UNINSTALL_RESULT_ARG) || process.argv.includes(UNINSTAvoid runDesktopUninstallResultWindow(options);}} else {+ applyUnpackagedDevChannel(process.env, app.isPackaged);await import('./index.ts');}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex c0e8feca7..e66eff458 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -54,6 +54,7 @@ import {estimateSkillCost,hasUninstallFeedbackContent,type LanguagePreference,+ type OkCliCommand,OPENKNOWLEDGE_SKILLS_REPO,PROTOCOL_VERSION,projectWorktreeCreateResult,@@ -86,7 +87,6 @@ import {getMeter,initContent,isProcessAlive,- type LocalOpCliInvocation,normalizeFsPath,ONBOARDING_BUNDLE_IDS,prepareSingleFileOpen,@@ -282,6 +282,7 @@ import {showDesktopUninstallResult,} from './desktop-uninstall-handoff.ts';import { desktopUninstallResultCommand } from './desktop-uninstall-result.ts';+import { desktopProtocolScheme } from './dev-channel.ts';import { promptForExistingFolder, promptForExistingMarkdownFile } from './dialog-helpers.ts';import {type DriverUtilityLike,@@ -355,7 +356,11 @@ import {runManualInstallFallbackDialog,} from './linux-install-fallback.ts';import { applyDevShmPosture } from './linux-shm-posture.ts';-import { resolveLocalOpCliInvocation } from './local-op-cli-invocation.ts';+import {+ type HostCliInvocation,+ mainProcessOkCli,+ resolveLocalOpCliInvocation,+} from './local-op-cli-invocation.ts';import { createMenuTranslator, resolveMenuCatalogDir } from './main-i18n.ts';import { createMainThreadWatchdog } from './main-thread-watchdog.ts';import { withMcpServerNameArg } from './mcp-server-name-arg.ts';@@ -1253,14 +1258,31 @@ function isDebugKeyringSmokeAllowed(): boolean {return !app.isPackaged || process.env.OK_DEBUG_KEYRING_SMOKE === '1';}-function resolveLocalOpCli(): LocalOpCliInvocation {- return resolveLocalOpCliInvocation({+let warnedUnbuiltWorkspaceCli = false;++function resolveLocalOpCli(): HostCliInvocation | undefined {+ const workspaceCliEntry = join(app.getAppPath(), '..', 'cli', 'dist', 'cli.mjs');+ const invocation = resolveLocalOpCliInvocation({platform: process.platform,isPackaged: app.isPackaged,execPath: app.getPath('exe'),resourcesPath: process.resourcesPath,parentEnv: process.env,+ workspaceCliEntry,+ workspaceCliBuilt: !app.isPackaged && existsSync(workspaceCliEntry),});+ if (invocation === undefined && !warnedUnbuiltWorkspaceCli) {+ warnedUnbuiltWorkspaceCli = true;+ getLogger('lifecycle').warn(+ { workspaceCliEntry },+ 'The workspace CLI is not built, so this dev build runs the open-knowledge on PATH as Stable and refuses sign-in, sign-out, token storage and clone. Run pnpm build in the checkout, then restart this dev build.',+ );+ }+ return invocation;+}++function resolveMainProcessLocalOpCli(): OkCliCommand {+ return mainProcessOkCli(resolveLocalOpCli(), process.env);}function runDriverBootSmokeInProduction(): void {@@ -5553,7 +5575,7 @@ function registerIpcHandlers() {});const localOpDeps: LocalOpDeps = {- resolveCliInvocation: resolveLocalOpCli,+ resolveOkCli: resolveMainProcessLocalOpCli,logFailure: logIpcError,state: createLocalOpState(),};@@ -6358,7 +6380,7 @@ function bootPrimaryInstance(): void {});const protocolControl = registerProtocolHandler({- protocolScheme: DESKTOP_VARIANT.protocolScheme,+ protocolScheme: desktopProtocolScheme(app.isPackaged, DESKTOP_VARIANT.protocolScheme),app: {on: (event, cb) => {app.on(event as Parameters<typeof app.on>[0], cb as Parameters<typeof app.on>[1]);@@ -6411,7 +6433,7 @@ function bootPrimaryInstance(): void {let authenticated = false;try {const status = await runAuthStatusSubprocess({- ...resolveLocalOpCli(),+ cli: resolveMainProcessLocalOpCli(),host,});authenticated = status.authenticated;diff --git a/packages/desktop/src/main/integrations-settings.test.ts b/packages/desktop/src/main/integrations-settings.test.tsindex 6d1b13f67..97bad673a 100644--- a/packages/desktop/src/main/integrations-settings.test.ts+++ b/packages/desktop/src/main/integrations-settings.test.ts@@ -1,6 +1,7 @@import { EMPTY_DETECTION_SNAPSHOT, EMPTY_PROBE_SNAPSHOT } from '@inkeep/open-knowledge-core';import type { IpcMainInvokeEvent } from 'electron';import { describe, expect, test, vi } from 'vitest';+import { writeUserMcpConfigs } from '../../../cli/src/commands/init.ts';import type {AgentIntegrationsApplyRequest,AgentIntegrationsApplyResult,@@ -423,6 +424,27 @@ describe('ok:integrations:dispatch — set editor', () => {}});+ test('a dev build says why it adds nothing to user-level editor config', async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ try {+ const cli = {+ ...makeCli(),+ writeUserMcpConfigs: (opts: { editors: McpWiringEditorId[]; home?: string }) =>+ writeUserMcpConfigs(opts),+ };+ const { set } = setup({ cli });+ const result = await set({ component: { kind: 'editor', id: 'claude' }, enabled: true });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toBe(+ "Couldn't add OpenKnowledge to Claude (A dev build registers OpenKnowledge MCP in project config only, never in user-level editor config. Run `node <checkout>/packages/cli/dist/cli.mjs init --dev-mcp` in the project, or set OK_CHANNEL=stable.).",+ );+ }+ } finally {+ vi.unstubAllEnvs();+ }+ });+test('a failed write surfaces its error', async () => {const { set } = setup({ cli: makeCli({ writeAction: 'failed', writeError: 'EROFS' }) });const result = await set({ component: { kind: 'editor', id: 'claude' }, enabled: true });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 da82b5d5b..74fa196fb 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@@ -1,3 +1,4 @@+import { OkCliCommand } from '@inkeep/open-knowledge-core';import type { AuthEvent, CloneEvent } from '@inkeep/open-knowledge-server';import { beforeEach, describe, expect, test, vi } from 'vitest';@@ -70,7 +71,7 @@ function makeSender() {function makeDeps() {return {- resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ resolveOkCli: () => OkCliCommand.resolve({ host: { cliArgs: ['open-knowledge'] }, env: {} }),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 6fe3ec3e4..476258c91 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@@ -1,3 +1,4 @@+import { OkCliCommand } from '@inkeep/open-knowledge-core';import type { CloneEvent } from '@inkeep/open-knowledge-server';import { describe, expect, test, vi } from 'vitest';@@ -49,7 +50,7 @@ function makeSender(captured: CapturedSend[]) {function makeDeps() {return {- resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ resolveOkCli: () => OkCliCommand.resolve({ host: { cliArgs: ['open-knowledge'] }, env: {} }),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.tsindex d7ad19e8b..fe0394ead 100644--- a/packages/desktop/src/main/ipc/local-op-failure-logging.test.ts+++ b/packages/desktop/src/main/ipc/local-op-failure-logging.test.ts@@ -1,3 +1,4 @@+import { OkCliCommand } from '@inkeep/open-knowledge-core';import type {AuthEvent,AuthReposResponse,@@ -58,7 +59,7 @@ function makeSender() {function makeDeps() {return {- resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ resolveOkCli: () => OkCliCommand.resolve({ host: { cliArgs: ['open-knowledge'] }, env: {} }),logFailure: vi.fn(),state: createLocalOpState(),};diff --git a/packages/desktop/src/main/ipc/local-op.test.ts b/packages/desktop/src/main/ipc/local-op.test.tsindex 114f9b21e..98322b4d7 100644--- a/packages/desktop/src/main/ipc/local-op.test.ts+++ b/packages/desktop/src/main/ipc/local-op.test.ts@@ -1,3 +1,4 @@+import { DEV_FALLBACK_CLI_REFUSAL, OkCliCommand } from '@inkeep/open-knowledge-core';import type { AuthReposResponse, AuthStatusResponse } from '@inkeep/open-knowledge-server';import { describe, expect, test, vi } from 'vitest';@@ -5,6 +6,9 @@ const statusCalls: Array<{ host: string | undefined; resolve: (r: AuthStatusResp[];const reposCalls: Array<{ host: string | undefined; resolve: (r: AuthReposResponse) => void }> = [];+const cloneSpawn = vi.fn(() => ({ done: Promise.resolve(), cancel: () => {} }));+const deviceFlowSpawn = vi.fn(() => ({ done: Promise.resolve(), cancel: () => {} }));+vi.doMock('@inkeep/open-knowledge-server', () => ({runAuthStatusSubprocess: ({ host }: { host?: string }) =>new Promise<AuthStatusResponse>((resolve) => {@@ -14,16 +18,17 @@ vi.doMock('@inkeep/open-knowledge-server', () => ({new Promise<AuthReposResponse>((resolve) => {reposCalls.push({ host, resolve });}),- runCloneSubprocess: () => ({ done: Promise.resolve(), cancel: () => {} }),- runDeviceFlowSubprocess: () => ({ done: Promise.resolve(), cancel: () => {} }),+ runCloneSubprocess: cloneSpawn,+ runDeviceFlowSubprocess: deviceFlowSpawn,validateCloneInputs: () => ({ ok: true }),}));-const { createLocalOpState, handleAuthRepos, handleAuthStatus } = await import('./local-op.ts');+const { createLocalOpState, handleAuthRepos, handleAuthStart, handleAuthStatus, handleCloneStart } =+ await import('./local-op.ts');function makeDeps() {return {- resolveCliInvocation: () => ({ cliArgs: ['open-knowledge'] }),+ resolveOkCli: () => OkCliCommand.resolve({ host: { cliArgs: ['open-knowledge'] }, env: {} }),logFailure: vi.fn(),state: createLocalOpState(),};@@ -145,3 +150,48 @@ describe('handleAuthRepos — coalescing + concurrency cap', () => {expect(deps.state.authReposInFlight.size).toBe(0);});});++describe('handleAuthStart on a dev build without its workspace CLI', () => {+ test('answers the sign-in request with the refusal, which the renderer shows as the error', () => {+ deviceFlowSpawn.mockClear();+ const deps = {+ ...makeDeps(),+ resolveOkCli: () => OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } }),+ };+ const sender = { send: vi.fn(), isDestroyed: () => false };+ expect(handleAuthStart(deps, sender)).toEqual({ ok: false, error: DEV_FALLBACK_CLI_REFUSAL });+ expect(deviceFlowSpawn).not.toHaveBeenCalled();+ expect(deps.state.authInFlight).toBeNull();+ });++ test('starts the flow when the dev build has its workspace CLI', () => {+ deviceFlowSpawn.mockClear();+ const deps = {+ ...makeDeps(),+ resolveOkCli: () =>+ OkCliCommand.resolve({+ host: { cliArgs: ['node', '/src/cli.mjs'] },+ env: { OK_CHANNEL: 'dev' },+ }),+ };+ const sender = { send: vi.fn(), isDestroyed: () => false };+ expect(handleAuthStart(deps, sender)).toMatchObject({ ok: true });+ expect(deviceFlowSpawn).toHaveBeenCalledTimes(1);+ });+});++describe('handleCloneStart on a dev build without its workspace CLI', () => {+ test('answers the clone request with the refusal and clones nothing', () => {+ cloneSpawn.mockClear();+ const deps = {+ ...makeDeps(),+ resolveOkCli: () => OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } }),+ };+ const sender = { send: vi.fn(), isDestroyed: () => false };+ expect(+ handleCloneStart(deps, sender, { url: 'https://github.com/o/r.git', dir: '/tmp/r' }),+ ).toEqual({ ok: false, error: DEV_FALLBACK_CLI_REFUSAL });+ expect(cloneSpawn).not.toHaveBeenCalled();+ expect(deps.state.cloneInFlight).toBeNull();+ });+});diff --git a/packages/desktop/src/main/ipc/local-op.ts b/packages/desktop/src/main/ipc/local-op.tsindex 898cb27e1..9523dd1f7 100644--- a/packages/desktop/src/main/ipc/local-op.ts+++ b/packages/desktop/src/main/ipc/local-op.ts@@ -1,8 +1,8 @@import { randomUUID } from 'node:crypto';+import type { OkCliCommand } from '@inkeep/open-knowledge-core';import {type AuthReposResponse,type AuthStatusResponse,- type LocalOpCliInvocation,type RunCloneController,type RunDeviceFlowController,runAuthReposSubprocess,@@ -49,7 +49,7 @@ interface LocalOpFailure {}export interface LocalOpDeps {- resolveCliInvocation: () => LocalOpCliInvocation;+ resolveOkCli: () => OkCliCommand;logFailure: (failure: LocalOpFailure) => void;state: LocalOpHandlerState;}@@ -58,6 +58,9 @@ export function handleAuthStart(deps: LocalOpDeps,sender: SendableWebContents,): { ok: true; streamId: string } | { ok: false; error: string } {+ const cli = deps.resolveOkCli();+ const refused = cli.refusalFor(['auth', 'login']);+ if (refused !== undefined) return { ok: false, error: refused };const streamId = randomUUID();const stale = deps.state.authInFlight;if (stale) {@@ -74,7 +77,7 @@ export function handleAuthStart(}let terminalError: string | null = null;const controller = runDeviceFlowSubprocess({- ...deps.resolveCliInvocation(),+ cli,onEvent: (event) => {if (event.type === 'error') terminalError = event.message;if (!sender.isDestroyed?.()) {@@ -121,6 +124,9 @@ export function handleCloneStart(: 'dir must be within the user home directory',};}+ const cli = deps.resolveOkCli();+ const refused = cli.refusalFor(['clone']);+ if (refused !== undefined) return { ok: false, error: refused };const streamId = randomUUID();const stale = deps.state.cloneInFlight;if (stale) {@@ -137,7 +143,7 @@ export function handleCloneStart(}let terminalError: string | null = null;const controller = runCloneSubprocess({- ...deps.resolveCliInvocation(),+ cli,url: request.url,dir: request.dir,branch: request.branch,@@ -217,7 +223,7 @@ export function handleAuthStatus(host,() =>runAuthStatusSubprocess({- ...deps.resolveCliInvocation(),+ cli: deps.resolveOkCli(),host: request?.host,}).then(logged),(h) =>@@ -250,7 +256,7 @@ export function handleAuthRepos(host,() =>runAuthReposSubprocess({- ...deps.resolveCliInvocation(),+ cli: deps.resolveOkCli(),host: request?.host,}).then(logged),() =>diff --git a/packages/desktop/src/main/local-op-cli-invocation.test.ts b/packages/desktop/src/main/local-op-cli-invocation.test.tsindex 0f43291c8..520fd4c2b 100644--- a/packages/desktop/src/main/local-op-cli-invocation.test.ts+++ b/packages/desktop/src/main/local-op-cli-invocation.test.ts@@ -1,5 +1,8 @@import { describe, expect, test } from 'vitest';import {+ type HostCliInvocation,+ mainProcessOkCli,+ type ResolveLocalOpCliInvocationInput,resolveLocalOpCliArgsForUtilityFork,resolveLocalOpCliInvocation,} from './local-op-cli-invocation.ts';@@ -9,28 +12,67 @@ const WIN_EXE =const WIN_RESOURCES ='C:\\Users\\q\\AppData\\Local\\Programs\\@inkeepopen-knowledge-desktop\\resources';+const WORKSPACE_CLI = '/src/open-knowledge/packages/cli/dist/cli.mjs';++function invocationFor(+ input: Omit<ResolveLocalOpCliInvocationInput, 'workspaceCliBuilt'>,+): HostCliInvocation {+ const invocation = resolveLocalOpCliInvocation({ ...input, workspaceCliBuilt: true });+ if (invocation === undefined) throw new Error('expected a CLI invocation');+ return invocation;+}+const isWindowsBatchFile = (file: string): boolean => /\.(cmd|bat)$/i.test(file);describe('resolveLocalOpCliInvocation', () => {- test('dev builds resolve the CLI from PATH with no env overlay', () => {+ test('an unpackaged build pinned to a shipped channel resolves the CLI from PATH with no env overlay', () => {expect(- resolveLocalOpCliInvocation({+ invocationFor({platform: 'win32',isPackaged: false,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,}),).toEqual({ cliArgs: ['open-knowledge'] });});+ test('a dev-channel build runs the workspace CLI, which knows the dev channel, never the CLI on PATH', () => {+ const invocation = invocationFor({+ platform: 'darwin',+ isPackaged: false,+ execPath: '/src/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron',+ resourcesPath: '/src/node_modules/electron/dist/Electron.app/Contents/Resources',+ parentEnv: { OK_CHANNEL: 'dev' },+ workspaceCliEntry: WORKSPACE_CLI,+ });+ expect(invocation).toEqual({ cliArgs: ['node', WORKSPACE_CLI] });+ expect(resolveLocalOpCliArgsForUtilityFork(invocation)).toEqual(['node', WORKSPACE_CLI]);+ });++ test('a dev-channel build with the workspace CLI unbuilt supplies no CLI, so the server never hands dev to the CLI on PATH', () => {+ expect(+ resolveLocalOpCliInvocation({+ platform: 'darwin',+ isPackaged: false,+ execPath: '/src/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron',+ resourcesPath: '/src/node_modules/electron/dist/Electron.app/Contents/Resources',+ parentEnv: { OK_CHANNEL: 'dev' },+ workspaceCliEntry: WORKSPACE_CLI,+ workspaceCliBuilt: false,+ }),+ ).toBeUndefined();+ });+test('packaged win32 spawns OpenKnowledge.exe as Node on the bundled CLI, never the .cmd wrapper', () => {- const invocation = resolveLocalOpCliInvocation({+ const invocation = invocationFor({platform: 'win32',isPackaged: true,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,});expect(invocation.cliArgs).toEqual([WIN_EXE, `${WIN_RESOURCES}\\cli\\dist\\cli.mjs`]);expect(isWindowsBatchFile(invocation.cliArgs[0] ?? '')).toBe(false);@@ -38,12 +80,13 @@ describe('resolveLocalOpCliInvocation', () => {});test('packaged win32 targets the keyring-resolvable cli/dist copy, not the app.asar.unpacked one', () => {- const invocation = resolveLocalOpCliInvocation({+ const invocation = invocationFor({platform: 'win32',isPackaged: true,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,});const entry = invocation.cliArgs[1] ?? '';expect(entry).toBe(`${WIN_RESOURCES}\\cli\\dist\\cli.mjs`);@@ -51,12 +94,13 @@ describe('resolveLocalOpCliInvocation', () => {});test('packaged win32 moves NODE_OPTIONS aside the way ok.cmd does', () => {- const invocation = resolveLocalOpCliInvocation({+ const invocation = invocationFor({platform: 'win32',isPackaged: true,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: { NODE_OPTIONS: '--require ./hook.js' },+ workspaceCliEntry: WORKSPACE_CLI,});expect(invocation.cliEnv).toEqual({ELECTRON_RUN_AS_NODE: '1',@@ -67,33 +111,36 @@ describe('resolveLocalOpCliInvocation', () => {});test('packaged win32 without NODE_OPTIONS still clears it and sets no OK_NODE_OPTIONS', () => {- const invocation = resolveLocalOpCliInvocation({+ const invocation = invocationFor({platform: 'win32',isPackaged: true,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: { PATH: 'C:\\Windows' },+ workspaceCliEntry: WORKSPACE_CLI,});expect(invocation.cliEnv).toEqual({ ELECTRON_RUN_AS_NODE: '1', NODE_OPTIONS: undefined });});test('packaged darwin and linux keep the executable shell wrapper', () => {expect(- resolveLocalOpCliInvocation({+ invocationFor({platform: 'darwin',isPackaged: true,execPath: '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',resourcesPath: '/Applications/OpenKnowledge.app/Contents/Resources',parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,}),).toEqual({ cliArgs: ['/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh'] });expect(- resolveLocalOpCliInvocation({+ invocationFor({platform: 'linux',isPackaged: true,execPath: '/opt/OpenKnowledge/openknowledge',resourcesPath: '/opt/OpenKnowledge/resources',parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,}),).toEqual({ cliArgs: ['/opt/OpenKnowledge/resources/cli/bin/ok.sh'] });});@@ -101,12 +148,13 @@ describe('resolveLocalOpCliInvocation', () => {describe('resolveLocalOpCliArgsForUtilityFork', () => {test('returns a detached copy of cliArgs when the invocation carries no env overlay', () => {- const invocation = resolveLocalOpCliInvocation({+ const invocation = invocationFor({platform: 'win32',isPackaged: false,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,});const args = resolveLocalOpCliArgsForUtilityFork(invocation);expect(args).toEqual(['open-knowledge']);@@ -116,24 +164,26 @@ describe('resolveLocalOpCliArgsForUtilityFork', () => {test('returns the darwin wrapper path, which is runnable without an env overlay', () => {expect(resolveLocalOpCliArgsForUtilityFork(- resolveLocalOpCliInvocation({+ invocationFor({platform: 'darwin',isPackaged: true,execPath: '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',resourcesPath: '/Applications/OpenKnowledge.app/Contents/Resources',parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,}),),).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({+ const invocation = invocationFor({platform: 'win32',isPackaged: true,execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: WORKSPACE_CLI,});expect(invocation.cliEnv).toBeDefined();expect(() => resolveLocalOpCliArgsForUtilityFork(invocation)).toThrow(/cliEnv/);@@ -148,3 +198,34 @@ describe('resolveLocalOpCliArgsForUtilityFork', () => {).toThrow(/cliEnv/);});});++describe('mainProcessOkCli', () => {+ test('a dev build pins dev on its workspace CLI, since the spawn drops the inherited channel', () => {+ const cli = mainProcessOkCli({ cliArgs: ['node', WORKSPACE_CLI] }, { OK_CHANNEL: 'dev' });+ expect(cli.runnerInvocation(['auth', 'login'])).toEqual({+ cliArgs: ['node', WORKSPACE_CLI, 'auth', 'login'],+ cliEnv: { OK_CHANNEL: 'dev' },+ });+ });++ test('a dev build with no workspace CLI reads through the CLI on PATH with no channel and refuses sign-in', () => {+ const cli = mainProcessOkCli(undefined, { OK_CHANNEL: 'dev' });+ expect(cli.runnerInvocation(['auth', 'status'])).toEqual({+ cliArgs: ['open-knowledge', 'auth', 'status'],+ cliEnv: {},+ });+ expect(cli.refusalFor(['auth', 'login'])).toContain('pnpm build');+ });++ test('keeps the packaged win32 overlay alongside the channel pin', () => {+ expect(+ mainProcessOkCli(+ { cliArgs: [WIN_EXE, 'cli.mjs'], cliEnv: { ELECTRON_RUN_AS_NODE: '1' } },+ { OK_CHANNEL: 'beta' },+ ).runnerInvocation([]),+ ).toEqual({+ cliArgs: [WIN_EXE, 'cli.mjs'],+ cliEnv: { ELECTRON_RUN_AS_NODE: '1', OK_CHANNEL: 'beta' },+ });+ });+});diff --git a/packages/desktop/src/main/local-op-cli-invocation.ts b/packages/desktop/src/main/local-op-cli-invocation.tsindex d5ff961c5..cae9f38a0 100644--- a/packages/desktop/src/main/local-op-cli-invocation.ts+++ b/packages/desktop/src/main/local-op-cli-invocation.ts@@ -1,13 +1,21 @@import { win32 } from 'node:path';-import type { LocalOpCliInvocation } from '@inkeep/open-knowledge-server';+import {+ type HostCliInvocation,+ isDevChannel,+ OkCliCommand,+} from '@inkeep/open-knowledge-core/constants/product';import { wrapperPathInBundle } from './bundle-paths.ts';+export type { HostCliInvocation };+export interface ResolveLocalOpCliInvocationInput {readonly platform: NodeJS.Platform;readonly isPackaged: boolean;readonly execPath: string;readonly resourcesPath: string;readonly parentEnv: Readonly<Record<string, string | undefined>>;+ readonly workspaceCliEntry: string;+ readonly workspaceCliBuilt: boolean;}function bundledCliEntryOnWindows(resourcesPath: string): string {@@ -16,9 +24,10 @@ function bundledCliEntryOnWindows(resourcesPath: string): string {export function resolveLocalOpCliInvocation(input: ResolveLocalOpCliInvocationInput,-): LocalOpCliInvocation {+): HostCliInvocation | undefined {if (!input.isPackaged) {- return { cliArgs: ['open-knowledge'] };+ if (!isDevChannel(input.parentEnv)) return { cliArgs: ['open-knowledge'] };+ return input.workspaceCliBuilt ? { cliArgs: ['node', input.workspaceCliEntry] } : undefined;}if (input.platform === 'win32') {const nodeOptions = input.parentEnv.NODE_OPTIONS;@@ -34,7 +43,7 @@ export function resolveLocalOpCliInvocation(return { cliArgs: [wrapperPathInBundle(input.execPath, input.platform)] };}-export function resolveLocalOpCliArgsForUtilityFork(invocation: LocalOpCliInvocation): string[] {+export function resolveLocalOpCliArgsForUtilityFork(invocation: HostCliInvocation): 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',@@ -42,3 +51,10 @@ export function resolveLocalOpCliArgsForUtilityFork(invocation: LocalOpCliInvoca}return [...invocation.cliArgs];}++export function mainProcessOkCli(+ invocation: HostCliInvocation | undefined,+ env: Readonly<Record<string, string | undefined>>,+): OkCliCommand {+ return OkCliCommand.resolve({ host: invocation, env });+}diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.tsindex 458c34d39..9dfa6427f 100644--- a/packages/desktop/src/main/mcp-wiring.test.ts+++ b/packages/desktop/src/main/mcp-wiring.test.ts@@ -18,7 +18,10 @@ import {type McpEntryClassification,} from '@inkeep/open-knowledge';import { afterEach, describe, expect, test, vi } from 'vitest';-import { classifyExistingMcpEntry as classifyWithOverridableEngine } from '../../../cli/src/commands/init.ts';+import {+ classifyExistingMcpEntry as classifyWithOverridableEngine,+ writeUserMcpConfigs,+} from '../../../cli/src/commands/init.ts';import {createTomlConfigEngine,setTomlConfigEngineForTesting,@@ -749,6 +752,36 @@ function buildWiringOpts(overrides: Partial<WiringOpts> = {}): WiringOpts {};}+describe('runMcpWiringOnFirstLaunch — dev channel', () => {+ test('a dev build reports why it wrote no user-level config and leaves the marker unwritten', async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ try {+ const ipcMain = stubIpcMain();+ const wc = fakeWebContents(11);+ const fs = memoryFs();+ const { cli } = buildFirstLaunchCli();+ runMcpWiringOnFirstLaunch(+ buildWiringOpts({+ ipcMain,+ cli: { ...cli, writeUserMcpConfigs: (opts) => writeUserMcpConfigs(opts) },+ fs,+ immediateDispatchTarget: wc,+ }),+ );++ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');+ const result = await confirm?.({ sender: { id: 11 } }, { editorIds: ['claude'] });+ expect(result).toMatchObject({ ok: false });+ expect((result as { error: string }).error).toContain(+ 'A dev build registers OpenKnowledge MCP in project config only',+ );+ expect(readMcpStatusMarker('/home/u', fs)).toBeNull();+ } finally {+ vi.unstubAllEnvs();+ }+ });+});+describe('runMcpWiringOnFirstLaunch — skills consent leg', () => {const TWO_SKILLS = [{diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.tsindex dd519a70c..acf25a317 100644--- a/packages/desktop/src/main/mcp-wiring.ts+++ b/packages/desktop/src/main/mcp-wiring.ts@@ -10,6 +10,7 @@ import { dirname, join } from 'node:path';import {buildMcpConfigDeclineEvent,buildMcpConfigMigrateEvent,+ canonicalEntryFor,droppedManagedKeys,type EditorMcpTarget,editorConfigPathDisplay,@@ -324,7 +325,7 @@ export function checkAndRepairMcpWiringOnStartup(logger.event({ event: 'mcp-wiring-repair-unsupported-format', severity: 'warn', editor });continue;}- const dropped = droppedManagedKeys(classification.entry, target.buildEntry('', {}));+ const dropped = droppedManagedKeys(classification.entry, canonicalEntryFor(target, ''));if (dropped.length === 0) {logger.event({ event: 'mcp-wiring-repair-healthy-current', severity: 'info', editor });continue;diff --git a/packages/desktop/src/main/path-install-dev.test.ts b/packages/desktop/src/main/path-install-dev.test.tsnew file mode 100644index 000000000..d1c8439a6--- /dev/null+++ b/packages/desktop/src/main/path-install-dev.test.ts@@ -0,0 +1,57 @@+import { existsSync, mkdtempSync, readFileSync, readlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterAll, describe, expect, test, vi } from 'vitest';++const previousChannel = vi.hoisted(() => {+ const previous = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'dev';+ return previous;+});++import { ensureCliOnPath, pathInstallMarkerPath } from './path-install.ts';++afterAll(() => {+ if (previousChannel === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = previousChannel;+});++const STABLE_EXE = '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';+const STABLE_WRAPPER = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';++describe('forced PATH install from a dev build', () => {+ test('lands in the dev home under dev command names, leaving Stable untouched', async () => {+ const userHome = mkdtempSync(join(tmpdir(), 'ok-dev-path-install-'));+ const zshrc = join(userHome, '.zshrc');+ const stableBlock = '# >>> open-knowledge cli >>>\nstable\n# <<< open-knowledge cli <<<\n';+ writeFileSync(zshrc, stableBlock);++ const result = await ensureCliOnPath({+ executablePath: STABLE_EXE,+ isPackaged: false,+ forceEnv: '1',+ platform: 'darwin',+ home: userHome,+ bundleVersion: '0.0.0-dev',+ env: { HOME: userHome, SHELL: '/bin/zsh' },+ spawn: async () => ({ code: 0, stdout: '/usr/bin:/bin', stderr: '' }),+ consentDecision: { status: 'granted', at: '2026-10-13T00:00:00.000Z' },+ });++ expect(result.status).toBe('installed');+ const devRoot = join(userHome, '.ok-dev');+ expect(pathInstallMarkerPath(userHome)).toBe(join(devRoot, 'path-install.json'));+ expect(readlinkSync(join(devRoot, 'bin', 'ok-dev'))).toBe(STABLE_WRAPPER);+ expect(readlinkSync(join(devRoot, 'bin', 'open-knowledge-dev'))).toBe(STABLE_WRAPPER);+ expect(readFileSync(join(devRoot, 'env.sh'), 'utf8')).toContain('$' + '{HOME}/.ok-dev/bin');+ const rc = readFileSync(zshrc, 'utf8');+ expect(rc).toContain(stableBlock);+ expect(rc).toContain('# >>> open-knowledge dev cli >>>');+ expect(existsSync(join(userHome, '.ok'))).toBe(false);+ expect(+ existsSync(+ join(userHome, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json'),+ ),+ ).toBe(false);+ });+});diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.tsindex 162cdab4c..470949e2f 100644--- a/packages/desktop/src/main/path-install.ts+++ b/packages/desktop/src/main/path-install.ts@@ -14,6 +14,9 @@ import {import { dirname, join } from 'node:path';import type { PathDiscovery, PathInstallConsent, PathInstallMarker } from '@inkeep/open-knowledge';import {+ DESKTOP_PRODUCTS,+ type DesktopProductName,+ isDevChannel,pathShimBinDir,pathShimBlockLabel,pathShimFishConfFileName,@@ -24,8 +27,8 @@ import { DESKTOP_VARIANT } from '../shared/desktop-variant.ts';import type { McpWiringPathInstallDescriptor } from '../shared/ipc-channels.ts';import { classifyInstallShape } from './install-shape.ts';-const NAMES = DESKTOP_VARIANT.cliCommandNames;-const CHANNEL = DESKTOP_VARIANT.name;+const CHANNEL: DesktopProductName = isDevChannel(process.env) ? 'dev' : DESKTOP_VARIANT.name;+const NAMES = DESKTOP_PRODUCTS[CHANNEL].cliCommandNames;const CLI_HOME_PREFIX = pathShimHomeDirName(CHANNEL);const RC_BIN_DIR = pathShimBinDir(CHANNEL, '$HOME');const ENV_SH_BIN_DIR = pathShimBinDir(CHANNEL, `\${HOME}`);@@ -528,7 +531,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensurefs.mkdirSync(dirname(shim), { recursive: true });fs.writeFileSync(shim,- `# ${DESKTOP_VARIANT.productName} CLI environment — managed file, do not edit.\ncase ":\${PATH}:" in\n *:"${ENV_SH_BIN_DIR}":*) ;;\n *) export PATH="${ENV_SH_BIN_DIR}:\${PATH}" ;;\nesac\n`,+ `# ${DESKTOP_PRODUCTS[CHANNEL].productName} CLI environment — managed file, do not edit.\ncase ":\${PATH}:" in\n *:"${ENV_SH_BIN_DIR}":*) ;;\n *) export PATH="${ENV_SH_BIN_DIR}:\${PATH}" ;;\nesac\n`,);phase = 'discoverPath';diff --git a/packages/desktop/src/main/project-mcp-reclaim.ts b/packages/desktop/src/main/project-mcp-reclaim.tsindex 6e9ca9e63..31ff09ddc 100644--- a/packages/desktop/src/main/project-mcp-reclaim.ts+++ b/packages/desktop/src/main/project-mcp-reclaim.ts@@ -2,6 +2,7 @@ import { join } from 'node:path';import {buildMcpConfigDeclineEvent,buildMcpConfigMigrateEvent,+ canonicalEntryFor,droppedManagedKeys,type EditorMcpTarget,isEntryUpToDate,@@ -229,7 +230,7 @@ export async function checkAndRepairProjectMcpOnProjectOpen(if (launcher.kind === 'recognized' && launcher.disposition === 'keep') {const dropped = droppedManagedKeys(classification.entry,- target.buildEntry(projectDir, {}),+ canonicalEntryFor(target, projectDir),);if (dropped.length === 0) {perEditor.push({ editor, status: 'healthy-current', configPath: projectPath });diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex b781f9ede..ea5c55883 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -10,7 +10,7 @@ import {sliceLastSpawnAttempt,} from '@inkeep/open-knowledge-core';import type { KeepaliveHandle } from '@inkeep/open-knowledge-core/keepalive';-import { getLocalDir, type LocalOpCliInvocation } from '@inkeep/open-knowledge-server';+import { getLocalDir } from '@inkeep/open-knowledge-server';import {BOOT_HEARTBEAT_EVENTS,isUtilityInitPhase,@@ -30,7 +30,10 @@ 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 HostCliInvocation,+ 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';@@ -315,7 +318,7 @@ interface CreateProjectWindowOpts {pendingShareBranchSwitch?: ShareDeepLinkBranchSwitchPayload;didEnsureGit?: boolean;consentVersion?: number;- localOpCliInvocation?: LocalOpCliInvocation;+ localOpCliInvocation?: HostCliInvocation;pendingServerRestartedToast?: boolean;freshlyCreated?: boolean;}@@ -902,7 +905,7 @@ export class WindowManager {async restartAttachedServer(projectPath: string,- opts?: { localOpCliInvocation?: LocalOpCliInvocation },+ opts?: { localOpCliInvocation?: HostCliInvocation },): Promise<OkServerRestartOutcome> {const resolved = resolve(projectPath);const canonicalKey = this.canonicalizeKey(resolved);@@ -1077,7 +1080,7 @@ export class WindowManager {async restartServerForWindow(sender: BrowserWindowLike | null,projectPath: string,- opts: { localOpCliInvocation?: LocalOpCliInvocation },+ opts: { localOpCliInvocation?: HostCliInvocation },): Promise<OkServerRestartOutcome> {if (sender !== null) {const ephemeralIdentity = this.getEphemeralIdentityForWindow(sender);diff --git a/packages/desktop/src/shared/desktop-variant.ts b/packages/desktop/src/shared/desktop-variant.tsindex 21fa91d29..f49d8fa06 100644--- a/packages/desktop/src/shared/desktop-variant.ts+++ b/packages/desktop/src/shared/desktop-variant.ts@@ -1,11 +1,11 @@-import { DESKTOP_PRODUCTS, type DesktopProductName } from '@inkeep/open-knowledge-core';+import { DESKTOP_PRODUCTS, type PackagedDesktopProductName } from '@inkeep/open-knowledge-core';const DESKTOP_VARIANT_NAMES = ['stable', 'beta', 'legacy-beta'] as const;export type DesktopVariantName = (typeof DESKTOP_VARIANT_NAMES)[number];interface DesktopVariantIdentity {- readonly name: DesktopProductName;+ readonly name: PackagedDesktopProductName;readonly appId: string;readonly productName: string;readonly artifactName: string;@@ -66,7 +66,7 @@ const DESKTOP_PRODUCT_VARIANTS = {cliCommandNames: DESKTOP_PRODUCTS.beta.cliCommandNames,cliHomeSegment: 'beta',},-} as const satisfies Record<DesktopProductName, DesktopVariantIdentity>;+} as const satisfies Record<PackagedDesktopProductName, DesktopVariantIdentity>;export const DESKTOP_VARIANTS = {...DESKTOP_PRODUCT_VARIANTS,diff --git a/packages/desktop/src/shared/ok-child-env.test.ts b/packages/desktop/src/shared/ok-child-env.test.tsindex 940aa3f62..61ec3cab8 100644--- a/packages/desktop/src/shared/ok-child-env.test.ts+++ b/packages/desktop/src/shared/ok-child-env.test.ts@@ -95,6 +95,30 @@ describe('composeOkChildEnv PATH grant', () => {});describe('composeOkChildEnv', () => {+ test('keeps the dev channel away from a terminal, whose ok on PATH may predate it', () => {+ const env = composeOkChildEnv(+ { PATH: '/usr/bin', OK_CHANNEL: 'dev' },+ { platform: 'darwin', home: '/Users/alice' },+ );+ expect(env.OK_CHANNEL).toBeUndefined();+ });++ test('drops the dev channel under the differently cased key a Windows environment can carry', () => {+ const env = composeOkChildEnv(+ { Path: 'C:\\Windows', Ok_Channel: 'dev' },+ { platform: 'win32', cliBinDir: 'C:\\ok\\bin' },+ );+ expect(Object.keys(env).filter((key) => key.toUpperCase() === 'OK_CHANNEL')).toEqual([]);+ });++ test('passes a shipped channel through, since every released CLI knows it', () => {+ const env = composeOkChildEnv(+ { PATH: '/usr/bin', OK_CHANNEL: 'beta' },+ { platform: 'darwin', home: '/Users/alice' },+ );+ expect(env.OK_CHANNEL).toBe('beta');+ });+test('strips OK and Electron markers, drops undefined, and grants the OK-managed bin dir', () => {const env = composeOkChildEnv({diff --git a/packages/desktop/src/shared/ok-child-env.ts b/packages/desktop/src/shared/ok-child-env.tsindex 02e0a5c8e..3201add9c 100644--- a/packages/desktop/src/shared/ok-child-env.ts+++ b/packages/desktop/src/shared/ok-child-env.ts@@ -1,5 +1,6 @@import { homedir } from 'node:os';import {+ envWithoutDevChannel,OK_DESKTOP_TERMINAL_ENV,OK_HOSTED_AGENT_ENV,posixOkManagedBinDir,@@ -109,8 +110,7 @@ export function composeOkChildEnv(): Record<string, string> {const stripped = new Set<string>(STRIPPED_ENV_MARKERS);const out: Record<string, string> = {};- for (const [key, value] of Object.entries(parentEnv)) {- if (value === undefined) continue;+ for (const [key, value] of Object.entries(envWithoutDevChannel(parentEnv))) {if (stripped.has(key) || key.startsWith('GDK_PIXBUF_')) continue;out[key] = value;}diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 4cf9df799..f70148425 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -1206,6 +1206,30 @@ describe('WindowManager', () => {});});+ test("installed Stable refuses a dev build's server, and a dev build refuses Stable's instead of reclaiming it", async () => {+ const killProbe = vi.fn(() => {});+ env.deps.killProbe = killProbe;+ env.deps.selfChannel = 'stable';+ enableAttachProbe({ readServerLock: () => ({ ...liveLock, channel: 'dev' }) });+ expect(await openOutcome(new WindowManager(env.deps))).toEqual({+ kind: 'refused',+ errKind: 'other-channel-holder',+ holderChannel: 'dev',+ message:+ 'OpenKnowledge Dev is serving this project (pid 65792). Only one OpenKnowledge app can edit a project at a time.',+ });++ env.deps.selfChannel = 'dev';+ env.deps.reclaimForeignServerInDev = true;+ enableAttachProbe({ readServerLock: () => stableLock });+ expect(await openOutcome(new WindowManager(env.deps))).toMatchObject({+ kind: 'refused',+ errKind: 'other-channel-holder',+ holderChannel: 'stable',+ });+ expect(killProbe).not.toHaveBeenCalled();+ });+test("restart refuses to stop another channel's server", async () => {const killProbe = vi.fn(() => {});env.deps.killProbe = killProbe;@@ -5356,6 +5380,8 @@ describe('WindowManager — local-op CLI invocation threading', () => {execPath: WIN_EXE,resourcesPath: WIN_RESOURCES,parentEnv: {},+ workspaceCliEntry: 'C:\\src\\open-knowledge\\packages\\cli\\dist\\cli.mjs',+ workspaceCliBuilt: true,});}diff --git a/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts b/packages/desktop/tests/unit/helper-bundle-name-agreement.test.tsindex 7cb0853f5..ac9a7b18c 100644--- a/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts+++ b/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts@@ -1,7 +1,11 @@import { readFileSync } from 'node:fs';import { dirname, resolve } from 'node:path';import { fileURLToPath } from 'node:url';-import { DESKTOP_PRODUCTS, desktopWindowsExecutableName } from '@inkeep/open-knowledge-core';+import {+ DESKTOP_PRODUCTS,+ desktopWindowsExecutableName,+ PACKAGED_DESKTOP_PRODUCT_NAMES,+} from '@inkeep/open-knowledge-core';import {HELPER_BUNDLE_NAME,HELPER_EXECUTABLE_NAME,@@ -121,7 +125,7 @@ describe('helper-bundle name agreement across spawn site / Info.plist / afterPacconst cmd = readFileSync(okCmdPath, 'utf8');const ps1 = readFileSync(okPs1Path, 'utf8');const linux = readFileSync(okLinuxPath, 'utf8');- for (const product of Object.values(DESKTOP_PRODUCTS)) {+ for (const product of PACKAGED_DESKTOP_PRODUCT_NAMES.map((name) => DESKTOP_PRODUCTS[name])) {expect(cmd).toContain(`"${desktopWindowsExecutableName(product)}"`);expect(ps1).toContain(`'${desktopWindowsExecutableName(product)}'`);expect(linux).toContain(product.linuxExecutableName);diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 06cff8535..2bd6f9cb9 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -242,6 +242,28 @@ describe('mergedEnv PATH augmentation', () => {}});+ test('keeps the dev channel away from agents, whose MCP children may run a CLI that predates it', () => {+ const prior = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'dev';+ try {+ expect(mergedEnv().OK_CHANNEL).toBeUndefined();+ } finally {+ if (prior === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = prior;+ }+ });++ test('passes a shipped channel through to agents', () => {+ const prior = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'beta';+ try {+ expect(mergedEnv().OK_CHANNEL).toBe('beta');+ } finally {+ if (prior === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = prior;+ }+ });+test('overlaySetsPath sees PATH under any spelling', () => {expect(overlaySetsPath({ Path: '/x' })).toBe(true);expect(overlaySetsPath({ PATH: '/x' })).toBe(true);diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex ff8ca53ef..773030483 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -5,7 +5,11 @@ import { access, chmod, readFile, stat } from 'node:fs/promises';import { homedir } from 'node:os';import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';import { stripVTControlCharacters } from 'node:util';-import { augmentAgentSpawnPath, OK_HOSTED_AGENT_ENV } from '@inkeep/open-knowledge-core';+import {+ augmentAgentSpawnPath,+ envWithoutDevChannel,+ OK_HOSTED_AGENT_ENV,+} from '@inkeep/open-knowledge-core';import { okUserHomeDir } from '@inkeep/open-knowledge-core/server';import { z } from 'zod';import {@@ -80,8 +84,7 @@ function isDir(dir: string): boolean {export function mergedEnv(overlay?: Record<string, string>): Record<string, string> {const base: Record<string, string> = {};- for (const [k, v] of Object.entries(process.env)) {- if (v === undefined) continue;+ for (const [k, v] of Object.entries(envWithoutDevChannel(process.env))) {if (k.toLowerCase() === 'npm_config_overrides') continue;base[k] = v;}diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 3bb0f044f..312dbc9a9 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -200,6 +200,21 @@ describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {expect(hostedMarker).toBe('stdio-entry-env');});+ test('the injected stdio server carries the channel its host CLI was built with', async () => {+ const m = makeManager(+ () => null,+ () => ({+ command: 'node',+ args: ['/src/cli.mjs', 'mcp', '--port', '4242'],+ env: { OK_CHANNEL: 'dev' },+ }),+ );+ const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});+ const env = (servers[0] as { env: Array<{ name: string; value: string }> }).env;+ expect(env).toContainEqual({ name: 'OK_CHANNEL', value: 'dev' });+ expect(env).toContainEqual({ name: OK_HOSTED_AGENT_ENV, value: '1' });+ });+test('the injected stdio PATH is the agent spawn PATH, not the server process PATH', async () => {const m = makeManager(() => null);const { servers } = await m.buildMcpServers(record('registry', 'claude-acp'), LAUNCH, {});diff --git a/packages/server/src/acp/mcp-stdio-command.test.ts b/packages/server/src/acp/mcp-stdio-command.test.tsindex 3324e14eb..39006c951 100644--- a/packages/server/src/acp/mcp-stdio-command.test.ts+++ b/packages/server/src/acp/mcp-stdio-command.test.ts@@ -55,6 +55,28 @@ describe('buildOkMcpStdioCommand', () => {});});+ test('a dev-channel host CLI carries the dev channel into the MCP entry', () => {+ const cli = ['node', '/src/open-knowledge/packages/cli/dist/cli.mjs'];+ expect(+ buildOkMcpStdioCommand(cli, 5173, {+ resolveCommand: () => '/usr/local/bin/node',+ env: { OK_CHANNEL: 'dev' },+ }),+ ).toEqual({+ command: '/usr/local/bin/node',+ args: ['/src/open-knowledge/packages/cli/dist/cli.mjs', 'mcp', '--port', '5173'],+ env: { OK_CHANNEL: 'dev' },+ });+ });++ test('never hands the dev channel to the open-knowledge on PATH, which may predate it', () => {+ const command = buildOkMcpStdioCommand(undefined, 5173, {+ resolveCommand: () => '/Users/alice/.ok/bin/open-knowledge',+ env: { OK_CHANNEL: 'dev' },+ });+ expect(command.env).toBeUndefined();+ });+test('always pins to the given port', () => {expect(buildOkMcpStdioCommand(['ok'], 61999, unresolvable).args).toContain('--port');expect(buildOkMcpStdioCommand(['ok'], 61999, unresolvable).args.at(-1)).toBe('61999');diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 5bda83b18..ca6c36070 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -41,6 +41,7 @@ import {type HostSnapshot,iconFromClientName,OK_HOSTED_AGENT_ENV,+ OkCliCommand,} from '@inkeep/open-knowledge-core';import type {AttachmentPart,@@ -460,7 +461,7 @@ export interface AcpThreadManagerOptions {isIgnoredPath: (relPosix: string) => boolean;getLoadedDocText?: (docName: string) => string | null;getServerUrl?: () => string;- getMcpStdioCommand?: () => { command: string; args: readonly string[] } | null | undefined;+ getMcpStdioCommand?: () => OkMcpStdioCommand | null | undefined;probeHarnessManagedMcpEntry?: (editorId: EditorId,cwd: string,@@ -493,18 +494,28 @@ export interface AcpThreadManagerOptions {browserInstallWaitMs?: number;}+export interface OkMcpStdioCommand {+ command: string;+ args: string[];+ env?: Record<string, string>;+}+export function buildOkMcpStdioCommand(localOpCliArgs: readonly string[] | undefined,port: number,deps?: {resolveCommand?: (name: string) => string | null;log?: PinoLogger;+ env?: Readonly<Record<string, string | undefined>>;},-): { command: string; args: string[] } {- const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];- const [command = 'open-knowledge', ...rest] = argv;- const args = [...rest, 'mcp', '--port', String(port)];- if (command.includes('/') || command.includes('\\')) return { command, args };+): OkMcpStdioCommand {+ const server = OkCliCommand.resolve({+ host: localOpCliArgs === undefined ? undefined : { cliArgs: localOpCliArgs },+ ...(deps?.env === undefined ? {} : { env: deps.env }),+ }).stdioServer(['mcp', '--port', String(port)]);+ const { command, args } = server;+ const channel = Object.keys(server.env).length > 0 ? { env: server.env } : {};+ if (command.includes('/') || command.includes('\\')) return { command, args, ...channel };const resolved = (deps?.resolveCommand ?? ((name) => resolveOnPath(name, agentSpawnPath())))(command,);@@ -513,9 +524,9 @@ export function buildOkMcpStdioCommand({ command },'[acp-threads] OK MCP stdio command did not resolve on PATH — injecting the bare name, which fails for harnesses that spawn MCP children under a minimal PATH',);- return { command, args };+ return { command, args, ...channel };}- return { command: resolved, args };+ return { command: resolved, args, ...channel };}export type OkMcpHostedMarker = 'http-header' | 'stdio-entry-env' | 'unknown' | 'none';@@ -1763,6 +1774,7 @@ export class AcpThreadManager {...(entryPath !== undefined && entryPath !== ''? [{ name: 'PATH', value: entryPath }]: []),+ ...Object.entries(stdio.env ?? {}).map(([name, value]) => ({ name, value })),],});hostedMarker = 'stdio-entry-env';diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 571b0a1f9..d20281eb1 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -1569,7 +1569,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {getSyncEngine,conflicts,setBatchInProgress,- localOpCliArgs = ['open-knowledge'],+ localOpCliArgs,authStreamHeartbeatMs,projectDir,getBridgeLossReporter,diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.tsindex c35470c1a..4da738602 100644--- a/packages/server/src/git-handle.test.ts+++ b/packages/server/src/git-handle.test.ts@@ -441,6 +441,21 @@ describe('buildSyncCredentialConfig()', () => {});});+ test('dev channel pins dev only on the CLI the host supplies, never on the CLI on PATH', () => {+ withEnvEntries({ OK_CHANNEL: 'dev' }, () => {+ const argv = ['/usr/local/bin/node', '/src/ok/packages/cli/dist/cli.mjs'];+ expect(argvFromHelper(buildSyncCredentialConfig(argv, { resetAmbient: true }))).toEqual([+ 'OK_CHANNEL=dev',+ ...argv,+ 'auth',+ 'git-credential',+ ]);+ expect(buildSyncCredentialConfig(undefined, { resetAmbient: true }).at(-1)).toBe(+ 'credential.helper=!open-knowledge auth git-credential',+ );+ });+ });+test('Stable channel keeps the helper unpinned', () => {withEnvEntries({ OK_CHANNEL: undefined }, () => {const config = buildSyncCredentialConfig(['/usr/local/bin/node', '/opt/ok/cli.mjs'], {diff --git a/packages/server/src/git-handle.ts b/packages/server/src/git-handle.tsindex 5f37c9bc2..9c2077e99 100644--- a/packages/server/src/git-handle.ts+++ b/packages/server/src/git-handle.ts@@ -1,11 +1,7 @@import { existsSync, statSync } from 'node:fs';import { homedir } from 'node:os';import { delimiter, resolve } from 'node:path';-import {- augmentGitSpawnPath,- OK_CHANNEL_ENV,- resolveDesktopProductName,-} from '@inkeep/open-knowledge-core';+import { augmentGitSpawnPath, OkCliCommand } from '@inkeep/open-knowledge-core';import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';import { shellEscape } from './bash/shell-escape.ts';@@ -138,10 +134,9 @@ export function buildSyncCredentialConfig(localOpCliArgs: string[] | undefined,opts: { resetAmbient: boolean },): string[] {- const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];- const cliPrefix = argv.map(shellEscape).join(' ');- const channel = resolveDesktopProductName();- const channelPin = channel === 'stable' ? '' : `${OK_CHANNEL_ENV}=${channel} `;- const helper = `credential.helper=!${channelPin}${cliPrefix} auth git-credential`;+ const cli = OkCliCommand.resolve({+ host: localOpCliArgs === undefined ? undefined : { cliArgs: localOpCliArgs },+ });+ const helper = `credential.helper=!${cli.shellCommand(['auth', 'git-credential'], shellEscape)}`;return opts.resetAmbient ? ['credential.helper=', helper] : [helper];}diff --git a/packages/server/src/http/local-op-routes.test.ts b/packages/server/src/http/local-op-routes.test.tsindex 1bafc36a1..78f5eab08 100644--- a/packages/server/src/http/local-op-routes.test.ts+++ b/packages/server/src/http/local-op-routes.test.ts@@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';import { createServer, type Server as HttpServer } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';+import { DEV_FALLBACK_CLI_REFUSAL } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test, vi } from 'vitest';import { configureTestGitRepository } from '../../../../test-support/configure-git-fixture.test-helper.ts';import { createConcurrencyGuard } from '../local-op-security.ts';@@ -377,6 +378,33 @@ describe('auth-login stream displacement (a second start orphans the first clien}});+ test('a dev build without its workspace CLI answers every Stable-changing route with the same refusal', async () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ vi.stubEnv('PATH', join(tmpdir(), 'ok-no-cli-on-path'));+ const homeDir = mkdtempSync(join(tmpdir(), 'ok-dev-fallback-clone-'));+ try {+ const baseUrl = await serveLocalOpGroup({ localOpCliArgs: undefined });+ const requests: Array<[string, Record<string, unknown>]> = [+ ['/api/local-op/auth/login', { host: 'github.com', json: true }],+ ['/api/local-op/auth/pat', { host: 'github.com', token: 'test-token' }],+ ['/api/local-op/auth/token', { host: 'github.com', username: 'u', token: 'test-token' }],+ ['/api/local-op/auth/signout', { host: 'github.com' }],+ ['/api/local-op/clone', { url: 'https://github.com/o/r.git', dir: join(homeDir, 'r') }],+ ];+ for (const [path, body] of requests) {+ const response = await postJson(baseUrl, path, body);+ expect({ path, status: response.status }).toEqual({ path, status: 409 });+ expect(await response.json()).toMatchObject({+ title: 'This dev build has no built CLI.',+ detail: DEV_FALLBACK_CLI_REFUSAL,+ });+ }+ } finally {+ vi.unstubAllEnvs();+ rmSync(homeDir, { recursive: true, force: true });+ }+ });+test('an unparseable origin reports an unknown host without a false provider classification', async () => {const projectDir = mkdtempSync(join(tmpdir(), 'ok-unparseable-origin-'));try {diff --git a/packages/server/src/http/local-op-routes.ts b/packages/server/src/http/local-op-routes.tsindex fdefa4cb8..029dfa32c 100644--- a/packages/server/src/http/local-op-routes.ts+++ b/packages/server/src/http/local-op-routes.ts@@ -25,7 +25,9 @@ import {LocalOpEmbeddingsTestResponseSchema,LocalOpOkInitRequestSchema,LocalOpOkInitResponseSchema,+ OkCliCommand,okUserHomeDisplayPath,+ type ProblemType,} from '@inkeep/open-knowledge-core';import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';import {@@ -97,7 +99,7 @@ export interface LocalOpRouteDeps {res: ServerResponse,opts: { handler: string },) => boolean;- localOpCliArgs: string[];+ localOpCliArgs: readonly string[] | undefined;localOpGuard: ConcurrencyGuard;getSyncEngine: (() => SyncEngine | null) | undefined;authStreamHeartbeatMs: number | undefined;@@ -122,6 +124,21 @@ export function createLocalOpRoutes(readSemanticProviderConfig,semanticSearch,} = deps;+ const okCli = OkCliCommand.resolve({+ host: localOpCliArgs === undefined ? undefined : { cliArgs: localOpCliArgs },+ });++ function rejectDevFallback(+ res: ServerResponse,+ handler: string,+ type: ProblemType,+ command: readonly string[],+ ): boolean {+ const refused = okCli.refusalFor(command);+ if (refused === undefined) return false;+ errorResponse(res, 409, type, 'This dev build has no built CLI.', { handler, detail: refused });+ return true;+ }const subprocessLifetime = new LocalOpSubprocessLifetime();const resolveGhBinaryPath = createGhBinaryPathResolver(subprocessLifetime);@@ -148,6 +165,9 @@ export function createLocalOpRoutes(body: LocalOpCloneRequest,): Promise<void> {const { url, dir, branch } = body;+ if (rejectDevFallback(res, HANDLE_LOCAL_OP_CLONE, 'urn:ok:error:clone-failed', ['clone'])) {+ return;+ }if (!isAllowedGitUrl(url)) {errorResponse(@@ -193,7 +213,7 @@ export function createLocalOpRoutes(let cloneCompleteDir: string | null = null;const flow = runCloneSubprocess({- cliArgs: localOpCliArgs,+ cli: okCli,url,dir,branch,@@ -293,17 +313,18 @@ export function createLocalOpRoutes(if (existing === 'no-ui') return { error: SERVER_WITHOUT_UI_ERROR };if (existing !== null) return { port: existing };- const [cmd, ...baseArgs] = localOpCliArgs;+ const startInvocation = okCli.spawn(['start'], { ...process.env, OK_LOCK_KIND: 'interactive' });+ if ('refused' in startInvocation) return { error: startInvocation.refused };const spawnAndAwaitServer = async (): Promise<{ port: number } | { error: string }> => {const child = spawn(- cmd,- [...baseArgs, 'start'],+ startInvocation.command,+ startInvocation.args,withHiddenWindowsConsole({...LOCAL_OP_STDERR_ONLY_OPTIONS,cwd: absDir,detached: true,- env: { ...process.env, OK_LOCK_KIND: 'interactive' },+ env: startInvocation.env,}),);@@ -702,6 +723,14 @@ export function createLocalOpRoutes(if (rejectShuttingDown(res, HANDLE_LOCAL_OP_AUTH_LOGIN)) return;const host = resolveAuthHost(res, HANDLE_LOCAL_OP_AUTH_LOGIN, body.host);if (host === null) return;+ if (+ rejectDevFallback(res, HANDLE_LOCAL_OP_AUTH_LOGIN, 'urn:ok:error:auth-failed', [+ 'auth',+ 'login',+ ])+ ) {+ return;+ }streamAuthFlow({res,handler: HANDLE_LOCAL_OP_AUTH_LOGIN,@@ -712,7 +741,7 @@ export function createLocalOpRoutes(makeFlow: (onEvent) =>runDeviceFlowSubprocess({lifetime: subprocessLifetime,- cliArgs: localOpCliArgs,+ cli: okCli,cwd: authProjectDir,host,timeoutMs: AUTH_DEVICE_FLOW_TIMEOUT_MS,@@ -826,17 +855,17 @@ export function createLocalOpRoutes(const finish = subprocessLifetime.begin();try {- const [cmd, ...baseArgs] = localOpCliArgs;- const spawnArgs = [...baseArgs, 'auth', 'status', '--json', '--host', host];+ const invocation = okCli.spawn(['auth', 'status', '--json', '--host', host], process.env);+ if ('refused' in invocation) throw new Error(invocation.refused);const output = await new Promise<string>((resolve, reject) => {const child = subprocessLifetime.spawn(() =>spawn(- cmd,- spawnArgs,+ invocation.command,+ invocation.args,withHiddenWindowsConsole({...LOCAL_OP_PIPE_STDIO_OPTIONS,- env: { ...process.env },+ env: invocation.env,cwd: authProjectDir,}),),@@ -930,6 +959,14 @@ export function createLocalOpRoutes(if (rejectShuttingDown(res, HANDLE_LOCAL_OP_AUTH_PAT)) return;const host = resolveAuthHost(res, HANDLE_LOCAL_OP_AUTH_PAT, body.host);if (host === null) return;+ if (+ rejectDevFallback(res, HANDLE_LOCAL_OP_AUTH_PAT, 'urn:ok:error:auth-failed', [+ 'auth',+ 'pat',+ ])+ ) {+ return;+ }if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_PAT_KEY)) {errorResponse(@@ -946,7 +983,7 @@ export function createLocalOpRoutes(try {const result = await runPatSubprocess({lifetime: subprocessLifetime,- cliArgs: localOpCliArgs,+ cli: okCli,cwd: authProjectDir,host,token: body.token,@@ -990,6 +1027,14 @@ export function createLocalOpRoutes(LocalOpAuthTokenRequestSchema,async (_req, res, body) => {if (rejectShuttingDown(res, HANDLE_LOCAL_OP_AUTH_TOKEN)) return;+ if (+ rejectDevFallback(res, HANDLE_LOCAL_OP_AUTH_TOKEN, 'urn:ok:error:auth-failed', [+ 'auth',+ 'token',+ ])+ ) {+ return;+ }if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_TOKEN_KEY)) {errorResponse(res,@@ -1005,7 +1050,7 @@ export function createLocalOpRoutes(try {const result = await runAuthTokenSubprocess({lifetime: subprocessLifetime,- cliArgs: localOpCliArgs,+ cli: okCli,host: body.host,username: body.username,token: body.token,@@ -1084,8 +1129,8 @@ export function createLocalOpRoutes(const writeStreamError = createStreamingErrorWriter(res, HANDLE_LOCAL_OP_AUTH_REPOS);- const [cmd, ...baseArgs] = localOpCliArgs;- const spawnArgs = [...baseArgs, 'auth', 'repos', '--json', '--host', host];+ const invocation = okCli.spawn(['auth', 'repos', '--json', '--host', host], process.env);+ if ('refused' in invocation) throw new Error(invocation.refused);let settled = false;let stdoutBuffer = '';@@ -1094,11 +1139,11 @@ export function createLocalOpRoutes(try {return subprocessLifetime.spawn(() =>spawn(- cmd,- spawnArgs,+ invocation.command,+ invocation.args,withHiddenWindowsConsole({...LOCAL_OP_PIPE_STDIO_OPTIONS,- env: { ...process.env },+ env: invocation.env,cwd: authProjectDir,}),),@@ -1214,6 +1259,14 @@ export function createLocalOpRoutes(if (rejectShuttingDown(res, HANDLE_LOCAL_OP_AUTH_SIGNOUT)) return;const host = body.host ?? resolveAuthHost(res, HANDLE_LOCAL_OP_AUTH_SIGNOUT, undefined);if (host === null) return;+ if (+ rejectDevFallback(res, HANDLE_LOCAL_OP_AUTH_SIGNOUT, 'urn:ok:error:auth-failed', [+ 'auth',+ 'signout',+ ])+ ) {+ return;+ }if (!localOpGuard.tryAcquire(LOCAL_OP_AUTH_SIGNOUT_KEY)) {errorResponse(@@ -1228,17 +1281,17 @@ export function createLocalOpRoutes(const finish = subprocessLifetime.begin();try {- const [cmd, ...baseArgs] = localOpCliArgs;- const spawnArgs = [...baseArgs, 'auth', 'signout', '--host', host];+ const invocation = okCli.spawn(['auth', 'signout', '--host', host], process.env);+ if ('refused' in invocation) throw new Error(invocation.refused);await new Promise<void>((resolve, reject) => {const child = subprocessLifetime.spawn(() =>spawn(- cmd,- spawnArgs,+ invocation.command,+ invocation.args,withHiddenWindowsConsole({...LOCAL_OP_IGNORED_STDIO_OPTIONS,- env: { ...process.env },+ env: invocation.env,cwd: authProjectDir,}),),diff --git a/packages/server/src/http/share-routes.ts b/packages/server/src/http/share-routes.tsindex bd202c3f8..493307569 100644--- a/packages/server/src/http/share-routes.ts+++ b/packages/server/src/http/share-routes.ts@@ -4,6 +4,7 @@ import {EmptyRequestSchema,encodeShareUrl,InvalidShareUrlError,+ OkCliCommand,parseCanonicalGitHubShareUrl,ShareConstructUrlRequestSchema,ShareConstructUrlResponseSchema,@@ -74,7 +75,7 @@ export interface ShareRouteDeps {res: ServerResponse,opts: { handler: string },) => boolean;- localOpCliArgs: string[];+ localOpCliArgs: readonly string[] | undefined;localOpGuard: ConcurrencyGuard;getSyncEngine: (() => SyncEngine | null) | undefined;resolveCredentialConfig: () => Promise<string[]>;@@ -94,6 +95,9 @@ export function createShareRoutes(deps: ShareRouteDeps): ApiRouteGroup {toGitRelativePath,} = deps;const declaredGitHubHosts = deps.declaredGitHubHosts ?? readDeclaredGitHubHosts();+ const okCli = OkCliCommand.resolve({+ host: localOpCliArgs === undefined ? undefined : { cliArgs: localOpCliArgs },+ });const handleShareConstructUrl = withValidation(ShareConstructUrlRequestSchema,@@ -336,15 +340,15 @@ export function createShareRoutes(deps: ShareRouteDeps): ApiRouteGroup {async function spawnShareSubprocess(args: readonly string[],): Promise<{ stdout: string; code: number | null }> {- const [cmd, ...baseArgs] = localOpCliArgs;- const spawnArgs = [...baseArgs, ...args];+ const invocation = okCli.spawn(args, process.env);+ if ('refused' in invocation) throw new Error(invocation.refused);return await new Promise<{ stdout: string; code: number | null }>((resolveSpawn, reject) => {const child = spawn(- cmd,- spawnArgs,+ invocation.command,+ invocation.args,withHiddenWindowsConsole({...LOCAL_OP_PIPE_STDIO_OPTIONS,- env: { ...process.env },+ env: invocation.env,}),);let settled = false;diff --git a/packages/server/src/local-ops/auth-flow.test.ts b/packages/server/src/local-ops/auth-flow.test.tsindex 253a5b47f..7dcd6546c 100644--- a/packages/server/src/local-ops/auth-flow.test.ts+++ b/packages/server/src/local-ops/auth-flow.test.ts@@ -1,19 +1,27 @@import { realpathSync } from 'node:fs';import { tmpdir } from 'node:os';+import { DEV_FALLBACK_CLI_REFUSAL, OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { type RunDeviceFlowController, runDeviceFlowSubprocess } from './auth-flow.ts';import type { AuthEvent } from './types.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];describe('runDeviceFlowSubprocess', () => {test('forwards verification + complete events parsed from stdout', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'verification', user_code:'ABCD', verification_uri:'https://example.com/login', expires_in:60}));console.log(JSON.stringify({type:'complete', host:'github.com', login:'me', name:'Me', email:'[email protected]', avatarUrl:'https://example.com/me.png'}));`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -37,7 +45,7 @@ describe('runDeviceFlowSubprocess', () => {test('synthesizes a complete event on clean exit without one (older CLI builds)', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`process.exit(0)`),+ cli: okCli(fixtureCli(`process.exit(0)`)),host: 'github.com',onEvent: (e) => events.push(e),});@@ -49,7 +57,7 @@ describe('runDeviceFlowSubprocess', () => {test('synthesized complete uses default host when not specified', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`process.exit(0)`),+ cli: okCli(fixtureCli(`process.exit(0)`)),onEvent: (e) => events.push(e),});await ctrl.done;@@ -59,7 +67,7 @@ describe('runDeviceFlowSubprocess', () => {test('emits structured error event on nonzero exit', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`process.exit(2)`),+ cli: okCli(fixtureCli(`process.exit(2)`)),onEvent: (e) => events.push(e),});await ctrl.done;@@ -73,7 +81,7 @@ describe('runDeviceFlowSubprocess', () => {test('emits "Sign-in timed out" error on timeout', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),timeoutMs: 100,onEvent: (e) => events.push(e),});@@ -88,10 +96,12 @@ describe('runDeviceFlowSubprocess', () => {test('CLI-emitted error event is forwarded and counts as terminal', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'error', message:'bad code'}));process.exit(0);`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -103,10 +113,12 @@ describe('runDeviceFlowSubprocess', () => {const events: AuthEvent[] = [];const token = `ghp_${'c'.repeat(36)}`;const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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;@@ -122,9 +134,11 @@ describe('runDeviceFlowSubprocess', () => {test('CLI-emitted error message that redacts to nothing falls back to "Unknown error"', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'error', message:' \\n '}));`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -134,13 +148,15 @@ describe('runDeviceFlowSubprocess', () => {test('a cancel landing after the timeout still reports the timeout', async () => {const events: AuthEvent[] = [];const ctrl: RunDeviceFlowController = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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);@@ -158,11 +174,13 @@ describe('runDeviceFlowSubprocess', () => {test('malformed JSON lines are silently dropped, not forwarded as errors', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log('this is not json');console.log(JSON.stringify({type:'verification', user_code:'X', verification_uri:'https://e.com', expires_in:60}));console.log(JSON.stringify({type:'complete', host:'github.com', login:'me'}));`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -172,10 +190,12 @@ describe('runDeviceFlowSubprocess', () => {test('verification events with missing required fields are dropped', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'verification', user_code:'X'}));console.log(JSON.stringify({type:'complete', host:'github.com', login:'me'}));`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -185,10 +205,12 @@ describe('runDeviceFlowSubprocess', () => {test('unknown JSON event types are dropped', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'keychain-probe', backend:'darwin'}));console.log(JSON.stringify({type:'complete', host:'github.com', login:'me'}));`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -198,10 +220,12 @@ describe('runDeviceFlowSubprocess', () => {test('non-zero exit folds the child stderr into the error message', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('spawn EINVAL');process.exitCode = 2;`),+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -217,10 +241,12 @@ describe('runDeviceFlowSubprocess', () => {const token = `ghp_${'a'.repeat(36)}`;const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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;@@ -235,10 +261,12 @@ describe('runDeviceFlowSubprocess', () => {const token = `ghp_${'f'.repeat(36)}`;const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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;@@ -249,13 +277,25 @@ describe('runDeviceFlowSubprocess', () => {}});+ test('a dev build without its workspace CLI refuses to sign in instead of running the CLI on PATH', async () => {+ const events: AuthEvent[] = [];+ const ctrl = runDeviceFlowSubprocess({+ cli: OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } }),+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toEqual([{ type: 'error', message: DEV_FALLBACK_CLI_REFUSAL }]);+ });+test('forwards cliEnv through to the spawned CLI', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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' },+ { OK_AUTH_FLOW_ENV_MARKER: 'marker-from-cli-env' },+ ),onEvent: (e) => events.push(e),});await ctrl.done;@@ -268,7 +308,7 @@ describe('runDeviceFlowSubprocess', () => {test('cancel terminates the subprocess without synthesizing an error event', async () => {const events: AuthEvent[] = [];const ctrl = runDeviceFlowSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),onEvent: (e) => events.push(e),});setTimeout(() => ctrl.cancel(), 50);@@ -282,8 +322,10 @@ test('device flow runs in the supplied project directory', async () => {const events: AuthEvent[] = [];const controller = runDeviceFlowSubprocess({cwd,- cliArgs: fixtureCli(- `console.log(JSON.stringify({type: 'complete', host: process.cwd(), login: 'octocat'}));`,+ cli: okCli(+ fixtureCli(+ `console.log(JSON.stringify({type: 'complete', host: process.cwd(), login: 'octocat'}));`,+ ),),onEvent: (event) => events.push(event),});diff --git a/packages/server/src/local-ops/auth-flow.ts b/packages/server/src/local-ops/auth-flow.tsindex 1494a6c4a..7fc2bf9d3 100644--- a/packages/server/src/local-ops/auth-flow.ts+++ b/packages/server/src/local-ops/auth-flow.ts@@ -1,5 +1,5 @@import { redactedStderrDetail, stderrDetailSuffix } from './clone-error-classify.ts';-import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';+import { type LocalOpCliInvocation, runOkCliSubprocess } from './subprocess.ts';import type { LocalOpSubprocessLifetime } from './subprocess-lifetime.ts';import type { AuthEvent } from './types.ts';@@ -57,10 +57,8 @@ export function runDeviceFlowSubprocess(opts: RunDeviceFlowOptions): RunDeviceFllet sawTerminal = false;- const proc = runSubprocess({+ const proc = runOkCliSubprocess(opts.cli, {lifetime: opts.lifetime,- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,cwd: opts.cwd,trailingArgs: ['auth', 'login', '--json', '--host', host],timeoutMs,@@ -78,6 +76,10 @@ export function runDeviceFlowSubprocess(opts: RunDeviceFlowOptions): RunDeviceFlconst done = proc.done.then((result) => {if (opts.lifetime?.stopped) return;+ if ('refused' in result) {+ opts.onEvent({ type: 'error', message: result.refused });+ return;+ }if (sawTerminal) return;if (result.timedOut) {opts.onEvent({ type: 'error', message: 'Sign-in timed out' });diff --git a/packages/server/src/local-ops/auth-pat.test.ts b/packages/server/src/local-ops/auth-pat.test.tsindex bf14efb56..3c388d22a 100644--- a/packages/server/src/local-ops/auth-pat.test.ts+++ b/packages/server/src/local-ops/auth-pat.test.ts@@ -1,6 +1,12 @@+import { OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { runPatSubprocess } from './auth-pat.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];const ECHO_STDIN_CLI = `@@ -19,7 +25,7 @@ process.stdin.on('end', () => {describe('runPatSubprocess', () => {test('feeds the token via stdin and returns the stored identity on complete', async () => {const result = await runPatSubprocess({- cliArgs: fixtureCli(ECHO_STDIN_CLI),+ cli: okCli(fixtureCli(ECHO_STDIN_CLI)),host: 'ghes.test',token: 'good-token',});@@ -28,7 +34,7 @@ describe('runPatSubprocess', () => {test('surfaces the CLI error message on a rejected token', async () => {const result = await runPatSubprocess({- cliArgs: fixtureCli(ECHO_STDIN_CLI),+ cli: okCli(fixtureCli(ECHO_STDIN_CLI)),host: 'ghes.test',token: 'wrong-token',});@@ -37,7 +43,7 @@ describe('runPatSubprocess', () => {test('falls back to a bounded generic error when the child exits with no terminal event', async () => {const result = await runPatSubprocess({- cliArgs: fixtureCli('process.exit(3)'),+ cli: okCli(fixtureCli('process.exit(3)')),host: 'ghes.test',token: 'x',});@@ -49,10 +55,12 @@ describe('runPatSubprocess', () => {test('folds the child stderr into the generic fallback error', async () => {const result = await runPatSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('spawn EINVAL');process.exitCode = 3;`),+ ),host: 'ghes.test',token: 'x',});@@ -66,10 +74,12 @@ describe('runPatSubprocess', () => {test('redacts credentialed stderr before it reaches the fallback error', async () => {const token = `ghp_${'b'.repeat(36)}`;const result = await runPatSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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,});@@ -83,10 +93,12 @@ describe('runPatSubprocess', () => {test('removes the submitted token from stderr even when no scrubber pattern knows its shape', async () => {const token = `${'a'.repeat(8)}0123456789abcdef0123456789abcdef`;const result = await runPatSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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,});@@ -100,10 +112,12 @@ describe('runPatSubprocess', () => {test('redacts a bare PAT in stderr other than the submitted token', async () => {const storedToken = `ghp_${'g'.repeat(36)}`;const result = await runPatSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${storedToken}");process.exitCode = 3;`),+ ),host: 'ghes.test',token: 'submitted-token',});@@ -116,7 +130,8 @@ describe('runPatSubprocess', () => {test('forwards cliEnv through to the spawned CLI', async () => {const result = await runPatSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`let d='';process.stdin.on('data', c => { d += c; });process.stdin.on('end', () => {@@ -124,7 +139,8 @@ describe('runPatSubprocess', () => {process.exit(0);});`),- cliEnv: { OK_AUTH_PAT_ENV_MARKER: 'marker-from-cli-env' },+ { OK_AUTH_PAT_ENV_MARKER: 'marker-from-cli-env' },+ ),host: 'ghes.test',token: 'good-token',});diff --git a/packages/server/src/local-ops/auth-pat.ts b/packages/server/src/local-ops/auth-pat.tsindex b98e5c318..f1ee380ab 100644--- a/packages/server/src/local-ops/auth-pat.ts+++ b/packages/server/src/local-ops/auth-pat.ts@@ -2,7 +2,7 @@ import { stderrDetailSuffix } from './clone-error-classify.ts';import {LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,type LocalOpCliInvocation,- runSubprocess,+ runOkCliSubprocess,} from './subprocess.ts';import type { LocalOpSubprocessLifetime } from './subprocess-lifetime.ts';@@ -21,10 +21,8 @@ export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResulconst host = opts.host ?? 'github.com';let terminal: RunPatResult | null = null;- const proc = runSubprocess({+ const proc = runOkCliSubprocess(opts.cli, {lifetime: opts.lifetime,- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,cwd: opts.cwd,trailingArgs: ['auth', 'pat', '--json', '--host', host, '--token-stdin'],stdinData: opts.token,@@ -48,6 +46,7 @@ export async function runPatSubprocess(opts: RunPatOptions): Promise<RunPatResul});const result = await proc.done;+ if ('refused' in result) return { ok: false, host, error: result.refused };if (terminal) return terminal;if (result.timedOut) return { ok: false, host, error: 'Token validation timed out.' };return {diff --git a/packages/server/src/local-ops/auth-query.test.ts b/packages/server/src/local-ops/auth-query.test.tsindex d5583edcb..c8ee5c8ec 100644--- a/packages/server/src/local-ops/auth-query.test.ts+++ b/packages/server/src/local-ops/auth-query.test.ts@@ -1,16 +1,24 @@import { realpathSync } from 'node:fs';import { tmpdir } from 'node:os';+import { OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { runAuthReposSubprocess, runAuthStatusSubprocess } from './auth-query.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];describe('runAuthStatusSubprocess', () => {test('parses an authenticated status emission', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'status', host:'github.com', authenticated:true, login:'octocat', name:'Octo Cat', email:'[email protected]'}));`),+ ),});expect(result).toEqual({authenticated: true,@@ -23,10 +31,12 @@ describe('runAuthStatusSubprocess', () => {test('parses an unauthenticated status emission (CLI exits 1, JSON still on stdout)', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'status', host:'github.com', authenticated:false}));process.exit(1);`),+ ),});expect(result).toEqual({authenticated: false,@@ -37,10 +47,12 @@ describe('runAuthStatusSubprocess', () => {test('forwards an "error" field on unauthenticated emissions (e.g. token invalid)', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'status', host:'github.com', authenticated:false, error:'token invalid'}));process.exit(1);`),+ ),});expect(result).toEqual({authenticated: false,@@ -51,10 +63,12 @@ describe('runAuthStatusSubprocess', () => {test('ignores non-status JSON lines, picks up the status one (older builds emit keychain probes)', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'keychain-probe', backend:'darwin'}));console.log(JSON.stringify({type:'status', host:'github.com', authenticated:true, login:'octocat'}));`),+ ),});expect(result.authenticated).toBe(true);if (result.authenticated) {@@ -64,7 +78,7 @@ describe('runAuthStatusSubprocess', () => {test('returns unauthenticated when no status line is emitted on clean exit', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`process.exit(0)`),+ cli: okCli(fixtureCli(`process.exit(0)`)),});expect(result).toEqual({authenticated: false,@@ -75,10 +89,12 @@ describe('runAuthStatusSubprocess', () => {test('surfaces stderr in error when CLI exits non-zero without a status line', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('bun: command not found: open-knowledge\\n');process.exit(127);`),+ ),});expect(result.authenticated).toBe(false);if (!result.authenticated) {@@ -88,7 +104,7 @@ describe('runAuthStatusSubprocess', () => {test('falls back to exit-code message when CLI exits non-zero without stderr', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`process.exit(2)`),+ cli: okCli(fixtureCli(`process.exit(2)`)),});expect(result.authenticated).toBe(false);if (!result.authenticated) {@@ -99,10 +115,12 @@ 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(`+ cli: okCli(+ 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) {@@ -113,10 +131,12 @@ describe('runAuthStatusSubprocess', () => {test('caps an overlong status stderr at the shared detail cap', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('x'.repeat(3000));process.exit(1);`),+ ),});expect(result.authenticated).toBe(false);if (!result.authenticated) {@@ -126,7 +146,7 @@ describe('runAuthStatusSubprocess', () => {test('reports a timeout-marker error when the subprocess hangs past timeoutMs', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),timeoutMs: 100,});expect(result.authenticated).toBe(false);@@ -137,9 +157,11 @@ describe('runAuthStatusSubprocess', () => {test.each(['A', 'B', 'C'] as const)('forwards tier %s through the parser', async (tier) => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'status', host:'github.com', authenticated:true, tier:'${tier}', login:'octocat'}));`),+ ),});expect(result.authenticated).toBe(true);if (result.authenticated) {@@ -149,9 +171,11 @@ describe('runAuthStatusSubprocess', () => {test('drops an unknown tier value (forward-compat: future tiers are ignored, not crashed)', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'status', host:'github.com', authenticated:true, tier:'Z', login:'octocat'}));`),+ ),});expect(result.authenticated).toBe(true);if (result.authenticated) {@@ -161,10 +185,12 @@ describe('runAuthStatusSubprocess', () => {test('forwards cliEnv through to the spawned CLI', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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' },+ { OK_AUTH_STATUS_ENV_MARKER: 'marker-from-cli-env' },+ ),});expect(result.authenticated).toBe(true);if (result.authenticated) {@@ -174,11 +200,13 @@ describe('runAuthStatusSubprocess', () => {test('uses a custom host when provided', async () => {const result = await runAuthStatusSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`// Echo the --host arg back to verify it was passed through.const host = process.argv[process.argv.indexOf('--host') + 1];console.log(JSON.stringify({type:'status', host, authenticated:false}));`),+ ),host: 'ghe.example.com',});expect(result.host).toBe('ghe.example.com');@@ -188,12 +216,14 @@ describe('runAuthStatusSubprocess', () => {describe('runAuthReposSubprocess', () => {test('parses a bounded repos response', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'repos', host:'github.com', repos:[{full_name:'octo/repo1', clone_url:'https://github.com/octo/repo1.git', private:false},{full_name:'octo/repo2', clone_url:'https://github.com/octo/repo2.git', private:true},]}));`),+ ),});expect(result.ok).toBe(true);if (result.ok) {@@ -210,7 +240,8 @@ describe('runAuthReposSubprocess', () => {test('drops malformed repo entries but keeps valid ones', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'repos', host:'github.com', repos:[{full_name:'good/one', clone_url:'https://github.com/good/one.git', private:false},{missing:'fields'},@@ -218,6 +249,7 @@ describe('runAuthReposSubprocess', () => {{full_name:'good/two', clone_url:'https://github.com/good/two.git'},]}));`),+ ),});expect(result.ok).toBe(true);if (result.ok) {@@ -228,10 +260,12 @@ describe('runAuthReposSubprocess', () => {test('returns an error when the CLI exits nonzero (e.g. not signed in)', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('Not logged in to github.com\\n');process.exit(1);`),+ ),});expect(result.ok).toBe(false);if (!result.ok) {@@ -241,10 +275,12 @@ describe('runAuthReposSubprocess', () => {test('flags the signed-out CLI exit as unauthenticated, not a command failure', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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) {@@ -261,10 +297,12 @@ describe('runAuthReposSubprocess', () => {],])('still flags %s as unauthenticated', async (_label, stderr) => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('${stderr}');process.exit(1);`),+ ),});expect(result.ok).toBe(false);if (!result.ok) {@@ -275,10 +313,12 @@ describe('runAuthReposSubprocess', () => {test('an auth.yml parse error beside the signed-out sentence stays a loggable failure', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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) {@@ -289,10 +329,12 @@ describe('runAuthReposSubprocess', () => {test('a genuine command failure carries no unauthenticated flag', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('spawn EINVAL\\n');process.exit(1);`),+ ),});expect(result.ok).toBe(false);if (!result.ok) {@@ -304,10 +346,12 @@ describe('runAuthReposSubprocess', () => {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(`+ cli: okCli(+ 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) {@@ -318,10 +362,12 @@ describe('runAuthReposSubprocess', () => {test('caps an overlong repos stderr at the shared detail cap', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('x'.repeat(3000));process.exit(1);`),+ ),});expect(result.ok).toBe(false);if (!result.ok) {@@ -331,7 +377,7 @@ describe('runAuthReposSubprocess', () => {test('returns an error when the CLI emits no repos line on clean exit', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`process.exit(0)`),+ cli: okCli(fixtureCli(`process.exit(0)`)),});expect(result.ok).toBe(false);if (!result.ok) {@@ -341,7 +387,7 @@ describe('runAuthReposSubprocess', () => {test('reports timeout error when the subprocess hangs', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),timeoutMs: 100,});expect(result.ok).toBe(false);@@ -352,12 +398,14 @@ describe('runAuthReposSubprocess', () => {test('forwards cliEnv through to the spawned CLI', async () => {const result = await runAuthReposSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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' },+ { OK_AUTH_REPOS_ENV_MARKER: 'marker/from-cli-env' },+ ),});expect(result.ok).toBe(true);if (result.ok) {@@ -374,8 +422,10 @@ for (const [name, run, type] of [const cwd = realpathSync(tmpdir());const response = await run({cwd,- cliArgs: fixtureCli(- `console.log(JSON.stringify({type: ${JSON.stringify(type)}, authenticated: true, login: 'octocat', repos: [], host: process.cwd()}));`,+ cli: okCli(+ fixtureCli(+ `console.log(JSON.stringify({type: ${JSON.stringify(type)}, authenticated: true, login: 'octocat', repos: [], host: process.cwd()}));`,+ ),),});expect(response).toMatchObject({ host: cwd });diff --git a/packages/server/src/local-ops/auth-query.ts b/packages/server/src/local-ops/auth-query.tsindex 6d9575c3e..0263f2419 100644--- a/packages/server/src/local-ops/auth-query.ts+++ b/packages/server/src/local-ops/auth-query.ts@@ -2,7 +2,7 @@ import { redactedStderrDetail } from './clone-error-classify.ts';import {LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,type LocalOpCliInvocation,- runSubprocess,+ runOkCliSubprocess,} from './subprocess.ts';const SIGNED_OUT_SENTENCE = /^not logged in to /i;@@ -50,9 +50,7 @@ export async function runAuthStatusSubprocess(): Promise<AuthStatusResponse> {const host = opts.host ?? 'github.com';const lines: Record<string, unknown>[] = [];- const proc = runSubprocess({- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,+ const proc = runOkCliSubprocess(opts.cli, {cwd: opts.cwd,trailingArgs: ['auth', 'status', '--json', '--host', host],timeoutMs: opts.timeoutMs ?? LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,@@ -61,6 +59,7 @@ export async function runAuthStatusSubprocess(},});const result = await proc.done;+ if ('refused' in result) return { authenticated: false, host, error: result.refused };for (let i = lines.length - 1; i >= 0; i--) {const line = lines[i] as Record<string, unknown>;if (line.type !== 'status') continue;@@ -99,9 +98,7 @@ export async function runAuthReposSubprocess(): Promise<AuthReposResponse> {const host = opts.host ?? 'github.com';const lines: Record<string, unknown>[] = [];- const proc = runSubprocess({- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,+ const proc = runOkCliSubprocess(opts.cli, {cwd: opts.cwd,trailingArgs: ['auth', 'repos', '--json', '--host', host],timeoutMs: opts.timeoutMs ?? LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,@@ -110,6 +107,7 @@ export async function runAuthReposSubprocess(},});const result = await proc.done;+ if ('refused' in result) return { ok: false, error: result.refused };if (result.timedOut) return { ok: false, error: 'auth repos timed out' };if (result.code !== 0) {const detail = redactedStderrDetail(result.stderr);diff --git a/packages/server/src/local-ops/auth-token.test.ts b/packages/server/src/local-ops/auth-token.test.tsindex cdf2fc45e..74430f420 100644--- a/packages/server/src/local-ops/auth-token.test.ts+++ b/packages/server/src/local-ops/auth-token.test.ts@@ -1,6 +1,12 @@+import { DEV_FALLBACK_CLI_REFUSAL, OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { runAuthTokenSubprocess } from './auth-token.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];const ECHO_STDIN_CLI = `@@ -28,7 +34,7 @@ process.stdin.on('end', () => {describe('runAuthTokenSubprocess', () => {test('feeds the token via stdin and returns the stored identity on complete', async () => {const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(ECHO_STDIN_CLI),+ cli: okCli(fixtureCli(ECHO_STDIN_CLI)),host: 'ghes.test',username: 'alice',token: 'good-token',@@ -38,7 +44,7 @@ describe('runAuthTokenSubprocess', () => {test('surfaces the CLI error message when the store fails', async () => {const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(ECHO_STDIN_CLI),+ cli: okCli(fixtureCli(ECHO_STDIN_CLI)),host: 'ghes.test',username: 'alice',token: 'wrong-token',@@ -52,7 +58,7 @@ describe('runAuthTokenSubprocess', () => {test('falls back to a bounded generic error when the child exits with no terminal event', async () => {const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli('process.exit(3)'),+ cli: okCli(fixtureCli('process.exit(3)')),host: 'ghes.test',username: 'alice',token: 'x',@@ -65,10 +71,12 @@ describe('runAuthTokenSubprocess', () => {test('folds the child stderr into the generic fallback error', async () => {const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('spawn EINVAL');process.exitCode = 3;`),+ ),host: 'ghes.test',username: 'alice',token: 'x',@@ -83,7 +91,7 @@ describe('runAuthTokenSubprocess', () => {test('keeps the token out of the child argv while passing the username through', async () => {const token = 'argv-must-not-carry-this-token';const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(ECHO_ARGV_CLI),+ cli: okCli(fixtureCli(ECHO_ARGV_CLI)),host: 'ghes.test',username: 'alice',token,@@ -103,10 +111,12 @@ describe('runAuthTokenSubprocess', () => {test('redacts credentialed stderr before it reaches the fallback error', async () => {const token = `ghp_${'b'.repeat(36)}`;const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write("fatal: unable to access 'https://x-access-token:${token}@ghes.test/o/r.git/'");process.exitCode = 3;`),+ ),host: 'ghes.test',username: 'alice',token,@@ -121,10 +131,12 @@ describe('runAuthTokenSubprocess', () => {test('redacts a bare PAT in stderr other than the submitted token', async () => {const storedToken = `ghp_${'g'.repeat(36)}`;const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${storedToken}");process.exitCode = 3;`),+ ),host: 'ghes.test',username: 'alice',token: 'submitted-token',@@ -139,10 +151,12 @@ describe('runAuthTokenSubprocess', () => {test('removes the submitted token from stderr even when no scrubber pattern knows its shape', async () => {const token = `${'a'.repeat(8)}0123456789abcdef0123456789abcdef`;const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write("[auth] Failed to parse auth.yml: bad indentation at line 2:\\n token: ${token}");process.exitCode = 3;`),+ ),host: 'gitea.internal',username: 'alice',token: `${token}\n`,@@ -154,9 +168,24 @@ describe('runAuthTokenSubprocess', () => {}});+ test('a dev build without its workspace CLI refuses to store a token instead of running the CLI on PATH', async () => {+ const result = await runAuthTokenSubprocess({+ cli: OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } }),+ host: 'github.com',+ username: 'octocat',+ token: 'test-token',+ });+ expect(result).toEqual({+ ok: false,+ host: 'github.com',+ error: DEV_FALLBACK_CLI_REFUSAL,+ });+ });+test('forwards cliEnv through to the spawned CLI', async () => {const result = await runAuthTokenSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`let d='';process.stdin.on('data', c => { d += c; });process.stdin.on('end', () => {@@ -164,7 +193,8 @@ describe('runAuthTokenSubprocess', () => {process.exit(0);});`),- cliEnv: { OK_AUTH_TOKEN_ENV_MARKER: 'marker-from-cli-env' },+ { OK_AUTH_TOKEN_ENV_MARKER: 'marker-from-cli-env' },+ ),host: 'ghes.test',username: 'alice',token: 'good-token',diff --git a/packages/server/src/local-ops/auth-token.ts b/packages/server/src/local-ops/auth-token.tsindex c13045f22..475fb29b6 100644--- a/packages/server/src/local-ops/auth-token.ts+++ b/packages/server/src/local-ops/auth-token.ts@@ -2,7 +2,7 @@ import { stderrDetailSuffix } from './clone-error-classify.ts';import {LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS,type LocalOpCliInvocation,- runSubprocess,+ runOkCliSubprocess,} from './subprocess.ts';import type { LocalOpSubprocessLifetime } from './subprocess-lifetime.ts';@@ -24,10 +24,8 @@ export async function runAuthTokenSubprocess(const host = opts.host;let terminal: RunAuthTokenResult | null = null;- const proc = runSubprocess({+ const proc = runOkCliSubprocess(opts.cli, {lifetime: opts.lifetime,- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,trailingArgs: ['auth','token',@@ -59,6 +57,7 @@ export async function runAuthTokenSubprocess(});const result = await proc.done;+ if ('refused' in result) return { ok: false, host, error: result.refused };if (terminal) return terminal;if (result.timedOut) return { ok: false, host, error: 'Storing the token timed out.' };return {diff --git a/packages/server/src/local-ops/clone-flow.preflight.test.ts b/packages/server/src/local-ops/clone-flow.preflight.test.tsindex c85d1527f..ab70f1516 100644--- a/packages/server/src/local-ops/clone-flow.preflight.test.ts+++ b/packages/server/src/local-ops/clone-flow.preflight.test.ts@@ -1,6 +1,7 @@import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { delimiter, isAbsolute, join } from 'node:path';+import { OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import {__resetResolveOnPathCacheForTests,@@ -13,6 +14,11 @@ import {} from '../git-unusable-setup.test-helper.ts';import { type RawCloneEvent, runCloneSubprocess } from './clone-flow.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];const RAW_GIT_FAILURE_CLI = fixtureCli(`process.stderr.write("xcrun: error: unable to load libxcrun (... incompatible architecture (have 'arm64', need 'arm64e')) ...\\n"); process.exit(128);`,@@ -51,7 +57,7 @@ describe('runCloneSubprocess — git-preflight at the clone-setup boundary (#356let controller: ReturnType<typeof runCloneSubprocess> | undefined;try {controller = runCloneSubprocess({- cliArgs: RAW_GIT_FAILURE_CLI,+ cli: okCli(RAW_GIT_FAILURE_CLI),url: 'https://github.com/octocat/hello.git',dir,timeoutMs: 30_000,@@ -91,7 +97,7 @@ describe('runCloneSubprocess — clone-child PATH binding (#356)', () => {try {await withBrokenBareGitOnly(async () => {const controller = runCloneSubprocess({- cliArgs: pathCapturingCli(pathFile, dir),+ cli: okCli(pathCapturingCli(pathFile, dir)),url: 'https://github.com/octocat/hello.git',dir,timeoutMs: 30_000,@@ -116,7 +122,7 @@ describe('runCloneSubprocess — clone-child PATH binding (#356)', () => {__seedResolveOnPathCacheForTests('git', 'git');try {const controller = runCloneSubprocess({- cliArgs: pathCapturingCli(pathFile, dir),+ cli: okCli(pathCapturingCli(pathFile, dir)),url: 'https://github.com/octocat/hello.git',dir,timeoutMs: 30_000,diff --git a/packages/server/src/local-ops/clone-flow.test.ts b/packages/server/src/local-ops/clone-flow.test.tsindex b9241bcff..a02316141 100644--- a/packages/server/src/local-ops/clone-flow.test.ts+++ b/packages/server/src/local-ops/clone-flow.test.ts@@ -1,5 +1,6 @@import { homedir } from 'node:os';import { join } from 'node:path';+import { DEV_FALLBACK_CLI_REFUSAL, OkCliCommand } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import { classifyCloneError } from './clone-error-classify.ts';import {@@ -10,6 +11,11 @@ import {validateCloneInputs,} from './clone-flow.ts';+const okCli = (+ cliArgs: readonly string[],+ cliEnv?: Readonly<Record<string, string | undefined>>,+): OkCliCommand => OkCliCommand.resolve({ host: { cliArgs, cliEnv }, env: {} });+const HOME_PATH = join(homedir(), 'open-knowledge-test-clone');const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];@@ -18,11 +24,13 @@ describe('runCloneSubprocess', () => {test('forwards progress + complete events parsed from stdout', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'progress', phase:'receiving', pct:25}));console.log(JSON.stringify({type:'progress', phase:'resolving', pct:80}));console.log(JSON.stringify({type:'complete', dir:'/tmp/cloned-repo'}));`),+ ),url: 'https://github.com/octocat/hello.git',dir: '/tmp/cloned-repo',onEvent: (e) => events.push(e),@@ -34,13 +42,27 @@ describe('runCloneSubprocess', () => {expect(events[2]).toEqual({ type: 'complete', dir: '/tmp/cloned-repo' });});+ test('a dev build without its workspace CLI reports the refusal and clones nothing', async () => {+ const events: RawCloneEvent[] = [];+ const ctrl = runCloneSubprocess({+ cli: OkCliCommand.resolve({ env: { OK_CHANNEL: 'dev' } }),+ url: 'https://github.com/octocat/hello.git',+ dir: '/tmp/cloned-repo',+ onEvent: (e) => events.push(e),+ });+ await ctrl.done;+ expect(events).toEqual([{ type: 'error', message: DEV_FALLBACK_CLI_REFUSAL }]);+ });+test('emits structured error event on nonzero exit, including stderr detail', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('fatal: repository not found\\n');process.exit(128);`),+ ),url: 'https://github.com/octocat/missing.git',dir: '/tmp/missing',onEvent: (e) => events.push(e),@@ -58,10 +80,12 @@ describe('runCloneSubprocess', () => {const events: RawCloneEvent[] = [];const token = `ghp_${'a'.repeat(36)}`;const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write("fatal: could not read Password for 'https://${token}@github.com': terminal prompts disabled\\n");process.exit(128);`),+ ),url: 'https://github.com/octocat/private.git',dir: '/tmp/private',onEvent: (e) => events.push(e),@@ -80,10 +104,12 @@ describe('runCloneSubprocess', () => {test('caps a very long stderr detail so the toast stays readable', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write('x'.repeat(3000) + '\\n');process.exit(128);`),+ ),url: 'https://github.com/octocat/huge.git',dir: '/tmp/huge',onEvent: (e) => events.push(e),@@ -100,10 +126,12 @@ describe('runCloneSubprocess', () => {test('whitespace-only stderr produces no dangling detail separator', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stderr.write(' \\n');process.exit(128);`),+ ),url: 'https://github.com/octocat/blank.git',dir: '/tmp/blank',onEvent: (e) => events.push(e),@@ -119,7 +147,7 @@ describe('runCloneSubprocess', () => {test('emits "Clone timed out" error on timeout', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),url: 'https://github.com/octocat/slow.git',dir: '/tmp/slow',timeoutMs: 100,@@ -136,10 +164,12 @@ describe('runCloneSubprocess', () => {test('CLI-emitted error event is forwarded as terminal — no second event synthesized', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'error', message:'permission denied'}));process.exit(0);`),+ ),url: 'https://github.com/octocat/locked.git',dir: '/tmp/locked',onEvent: (e) => events.push(e),@@ -152,7 +182,8 @@ describe('runCloneSubprocess', () => {test('an unsafe-symlink refusal reaches the consumer with fixed wording and a structured path list', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type: 'error',code: 'unsafe-symlinks',@@ -160,6 +191,7 @@ describe('runCloneSubprocess', () => {refusedSymlinkPaths: ['docs/permission denied.md', 42, ''],}));`),+ ),url: 'https://github.com/octocat/linked.git',dir: '/tmp/linked',onEvent: (e) => events.push(e),@@ -180,10 +212,12 @@ describe('runCloneSubprocess', () => {const events: RawCloneEvent[] = [];const token = `ghp_${'b'.repeat(36)}`;const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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),@@ -201,9 +235,11 @@ describe('runCloneSubprocess', () => {test('CLI-emitted error message that redacts to nothing falls back to "Unknown error"', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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),@@ -215,13 +251,15 @@ describe('runCloneSubprocess', () => {test('a cancel landing after the timeout still reports the timeout', async () => {const events: RawCloneEvent[] = [];const ctrl: RunCloneController = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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,@@ -241,10 +279,12 @@ describe('runCloneSubprocess', () => {test('progress events with missing fields are dropped', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'progress', phase:'receiving'}));console.log(JSON.stringify({type:'complete', dir:'/tmp/x'}));`),+ ),url: 'https://github.com/x/y.git',dir: '/tmp/x',onEvent: (e) => events.push(e),@@ -256,13 +296,15 @@ describe('runCloneSubprocess', () => {test('synthesizes a complete event when CLI exits 0 without emitting one', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`// Emit only an invalid (missing dir) line, then clean exit. The runner// ignores the malformed line and synthesizes a complete from opts.dir// so the IPC stream consumer's iterator can resolve.console.log(JSON.stringify({type:'complete'}));process.exit(0);`),+ ),url: 'https://github.com/x/y.git',dir: HOME_PATH,onEvent: (e) => events.push(e),@@ -275,10 +317,12 @@ describe('runCloneSubprocess', () => {test('unknown JSON event types are dropped, terminal still detected', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`console.log(JSON.stringify({type:'unknown-event', stuff:'ignored'}));console.log(JSON.stringify({type:'complete', dir:'/tmp/y'}));`),+ ),url: 'https://github.com/x/y.git',dir: '/tmp/y',onEvent: (e) => events.push(e),@@ -290,7 +334,7 @@ describe('runCloneSubprocess', () => {test('cancel SIGTERMs the subprocess without synthesizing an error event', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`setInterval(() => {}, 1000)`),+ cli: okCli(fixtureCli(`setInterval(() => {}, 1000)`)),url: 'https://github.com/x/y.git',dir: '/tmp/y',onEvent: (e) => events.push(e),@@ -303,10 +347,12 @@ describe('runCloneSubprocess', () => {test('forwards cliEnv through to the spawned CLI', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ 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' },+ { 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),@@ -318,11 +364,13 @@ describe('runCloneSubprocess', () => {test('handles a chunked stream that splits a JSON line across writes', async () => {const events: RawCloneEvent[] = [];const ctrl = runCloneSubprocess({- cliArgs: fixtureCli(`+ cli: okCli(+ fixtureCli(`process.stdout.write('{"type":"prog');setTimeout(() => process.stdout.write('ress","phase":"receiving","pct":50}\\n'), 30);setTimeout(() => console.log(JSON.stringify({type:'complete', dir:'/tmp/c'})), 60);`),+ ),url: 'https://github.com/x/y.git',dir: '/tmp/c',onEvent: (e) => events.push(e),diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.tsindex 4031c857b..dee4ab3d3 100644--- a/packages/server/src/local-ops/clone-flow.ts+++ b/packages/server/src/local-ops/clone-flow.ts@@ -10,7 +10,7 @@ import { emitPreflightFailureSpan } from '../git-preflight-telemetry.ts';import { expandTilde, isAllowedGitUrl, isSafeLocalPath } from '../local-op-security.ts';import { getLogger } from '../logger.ts';import { redactedStderrDetail, stderrDetailSuffix } from './clone-error-classify.ts';-import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';+import { type LocalOpCliInvocation, runOkCliSubprocess } from './subprocess.ts';const log = getLogger('clone-flow');@@ -130,9 +130,7 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {const branchArgs =typeof opts.branch === 'string' && opts.branch.length > 0 ? ['-b', opts.branch] : [];- const proc = runSubprocess({- cliArgs: opts.cliArgs,- cliEnv: opts.cliEnv,+ const proc = runOkCliSubprocess(opts.cli, {trailingArgs: ['clone', '--json', ...branchArgs, opts.url, targetDir],extraPathDirs,timeoutMs,@@ -148,6 +146,10 @@ export function runCloneSubprocess(opts: RunCloneOptions): RunCloneController {});const done = proc.done.then((result) => {+ if ('refused' in result) {+ opts.onEvent({ type: 'error', message: result.refused });+ return;+ }if (sawTerminal) return;if (result.timedOut) {opts.onEvent({ type: 'error', message: 'Clone timed out after 10 minutes' });diff --git a/packages/server/src/local-ops/subprocess.test.ts b/packages/server/src/local-ops/subprocess.test.tsindex 7a0aba96c..cc2a33f5b 100644--- a/packages/server/src/local-ops/subprocess.test.ts+++ b/packages/server/src/local-ops/subprocess.test.ts@@ -242,6 +242,33 @@ describe('runSubprocess — cliEnv overlay', () => {});});+ test('an inherited dev channel reaches the child only through the overlay', async () => {+ const previous = process.env.OK_CHANNEL;+ process.env.OK_CHANNEL = 'dev';+ const channelCli = fixtureCli(+ `process.stdout.write(JSON.stringify({ channel: process.env.OK_CHANNEL ?? null }))`,+ );+ const channelOf = async (cliEnv?: Record<string, string>): Promise<unknown> => {+ const lines: { parsed: Record<string, unknown> | null }[] = [];+ const proc = runSubprocess({+ cliArgs: channelCli,+ ...(cliEnv === undefined ? {} : { cliEnv }),+ trailingArgs: [],+ timeoutMs: 5000,+ onLine: (line) => lines.push(line),+ });+ await proc.done;+ return lines[0]?.parsed?.channel;+ };+ try {+ expect(await channelOf()).toBeNull();+ expect(await channelOf({ OK_CHANNEL: 'dev' })).toBe('dev');+ } finally {+ if (previous === undefined) delete process.env.OK_CHANNEL;+ else process.env.OK_CHANNEL = previous;+ }+ });+test('no overlay leaves the inherited environment untouched', async () => {await withInheritedB(async () => {const lines: { parsed: Record<string, unknown> | null }[] = [];diff --git a/packages/server/src/local-ops/subprocess.ts b/packages/server/src/local-ops/subprocess.tsindex d96e3a584..084b52558 100644--- a/packages/server/src/local-ops/subprocess.ts+++ b/packages/server/src/local-ops/subprocess.ts@@ -1,5 +1,10 @@import { spawn } from 'node:child_process';import { posix, win32 } from 'node:path';+import {+ envWithoutDevChannel,+ type OkCliCommand,+ type OkCliRefusal,+} from '@inkeep/open-knowledge-core';import { withHiddenWindowsConsole } from '../child-process-windows-hide.ts';import type { LocalOpSubprocessLifetime } from './subprocess-lifetime.ts';@@ -13,12 +18,14 @@ type LocalOpCliEnv = Readonly<Record<string, string | undefined>>;export const LOCAL_OP_AUTH_SUBPROCESS_TIMEOUT_MS = 30_000;export interface LocalOpCliInvocation {- readonly cliArgs: readonly string[];- readonly cliEnv?: LocalOpCliEnv;+ readonly cli: OkCliCommand;readonly cwd?: string;}-interface SubprocessRunOptions extends LocalOpCliInvocation {+interface SubprocessRunOptions {+ readonly cliArgs: readonly string[];+ readonly cliEnv?: LocalOpCliEnv;+ readonly cwd?: string;lifetime?: LocalOpSubprocessLifetime;trailingArgs: readonly string[];extraPathDirs?: readonly string[];@@ -41,6 +48,13 @@ interface SubprocessController {cancel(): void;}+type OkCliRunResult = SubprocessRunResult | OkCliRefusal;++interface OkCliSubprocessController {+ done: Promise<OkCliRunResult>;+ cancel(): void;+}+function overlayEnvEntry(env: NodeJS.ProcessEnv,key: string,@@ -130,7 +144,12 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessControllerconst stderrChunks: Buffer[] = [];const platform = opts.platform ?? process.platform;- const childEnv = buildOverlaidEnv(process.env, opts.cliEnv, opts.extraPathDirs, platform);+ const childEnv = buildOverlaidEnv(+ envWithoutDevChannel(process.env),+ opts.cliEnv,+ opts.extraPathDirs,+ platform,+ );const stdio: ['ignore' | 'pipe', 'pipe', 'pipe'] =opts.stdinData !== undefined ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'];@@ -231,3 +250,14 @@ export function runSubprocess(opts: SubprocessRunOptions): SubprocessController},};}++export function runOkCliSubprocess(+ cli: OkCliCommand,+ opts: Omit<SubprocessRunOptions, 'cliArgs' | 'cliEnv'>,+): OkCliSubprocessController {+ const invocation = cli.runnerInvocation(opts.trailingArgs);+ if ('refused' in invocation) {+ return { done: Promise.resolve({ refused: invocation.refused }), cancel: () => {} };+ }+ return runSubprocess({ ...opts, ...invocation, trailingArgs: [] });+}diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.tsindex 38678a925..8eec4e0bd 100644--- a/packages/server/src/process-lock.test.ts+++ b/packages/server/src/process-lock.test.ts@@ -730,6 +730,17 @@ describe('channel metadata (one writer per project across channels)', () => {expect(detailed.status === 'live' ? detailed.lock.channel : null).toBe('beta');});+ test('a dev build records the dev channel, not Stable', () => {+ vi.stubEnv('OK_CHANNEL', 'dev');+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/me' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.channel).toBe('dev');+ });+test('a lock with no channel reads back without one, and a channel this build does not know is kept', () => {mkdirSync(lockDir, { recursive: true });for (const channel of [undefined, 'cloud']) {diff --git a/turbo.json b/turbo.jsonindex 223ba40bc..95ac2c9f2 100644--- a/turbo.json+++ b/turbo.json@@ -41,6 +41,7 @@"cache": false,"persistent": true,"passThroughEnv": [+ "OK_CHANNEL","OK_INSTANCE","OK_AUTO_INSTANCE","OK_DEV_PROTOCOL",