Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): extend Windows console-hide to CLI spawns + enforce with a lint rule (#2533)
mike-inkeep5f749b2e9274
diff --git a/.changeset/windows-console-flash-cli.md b/.changeset/windows-console-flash-cli.mdnew file mode 100644index 000000000..be02eb38c--- /dev/null+++ b/.changeset/windows-console-flash-cli.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Windows: hide the remaining brief console windows that could flash during CLI and MCP operations. A recent release stopped the server's per-edit `git` reads from popping a console window; this extends the same hiding to the hand-rolled `child_process` spawns on the CLI side — the MCP host launching the server (`ok start`) and the UI (`ok ui`), the git worktree probe, project-root detection, `share` git calls, the `npm` uninstall step, the browser opener (`cmd /c start`), and diagnostics. Each now runs with the console hidden. No effect on macOS or Linux (the flag is a no-op there).diff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 216c2cf7c..addded3bb 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -184,6 +184,29 @@ The rule does NOT catch:Plugin: [`biome-plugins/no-inline-tolerance-class.grit`](no-inline-tolerance-class.grit). Fixture: [`biome-plugins/__fixtures__/no-inline-tolerance-class.fixture.tsx`](__fixtures__/no-inline-tolerance-class.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts`](../packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+### `require-windowshide-on-spawn.grit`++Windows console-flash prevention. Every hand-rolled `node:child_process` process-spawn (`spawn` / `spawnSync` / `execSync` / `execFile` / `execFileSync`, plus the repo aliases `nodeSpawn` and `execFileAsync`) must hide the Windows console it would otherwise pop — either by wrapping its options in `withHiddenWindowsConsole(...)` (from `@inkeep/open-knowledge-server`, the preferred form shared with the server package) or by an inline `windowsHide: true`.++**Why.** On Windows, `windowsHide` defaults to `false`. When a console-LESS parent — the OK server auto-started by an MCP host with `stdio: 'ignore'`, or spawned detached — spawns a console-subsystem binary like `git.exe`, Windows creates a new console window that flashes on screen and vanishes, once per spawn. During an editing / agent-write session the per-edit `git` reads produce a steady stream of these. Hiding the console fixes it. The flag is a **no-op on both macOS and Linux** (neither allocates a console for child processes), so it is applied uniformly regardless of the command's target platform.++`simple-git` already sets `windowsHide: true` internally, so git routed through it (shadow repo, share, conflicts) is out of scope by nature — this rule governs only the hand-rolled call sites that bypass it.++**Scoped via `overrides[].plugins`** to `packages/{server,cli}/src/**/*.ts` (the packages that spawn processes at runtime on Windows), with `!**/*.test.ts` + `!**/*.test-helper.ts` excluded. `packages/desktop` is deliberately **out of scope** — the Electron app is macOS-only and never runs on Windows.++**Opting out (macOS/Linux-only spawns).** For a spawn that only ever runs on macOS and/or Linux — `codesign`, `sw_vers`, an `open(1)` launch — hiding a console is meaningless. Either add the flag anyway (a harmless no-op that keeps the rule uniform) or suppress that one call with a reason:++```ts+// biome-ignore lint/plugin/require-windowshide-on-spawn: macOS-only (never spawned on Windows)+const r = spawnSync('codesign', [...], { ... });+```++Reference opt-out in the tree: [`packages/cli/src/commands/diagnose-health-checks/macos-codesig.ts`](../packages/cli/src/commands/diagnose-health-checks/macos-codesig.ts). Same-named wrapper false positives (a local `const spawn = deps.spawnDetached ?? …`, or an injected `spawn` param) use the same suppression with a "not node:child_process" reason.++The rule does NOT catch: bare `exec(...)` (the identifier is too commonly shadowed); member calls (`deps.spawn(...)` — a different AST, so the real impl behind the injection is the enforced site); a `windowsHide` / `withHiddenWindowsConsole` written inside a spawn's callback body (would spuriously satisfy the check — no realistic occurrence).++Plugin: [`biome-plugins/require-windowshide-on-spawn.grit`](require-windowshide-on-spawn.grit). Fixture: [`biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx`](__fixtures__/require-windowshide-on-spawn.fixture.tsx). Test: [`packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts`](../packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+## SuppressionInline `// biome-ignore` comments silence individual diagnostics. The most specific form names the rule and the reason:diff --git a/biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx b/biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsxnew file mode 100644index 000000000..b32a17c2f--- /dev/null+++ b/biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx@@ -0,0 +1,57 @@+// FIXTURE — drives `require-windowshide-on-spawn.test.ts` via shell-out to+// `bunx biome check`. Not part of the main lint (override scope keeps the rule+// off this fixture's path under normal `bun run lint`; the test explicitly+// invokes biome on this file path via the fixture self-include in the+// override's `includes[]`).+//+// 7 expected diagnostic fires (one per spawn that hides neither via+// `windowsHide: true` nor `withHiddenWindowsConsole(...)`):+// P1 spawn, no options P5 execSync, options w/o hide+// P2 spawnSync, options w/o hide P6 nodeSpawn, options w/o hide+// P3 execFile, callback no opts P7 execFileAsync, options w/o hide+// P4 execFileSync, options w/o hide+//+// Negatives (0 fires): inline `windowsHide: true`, the `withHiddenWindowsConsole`+// helper (both the options-wrapping and the no-options `({})` forms), a member+// call (`deps.spawn` — different AST), a differently-named helper, and bare+// `exec` (intentionally outside the matcher). Exact-equality (`toBe(7)`)+// catches false-negative regressions (< 7) and false-positive widenings (> 7).++type Opts = Record<string, unknown>;+type Cb = (err: unknown) => void;+declare function spawn(cmd: string, args: string[], opts?: Opts): unknown;+declare function spawnSync(cmd: string, args: string[], opts?: Opts): unknown;+declare function exec(cmd: string, opts?: Opts): unknown;+declare function execSync(cmd: string, opts?: Opts): unknown;+declare function execFile(cmd: string, args: string[], opts?: Opts | Cb, cb?: Cb): unknown;+declare function execFileSync(cmd: string, args: string[], opts?: Opts): unknown;+declare function nodeSpawn(cmd: string, args: string[], opts?: Opts): unknown;+declare function execFileAsync(cmd: string, args: string[], opts?: Opts): unknown;+declare function withHiddenWindowsConsole<T extends object>(o: T): T & { windowsHide: true };+declare const deps: { spawn: (cmd: string, args: string[]) => unknown };+declare function mySpawnHelper(cmd: string, args: string[]): unknown;++// === Positive cases — must fire (7 total) ===++export const p1 = spawn('git', ['status']);+export const p2 = spawnSync('git', ['status'], { cwd: '.' });+export const p3 = execFile('git', ['status'], (_e: unknown) => {});+export const p4 = execFileSync('git', ['status'], { cwd: '.' });+export const p5 = execSync('git status', { cwd: '.' });+export const p6 = nodeSpawn('git', ['status'], { stdio: 'ignore' });+export const p7 = execFileAsync('git', ['status'], { cwd: '.' });++// === Negative cases — must NOT fire ===++// (1) Inline flag.+export const n1 = spawn('git', ['status'], { windowsHide: true });+// (2-3) The withHiddenWindowsConsole helper — options-wrapping and no-options forms.+export const n2 = spawnSync('git', ['status'], withHiddenWindowsConsole({ cwd: '.' }));+export const n3 = execFile('git', ['status'], withHiddenWindowsConsole({}), (_e: unknown) => {});+// (4) Member call — different AST; the real impl behind an injected `deps.spawn`+// is the enforced site, not the injection point.+export const n4 = deps.spawn('git', ['status']);+// (5) A differently-named helper — the rule matches literal callee identifiers.+export const n5 = mySpawnHelper('git', ['status']);+// (6) Bare `exec` — intentionally outside the matcher (documented gap).+export const n6 = exec('git status');diff --git a/biome-plugins/require-windowshide-on-spawn.grit b/biome-plugins/require-windowshide-on-spawn.gritnew file mode 100644index 000000000..a3371b15d--- /dev/null+++ b/biome-plugins/require-windowshide-on-spawn.grit@@ -0,0 +1,77 @@+// require-windowshide-on-spawn — Windows console-flash prevention.+//+// Every `node:child_process` process-spawn (`spawn`, `spawnSync`, `exec`,+// `execSync`, `execFile`, `execFileSync`, plus the repo's `nodeSpawn` /+// `execFileAsync` aliases) MUST hide the Windows console window it would+// otherwise pop. Two accepted forms:+//+// spawnSync('git', args, withHiddenWindowsConsole({ cwd, ... })) // preferred+// spawnSync('git', args, { cwd, ..., windowsHide: true }) // inline+//+// Why: on Windows, `windowsHide` defaults to `false`. When a console-LESS+// parent (the OK server auto-started by an MCP host with `stdio:'ignore'`, or+// spawned detached) spawns a console-subsystem binary like `git.exe`, Windows+// creates a new console window that flashes on screen and vanishes — once per+// spawn. During an editing / agent-write session the per-write `git config`+// attribution reads fire a burst of these, so the flashing is continuous and+// user-visible. Hiding it fixes that. It is a harmless no-op on macOS AND+// Linux (neither has the Windows console-allocation behavior), so it belongs+// on EVERY spawn regardless of the command's target platform — uniform+// application is what makes the rule enforceable. `withHiddenWindowsConsole`+// lives in `packages/server/src/child-process-windows-hide.ts` and is+// re-exported from `@inkeep/open-knowledge-server`.+//+// `simple-git` already sets `windowsHide: true` internally, so git routed+// through it (shadow repo, share, conflicts) is unaffected — this rule is only+// about the hand-rolled `child_process` call sites that bypass it.+//+// OPTING OUT — for a spawn that only ever runs on macOS and/or Linux (never+// Windows), e.g. `codesign`, `sw_vers`, an `open(1)` launch, hiding a console+// is meaningless. Add `windowsHide` anyway (harmless no-op, keeps the rule+// uniform) OR suppress this one call with a reason:+//+// // biome-ignore lint/plugin/require-windowshide-on-spawn: macOS-only (never spawned on Windows)+// const r = spawnSync('codesign', [...], { ... });+//+// Scoped via `overrides[].plugins` to `packages/{server,cli}/src/**` — the+// packages that spawn processes at runtime on Windows. `packages/desktop` is+// macOS-only (the Electron app never runs on Windows), so it is out of scope.+//+// The rule keys on the CALL-EXPRESSION CALLEE IDENTIFIER, so it can't tell a+// real `node:child_process` import from a same-named wrapper. A few call sites+// bind a local `const spawn = deps.spawnDetached ?? spawnDetachedReal` (already+// windows-safe) or take an injected `spawn` param — those are false positives;+// suppress with the biome-ignore line above and a "not node:child_process"+// reason.+//+// Known gaps (documented honestly): bare `exec(...)` is NOT matched (the+// identifier is too commonly shadowed); member calls (`deps.spawn(...)`) are+// not matched (different AST — the real impl behind the injection is the+// enforced site); injected spawn-wrapper aliases (`const spawnFn = opts.spawn ??+// realSpawn; spawnFn(...)`) are NOT matched by callee name, so those call sites+// are hidden by hand (`windowsHide: true` at the site) rather than enforced here+// — adding `spawnFn` to the matcher would flag the by-reference options-var+// wrappers (e.g. skill-install's `detached`) as false positives; a `windowsHide`+// / `withHiddenWindowsConsole` written inside a spawn's callback body would+// spuriously satisfy the check (no realistic case).+//+// See PRECEDENTS.md #42 (custom Biome enforcement is GritQL plugins).++language js++or {+ `spawn($...)` as $call,+ `spawnSync($...)` as $call,+ `execSync($...)` as $call,+ `execFile($...)` as $call,+ `execFileSync($...)` as $call,+ `nodeSpawn($...)` as $call,+ `execFileAsync($...)` as $call+} where {+ not $call <: contains `windowsHide: $_`,+ not $call <: contains `withHiddenWindowsConsole($...)`,+ register_diagnostic(+ span = $call,+ message = "child_process spawn without a hidden Windows console — wrap the options in `withHiddenWindowsConsole(...)` (from @inkeep/open-knowledge-server) or add `windowsHide: true`. On Windows a console-less parent (MCP-spawned/detached OK server) flashes a terminal window on every spawn; the flag is a no-op on macOS/Linux, so add it unconditionally. macOS/Linux-only spawn, or a same-named wrapper (not node:child_process)? suppress with `// biome-ignore lint/plugin/require-windowshide-on-spawn: <reason>`. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#require-windowshide-on-spawngrit"+ )+}diff --git a/biome.jsonc b/biome.jsoncindex e8695cdc7..303c81198 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -104,6 +104,24 @@],"plugins": ["./biome-plugins/class-proof-registration-discipline.grit"]},+ {+ // Windows console-flash prevention: every hand-rolled `child_process`+ // spawn in the runtime-spawning packages must hide the Windows console+ // (via `withHiddenWindowsConsole(...)` or `windowsHide: true`), else a+ // console-less parent (MCP-spawned/detached OK server) flashes a terminal+ // window per spawn on Windows. Scoped to server + cli (the packages that+ // spawn on Windows); `packages/desktop` is macOS-only and out of scope.+ // Tests excluded. `simple-git` sets the flag internally, so git routed+ // through it is out of scope by nature.+ "includes": [+ "packages/server/src/**/*.ts",+ "packages/cli/src/**/*.ts",+ "!**/*.test.ts",+ "!**/*.test-helper.ts",+ "biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx"+ ],+ "plugins": ["./biome-plugins/require-windowshide-on-spawn.grit"]+ },{// One-shot `expect(await locator.count())` reads never retry and are// the canonical hidden-flake assertion shape (2026-06 e2e audit).diff --git a/packages/cli/src/commands/bug-report.ts b/packages/cli/src/commands/bug-report.tsindex 9fecb35e9..f26436a69 100644--- a/packages/cli/src/commands/bug-report.ts+++ b/packages/cli/src/commands/bug-report.ts@@ -4,6 +4,7 @@ import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } fimport { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';import { basename, join, resolve } from 'node:path';import type { BundleManifest, BundleRedaction } from '@inkeep/open-knowledge-core';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { Command } from 'commander';import { getCliLogger } from '../cli.ts';import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';@@ -45,7 +46,10 @@ function collectSysinfo(): Record<string, unknown> {};try {- const ver = execSync('sw_vers -productVersion 2>/dev/null', { encoding: 'utf8' }).trim();+ const ver = execSync(+ 'sw_vers -productVersion 2>/dev/null',+ withHiddenWindowsConsole({ encoding: 'utf8' }),+ ).trim();info.macosVersion = ver;} catch {}@@ -242,7 +246,11 @@ async function createBundle(opts: {if (!opts.noReveal && platform() === 'darwin') {try {- childSpawn('/usr/bin/open', ['-R', zipPath], { detached: true, stdio: 'ignore' }).unref();+ childSpawn(+ '/usr/bin/open',+ ['-R', zipPath],+ withHiddenWindowsConsole({ detached: true, stdio: 'ignore' as const }),+ ).unref();} catch {}}diff --git a/packages/cli/src/commands/diagnose-health-checks/bun.ts b/packages/cli/src/commands/diagnose-health-checks/bun.tsindex 8b2494883..f599580da 100644--- a/packages/cli/src/commands/diagnose-health-checks/bun.ts+++ b/packages/cli/src/commands/diagnose-health-checks/bun.ts@@ -11,6 +11,7 @@*/import { spawnSync } from 'node:child_process';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import type { CheckDefinition, CheckResult } from './types.ts';interface BunCheckDeps {@@ -20,11 +21,15 @@ interface BunCheckDeps {const PROBE_TIMEOUT_MS = 5000;function defaultProbe(): { ok: boolean; version?: string; error?: string } {- const result = spawnSync('bun', ['--version'], {- encoding: 'utf-8',- timeout: PROBE_TIMEOUT_MS,- env: { ...process.env, LANG: 'C', LC_ALL: 'C' },- });+ const result = spawnSync(+ 'bun',+ ['--version'],+ withHiddenWindowsConsole({+ encoding: 'utf-8',+ timeout: PROBE_TIMEOUT_MS,+ env: { ...process.env, LANG: 'C', LC_ALL: 'C' },+ }),+ );if (result.error) return { ok: false, error: result.error.message };if (result.signal === 'SIGTERM') {return { ok: false, error: 'probe timed out' };diff --git a/packages/cli/src/commands/diagnose-health-checks/macos-codesig.ts b/packages/cli/src/commands/diagnose-health-checks/macos-codesig.tsindex 8e9740e1b..39cccd797 100644--- a/packages/cli/src/commands/diagnose-health-checks/macos-codesig.ts+++ b/packages/cli/src/commands/diagnose-health-checks/macos-codesig.ts@@ -27,6 +27,7 @@ const PROBE_TIMEOUT_MS = 5000;const TRANSLOCATED_PREFIX = '/private/var/folders/';function defaultCodesignVerify(bundlePath: string): { ok: boolean; stderr: string } {+ // biome-ignore lint/plugin/require-windowshide-on-spawn: macOS-only (codesign; never spawned on Windows or Linux)const r = spawnSync('codesign', ['--verify', '--deep', '--strict', bundlePath], {encoding: 'utf-8',timeout: PROBE_TIMEOUT_MS,diff --git a/packages/cli/src/commands/diagnose.ts b/packages/cli/src/commands/diagnose.tsindex 5cf1178da..0c47dba5f 100644--- a/packages/cli/src/commands/diagnose.ts+++ b/packages/cli/src/commands/diagnose.ts@@ -17,6 +17,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSyncimport { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { createInterface } from 'node:readline/promises';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { Command } from 'commander';import pc from 'picocolors';import {@@ -48,10 +49,14 @@ interface ProcessStat {}function sampleProcessStat(pid: number): ProcessStat | null {- const r = spawnSync('ps', ['-p', String(pid), '-o', '%cpu=,%mem=,rss=,vsz='], {- encoding: 'utf-8',- timeout: 2000,- });+ const r = spawnSync(+ 'ps',+ ['-p', String(pid), '-o', '%cpu=,%mem=,rss=,vsz='],+ withHiddenWindowsConsole({+ encoding: 'utf-8',+ timeout: 2000,+ }),+ );if (r.error || !r.stdout?.trim()) return null;const [cpu, mem, rss, vsz] = r.stdout.trim().split(/\s+/);const cpuPercent = Number.parseFloat(cpu ?? '');@@ -73,7 +78,11 @@ function sampleProcessStat(pid: number): ProcessStat | null {// ---------------------------------------------------------------------------function collectLsof(pid: number): string | null {- const r = spawnSync('lsof', ['-p', String(pid)], { encoding: 'utf-8', timeout: 5000 });+ const r = spawnSync(+ 'lsof',+ ['-p', String(pid)],+ withHiddenWindowsConsole({ encoding: 'utf-8', timeout: 5000 }),+ );return r.error || !r.stdout ? null : r.stdout;}@@ -95,10 +104,14 @@ function localhostListenPorts(lsofOutput: string): number[] {// ---------------------------------------------------------------------------function getInspectorEndpoints(port: number): unknown[] | null {- const r = spawnSync('curl', ['-s', '--max-time', '2', `http://127.0.0.1:${port}/json/list`], {- encoding: 'utf-8',- timeout: 3000,- });+ const r = spawnSync(+ 'curl',+ ['-s', '--max-time', '2', `http://127.0.0.1:${port}/json/list`],+ withHiddenWindowsConsole({+ encoding: 'utf-8',+ timeout: 3000,+ }),+ );if (r.error || !r.stdout?.trim()) return null;try {const parsed = JSON.parse(r.stdout);@@ -152,7 +165,11 @@ async function runProfiler(const scriptPath = writeCdpScript(wsUrl, profileMs, profilePath);let succeeded = false;- const child = spawn(process.execPath, [scriptPath], { stdio: 'ignore' });+ const child = spawn(+ process.execPath,+ [scriptPath],+ withHiddenWindowsConsole({ stdio: 'ignore' as const }),+ );const interval = setInterval(() => {const s = sampleProcessStat(pid);if (s) onStat(s);diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.tsindex 955b69a76..ba91aba56 100644--- a/packages/cli/src/commands/open.ts+++ b/packages/cli/src/commands/open.ts@@ -37,6 +37,7 @@ import {encodeSkillRoute,resolveLockDir,resolveUiInfo,+ withHiddenWindowsConsole,} from '@inkeep/open-knowledge-server';import { Command } from 'commander';import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';@@ -115,11 +116,15 @@ export function createRealOpenDeps(}},openTarget: (target) => {- const child = nodeSpawn('open', [target], {- detached: true,- stdio: 'ignore',- env: scrubElectronRunAsNode(process.env),- });+ const child = nodeSpawn(+ 'open',+ [target],+ withHiddenWindowsConsole({+ detached: true,+ stdio: 'ignore' as const,+ env: scrubElectronRunAsNode(process.env),+ }),+ );child.unref();},log: (message) => process.stdout.write(`${message}\n`),diff --git a/packages/cli/src/commands/share/publish.ts b/packages/cli/src/commands/share/publish.tsindex 200670f85..31f09975b 100644--- a/packages/cli/src/commands/share/publish.ts+++ b/packages/cli/src/commands/share/publish.ts@@ -29,7 +29,7 @@import { execSync } from 'node:child_process';import { existsSync } from 'node:fs';import { join, resolve } from 'node:path';-import { initContent } from '@inkeep/open-knowledge-server';+import { initContent, withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { Octokit } from '@octokit/rest';import { Command } from 'commander';import simpleGit, { type SimpleGit, type SimpleGitOptions } from 'simple-git';@@ -471,7 +471,10 @@ async function runSharePublish(opts: PublishOptions, tokenStore: TokenStore): Pr// running on a real user's machine inherits global git config; on a// pristine box we fall back to the OAuth profile via `git config user.*`.try {- execSync('git config user.email', { cwd: projectDir, stdio: 'ignore' });+ execSync(+ 'git config user.email',+ withHiddenWindowsConsole({ cwd: projectDir, stdio: 'ignore' }),+ );} catch {process.env.GIT_AUTHOR_NAME ??= 'OpenKnowledge';process.env.GIT_AUTHOR_EMAIL ??= '[email protected]';diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.tsindex c9b9fc16f..5df6d55db 100644--- a/packages/cli/src/commands/single-file-open.ts+++ b/packages/cli/src/commands/single-file-open.ts@@ -24,6 +24,7 @@ import {SingleFileNotFoundError,SingleFileNotMarkdownError,type SingleFileOpenPlan,+ withHiddenWindowsConsole,} from '@inkeep/open-knowledge-server';import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';import { createRealOpenDeps, runOpen } from './open.ts';@@ -71,11 +72,15 @@ export function createRealSingleFileOpenDeps(prepare: prepareSingleFileOpen,detectBundlePath: () => detect().bundlePath ?? null,openTarget: (target) => {- const child = nodeSpawn('open', [target], {- detached: true,- stdio: 'ignore',- env: scrubElectronRunAsNode(process.env),- });+ const child = nodeSpawn(+ 'open',+ [target],+ withHiddenWindowsConsole({+ detached: true,+ stdio: 'ignore' as const,+ env: scrubElectronRunAsNode(process.env),+ }),+ );child.unref();},runProjectOpen: (docName, projectRoot) =>diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex d19549f4e..9554c2484 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -175,6 +175,7 @@ export function spawnOkUi(opts: SpawnOkUiOptions): ChildProcess {const child = spawnFn(self.command, [...self.prefixArgs, ...(opts.args ?? ['ui'])], {detached: true,stdio: ['ignore', 'ignore', stderrFd],+ windowsHide: true,cwd: opts.cwd,env: {...childEnv,@@ -297,6 +298,7 @@ export async function connectUiSibling(opts: ConnectUiSiblingOptions): Promise<vconst child = spawnFn(self.command, [...self.prefixArgs, 'ui', '--port', String(opts.uiPort)], {cwd: opts.cwd,stdio: 'inherit',+ windowsHide: true,env: {...parentEnv,// Mirror spawnOkUi: under the packaged .app `self.command` is thediff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.tsindex 9ea53c001..9f4ce0d78 100644--- a/packages/cli/src/commands/uninstall.ts+++ b/packages/cli/src/commands/uninstall.ts@@ -17,7 +17,7 @@ import { execFileSync } from 'node:child_process';import { existsSync } from 'node:fs';import { homedir } from 'node:os';import { join, resolve } from 'node:path';-import { findEnclosingProjectRoot } from '@inkeep/open-knowledge-server';+import { findEnclosingProjectRoot, withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import checkbox from '@inquirer/checkbox';import { Command } from 'commander';import { desktopUserDataDir, readDesktopRecentProjects } from '../integrations/desktop-state.ts';@@ -93,11 +93,15 @@ export function detectInstallMethods(function defaultNpmLs(args: string[]): string | null {try {- return execFileSync('npm', args, {- encoding: 'utf-8',- timeout: 5000,- stdio: ['ignore', 'pipe', 'ignore'],- });+ return execFileSync(+ 'npm',+ args,+ withHiddenWindowsConsole({+ encoding: 'utf-8',+ timeout: 5000,+ stdio: ['ignore', 'pipe', 'ignore'],+ }),+ );} catch {// npm absent, not a global install, or the probe timed out — treat as "not// installed via npm global".diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.tsindex ab606985c..35918fe28 100644--- a/packages/cli/src/diagnose/bundle.ts+++ b/packages/cli/src/diagnose/bundle.ts@@ -33,6 +33,7 @@ import {DEFAULT_SPANS_MAX_BYTES,resolveConfigPath,} from '@inkeep/open-knowledge-core/server';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { parse as parseYaml } from 'yaml';import { ZipFile } from 'yazl';import { PACKAGE_VERSION } from '../constants.ts';@@ -308,7 +309,7 @@ function defaultReadShadowHead(contentDir: string): string | null {const result = spawnSync('git',['-C', shadowDir, 'log', '--oneline', `-${SHADOW_GIT_LOG_LIMIT}`],- { encoding: 'utf-8', timeout: 2000 },+ withHiddenWindowsConsole({ encoding: 'utf-8', timeout: 2000 }),);if (result.error || result.status !== 0) return null;return result.stdout ?? '';diff --git a/packages/cli/src/integrations/pi-extension.ts b/packages/cli/src/integrations/pi-extension.tsindex b3531793e..b2eba90b8 100644--- a/packages/cli/src/integrations/pi-extension.ts+++ b/packages/cli/src/integrations/pi-extension.ts@@ -159,6 +159,10 @@ class OkMcpClient {cwd,env,stdio: ["pipe", "pipe", "pipe"],+ // Inline (not the withHiddenWindowsConsole helper): this spawn lives in the+ // GENERATED Pi extension source, which must stay dependency-free (Pi loads+ // it with jiti; no npm packages resolve). Hide the console on Windows anyway.+ windowsHide: true,});this.child.stdout.setEncoding("utf8");this.child.stdout.on("data", (chunk: string) => this.onStdout(chunk));diff --git a/packages/cli/src/integrations/resolve-project-root.ts b/packages/cli/src/integrations/resolve-project-root.tsindex 533e2715a..81d35a747 100644--- a/packages/cli/src/integrations/resolve-project-root.ts+++ b/packages/cli/src/integrations/resolve-project-root.ts@@ -30,7 +30,7 @@ import { execFileSync } from 'node:child_process';import { realpathSync } from 'node:fs';import { homedir as nodeHomedir } from 'node:os';import { dirname, isAbsolute, relative, resolve } from 'node:path';-import { isProjectRoot } from '@inkeep/open-knowledge-server';+import { isProjectRoot, withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';const ANCESTOR_WALK_DEPTH_LIMIT = 30;@@ -74,11 +74,15 @@ function isDescendantOfHome(p: string, home: string): boolean {const defaultGitTopLevel = (cwd: string): string | null => {try {- const result = execFileSync('git', ['rev-parse', '--show-toplevel'], {- cwd,- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'ignore'],- });+ const result = execFileSync(+ 'git',+ ['rev-parse', '--show-toplevel'],+ withHiddenWindowsConsole({+ cwd,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }),+ );const trimmed = result.trim();return trimmed.length > 0 ? trimmed : null;} catch {diff --git a/packages/cli/src/mcp/bundle-proxy.ts b/packages/cli/src/mcp/bundle-proxy.tsindex 77806b038..3d7324151 100644--- a/packages/cli/src/mcp/bundle-proxy.ts+++ b/packages/cli/src/mcp/bundle-proxy.ts@@ -97,6 +97,7 @@ export function proxyToBundle(params: {{env: { ...params.env, OK_BUNDLE_PROXY: '0' },stdio: 'inherit',+ windowsHide: true,},);diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.tsindex 2130729a4..dde52e1ec 100644--- a/packages/cli/src/mcp/server.ts+++ b/packages/cli/src/mcp/server.ts@@ -44,6 +44,7 @@ import {registerAllTools,resolveContentDir,sanitizeClientName,+ withHiddenWindowsConsole,} from '@inkeep/open-knowledge-server';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';@@ -81,9 +82,13 @@ const execFileAsync = promisify(execFile);*/export async function countWorktrees(dir: string): Promise<number> {try {- const { stdout } = await execFileAsync('git', ['-C', dir, 'worktree', 'list', '--porcelain'], {- timeout: 2000,- });+ const { stdout } = await execFileAsync(+ 'git',+ ['-C', dir, 'worktree', 'list', '--porcelain'],+ withHiddenWindowsConsole({+ timeout: 2000,+ }),+ );return stdout.split('\n').filter((line) => line.startsWith('worktree ')).length;} catch {return 0;diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.tsindex 714ea247d..a355c65f0 100644--- a/packages/cli/src/mcp/shim.ts+++ b/packages/cli/src/mcp/shim.ts@@ -314,6 +314,7 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promisechild = spawnFn(self.command, [...self.prefixArgs, 'start'], {detached: true,stdio: ['ignore', 'ignore', stderrFd],+ windowsHide: true,cwd: opts.contentDir,env: {...process.env,diff --git a/packages/cli/src/sharing/git-exclude.ts b/packages/cli/src/sharing/git-exclude.tsindex 07f018bbf..59d969034 100644--- a/packages/cli/src/sharing/git-exclude.ts+++ b/packages/cli/src/sharing/git-exclude.ts@@ -35,6 +35,7 @@ import {// the barrel deliberately omits it to keep the main entry browser-safe// (see `packages/core/src/index.ts`).import { resolveGitDirDetailed } from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';import { ALL_EDITOR_IDS, EDITOR_TARGETS } from '../commands/editors.ts';/**@@ -387,10 +388,14 @@ export function probeTrackedOkPaths(const abs = resolve(projectRoot, p);if (!existsSync(abs)) continue;try {- execFileSync('git', ['ls-files', '--error-unmatch', '--', p], {- cwd: projectRoot,- stdio: ['ignore', 'ignore', 'ignore'],- });+ execFileSync(+ 'git',+ ['ls-files', '--error-unmatch', '--', p],+ withHiddenWindowsConsole({+ cwd: projectRoot,+ stdio: ['ignore', 'ignore', 'ignore'],+ }),+ );tracked.push(p);} catch {// Non-zero exit — `--error-unmatch` failed because no index entrydiff --git a/packages/cli/src/utils/open-browser.test.ts b/packages/cli/src/utils/open-browser.test.tsindex f899308d3..000126145 100644--- a/packages/cli/src/utils/open-browser.test.ts+++ b/packages/cli/src/utils/open-browser.test.ts@@ -57,6 +57,7 @@ describe('openBrowser', () => {execFileSpy.mockImplementation(((_cmd: string,_args: string[],+ _opts: unknown,callback: (err: Error | null) => void,) => {callback(new Error('ENOENT'));diff --git a/packages/cli/src/utils/open-browser.ts b/packages/cli/src/utils/open-browser.tsindex f0b59a0bf..cefb32581 100644--- a/packages/cli/src/utils/open-browser.ts+++ b/packages/cli/src/utils/open-browser.ts@@ -16,6 +16,7 @@* scheme allowlist and a metacharacter denylist before spawning.*/import { execFile } from 'node:child_process';+import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);@@ -59,7 +60,7 @@ export function openBrowser(url: string): void {const cmd =process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];- execFile(cmd, args, (err) => {+ execFile(cmd, args, withHiddenWindowsConsole({}), (err) => {if (err) console.warn(`Could not auto-open browser (${err.message}); visit ${url} manually`);});}diff --git a/packages/server/src/git-preflight.ts b/packages/server/src/git-preflight.tsindex 712583e48..9c2ecbf31 100644--- a/packages/server/src/git-preflight.ts+++ b/packages/server/src/git-preflight.ts@@ -204,6 +204,7 @@ function probeGit(command: string): ProbeResult {timeout: PROBE_TIMEOUT_MS,env: { ...process.env, LANG: 'C', LC_ALL: 'C' },});+ // biome-ignore lint/plugin/require-windowshide-on-spawn: windowsHide is set on `opts` via withHiddenWindowsConsole above; the rule can't see through the by-reference options variable.const result = spawnSync(command, ['--version'], opts);if (result.error) {// `spawnSync` sets `signal` to `'SIGTERM'` on timeout.diff --git a/packages/server/src/handoff-dispatch-api.ts b/packages/server/src/handoff-dispatch-api.tsindex ce3bc8e2b..a9bc00f00 100644--- a/packages/server/src/handoff-dispatch-api.ts+++ b/packages/server/src/handoff-dispatch-api.ts@@ -278,7 +278,7 @@ export async function handleHandoffDispatch(}const sleep = deps.sleep ?? defaultSleep;- const spawn = deps.spawnDetached ?? spawnDetachedReal;+ const spawnDetached = deps.spawnDetached ?? spawnDetachedReal;const isSchemeRegistered = deps.isSchemeRegistered ?? createOsProbe(deps.platform);if (recipe.type === 'app-bundle') {@@ -291,7 +291,7 @@ export async function handleHandoffDispatch(// Best-effort quit — if the app wasn't running, `to quit` no-ops cleanly.// Don't abort the recipe on quit failure; spawn handles a still-running// app gracefully (it activates instead of relaunching).- await spawn(+ await spawnDetached('/usr/bin/osascript',['-e', `tell application "${recipe.appName}" to quit`],SPAWN_TIMEOUT_MS,@@ -299,7 +299,11 @@ export async function handleHandoffDispatch(await sleep(QUIT_SETTLE_MS);}- const activate = await spawn('/usr/bin/open', ['-a', recipe.appName], SPAWN_TIMEOUT_MS);+ const activate = await spawnDetached(+ '/usr/bin/open',+ ['-a', recipe.appName],+ SPAWN_TIMEOUT_MS,+ );if (!activate.ok) {emitSpawnFailure(res, target, activate.reason);return;@@ -326,7 +330,7 @@ export async function handleHandoffDispatch(}const open = resolveUrlOpenInvocation(url, deps.platform);- const openUrl = await spawn(open.exec, open.args, SPAWN_TIMEOUT_MS);+ const openUrl = await spawnDetached(open.exec, open.args, SPAWN_TIMEOUT_MS);if (!openUrl.ok) {emitSpawnFailure(res, target, openUrl.reason);return;@@ -365,14 +369,14 @@ export async function handleHandoffDispatch(return;}const invocation = resolveCursorSpawnInvocation(cursorBin, workspacePath, deps.platform);- const spawnBinary = await spawn(invocation.exec, invocation.args, SPAWN_TIMEOUT_MS);+ const spawnBinary = await spawnDetached(invocation.exec, invocation.args, SPAWN_TIMEOUT_MS);if (!spawnBinary.ok) {emitSpawnFailure(res, target, spawnBinary.reason);return;}await sleep(CURSOR_SETTLE_MS);const open = resolveUrlOpenInvocation(url, deps.platform);- const openUrl = await spawn(open.exec, open.args, SPAWN_TIMEOUT_MS);+ const openUrl = await spawnDetached(open.exec, open.args, SPAWN_TIMEOUT_MS);if (!openUrl.ok) {emitSpawnFailure(res, target, openUrl.reason);return;diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 45cd79b33..dc589f1ed 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -81,6 +81,10 @@ export {isSystemDoc,SYSTEM_DOC_NAME,} from './cc1-broadcast.ts';+export {+ type HiddenWindowsConsoleOptions,+ withHiddenWindowsConsole,+} from './child-process-windows-hide.ts';export { getLocalDir, resolveContentDir, resolveLockDir } from './config/paths.ts';export { type Config, ConfigSchema } from './config/schema.ts';export { MCP_SERVER_NAME } from './constants.ts';diff --git a/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.tsnew file mode 100644index 000000000..55f6de7f4--- /dev/null+++ b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts@@ -0,0 +1,81 @@+/**+ * Windows console-flash prevention — `require-windowshide-on-spawn` GritQL+ * plugin.+ *+ * Plugin: `biome-plugins/require-windowshide-on-spawn.grit`+ * Fixture: `biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx`+ *+ * The fixture pairs 7 positive cases (spawn / spawnSync / execFile /+ * execFileSync / execSync / nodeSpawn / execFileAsync, each hiding the console+ * via NEITHER `windowsHide: true` NOR `withHiddenWindowsConsole(...)`) with+ * negatives (inline flag, the helper in both forms, a member call, a+ * differently-named helper, and bare `exec`). Exact equality on the fire count+ * catches drift in both directions — a false-negative regression (< 7) and a+ * false-positive widening (> 7). The helper-form negatives specifically guard+ * that the rule accepts #2514's `withHiddenWindowsConsole(...)` wrapping.+ *+ * The plugin is registered via `overrides[].plugins` in `biome.jsonc`, scoped+ * to `packages/{server,cli}/src/**` (the packages that spawn processes on+ * Windows; `packages/desktop` is macOS-only and out of scope) with tests+ * excluded.+ */++import { describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { join } from 'node:path';++const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx';++describe('require-windowshide-on-spawn GritQL plugin', () => {+ test('fires exactly 7 times — one per spawn that hides neither way', () => {+ const result = spawnSync('bunx', ['biome', 'check', FIXTURE_REL], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ windowsHide: true,+ });+ // Guard against a vacuous pass if `bunx` itself fails to spawn (missing+ // binary / PATH) — `result.status` would be null and `not.toBe(0)` would+ // pass while asserting nothing about biome's output.+ expect(result.error).toBeUndefined();+ expect(result.status).not.toBe(0);+ const output = `${result.stdout}\n${result.stderr}`;++ const fires = (output.match(/without a hidden Windows console/g) ?? []).length;+ expect(fires).toBe(7);++ // Message names the fix (the helper + the inline flag) + links the docs.+ expect(output).toContain('withHiddenWindowsConsole');+ expect(output).toContain('windowsHide: true');+ expect(output).toMatch(/https?:\/\/[^\s]+/);+ expect(output).toContain('biome-plugins/README.md#require-windowshide-on-spawngrit');+ });++ test('plugin is registered in biome.jsonc via overrides (not root plugins)', () => {+ const config = require(join(REPO_ROOT, 'biome.jsonc')) as {+ plugins?: string[];+ overrides?: Array<{ includes?: string[]; plugins?: string[] }>;+ };++ const rootPlugins = config.plugins ?? [];+ expect(rootPlugins).not.toContain('./biome-plugins/require-windowshide-on-spawn.grit');++ const overrides = config.overrides ?? [];+ const matchingOverride = overrides.find((entry) =>+ (entry.plugins ?? []).includes('./biome-plugins/require-windowshide-on-spawn.grit'),+ );+ expect(matchingOverride).toBeDefined();++ const includes = matchingOverride?.includes ?? [];+ // Scoped to the runtime-spawning packages (server + cli), tests excluded.+ // desktop is macOS-only, deliberately absent.+ expect(includes).toContain('packages/server/src/**/*.ts');+ expect(includes).toContain('packages/cli/src/**/*.ts');+ expect(includes).not.toContain('packages/desktop/src/**/*.ts');+ expect(includes).toContain('!**/*.test.ts');+ // Fixture self-include so this test's positive cases still trigger.+ expect(includes).toContain(+ 'biome-plugins/__fixtures__/require-windowshide-on-spawn.fixture.tsx',+ );+ });+});diff --git a/packages/server/src/spawn-cursor-api.ts b/packages/server/src/spawn-cursor-api.tsindex 95851b4fd..da8d4f039 100644--- a/packages/server/src/spawn-cursor-api.ts+++ b/packages/server/src/spawn-cursor-api.ts@@ -196,8 +196,12 @@ export async function handleSpawnCursor(}const invocation = resolveCursorSpawnInvocation(exec, userPath, deps.platform);- const spawn = deps.spawnDetached ?? spawnDetachedReal;- const outcome = await spawn(invocation.exec, invocation.args, SPAWN_CURSOR_SPAWN_TIMEOUT_MS);+ const spawnDetached = deps.spawnDetached ?? spawnDetachedReal;+ const outcome = await spawnDetached(+ invocation.exec,+ invocation.args,+ SPAWN_CURSOR_SPAWN_TIMEOUT_MS,+ );if (outcome.ok) {successResponse(res, 200, SpawnCursorSuccessSchema, {}, { handler: HANDLER });return;