Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
P4.11 #4992: subprocess launches go through src/core/spawn.ts (windowsHide default) behind a ratchet guard
garrytana3e06fa4aed3
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 1a37cee3c8..4cf3be6c34 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -213,6 +213,8 @@ jobs:run: bun test --timeout 120000 test/postgres-disconnect-bounded.test.ts test/persistence-administration.test.ts- name: Backup archive round trip on this host (#5312)run: bun test --timeout 60000 test/backup-archive-roundtrip-5312.test.ts+ - name: Hidden console windows from detached processes (#4992)+ run: bun test --timeout 300000 test/windows-hidden-console.test.ts test/spawn-windows-hide.test.ts test/scripts/windows-hide-guard.test.ts# bun audit blocks on pushes, schedules, manual runs, and pull requests or# merge-queue entries that change bun.lock, admin/bun.lock, patches/ or adiff --git a/docs/TESTING.md b/docs/TESTING.mdindex 0000168379..6046db371c 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -880,12 +880,11 @@ parameter and import types from `src/core/engine.ts`; migration helpers live in`scripts/check-ai-sdk-importers.ts` (in `bun run verify`) fails when a fileoutside `scripts/ai-sdk-importers.allowlist` imports a provider SDK (`ai`,`@ai-sdk/*`, `@anthropic-ai/sdk`, `openai`) as a value, so every model call-goes through `invokeAI`. Each mutating op has a-write-inference class (`src/core/ops/write-inference.ts`).-`test/write-path-zero-llm.serial.test.ts` asserts no generative call before-commit and only attributed facts extraction after it.-`test/write-path-no-egress.serial.test.ts`: keyless CLI writes open no-connection. Helper: `test/helpers/ai-tripwire.ts`.+goes through `invokeAI`. Each mutating op has a write-inference class+(`src/core/ops/write-inference.ts`). `test/write-path-zero-llm.serial.test.ts`+asserts no generative call before commit and only attributed facts extraction+after it; `test/write-path-no-egress.serial.test.ts`: keyless CLI writes open+no connection. Helper: `test/helpers/ai-tripwire.ts`.#### Durable-flush guard@@ -894,21 +893,23 @@ connection. Helper: `test/helpers/ai-tripwire.ts`.`src/core/fs-durable.ts` whose `fd` is assigned from a read-only `openSync`(flags omitted, a flag string without `w`/`a`/`+`, or `O_RDONLY` without`O_WRONLY`/`O_RDWR`), file or directory, and on one whose flags it cannot-read. Windows refuses fsync on a read-only handle and has no directory flush-(EPERM), which wedges the managed write queue (#5595) and every skill-bundle-publication (#5475). Flushes of descriptors opened for writing pass. Each-failure prints `FAIL [durable_flush_read_handle]: <file>:<line>`, the open it-traced, a `Fix:` line and this anchor. Fix: fsync the descriptor you wrote-through before closing it (set its final mode with `fchmodSync(fd)` first), or-call `flushFile(path)` / `flushDirectory(path, { bestEffort? })` from-`src/core/fs-durable.ts`. A file that cannot migrate yet goes in the guard's-`ALLOWLIST` with a reason (empty today); an entry whose file no longer needs it fails as-`durable_flush_stale_allowlist`. Fixtures:-`test/fixtures/guards/check-durable-flush.ts/`; forms are driven in-`test/scripts/durable-flush-guard.test.ts`. The helper and the #5595/#5475-regressions run natively on the `windows-latest` row of the test.yml-`security-regressions` job; `test/helpers/win32-flush-semantics.ts` makes them-discriminate on POSIX hosts too.+read: Windows refuses fsync on a read-only handle and has no directory flush+(EPERM; #5595, #5475). Fix: fsync the descriptor you wrote through before+closing it (`fchmodSync(fd)` first for its final mode), or call `flushFile` /+`flushDirectory(path, { bestEffort? })` from `src/core/fs-durable.ts`. A file+that cannot migrate yet goes in the guard's `ALLOWLIST` with a reason; a stale+entry fails. Fixtures: `test/fixtures/guards/check-durable-flush.ts/`. The+#5595/#5475 regressions run natively on the `windows-latest` row of the+test.yml `security-regressions` job; `test/helpers/win32-flush-semantics.ts`+makes them discriminate on POSIX.++#### Windows hidden-console guard++`scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`;+#4992): a runtime `child_process` import or `Bun.spawn*` in `src/` outside+`src/core/spawn.ts` fails unless the file is in `NOT_YET_MIGRATED` (a ratchet;+a stale entry fails); `windowsHide: false` needs an `ALLOWLIST` reason.+`test/windows-hidden-console.test.ts` is the native proof on the same row.#### Engine-sql ratchetdiff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex 309061cf1c..2680c71e33 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -29,6 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Optional `progressWindowMs` makes the deadline progress-aware: the handle forwards `noteForwardProgress()` notes (`src/core/forward-progress.ts`, throttled to at most one `postMessage` per min(1 s, window/4)) to the worker, which past the deadline extends while the last note is younger than the window and sends SIGTERM only after a full window without progress (pure mirror `progressDeadlineDecision(elapsedMs, deadlineMs, sinceProgressMs, windowMs) → 'wait'|'extend'|'stop'`; the window starts at install). A starved loop sends no notes, so starvation is still killed. Optional `stopNotice` is written to stdout (fd 1) when the watchdog stops the run, so the agent sees why and how to resume. Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrices + clamp arithmetic + handle contract) + `test/process-watchdog-harness.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills, a progressing run outlives its deadline, a run that stops progressing is stopped one window later with its stop notice on stdout). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too) through `syncWatchdogPlan` in `src/core/sync-reconcile.ts`; deadline resolved by `resolveSyncHardDeadline` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none). The env and default deadlines carry `progressWindowMs` = the sync stall window (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900 s; the default when that is disabled), so a large first sync that keeps importing is never stopped; the explicit flags stay strict. The stop notice (`syncDeadlineStopNotice`: `code=sync_deadline_stop`, cause, resume command; one JSON object under `--json`) is pinned by `test/sync-hard-deadline.test.ts`, and the real CLI journey by `test/large-brain-ceilings.test.ts`.- `src/core/forward-progress.ts` — process-wide forward-progress signal, zero imports. `noteForwardProgress()` records that a unit of work completed (called by every `progress.ts` tick); `onForwardProgress(listener)` subscribes and returns the unsubscribe; `lastForwardProgressAt()` reads the last note. Consumers are deadlines that must never stop a run that is still progressing: the sync watchdog (`process-watchdog.ts`, `progressWindowMs`) and the `gbrain serve` boot deadline. Heartbeats are not progress.+- `src/core/spawn.ts` — the one module in `src/` that launches subprocesses with `windowsHide` defaulted (#4992, contributed by @rokas-tarasevicius in PR #6105). A `detached: true` child on Windows has no console, so every console program it launches without `windowsHide` opens a visible console window that takes focus; the Stop-hook push, the backup check, the job supervisor, its worker and every job child run that way. Wraps `spawn`, `spawnSync`, `exec`, `execSync`, `execFile`, `execFileSync` (Node's overloads and `util.promisify.custom` kept) plus `bunSpawn` / `bunSpawnSync`, each defaulting `windowsHide: true` and keeping an explicit `false` (only `openBrowser` in `creds/redirect.ts`). Calls go through `child_process` and `Bun` at call time, so `spyOn` in tests still intercepts them. Trade-off: with every stdio stream piped or ignored, libuv turns the flag into CREATE_NO_WINDOW and the child gets a windowless console of its own, so a program that prompts on the console directly prompts invisibly; gbrain's networked git calls set `GIT_TERMINAL_PROMPT=0` (git-remote.ts also `SSH_ASKPASS_REQUIRE=never`), and inherited-stdio launches still attach to the terminal. `scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`) is a RATCHET: a new runtime `child_process` import or `Bun.spawn*` in `src/` fails unless the file is in its `NOT_YET_MIGRATED` list (the minions supervisor/worker/child/readiness/isolation/registry/shell handler, `workspace-push.ts`, `cli/main.ts`, `context/hook-heartbeat.ts`, the backup check, `cli-force-exit.ts`, `cli-preflight.ts`, `autopilot-lock.ts`, the autopilot commands and `bounded-child-exec.ts` are migrated; the rest, wave-13-claimed files included, are listed and lose the entry when they move), and a listed file that stops launching directly fails as stale. Pinned by `test/spawn-windows-hide.test.ts` (argument shapes; the detached supervisor, worker and push-git sites), `test/scripts/windows-hide-guard.test.ts` (forms, allowlist, ratchet, stale entries, the repository) and, natively on the test.yml `security-regressions` Windows row, `test/windows-hidden-console.test.ts` (a compiled console probe launched from a console-less detached process: the unhidden CONTROL launch must show a window or the run fails as `windows_console_gate_unsupported`; then the worker, the push's git and every seam launcher show none).- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Every `tick` calls `noteForwardProgress()`, so bulk work feeds the progress-aware deadlines; its only import is that zero-import leaf. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape. JSON `tick` events carry `cpu_ms`, the main thread's CPU time since the phase started (`process.threadCpuUsage()`); the scale tier's PGLite import-rate gate (`scripts/scale/gates.ts`) judges on it.- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter would allow near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).diff --git a/package.json b/package.jsonindex 0f1ef502a8..63a7769147 100644--- a/package.json+++ b/package.json@@ -155,6 +155,7 @@"check:layering": "bun scripts/check-layering.ts","check:ai-sdk-importers": "bun scripts/check-ai-sdk-importers.ts","check:durable-flush": "bun scripts/check-durable-flush.ts",+ "check:windows-hide": "bun scripts/check-windows-hide.ts","check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts","check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts","check:engine-sql-brands": "bun scripts/check-engine-sql-brands.ts",diff --git a/scripts/check-windows-hide.ts b/scripts/check-windows-hide.tsnew file mode 100644index 0000000000..0c25b1676c--- /dev/null+++ b/scripts/check-windows-hide.ts@@ -0,0 +1,216 @@+#!/usr/bin/env bun+/**+ * Windows hidden-console guard (#4992; docs/TESTING.md#windows-hidden-console-guard).+ *+ * On Windows a detached gbrain child has no console, so every console program+ * it launches without `windowsHide` opens a visible console window that takes+ * focus. src/core/spawn.ts is the one module that launches subprocesses and+ * defaults `windowsHide: true`. Outside it, this guard fails on any runtime+ * use of `child_process` in src/ (a static, dynamic or `require` import that+ * is not type-only) and on any `Bun.spawn` / `Bun.spawnSync` reference, so a+ * NEW spawn site, detached or not, cannot skip the default. It is a RATCHET:+ * NOT_YET_MIGRATED lists the files that still launch directly today, each+ * with its reason; a listed file that no longer does fails as stale, so the+ * list only shrinks. It also fails on an explicit `windowsHide: false` outside+ * ALLOWLIST, which names each deliberate opt-out; a stale entry fails.+ *+ * Fix: import the launcher from src/core/spawn.ts (`spawn`, `spawnSync`,+ * `exec`, `execSync`, `execFile`, `execFileSync`, `bunSpawn`, `bunSpawnSync`)+ * and delete the file's NOT_YET_MIGRATED entry if it has one.+ *+ * Contributed by @rokas-tarasevicius (PR #6105); the ratchet form is wave 14's.+ * Seam: GBRAIN_GUARD_ROOT (fixture tree root).+ */+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const ANCHOR = 'docs/TESTING.md#windows-hidden-console-guard';+const SEAM = 'src/core/spawn.ts';+const MODULES = new Set(['child_process', 'node:child_process']);++/** Files allowed an explicit `windowsHide: false`. Each entry names its reason; a stale entry fails. */+const ALLOWLIST: Record<string, string> = {+ 'src/core/creds/redirect.ts': 'openBrowser launches the system browser through `cmd /c start`; the launch stays as visible as before',+};++/**+ * Files that still import child_process or call Bun.spawn* directly. Delete+ * a file's entry when you move it onto the seam; an entry whose file no+ * longer launches directly fails as stale (the ratchet only goes down).+ */+const NOT_YET_MIGRATED: Record<string, string> = {+ 'src/cli/commands/smoke-test.ts': 'not yet migrated',+ 'src/commands/bootstrap.ts': 'not yet migrated',+ 'src/commands/claw-test.ts': 'not yet migrated',+ 'src/commands/connect.ts': 'not yet migrated',+ 'src/commands/doctor/bootstrap-checks.ts': 'not yet migrated',+ 'src/commands/doctor/checks/git-convergence.ts': 'not yet migrated',+ 'src/commands/doctor/checks/local-audits.ts': 'not yet migrated',+ 'src/commands/eval-brainbench.ts': 'not yet migrated',+ 'src/commands/eval-compare.ts': 'not yet migrated',+ 'src/commands/eval-longmemeval.ts': 'not yet migrated',+ 'src/commands/eval-run-all.ts': 'not yet migrated',+ 'src/commands/frontmatter-install-hook.ts': 'not yet migrated',+ 'src/commands/frontmatter.ts': 'not yet migrated',+ 'src/commands/hook.ts': 'wave 13 (GBRA-57) file: migrates with that wave',+ 'src/commands/import.ts': 'not yet migrated',+ 'src/commands/init.ts': 'not yet migrated',+ 'src/commands/integrations.ts': 'not yet migrated',+ 'src/commands/migrations/in-process.ts': 'not yet migrated',+ 'src/commands/migrations/v0_11_0.ts': 'not yet migrated',+ 'src/commands/migrations/v0_12_0.ts': 'not yet migrated',+ 'src/commands/migrations/v0_12_2.ts': 'not yet migrated',+ 'src/commands/migrations/v0_13_0.ts': 'not yet migrated',+ 'src/commands/migrations/v0_32_2.ts': 'not yet migrated',+ 'src/commands/serve.ts': 'not yet migrated',+ 'src/commands/setup.ts': 'not yet migrated',+ 'src/commands/skillify-check.ts': 'not yet migrated',+ 'src/commands/skillopt.ts': 'not yet migrated',+ 'src/commands/skillpack-check.ts': 'not yet migrated',+ 'src/commands/sources.ts': 'not yet migrated',+ 'src/commands/takes.ts': 'not yet migrated',+ 'src/commands/upgrade.ts': 'not yet migrated',+ 'src/core/agent-install/setup.ts': 'not yet migrated',+ 'src/core/ai/providers/claude-cli-language-model.ts': 'wave 13 (GBRA-57) file: migrates with that wave',+ 'src/core/ai/recipes/azure-openai.ts': 'not yet migrated',+ 'src/core/binary-self-update.ts': 'not yet migrated',+ 'src/core/bootstrap/status.ts': 'not yet migrated',+ 'src/core/bootstrap/verify.ts': 'not yet migrated',+ 'src/core/brain-repo-durability.ts': 'wave 13 (GBRA-57) file: migrates with that wave',+ 'src/core/bun-floor.ts': 'not yet migrated',+ 'src/core/calibration/gstack-coupling.ts': 'not yet migrated',+ 'src/core/calibration/undo-wave.ts': 'not yet migrated',+ 'src/core/claw-test/agent-runner.ts': 'not yet migrated',+ 'src/core/claw-test/runners/grok.ts': 'not yet migrated',+ 'src/core/claw-test/runners/opencode.ts': 'not yet migrated',+ 'src/core/claw-test/transcript-capture.ts': 'not yet migrated',+ 'src/core/company-brain/revision.ts': 'not yet migrated',+ 'src/core/context/compiled-core.ts': 'not yet migrated',+ 'src/core/cycle/derived-write-through.ts': 'not yet migrated',+ 'src/core/docker-postgres.ts': 'not yet migrated',+ 'src/core/embed-stale-images.ts': 'not yet migrated',+ 'src/core/eval/drift-watch.ts': 'not yet migrated',+ 'src/core/facts/fence-write.ts': 'not yet migrated',+ 'src/core/facts/purge-verify.ts': 'not yet migrated',+ 'src/core/fence-repair/census.ts': 'not yet migrated',+ 'src/core/fence-repair/repair-io.ts': 'not yet migrated',+ 'src/core/fence-repair/uncommitted.ts': 'not yet migrated',+ 'src/core/git-first-commit.ts': 'not yet migrated',+ 'src/core/git-head.ts': 'not yet migrated',+ 'src/core/git-remote.ts': 'not yet migrated',+ 'src/core/git-visible-files.ts': 'not yet migrated',+ 'src/core/google/access.ts': 'not yet migrated',+ 'src/core/hardened-git.ts': 'wave 13 (GBRA-57) file: migrates with that wave',+ 'src/core/harness/install.ts': 'not yet migrated',+ 'src/core/persistence/engine-graduation.ts': 'not yet migrated',+ 'src/core/persistence/sync-blobs.ts': 'not yet migrated',+ 'src/core/persistence/sync-discovery.ts': 'not yet migrated',+ 'src/core/persistence/topology-filesystem.ts': 'not yet migrated',+ 'src/core/pglite-lock.ts': 'not yet migrated',+ 'src/core/repair/frontmatter.ts': 'not yet migrated',+ 'src/core/repair/slug-conflicts.ts': 'not yet migrated',+ 'src/core/repo-visibility.ts': 'not yet migrated',+ 'src/core/shared-skills/migration-export.ts': 'not yet migrated',+ 'src/core/shared-skills/setup.ts': 'not yet migrated',+ 'src/core/skill-fix-gates.ts': 'not yet migrated',+ 'src/core/skillopt/apply-edits.ts': 'not yet migrated',+ 'src/core/skillpack/bundle.ts': 'not yet migrated',+ 'src/core/skillpack/endorse.ts': 'not yet migrated',+ 'src/core/skillpack/remote-source.ts': 'not yet migrated',+ 'src/core/skillpack/tarball.ts': 'not yet migrated',+ 'src/core/source-health.ts': 'not yet migrated',+ 'src/core/sync-delta.ts': 'not yet migrated',+ 'src/core/sync-git.ts': 'not yet migrated',+ 'src/core/sync-reconcile.ts': 'not yet migrated',+ 'src/core/sync-upstream.ts': 'not yet migrated',+ 'src/core/tailscale.ts': 'not yet migrated',+ 'src/core/thin-client-upgrade-prompt.ts': 'not yet migrated',+ 'src/core/transcription.ts': 'not yet migrated',+ 'src/eval/brainbench/trust-scenario.ts': 'not yet migrated',+ 'src/eval/code-retrieval/harness.ts': 'not yet migrated',+};++function tsFiles(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...tsFiles(full));+ else if (/\.(ts|tsx|mts)$/.test(entry) && !entry.endsWith('.d.ts')) out.push(full);+ }+ return out;+}++const isModule = (node: ts.Node | undefined): boolean => !!node && ts.isStringLiteralLike(node) && MODULES.has(node.text);++/** An import that loads child_process at runtime (not `import type`, not all-`type` specifiers). */+function valueImport(node: ts.ImportDeclaration | ts.ExportDeclaration): boolean {+ if (ts.isImportDeclaration(node)) {+ const clause = node.importClause;+ if (!clause) return true;+ if (clause.isTypeOnly) return false;+ if (clause.name) return true;+ const bindings = clause.namedBindings;+ return !bindings || ts.isNamespaceImport(bindings) || bindings.elements.length === 0 || bindings.elements.some(e => !e.isTypeOnly);+ }+ if (node.isTypeOnly) return false;+ const clause = node.exportClause;+ return !clause || !ts.isNamedExports(clause) || clause.elements.some(e => !e.isTypeOnly);+}++const violations: string[] = [];+const optedOut = new Set<string>();+const launchesDirectly = new Set<string>();+for (const abs of tsFiles(join(ROOT, 'src'))) {+ const rel = relative(ROOT, abs).replace(/\\/g, '/');+ if (rel === SEAM) continue;+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const fail = (node: ts.Node, code: string, what: string, fix: string) => {+ const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;+ violations.push(`FAIL [${code}]: ${rel}:${line} ${what}\n Fix: ${fix}`);+ };+ const direct = (node: ts.Node, code: string, what: string, fix: string) => {+ launchesDirectly.add(rel);+ if (!NOT_YET_MIGRATED[rel]) fail(node, code, what, fix);+ };+ const useSeam = `import it from ${SEAM}, which defaults windowsHide: true`;+ const visit = (node: ts.Node): void => {+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && isModule(node.moduleSpecifier) && valueImport(node)) {+ direct(node, 'windows_hide_direct_child_process', 'imports child_process directly', useSeam);+ } else if (ts.isCallExpression(node) && isModule(node.arguments[0])+ && (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {+ direct(node, 'windows_hide_direct_child_process', `loads child_process with ${node.expression.getText(sf)}()`, useSeam);+ } else if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'Bun'+ && (node.name.text === 'spawn' || node.name.text === 'spawnSync')) {+ const wrapper = node.name.text === 'spawn' ? 'bunSpawn' : 'bunSpawnSync';+ direct(node, 'windows_hide_direct_bun_spawn', `calls Bun.${node.name.text}`, `call ${wrapper} from ${SEAM}, which defaults windowsHide: true`);+ } else if (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name))+ && node.name.text === 'windowsHide' && node.initializer.kind === ts.SyntaxKind.FalseKeyword) {+ optedOut.add(rel);+ if (!ALLOWLIST[rel]) fail(node, 'windows_hide_opt_out', 'sets windowsHide: false', `drop it, or add ${rel} to ALLOWLIST in scripts/check-windows-hide.ts with the reason the window must show`);+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+}+for (const [rel, reason] of Object.entries(ALLOWLIST)) {+ if (existsSync(join(ROOT, rel)) && !optedOut.has(rel)) {+ violations.push(`FAIL [windows_hide_stale_allowlist]: ${rel} no longer sets windowsHide: false (allowlisted: ${reason})\n Fix: delete its ALLOWLIST entry in scripts/check-windows-hide.ts`);+ }+}+for (const [rel, reason] of Object.entries(NOT_YET_MIGRATED)) {+ if (existsSync(join(ROOT, rel)) && !launchesDirectly.has(rel)) {+ violations.push(`FAIL [windows_hide_stale_migration_entry]: ${rel} no longer launches subprocesses directly (listed: ${reason})\n Fix: delete its NOT_YET_MIGRATED entry in scripts/check-windows-hide.ts; the ratchet only goes down`);+ }+}++if (violations.length) {+ for (const v of violations) console.error(v);+ console.error('Why: on Windows a console program launched from a detached gbrain process without windowsHide opens a visible console window that takes focus (#4992).');+ console.error(`See: ${ANCHOR}`);+ console.error(`check-windows-hide: ${violations.length} violation(s)`);+ process.exit(1);+}+console.log(`check-windows-hide: ok (src/, seam ${SEAM}, ${Object.keys(ALLOWLIST).length} allowlisted opt-out, ${Object.keys(NOT_YET_MIGRATED).length} not yet migrated)`);diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 3a727ec605..44ddaab90e 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -71,6 +71,7 @@ check-sync-run-state.ts scanner yes A17 (W4 sync): SyncRun mutable fields (non-rcheck-layering.ts scanner yes EO10 layering (TS AST, every import form): src/core/engine-sql/** imports no engine façade; src/core/schema-migrations/** imports no migrate.ts; src/core/persistence/** imports no ai/gateway.ts (P8 write-inference contract)check-ai-sdk-importers.ts scanner yes P8: provider SDKs (ai, @ai-sdk/*, @anthropic-ai/sdk, openai) imported as runtime values only by scripts/ai-sdk-importers.allowlist (shrink-only), so every model call is observable through invokeAIcheck-durable-flush.ts scanner yes #5595/#5475 Windows durability (TS AST, scope-resolved): fsyncSync of a descriptor from a read-only or unreadable-flags openSync in src/ outside src/core/fs-durable.ts fails, file or directory; write-fd flushes pass; reasoned ALLOWLIST, stale entries fail; bad-directory fixture covers an O_RDONLY directory flush+check-windows-hide.ts scanner yes #4992 Windows hidden consoles (TS AST): runtime child_process import or Bun.spawn* outside src/core/spawn.ts fails unless the file is in NOT_YET_MIGRATED (ratchet: a listed file that stops launching directly fails as stale); explicit windowsHide: false outside ALLOWLIST fails, stale entries failcheck-schema-migrations-fresh.sh buildfresh exempt regenerates src/core/schema-migrations/registry.generated.ts + diffs; generator enforces filename/version/name cross-check and duplicate versions (unit: test/scripts/build-schema-migrations.test.ts)check-schema-fresh.sh buildfresh exempt W2: regenerates the schema chain (fragments -> schema.sql regions -> schema-embedded -> PGLite template) into a temp dir and diffs every output; names the source to edit (unit: test/scripts/build-schema.test.ts)check-retired-phrases.sh scanner yes W7 (refactor wave 1): retired contributor-workflow phrases (migrations array, two-engine SQL rule, CLI switch case, region policy, hand-synced PGLite schema) fail in CLAUDE.md, AGENTS.md, CONTRIBUTING.md, docs/, skills/; historical records and the porting kit exempt; GBRAIN_GUARD_ROOT seam; bad-<location> fixturesdiff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex 29d542a7d7..eea5de632a 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -171,6 +171,9 @@ CHECKS=(# #5595/#5475: no fsync of a read-only descriptor outside src/core/fs-durable.ts# (Windows refuses it with EPERM)."check:durable-flush"+ # #4992: subprocess launches go through src/core/spawn.ts (windowsHide+ # default); NOT_YET_MIGRATED is a ratchet that only shrinks.+ "check:windows-hide"# Goal (a) (refactor wave 1): engine SQL only shrinks; baseline# scripts/engine-sql-baseline.tsv."check:engine-sql-ratchet"diff --git a/src/cli/main.ts b/src/cli/main.tsindex f255b94b13..57fdebb4b8 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -11,7 +11,7 @@ installSigchldHandler();import { readFileSync, existsSync, unlinkSync } from 'fs';import { readStdinBounded as readStdinPayload } from '../core/interaction.ts';-import { spawn } from 'child_process';+import { spawn } from '../core/spawn.ts';import {readUpdateCache,isCacheFresh,diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.tsindex 63a00c4c1b..8f19b486b7 100644--- a/src/commands/autopilot.ts+++ b/src/commands/autopilot.ts@@ -21,7 +21,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, unlimport { setCliExitVerdict } from '../core/cli-force-exit.ts';import { detectExecutionEnvironment } from '../core/execution-env.ts';import { join, dirname, isAbsolute, resolve as resolvePath } from 'path';-import { execSync } from 'child_process';+import { execSync } from '../core/spawn.ts';import type { BrainEngine } from '../core/engine.ts';import { loadConfig, saveConfig, gbrainPath as gbrainHomePath } from '../core/config.ts';import {diff --git a/src/commands/autopilot/jobs.ts b/src/commands/autopilot/jobs.tsindex 35a9aa18ec..218ac3bba9 100644--- a/src/commands/autopilot/jobs.ts+++ b/src/commands/autopilot/jobs.ts@@ -7,7 +7,7 @@*/import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs';import { dirname, join, resolve as resolvePath } from 'path';-import { execSync } from 'child_process';+import { execSync } from '../../core/spawn.ts';import {autopilotLaunchdLabel,autopilotWrapperOwner,diff --git a/src/core/autopilot-lock.ts b/src/core/autopilot-lock.tsindex dd1500b99f..1b624224b6 100644--- a/src/core/autopilot-lock.ts+++ b/src/core/autopilot-lock.ts@@ -1,4 +1,4 @@-import { execFileSync, type ExecFileSyncOptionsWithStringEncoding } from 'node:child_process';+import { execFileSync, type ExecFileSyncOptionsWithStringEncoding } from './spawn.ts';import { readFileSync } from 'node:fs';export type AutopilotLockHolder =diff --git a/src/core/backup/private-path.ts b/src/core/backup/private-path.tsindex fa5aa9358c..279f162f9f 100644--- a/src/core/backup/private-path.ts+++ b/src/core/backup/private-path.ts@@ -1,4 +1,4 @@-import { execFile } from 'node:child_process';+import { execFile } from '../spawn.ts';import { lstatSync, readdirSync } from 'node:fs';import { join } from 'node:path';import { AgentInstallError, assertNoSymlinks } from '../agent-install/state.ts';diff --git a/src/core/backup/repository.ts b/src/core/backup/repository.tsindex 5bd95cad90..c2de66b09d 100644--- a/src/core/backup/repository.ts+++ b/src/core/backup/repository.ts@@ -1,4 +1,4 @@-import { execFile, execFileSync } from 'node:child_process';+import { execFile, execFileSync } from '../spawn.ts';import { createHash } from 'node:crypto';import { existsSync, realpathSync, statSync } from 'node:fs';import { buildGitEnv } from '../git-remote.ts';diff --git a/src/core/bounded-child-exec.ts b/src/core/bounded-child-exec.tsindex efe5cc0732..5b38551646 100644--- a/src/core/bounded-child-exec.ts+++ b/src/core/bounded-child-exec.ts@@ -6,7 +6,7 @@* `brain-repo-durability.ts` re-exports it for its older callers.*/import { readFileSync } from 'fs';-import { execFile, type ChildProcess, type ExecFileException } from 'child_process';+import { execFile, type ChildProcess, type ExecFileException } from './spawn.ts';const BOUNDED_EXEC_TERM_GRACE_MS = 2_000;diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.tsindex 6a829844c0..6535ae905a 100644--- a/src/core/cli-force-exit.ts+++ b/src/core/cli-force-exit.ts@@ -56,7 +56,7 @@*/import { writeSync } from 'node:fs';-import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process';+import { spawn, type ChildProcess, type SpawnOptions } from './spawn.ts';import { formatWithOptions } from 'node:util';import {drainAllBackgroundWorkForCliExit,diff --git a/src/core/cli-preflight.ts b/src/core/cli-preflight.tsindex 92a95606a9..2cbf7497ab 100644--- a/src/core/cli-preflight.ts+++ b/src/core/cli-preflight.ts@@ -213,6 +213,7 @@ import {} from './env-trust.ts';import { loadGbrainEnvFile } from './gbrain-env-file.ts';import { configDir } from './config.ts';+import { bunSpawn } from './spawn.ts';/*** Set on the sanitized re-run to `JSON {cwd, neutral}` (see "Loop guard").@@ -525,7 +526,7 @@ async function reexecSanitized(originalCwd: string, dropped: readonly string[]):// none: nothing else will deliver it — forward.process.on('SIGINT', hasControllingTerminal() ? () => {} : forward('SIGINT'));try {- child = Bun.spawn([process.execPath, ...argv], {+ child = bunSpawn([process.execPath, ...argv], {cwd: neutral,env,stdio: ['inherit', 'inherit', 'inherit'],diff --git a/src/core/context/hook-heartbeat.ts b/src/core/context/hook-heartbeat.tsindex 85e3ac4cb8..c2b0a350b3 100644--- a/src/core/context/hook-heartbeat.ts+++ b/src/core/context/hook-heartbeat.ts@@ -11,7 +11,7 @@* allowlist is enforced by construction, not by trust. Never throws.*/-import { spawn } from 'node:child_process';+import { spawn } from '../spawn.ts';import { createHash } from 'node:crypto';import { accessSync, appendFileSync, chmodSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { homedir } from 'node:os';diff --git a/src/core/creds/redirect.ts b/src/core/creds/redirect.tsindex 15d7b34190..60b62b3a04 100644--- a/src/core/creds/redirect.ts+++ b/src/core/creds/redirect.ts@@ -17,6 +17,7 @@*/import { CredentialError } from './errors.ts';+import { bunSpawn } from '../spawn.ts';export type RedirectStrategy = 'loopback' | 'paste' | 'hosted-callback';@@ -239,7 +240,8 @@ export function openBrowser(url: string, platform: NodeJS.Platform = process.pla? ['cmd', '/c', 'start', '', url.replace(/&/g, '^&')]: ['xdg-open', url];try {- Bun.spawn(argv, { stdout: 'ignore', stderr: 'ignore', stdin: 'ignore' });+ // The one launch that must stay visible: `cmd /c start` hands the URL to the user's browser (#4992).+ bunSpawn(argv, { stdout: 'ignore', stderr: 'ignore', stdin: 'ignore', windowsHide: false });return true;} catch {return false;diff --git a/src/core/minions/child-job-runner.ts b/src/core/minions/child-job-runner.tsindex 7c294a1d67..0ae4da6d0a 100644--- a/src/core/minions/child-job-runner.ts+++ b/src/core/minions/child-job-runner.ts@@ -32,7 +32,7 @@* queue; the CLI layer also fail-fast validates at startup).*/-import { spawn, type ChildProcess } from 'node:child_process';+import { spawn, type ChildProcess } from '../spawn.ts';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';diff --git a/src/core/minions/child-readiness.ts b/src/core/minions/child-readiness.tsindex 80be1174f3..f7c82840e0 100644--- a/src/core/minions/child-readiness.ts+++ b/src/core/minions/child-readiness.ts@@ -1,4 +1,4 @@-import { spawn } from 'node:child_process';+import { spawn } from '../spawn.ts';import type { BrainEngine } from '../engine.ts';import { VERSION } from '../../version.ts';import { isLocalConfigurationError } from './configuration-error.ts';diff --git a/src/core/minions/child-worker-supervisor.ts b/src/core/minions/child-worker-supervisor.tsindex 64dd98c918..85512f43e1 100644--- a/src/core/minions/child-worker-supervisor.ts+++ b/src/core/minions/child-worker-supervisor.ts@@ -36,7 +36,7 @@* (escalating exponential backoff).*/-import { spawn, type ChildProcess } from 'child_process';+import { spawn, type ChildProcess } from '../spawn.ts';import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { basename, isAbsolute, join, resolve as resolvePath } from 'node:path';diff --git a/src/core/minions/detached-stderr.ts b/src/core/minions/detached-stderr.tsindex 64181a5790..898915140e 100644--- a/src/core/minions/detached-stderr.ts+++ b/src/core/minions/detached-stderr.ts@@ -19,7 +19,7 @@* descriptor covers both processes — not a per-call EPIPE swallow.*/-import { spawn } from 'node:child_process';+import { spawn } from '../spawn.ts';import { closeSync, mkdirSync, openSync } from 'node:fs';import { join } from 'node:path';import { resolveAuditDir } from '../audit/audit-writer.ts';diff --git a/src/core/minions/handlers/shell.ts b/src/core/minions/handlers/shell.tsindex 781cc4654e..d900f037ab 100644--- a/src/core/minions/handlers/shell.ts+++ b/src/core/minions/handlers/shell.ts@@ -26,7 +26,7 @@* `shutdownSignal` so deploy restarts don't interrupt them mid-flight.*/-import { spawn, type ChildProcess } from 'node:child_process';+import { spawn, type ChildProcess } from '../../spawn.ts';import { StringDecoder } from 'node:string_decoder';import type { MinionJobContext } from '../types.ts';import { UnrecoverableError } from '../types.ts';diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 4730258bfe..e0d5b30352 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -35,7 +35,7 @@import { accessSync, constants, readdirSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';import { readFile, stat } from 'node:fs/promises';-import { spawnSync } from 'node:child_process';+import { spawnSync } from '../spawn.ts';import { JobDeferredError, UnrecoverableError } from './types.ts';import { RateLeaseUnavailableError } from './handlers/subagent.ts';import { SpendGroupRefusedError, type SpendRefusalEnvelope } from './spend-authorization.ts';diff --git a/src/core/minions/spawn-helpers.ts b/src/core/minions/spawn-helpers.tsindex 89cf41a64d..1f4837aabe 100644--- a/src/core/minions/spawn-helpers.ts+++ b/src/core/minions/spawn-helpers.ts@@ -15,7 +15,7 @@* any module mocking.*/-import { execFileSync } from 'child_process';+import { execFileSync } from '../spawn.ts';/*** Resolve the tini binary path, or return an empty string when not on PATH.diff --git a/src/core/minions/worker-registry.ts b/src/core/minions/worker-registry.tsindex 21e5b3c57d..50121b5da3 100644--- a/src/core/minions/worker-registry.ts+++ b/src/core/minions/worker-registry.ts@@ -27,7 +27,7 @@ import {writeFileSync,} from 'fs';import { join } from 'path';-import { execFileSync } from 'child_process';+import { execFileSync } from '../spawn.ts';import { gbrainPath, loadConfig } from '../config.ts';import { getEffectiveNiceness } from './niceness.ts';diff --git a/src/core/spawn.ts b/src/core/spawn.tsnew file mode 100644index 0000000000..f44475d775--- /dev/null+++ b/src/core/spawn.ts@@ -0,0 +1,105 @@+/**+ * The one module in src/ that launches subprocesses, so that none of them+ * opens a console window on Windows (#4992). Contributed by+ * @rokas-tarasevicius (PR #6105); wave 14 lands it as a ratchet, so sites+ * still importing child_process directly are listed in+ * scripts/check-windows-hide.ts and migrate one by one.+ *+ * On Windows a `detached: true` child has no console (Bun starts it with+ * DETACHED_PROCESS). Every console program such a process launches without+ * `windowsHide` gets a new, visible console window that takes keyboard focus:+ * git, PowerShell, or the CLI re-executing itself. Any gbrain command can run+ * that way (the Stop-hook push, the backup check, the job supervisor, its+ * worker and every job child), so each wrapper here defaults+ * `windowsHide: true`. An explicit `windowsHide: false` is kept, for a launcher+ * that must show a window. The option does nothing on other platforms.+ *+ * The wrappers look up `child_process` and `Bun` at call time, so a test's+ * `spyOn(childProcess, 'spawn')` or `spyOn(Bun, 'spawn')` still sees the call.+ * `scripts/check-windows-hide.ts` (in `bun run verify`) fails on any other+ * runtime use of `child_process` or `Bun.spawn*` in src/ outside its+ * not-yet-migrated list.+ *+ * Trade-off (Windows only): with every stdio stream piped or ignored, libuv+ * turns `windowsHide` into CREATE_NO_WINDOW and the child gets a windowless+ * console of its own, so a program that prompts on the console directly+ * prompts invisibly. gbrain's networked git calls set GIT_TERMINAL_PROMPT=0+ * (and git-remote.ts SSH_ASKPASS_REQUIRE=never); launches with inherited+ * stdio still attach to the terminal.+ */+import * as childProcess from 'node:child_process';+import { promisify } from 'node:util';++export type {+ ChildProcess,+ ExecFileException,+ ExecFileSyncOptionsWithStringEncoding,+ SpawnOptions,+} from 'node:child_process';++type Options = { windowsHide?: boolean } | null | undefined;++/** Call a launcher past its overloads; each wrapper keeps the original's type. */+function launch(fn: unknown, ...args: unknown[]): unknown {+ return (fn as (...a: unknown[]) => unknown)(...args);+}++/** `options` with `windowsHide` defaulted to true. */+function hidden(options: unknown): object {+ const given = options as Options;+ return { ...given, windowsHide: given?.windowsHide ?? true };+}++/** Node's `(file, args?, options?)` overloads as `[args, hidden options]`. */+function argsAndOptions(rest: unknown[]): [unknown, object] {+ const [first, second] = rest;+ return Array.isArray(first) || first == null ? [first ?? [], hidden(second)] : [[], hidden(first)];+}++/** A trailing callback, removed from `rest`. */+function takeCallback(rest: unknown[]): unknown[] {+ return typeof rest[rest.length - 1] === 'function' ? [rest.pop()] : [];+}++export const spawn = ((command: string, ...rest: unknown[]) =>+ launch(childProcess.spawn, command, ...argsAndOptions(rest))) as typeof childProcess.spawn;++export const spawnSync = ((command: string, ...rest: unknown[]) =>+ launch(childProcess.spawnSync, command, ...argsAndOptions(rest))) as typeof childProcess.spawnSync;++export const execFileSync = ((file: string, ...rest: unknown[]) =>+ launch(childProcess.execFileSync, file, ...argsAndOptions(rest))) as typeof childProcess.execFileSync;++export const execSync = ((command: string, options?: unknown) =>+ launch(childProcess.execSync, command, hidden(options))) as typeof childProcess.execSync;++export const execFile = ((file: string, ...rest: unknown[]) => {+ const callback = takeCallback(rest);+ return launch(childProcess.execFile, file, ...argsAndOptions(rest), ...callback);+}) as typeof childProcess.execFile;++export const exec = ((command: string, ...rest: unknown[]) => {+ const callback = takeCallback(rest);+ return launch(childProcess.exec, command, hidden(rest[0]), ...callback);+}) as typeof childProcess.exec;++// `promisify(execFile)` / `promisify(exec)` resolve `{ stdout, stderr }`+// through Node's custom promisified forms; keep that shape for the wrappers.+Object.defineProperty(execFile, promisify.custom, {+ value: (file: string, ...rest: unknown[]) =>+ launch(promisify(childProcess.execFile), file, ...argsAndOptions(rest)),+});+Object.defineProperty(exec, promisify.custom, {+ value: (command: string, options?: unknown) =>+ launch(promisify(childProcess.exec), command, hidden(options)),+});++export const bunSpawn = ((first: unknown, options?: unknown) =>+ Array.isArray(first)+ ? launch(Bun.spawn, first, hidden(options))+ : launch(Bun.spawn, hidden(first))) as typeof Bun.spawn;++export const bunSpawnSync = ((first: unknown, options?: unknown) =>+ Array.isArray(first)+ ? launch(Bun.spawnSync, first, hidden(options))+ : launch(Bun.spawnSync, hidden(first))) as typeof Bun.spawnSync;diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex 647ebce48c..a804022b71 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -57,7 +57,7 @@ import {} from 'fs';import { dirname, join, resolve } from 'path';import { createHash, randomBytes } from 'crypto';-import { execFileSync } from 'child_process';+import { execFileSync } from './spawn.ts';import { GIT_ENV, GIT_ENV_AUTH, GIT_SSRF_SUBCOMMAND_FLAGS, detectDefaultBranch, divergenceSafePull } from './git-remote.ts';import { loadConfigFileOnly } from './config.ts';import { ensureGbrainHome } from './gbrain-home.ts';diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-bun-spawn/src/core/new-tailscale.ts b/test/fixtures/guards/check-windows-hide.ts/bad-bun-spawn/src/core/new-tailscale.tsnew file mode 100644index 0000000000..c51a508901--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-bun-spawn/src/core/new-tailscale.ts@@ -0,0 +1,3 @@+export function status(): number {+ return Bun.spawnSync(['tailscale', 'status']).exitCode;+}diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-dynamic/src/core/new-transcription.ts b/test/fixtures/guards/check-windows-hide.ts/bad-dynamic/src/core/new-transcription.tsnew file mode 100644index 0000000000..a58b506284--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-dynamic/src/core/new-transcription.ts@@ -0,0 +1,4 @@+export async function tempDir(): Promise<string> {+ const { execFileSync } = await import('child_process');+ return execFileSync('mktemp', ['-d'], { encoding: 'utf8' }).trim();+}diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/spawn.ts b/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/spawn.tsnew file mode 100644index 0000000000..a867df7eb1--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/spawn.ts@@ -0,0 +1,3 @@+import * as childProcess from 'node:child_process';++export const spawn = childProcess.spawn;diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/worker.ts b/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/worker.tsnew file mode 100644index 0000000000..3ba4323da8--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-opt-out/src/core/worker.ts@@ -0,0 +1,5 @@+import { spawn } from './spawn.ts';++export function startWorker(cli: string): void {+ spawn(cli, ['jobs', 'work'], { stdio: 'inherit', windowsHide: false });+}diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/spawn.ts b/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/spawn.tsnew file mode 100644index 0000000000..7a20b4dc33--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/spawn.ts@@ -0,0 +1,5 @@+import * as childProcess from 'node:child_process';++export type { ChildProcess } from 'node:child_process';+export const spawn = childProcess.spawn;+export const bunSpawn = Bun.spawn;diff --git a/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/tailscale.ts b/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/tailscale.tsnew file mode 100644index 0000000000..3fe1f64b74--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad-stale-migration/src/core/tailscale.ts@@ -0,0 +1,2 @@+import { bunSpawn } from './spawn.ts';+export const status = () => bunSpawn(['tailscale', 'status']);diff --git a/test/fixtures/guards/check-windows-hide.ts/bad/src/commands/new-command.ts b/test/fixtures/guards/check-windows-hide.ts/bad/src/commands/new-command.tsnew file mode 100644index 0000000000..2b21dfb440--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/bad/src/commands/new-command.ts@@ -0,0 +1,5 @@+import { spawn } from 'node:child_process';++export function spawnDetachedPush(exec: string, argv: string[]): void {+ spawn(exec, argv, { detached: true, stdio: 'ignore' }).unref();+}diff --git a/test/fixtures/guards/check-windows-hide.ts/good/src/core/spawn.ts b/test/fixtures/guards/check-windows-hide.ts/good/src/core/spawn.tsnew file mode 100644index 0000000000..7a20b4dc33--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/good/src/core/spawn.ts@@ -0,0 +1,5 @@+import * as childProcess from 'node:child_process';++export type { ChildProcess } from 'node:child_process';+export const spawn = childProcess.spawn;+export const bunSpawn = Bun.spawn;diff --git a/test/fixtures/guards/check-windows-hide.ts/good/src/core/tailscale.ts b/test/fixtures/guards/check-windows-hide.ts/good/src/core/tailscale.tsnew file mode 100644index 0000000000..b9dbb5a561--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/good/src/core/tailscale.ts@@ -0,0 +1 @@+export const status = () => Bun.spawn(['tailscale', 'status']);diff --git a/test/fixtures/guards/check-windows-hide.ts/good/src/core/worker.ts b/test/fixtures/guards/check-windows-hide.ts/good/src/core/worker.tsnew file mode 100644index 0000000000..96a88a129a--- /dev/null+++ b/test/fixtures/guards/check-windows-hide.ts/good/src/core/worker.ts@@ -0,0 +1,10 @@+import type { SpawnOptions } from 'node:child_process';+import { bunSpawn, spawn, type ChildProcess } from './spawn.ts';++export function startWorker(cli: string, options: SpawnOptions): ChildProcess {+ return spawn(cli, ['jobs', 'work'], { ...options, detached: true, windowsHide: true });+}++export function probe(argv: string[]): ReturnType<typeof Bun.spawn> {+ return bunSpawn(argv, { stdout: 'pipe' });+}diff --git a/test/fixtures/windows-console/console-less-launcher.ts b/test/fixtures/windows-console/console-less-launcher.tsnew file mode 100644index 0000000000..563ea3f271--- /dev/null+++ b/test/fixtures/windows-console/console-less-launcher.ts@@ -0,0 +1,71 @@+/**+ * Launcher for test/windows-hidden-console.test.ts (Windows only).+ *+ * The test starts it with spawnDetachedSupervisor, the production+ * `gbrain jobs supervisor start --detach` path, so it runs with no console like+ * every detached gbrain process. It launches the console probe (argv[3], also+ * on PATH as git.exe) through raw child_process without windowsHide (the+ * control), the supervisor's worker spawn, the Stop-hook push's git call and+ * every launcher in src/core/spawn.ts, then writes what each probe saw to+ * <argv[2]>/result.json.+ */+import { spawnSync as unhiddenSpawnSync } from 'node:child_process';+import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { ChildWorkerSupervisor } from '../../../src/core/minions/child-worker-supervisor.ts';+import { resolveWorkspaceRoot } from '../../../src/core/workspace-push.ts';+import { consoleState } from './console-state.ts';++const [dir, probe] = process.argv.slice(2);+const pathKey = Object.keys(process.env).find(k => k.toUpperCase() === 'PATH') ?? 'PATH';+process.env[pathKey] = `${dirname(probe)};${process.env[pathKey] ?? ''}`;+const results: Record<string, unknown> = { launcher: consoleState() };++async function record(label: string, launch: () => unknown): Promise<void> {+ const out = join(dir, `${label.replace(/\W+/g, '-')}.json`);+ process.env.GBRAIN_TEST_CONSOLE_STATE_OUT = out;+ try {+ await launch();+ for (let waited = 0; !existsSync(out) && waited < 30_000; waited += 50) await Bun.sleep(50);+ results[label] = existsSync(out) ? JSON.parse(readFileSync(out, 'utf8')) : 'probe did not run';+ } catch (error) {+ results[label] = `launch failed: ${error}`;+ }+}++const env = () => ({ ...process.env });+const exited = (child: { once(event: 'exit', listener: () => void): unknown }) => new Promise<void>(resolve => child.once('exit', resolve));++await record('control', () => unhiddenSpawnSync(probe, [], { env: env() }));+await record('worker', async () => {+ let stopping = false;+ await new ChildWorkerSupervisor({+ cliPath: probe, args: [], maxCrashes: 1, _backoffFloorMs: 1,+ isStopping: () => stopping,+ onMaxCrashesExceeded: () => { stopping = true; },+ onEvent: event => { if (event.kind === 'worker_exited') stopping = true; },+ }).run();+});+await record('git', () => resolveWorkspaceRoot(dir));++let seam: Record<string, (...args: any[]) => any> | null = null;+try {+ seam = await import('../../../src/core/spawn.ts');+} catch (error) {+ results.seam = `missing: ${error}`;+}+if (seam) {+ const s = seam;+ await record('spawn', () => exited(s.spawn(probe, [], { env: env(), stdio: 'ignore' })));+ await record('spawnSync', () => s.spawnSync(probe, { env: env() }));+ await record('execFile', () => new Promise(resolve => s.execFile(probe, { env: env() }, resolve)));+ await record('execFileSync', () => s.execFileSync(probe, [], { env: env() }));+ await record('exec', () => new Promise(resolve => s.exec(`"${probe}"`, { env: env() }, resolve)));+ await record('execSync', () => s.execSync(`"${probe}"`, { env: env() }));+ await record('bunSpawn', () => s.bunSpawn([probe], { env: env() }).exited);+ await record('bunSpawnSync', () => s.bunSpawnSync({ cmd: [probe], env: env() }));+}++writeFileSync(join(dir, 'result.tmp'), JSON.stringify(results));+renameSync(join(dir, 'result.tmp'), join(dir, 'result.json'));+process.exit(0);diff --git a/test/fixtures/windows-console/console-state.ts b/test/fixtures/windows-console/console-state.tsnew file mode 100644index 0000000000..fabe881018--- /dev/null+++ b/test/fixtures/windows-console/console-state.ts@@ -0,0 +1,26 @@+/**+ * Console probe for test/windows-hidden-console.test.ts (Windows only).+ *+ * `consoleState()` reports whether this process has a console and whether that+ * console's window is visible. Run as a program, it writes that state as JSON+ * to $GBRAIN_TEST_CONSOLE_STATE_OUT. The test compiles it to a console .exe,+ * the same kind of binary as gbrain.exe and git.exe, so it also stands in for+ * git on PATH.+ */+import { dlopen, FFIType } from 'bun:ffi';+import { writeFileSync } from 'node:fs';++export function consoleState(): { console: boolean; visibleWindow: boolean } {+ const kernel32 = dlopen('kernel32.dll', {+ GetConsoleWindow: { args: [], returns: FFIType.ptr },+ GetConsoleProcessList: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.u32 },+ });+ const user32 = dlopen('user32.dll', { IsWindowVisible: { args: [FFIType.ptr], returns: FFIType.i32 } });+ const window = kernel32.symbols.GetConsoleWindow();+ return {+ console: kernel32.symbols.GetConsoleProcessList(new Uint32Array(8), 8) > 0,+ visibleWindow: !!window && user32.symbols.IsWindowVisible(window) !== 0,+ };+}++if (import.meta.main) writeFileSync(process.env.GBRAIN_TEST_CONSOLE_STATE_OUT!, JSON.stringify(consoleState()));diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.tsindex f1b7f35a3c..f40a88ea20 100644--- a/test/operations-trust-boundary.test.ts+++ b/test/operations-trust-boundary.test.ts@@ -483,8 +483,10 @@ describe('ops-module system-access containment — top-level fs/child_process im// GRANULARITY (the closest enforceable version of the file→ops mapping):// - DETECTION is per-FILE and text-based: a static top-level ESM// import/re-export of 'fs' / 'fs/promises' / 'child_process' (with or- // without the node: prefix). Static import statements are top-level by- // ESM grammar, so matching the `from '<specifier>'` clause is exact.+ // without the node: prefix), or of src/core/spawn.ts, the seam every+ // src/ subprocess launch goes through. Static import statements are+ // top-level by ESM grammar, so matching the `from '<specifier>'`+ // clause is exact.// Lazy dynamic `await import('node:fs')` INSIDE a handler is// deliberately out of scope (schema-packs.ts and skillopt.ts use that// form today) — it is runtime-gated per call site, the same doctrine@@ -520,7 +522,7 @@ describe('ops-module system-access containment — top-level fs/child_process im// import keyword at a line start) or commented-out imports (`//` and `*`// are not whitespace, so the line-start anchor excludes them).const SYSTEM_IMPORT_RE =- /(?:^|\n)\s*(?:import|export)\s+(?:[^;]*?\bfrom\s+)?['"](?:node:)?(?:fs|fs\/promises|child_process)['"]/;+ /(?:^|\n)\s*(?:import|export)\s+(?:[^;]*?\bfrom\s+)?['"](?:(?:node:)?(?:fs|fs\/promises|child_process)|\.\.\/spawn\.ts)['"]/;/*** Canonical ops contributed by one ops module: import it, walk every@@ -557,6 +559,8 @@ describe('ops-module system-access containment — top-level fs/child_process imexpect(SYSTEM_IMPORT_RE.test(`import {\n readFileSync,\n writeFileSync,\n} from 'fs/promises';`)).toBe(true);expect(SYSTEM_IMPORT_RE.test(`import 'node:fs';`)).toBe(true);expect(SYSTEM_IMPORT_RE.test(`export { execSync } from 'node:child_process';`)).toBe(true);+ expect(SYSTEM_IMPORT_RE.test(`import { execFileSync } from '../spawn.ts';`)).toBe(true);+ expect(SYSTEM_IMPORT_RE.test(`import { buildSpawnInvocation } from '../minions/spawn-helpers.ts';`)).toBe(false);expect(SYSTEM_IMPORT_RE.test(`const nodeFs = await import('node:fs');`)).toBe(false);expect(SYSTEM_IMPORT_RE.test(`import { resolve } from 'node:path';`)).toBe(false);expect(SYSTEM_IMPORT_RE.test(`code();\n// import { x } from 'node:fs'`)).toBe(false);diff --git a/test/scripts/windows-hide-guard.test.ts b/test/scripts/windows-hide-guard.test.tsnew file mode 100644index 0000000000..b973e0a065--- /dev/null+++ b/test/scripts/windows-hide-guard.test.ts@@ -0,0 +1,107 @@+/**+ * #4992: scripts/check-windows-hide.ts keeps every NEW subprocess launch in+ * src/ behind src/core/spawn.ts (which defaults windowsHide: true): it fails+ * on a runtime child_process import or a Bun.spawn* call anywhere else, and+ * on an explicit windowsHide: false outside its allowlist. It is a ratchet: a+ * file in NOT_YET_MIGRATED may still launch directly, and loses that licence+ * (stale entry) the moment it stops. Contributed by @rokas-tarasevicius+ * (PR #6105); the ratchet cases are wave 14's.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-windows-hide.ts');+const SEAM = "import * as childProcess from 'node:child_process';\nexport const spawn = childProcess.spawn;\nexport const bunSpawn = Bun.spawn;\n";+const dirs: string[] = [];+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++function run(files: Record<string, string>) {+ const tree = mkdtempSync(join(tmpdir(), 'gbrain-windows-hide-'));+ dirs.push(tree);+ for (const [rel, body] of Object.entries({ 'src/core/spawn.ts': SEAM, ...files })) {+ mkdirSync(join(tree, rel, '..'), { recursive: true });+ writeFileSync(join(tree, rel), body);+ }+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: tree } });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}++describe('check-windows-hide.ts', () => {+ test.each([+ ['a named import', "import { spawn } from 'node:child_process';\nspawn('git', [], { detached: true });\n", 'imports child_process directly'],+ ['the bare specifier', "import { execFileSync } from 'child_process';\nexecFileSync('git');\n", 'imports child_process directly'],+ ['a namespace import', "import * as cp from 'node:child_process';\ncp.spawn('git');\n", 'imports child_process directly'],+ ['a value import beside a type', "import { spawn, type ChildProcess } from 'node:child_process';\nexport let c: ChildProcess = spawn('git');\n", 'imports child_process directly'],+ ['a re-export', "export { spawn } from 'node:child_process';\n", 'imports child_process directly'],+ ['a dynamic import', "export async function f() { const { spawn } = await import('child_process'); spawn('git'); }\n", 'loads child_process with import()'],+ ['a require', "export function f() { const { spawnSync } = require('node:child_process'); spawnSync('git'); }\n", 'loads child_process with require()'],+ ])('%s fails with code, location, fix and docs anchor', (_label, body, what) => {+ const r = run({ 'src/commands/new-command.ts': body });+ expect(r.code).toBe(1);+ expect(r.out).toContain(`FAIL [windows_hide_direct_child_process]: src/commands/new-command.ts:`);+ expect(r.out).toContain(what);+ expect(r.out).toContain('Fix: import it from src/core/spawn.ts, which defaults windowsHide: true');+ expect(r.out).toContain('See: docs/TESTING.md#windows-hidden-console-guard');+ });++ test.each([+ ['Bun.spawn', 'bunSpawn'],+ ['Bun.spawnSync', 'bunSpawnSync'],+ ])('%s fails and names its wrapper', (call, wrapper) => {+ const r = run({ 'src/core/new-tailscale.ts': `export const p = ${call}(['tailscale', 'status']);\n` });+ expect(r.code).toBe(1);+ expect(r.out).toContain(`FAIL [windows_hide_direct_bun_spawn]: src/core/new-tailscale.ts:1 calls ${call}`);+ expect(r.out).toContain(`Fix: call ${wrapper} from src/core/spawn.ts`);+ });++ test('an explicit windowsHide: false fails outside the allowlist and passes in it', () => {+ const optOut = "import { bunSpawn } from '../spawn.ts';\nexport function open(argv: string[]) { bunSpawn(argv, { windowsHide: false }); }\n";+ const outside = run({ 'src/core/creds/other.ts': optOut });+ expect(outside.code).toBe(1);+ expect(outside.out).toContain('FAIL [windows_hide_opt_out]: src/core/creds/other.ts:2 sets windowsHide: false');+ const listed = run({ 'src/core/creds/redirect.ts': optOut });+ expect(listed.out).toContain('check-windows-hide: ok');+ expect(listed.code).toBe(0);+ });++ test('an allowlisted file that no longer opts out fails as stale', () => {+ const r = run({ 'src/core/creds/redirect.ts': "import { bunSpawn } from '../spawn.ts';\nexport function open(argv: string[]) { bunSpawn(argv); }\n" });+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL [windows_hide_stale_allowlist]: src/core/creds/redirect.ts');+ });++ test('the seam itself, seam imports, type-only imports and typeof Bun.spawn pass', () => {+ const r = run({+ 'src/core/worker.ts': [+ "import type { SpawnOptions } from 'node:child_process';",+ "import { type ChildProcess as Child } from 'child_process';",+ "import { bunSpawn, spawn } from './spawn.ts';",+ 'export function start(cli: string, o: SpawnOptions): Child { return spawn(cli, [], { ...o, detached: true }); }',+ "export function probe(): ReturnType<typeof Bun.spawn> { return bunSpawn(['git'], { windowsHide: true }); }",+ "export const lazy = () => import('./spawn.ts');",+ ].join('\n') + '\n',+ });+ expect(r.out).toContain('check-windows-hide: ok');+ expect(r.code).toBe(0);+ });++ test('the ratchet: a listed file may still launch directly, and fails as stale once it stops', () => {+ const listed = run({ 'src/core/tailscale.ts': "export const p = Bun.spawn(['tailscale', 'status']);\n" });+ expect(listed.out).toContain('check-windows-hide: ok');+ expect(listed.code).toBe(0);+ const migrated = run({ 'src/core/tailscale.ts': "import { bunSpawn } from './spawn.ts';\nexport const p = bunSpawn(['tailscale', 'status']);\n" });+ expect(migrated.code).toBe(1);+ expect(migrated.out).toContain('FAIL [windows_hide_stale_migration_entry]: src/core/tailscale.ts no longer launches subprocesses directly');+ expect(migrated.out).toContain('Fix: delete its NOT_YET_MIGRATED entry');+ });++ test('the repository passes', () => {+ const r = spawnSync(process.execPath, [GUARD], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: REPO } });+ expect(`${r.stdout}${r.stderr}`).toContain('check-windows-hide: ok');+ expect(r.status).toBe(0);+ });+});diff --git a/test/spawn-windows-hide.test.ts b/test/spawn-windows-hide.test.tsnew file mode 100644index 0000000000..12a30b15ee--- /dev/null+++ b/test/spawn-windows-hide.test.ts@@ -0,0 +1,138 @@+/**+ * #4992: every subprocess gbrain launches defaults `windowsHide: true` through+ * src/core/spawn.ts, so a detached gbrain process on Windows (no console)+ * stops opening a visible console window for each program it runs.+ *+ * The wrappers are checked for every argument shape Node accepts, and the+ * production sites behind the reported windows (the detached supervisor, its+ * worker, the Stop-hook push's git) are checked at the child_process boundary.+ * The window itself is observed natively in test/windows-hidden-console.test.ts.+ */+import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';+import * as childProcess from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { promisify } from 'node:util';+import * as seam from '../src/core/spawn.ts';+import { spawnDetachedSupervisor } from '../src/core/minions/detached-stderr.ts';+import { ChildWorkerSupervisor } from '../src/core/minions/child-worker-supervisor.ts';+import { resolveWorkspaceRoot } from '../src/core/workspace-push.ts';++afterEach(() => { mock.restore(); });++/** Replace `name` on child_process with a recorder; returns the recorded argument lists. */+function record(name: 'spawn' | 'spawnSync' | 'execFile' | 'execFileSync' | 'exec' | 'execSync') {+ const calls: unknown[][] = [];+ spyOn(childProcess, name).mockImplementation(((...args: unknown[]) => { calls.push(args); return 'recorded'; }) as never);+ return calls;+}++describe('src/core/spawn.ts defaults windowsHide: true', () => {+ const callback = () => {};++ test.each([+ ['spawn(cmd)', () => seam.spawn('cmd'), [[], { windowsHide: true }]],+ ['spawn(cmd, args)', () => seam.spawn('cmd', ['a']), [['a'], { windowsHide: true }]],+ ['spawn(cmd, options)', () => seam.spawn('cmd', { cwd: '/w' }), [[], { cwd: '/w', windowsHide: true }]],+ ['spawn(cmd, args, options)', () => seam.spawn('cmd', ['a'], { detached: true, stdio: 'ignore' }), [['a'], { detached: true, stdio: 'ignore', windowsHide: true }]],+ ['spawn(cmd, undefined, options)', () => seam.spawn('cmd', undefined as never, { cwd: '/w' }), [[], { cwd: '/w', windowsHide: true }]],+ ['spawn explicit false', () => seam.spawn('cmd', ['a'], { windowsHide: false }), [['a'], { windowsHide: false }]],+ ])('%s', (_label, call, rest) => {+ const calls = record('spawn');+ call();+ expect(calls).toEqual([['cmd', ...rest]]);+ });++ test.each([+ ['spawnSync', () => seam.spawnSync('cmd', { encoding: 'utf8' }), 'spawnSync', [[], { encoding: 'utf8', windowsHide: true }]],+ ['execFileSync(file, args, options)', () => seam.execFileSync('git', ['status'], { encoding: 'utf8', timeout: 5 }), 'execFileSync', [['status'], { encoding: 'utf8', timeout: 5, windowsHide: true }]],+ ['execFileSync(file, options)', () => seam.execFileSync('git', { stdio: 'pipe' }), 'execFileSync', [[], { stdio: 'pipe', windowsHide: true }]],+ ['execSync(command)', () => seam.execSync('git status'), 'execSync', [{ windowsHide: true }]],+ ['execSync explicit false', () => seam.execSync('git status', { windowsHide: false }), 'execSync', [{ windowsHide: false }]],+ ] as const)('%s', (_label, call, name, rest) => {+ const calls = record(name);+ call();+ expect(calls).toEqual([[name === 'execSync' ? 'git status' : name === 'spawnSync' ? 'cmd' : 'git', ...rest]]);+ });++ test.each([+ ['execFile(file, callback)', () => seam.execFile('git', callback), ['git', [], { windowsHide: true }, callback]],+ ['execFile(file, args, callback)', () => seam.execFile('git', ['log'], callback), ['git', ['log'], { windowsHide: true }, callback]],+ ['execFile(file, options, callback)', () => seam.execFile('git', { cwd: '/w' }, callback), ['git', [], { cwd: '/w', windowsHide: true }, callback]],+ ['execFile(file, args, options, callback)', () => seam.execFile('git', ['log'], { timeout: 9 }, callback), ['git', ['log'], { timeout: 9, windowsHide: true }, callback]],+ ['execFile(file, args, options)', () => seam.execFile('git', ['log'], { timeout: 9 }), ['git', ['log'], { timeout: 9, windowsHide: true }]],+ ])('%s', (_label, call, expected) => {+ const calls = record('execFile');+ call();+ expect(calls).toEqual([expected]);+ });++ test.each([+ ['exec(command, callback)', () => seam.exec('git log', callback), ['git log', { windowsHide: true }, callback]],+ ['exec(command, options, callback)', () => seam.exec('git log', { cwd: '/w' }, callback), ['git log', { cwd: '/w', windowsHide: true }, callback]],+ ])('%s', (_label, call, expected) => {+ const calls = record('exec');+ call();+ expect(calls).toEqual([expected]);+ });++ test('bunSpawn and bunSpawnSync default it in both call forms and keep an explicit false', () => {+ const spawned: unknown[][] = [];+ spyOn(Bun, 'spawn').mockImplementation(((...args: unknown[]) => { spawned.push(args); return {}; }) as never);+ spyOn(Bun, 'spawnSync').mockImplementation(((...args: unknown[]) => { spawned.push(args); return {}; }) as never);+ seam.bunSpawn(['git', 'log'], { stdout: 'pipe' });+ seam.bunSpawn({ cmd: ['git', 'log'] });+ seam.bunSpawnSync(['git', 'log']);+ seam.bunSpawnSync({ cmd: ['git', 'log'], windowsHide: false });+ expect(spawned).toEqual([+ [['git', 'log'], { stdout: 'pipe', windowsHide: true }],+ [{ cmd: ['git', 'log'], windowsHide: true }],+ [['git', 'log'], { windowsHide: true }],+ [{ cmd: ['git', 'log'], windowsHide: false }],+ ]);+ });++ test('real launches keep their results: sync output, async callback and promisified { stdout, stderr }', async () => {+ const script = ['-e', 'process.stdout.write("out"); process.stderr.write("err")'];+ expect(seam.execFileSync(process.execPath, script, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })).toBe('out');+ const viaCallback = await new Promise<string>((resolve, reject) =>+ seam.execFile(process.execPath, script, (error, stdout) => (error ? reject(error) : resolve(String(stdout)))));+ expect(viaCallback).toBe('out');+ expect(await promisify(seam.execFile)(process.execPath, script)).toEqual({ stdout: 'out', stderr: 'err' });+ });+});++describe('the spawn sites behind the reported windows pass windowsHide: true', () => {+ test('the detached job supervisor (`jobs supervisor start --detach`)', () => {+ const spawn = spyOn(childProcess, 'spawn');+ const started = spawnDetachedSupervisor(process.execPath, '-e', ['void 0']);+ expect(started.pid).toBeGreaterThan(0);+ expect(spawn.mock.calls[0]?.[2]).toMatchObject({ detached: true, windowsHide: true });+ });++ test("the supervisor's worker", async () => {+ const spawn = spyOn(childProcess, 'spawn');+ let stopping = false;+ await new ChildWorkerSupervisor({+ cliPath: process.execPath, args: ['-e', 'void 0'], maxCrashes: 1, _backoffFloorMs: 1,+ isStopping: () => stopping,+ onMaxCrashesExceeded: () => { stopping = true; },+ onEvent: event => { if (event.kind === 'worker_exited') stopping = true; },+ }).run();+ expect(spawn.mock.calls.length).toBe(1);+ expect(spawn.mock.calls[0][2]).toMatchObject({ stdio: 'inherit', windowsHide: true });+ });++ test("the Stop-hook push's git commands", () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-push-git-'));+ try {+ const git = spyOn(childProcess, 'execFileSync');+ resolveWorkspaceRoot(dir);+ expect(git.mock.calls[0]?.[0]).toBe('git');+ expect(git.mock.calls[0]?.[2]).toMatchObject({ windowsHide: true });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/test/windows-hidden-console.test.ts b/test/windows-hidden-console.test.tsnew file mode 100644index 0000000000..61922592e4--- /dev/null+++ b/test/windows-hidden-console.test.ts@@ -0,0 +1,81 @@+/**+ * #4992 on Windows: a detached gbrain process (the Stop-hook push, the backup+ * check, the job supervisor, its worker, every job child) has no console, so+ * each console program it launches without windowsHide opens a visible+ * console window that takes focus.+ *+ * The launcher fixture runs detached through the production supervisor path+ * and launches a compiled console probe the ways gbrain does; the probe+ * reports whether its own console window is visible. The CONTROL launch (raw+ * child_process, no windowsHide) must show a window first: a runner without+ * an interactive console cannot tell a hidden launch from one that never had+ * a window, so that case fails as `windows_console_gate_unsupported` and the+ * seam assertions are never a vacuous green. Runs natively on the+ * windows-latest row of the test.yml security-regressions job; on another+ * platform the whole describe is reported skipped, not passed. Contributed by+ * @rokas-tarasevicius (PR #6105).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawnDetachedSupervisor } from '../src/core/minions/detached-stderr.ts';++const FIXTURES = join(import.meta.dir, 'fixtures', 'windows-console');+const HIDDEN = { console: true, visibleWindow: false };+const SEAM_LAUNCHERS = ['spawn', 'spawnSync', 'execFile', 'execFileSync', 'exec', 'execSync', 'bunSpawn', 'bunSpawnSync'];++describe.skipIf(process.platform !== 'win32')('console windows from a detached gbrain process (#4992)', () => {+ let dir = '';+ let results: Record<string, unknown> = {};++ beforeAll(async () => {+ dir = mkdtempSync(join(tmpdir(), 'gbrain-console-'));+ mkdirSync(join(dir, 'bin'));+ const probe = join(dir, 'bin', 'git.exe');+ const build = spawnSync(process.execPath, ['build', '--compile', '--no-compile-autoload-bunfig', join(FIXTURES, 'console-state.ts'), '--outfile', probe], { encoding: 'utf8' });+ if (build.status !== 0) throw new Error(`probe build failed: ${build.stderr}`);++ const started = spawnDetachedSupervisor(process.execPath, join(FIXTURES, 'console-less-launcher.ts'), [dir, probe]);+ const result = join(dir, 'result.json');+ for (let waited = 0; !existsSync(result) && waited < 120_000; waited += 100) await Bun.sleep(100);+ if (!existsSync(result)) {+ const stderr = started.stderrPath && existsSync(started.stderrPath) ? readFileSync(started.stderrPath, 'utf8') : '';+ throw new Error(`launcher wrote no result (pid ${started.pid}): ${stderr.slice(-2000)}`);+ }+ results = JSON.parse(readFileSync(result, 'utf8'));+ process.stderr.write(`Windows console windows: ${JSON.stringify({ arch: process.arch, runtime: Bun.version, results })}\n`);+ }, 240_000);++ afterAll(() => { if (dir) rmSync(dir, { recursive: true, force: true }); });++ test('control: the detached process has no console, and an unhidden launch from it shows a window', () => {+ expect(results.launcher).toEqual({ console: false, visibleWindow: false });+ if (JSON.stringify(results.control) !== JSON.stringify({ console: true, visibleWindow: true })) {+ throw new Error(`windows_console_gate_unsupported: the unhidden control launch showed no visible console window (${JSON.stringify(results.control)}), so this runner cannot discriminate a hidden launch; the seam assertions below are not evidence here`);+ }+ });++ const gated = () => {+ if (JSON.stringify(results.control) !== JSON.stringify({ console: true, visibleWindow: true })) {+ throw new Error('windows_console_gate_unsupported: see the control test');+ }+ };++ test("the job supervisor's worker opens no visible console window", () => {+ gated();+ expect(results.worker).toEqual(HIDDEN);+ });++ test("the Stop-hook push's git command opens no visible console window", () => {+ gated();+ expect(results.git).toEqual(HIDDEN);+ });++ test('every src/core/spawn.ts launcher opens no visible console window', () => {+ gated();+ const seen = Object.fromEntries(SEAM_LAUNCHERS.map(name => [name, results[name] ?? results.seam]));+ expect(seen).toEqual(Object.fromEntries(SEAM_LAUNCHERS.map(name => [name, HIDDEN])));+ });+});