Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(minions): hide the last Windows spawn sites and kill Windows job trees with taskkill (#4992)

time-attack18e5eb5185c1
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index d28ff6ec17..229bed65f4 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -48,7 +48,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/handlers/shell-validate.ts` — `validateShellJobParams(data, opts?)` shared pre-enqueue validator. Throws `UnrecoverableError` with paste-ready operator hints on every failure. Three rules: (1) cmd/argv/cwd/env shape, (2) inherit array shape + snake_case regex per element (prototype-pollution defense), (3) fail-fast on missing config value with `gbrain config set <key>` hint. Optional `redact_secrets?: boolean` for output-side scrubbing. Deliberately does NOT police WHICH secrets the agent passes — single-uid trust model. Test seam: `opts.config` drives the validator hermetically without mocking. Re-called at `shell.ts` handler entry for defense-in-depth (catches rows that bypassed the pre-enqueue validator).
-- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (`registerBuiltinHandlers`) and self-gated: unless `GBRAIN_ALLOW_SHELL_JOBS === '1'` in the worker env — set by `gbrain jobs work --allow-shell-jobs` after the cwd-`.env` preflight, or exported from the operator's shell (a cwd `.env` cannot set it: `env-trust.ts`) — a claimed job throws `UnrecoverableError` naming `--allow-shell-jobs` (dead-letter, no retries). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker. #5062: on POSIX the job runs in its own process group (`detached`); abort signals the whole group, escalates SIGTERM→SIGKILL by group liveness (`processGroupAlive` in `job-isolation.ts`, not `proc.killed`), and after the leader exits anything left in the group is terminated and confirmed gone before the job settles (a backgrounded `cmd &` no longer outlives its job). Windows keeps the direct-child kill. Pinned by `test/minions-shell-process-tree.test.ts`.
+- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides + `inherit:`-resolved keys. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Always registered (`registerBuiltinHandlers`) and self-gated: unless `GBRAIN_ALLOW_SHELL_JOBS === '1'` in the worker env — set by `gbrain jobs work --allow-shell-jobs` after the cwd-`.env` preflight, or exported from the operator's shell (a cwd `.env` cannot set it: `env-trust.ts`) — a claimed job throws `UnrecoverableError` naming `--allow-shell-jobs` (dead-letter, no retries). `ShellJobParams.inherit?: string[]` is a free-form list of snake_case config-key names; the worker resolves each via `loadConfig()` and injects the value under the derived env key (`database_url` → `GBRAIN_DATABASE_URL`; else uppercased). Names persist in `minion_jobs.data` (and the shell-audit JSONL); values never do. The canonical validator `validateShellJobParams` (sibling `shell-validate.ts`) runs PRE-ENQUEUE in both submit surfaces — `gbrain jobs submit shell` (jobs.ts:271) AND the `submit_job` op for `name='shell'` (operations.ts:2085); the handler-entry re-validation here is defense-in-depth (so validation can never run only AFTER `queue.add()` has persisted the row). The validator does NOT police which config keys the agent inherits — same-uid trust model treats the agent as a peer of the worker. #5062: on POSIX the job runs in its own process group (`detached`); abort signals the whole group, escalates SIGTERM→SIGKILL by group liveness (`processGroupAlive` in `job-isolation.ts`, not `proc.killed`), and after the leader exits anything left in the group is terminated and confirmed gone before the job settles (a backgrounded `cmd &` no longer outlives its job). On Windows abort signals the tree under the direct child with `signalProcessTree` (taskkill `/T`, forced by `/F` after the grace window; a refused polite close waits for that escalation, and only a failed forced kill falls back to `proc.kill`); liveness is the direct child's, so a descendant orphaned by its parent's exit is not reaped. Pinned by `test/minions-shell-process-tree.test.ts`.
- `src/core/minions/handlers/subagent-aggregator.ts` — `subagent_aggregator` handler. Claims AFTER all children resolve (queue guarantees every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds a deterministic mixed-outcome markdown summary. No LLM call.
@@ -66,7 +66,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.
-- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError` (a `SpendGroupRefusedError` keeps its envelope: code, fix, group amounts), `RateLeaseUnavailableError` (with its retry delay), and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; `spend-enforcement-v1` is advertised but required only for spend-authorized rows; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.
+- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError` (a `SpendGroupRefusedError` keeps its envelope: code, fix, group amounts), `RateLeaseUnavailableError` (with its retry delay), and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; `spend-enforcement-v1` is advertised but required only for spend-authorized rows; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. On Windows (no process groups) it runs `taskkillCommand`: `%SystemRoot%\System32\taskkill.exe /PID <pid> /T` for SIGTERM and `/T /F` for SIGKILL, by absolute path; a descendant whose parent already exited is outside the tree and survives. `signalProcessTree` returns `signalled` | `gone` (ESRCH, taskkill exit 128) | `failed` (state unknown); `killProcessGroup` is its boolean (`signalled`). Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death) and `test/spawn-windows-hide.test.ts` (taskkill argv and outcomes; native tree kill on the windows-latest row). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.
- `src/core/minions/legacy-cancel.ts` — `gbrain jobs cancel --select` (DX-T2, ENG-O5): selects live rows with SQL NULL or unsupported authority, hashes the full `cancelJobs` closure (selected rows plus parents that return from waiting-children to waiting), refuses a selection that would cascade to a descendant outside it (`legacy_job_selection_invalid`, E-T4), and applies under a table lock through `cancelJobs` in one transaction after re-hashing (`preview_changed` on drift). Tests: `test/jobs-cancel-select.test.ts`.
diff --git a/scripts/check-windows-hide.ts b/scripts/check-windows-hide.ts
index 533cf2246a..76bb6a2aed 100644
--- a/scripts/check-windows-hide.ts
+++ b/scripts/check-windows-hide.ts
@@ -42,12 +42,9 @@ const ALLOWLIST: Record<string, string> = {
*/
const NOT_YET_MIGRATED: Record<string, string> = {
'src/commands/bootstrap.ts': 'not yet migrated: open PR #6283, #6319 edits this file',
- 'src/commands/eval-longmemeval.ts': 'not yet migrated: open PR #6790 edits this file',
'src/commands/serve.ts': 'not yet migrated: open PR #6437 edits this file',
'src/commands/setup.ts': 'not yet migrated: open PR #6406 edits this file',
'src/commands/takes.ts': 'not yet migrated: open PR #6505 edits this file',
- 'src/commands/upgrade.ts': 'not yet migrated: open PR #6769 edits this file',
- 'src/core/bootstrap/verify.ts': 'not yet migrated: open PR #6793 edits this file',
'src/core/harness/install.ts': 'not yet migrated: open PR #6319, #6406 edits this file',
'src/core/persistence/engine-graduation.ts': 'not yet migrated: persistence write path, migrated with its owning work (GBRA-101)',
'src/core/persistence/sync-blobs.ts': 'not yet migrated: persistence write path, migrated with its owning work (GBRA-101)',
diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.ts
index 3954ada315..afa32c8d3b 100644
--- a/src/commands/eval-longmemeval.ts
+++ b/src/commands/eval-longmemeval.ts
@@ -42,7 +42,7 @@
import { homedir } from 'os';
import { join } from 'path';
-import { execFileSync } from 'child_process';
+import { execFileSync } from '../core/spawn.ts';
import { brainRecycler, createBenchmarkBrain, LME_BRAIN_RECYCLE_EVERY, resetTables } from '../eval/longmemeval/harness.ts';
export { LME_BRAIN_RECYCLE_EVERY };
import { haystackToPages, normalizeSessions } from '../eval/longmemeval/adapter.ts';
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 8db371223d..80a5cd3eba 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -1,5 +1,5 @@
import type { BrainEngine } from '../core/engine.ts';
-import { execSync, execFileSync, spawnSync } from 'child_process';
+import { execSync, execFileSync, spawnSync } from '../core/spawn.ts';
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';
import { basename, join, dirname, resolve } from 'path';
import { isNewerVersion, parseSemver, semverGt } from '../core/semver.ts';
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 0039ea3480..bb999e0552 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -905,6 +905,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
{ since: '0.60.307.0', text: 'A name written only in Katakana (an alias such as デン) no longer links a page that has it inside a longer Katakana word (インシデント, デンタル): the name must stand as a whole Katakana run, so 「デン」, デンに, 喫茶デン and デン・カフェ still link. A short name inside a real Katakana compound is refused too; add the compound as its own alias when it names the entity. Mention links already written that way are counted by `gbrain doctor` (`stale_mentions`) and removed by `gbrain extract links --by-mention --rebuild --source db`.', id: 'katakana_mention_boundaries' },
+ { since: '0.60.307.0', text: 'On Windows, cancelling or timing out a job now ends its whole process tree with taskkill: a per-job child and a shell job first get a polite close (`taskkill /T`), then a forced one (`/T /F`) after the grace window, instead of only the direct child being killed. A windowless console program refuses the polite close, so a cancelled Windows shell job now takes up to its 5-second grace window to end. A descendant whose parent already exited is no longer in the tree and is not ended.', id: 'windows_tree_kill' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/verify.ts b/src/core/bootstrap/verify.ts
index 244964d9ca..79239101a8 100644
--- a/src/core/bootstrap/verify.ts
+++ b/src/core/bootstrap/verify.ts
@@ -36,7 +36,7 @@ import { pendingReceiptOf, pollCommand, resolveCliWriteWaitMs, WRITE_WAIT_ENV }
import { maintenanceAttribution } from '../persistence/attribution.ts';
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { createHash, randomUUID } from 'node:crypto';
-import { execFileSync } from 'node:child_process';
+import { execFileSync } from '../spawn.ts';
import { join, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
diff --git a/src/core/minions/handlers/shell.ts b/src/core/minions/handlers/shell.ts
index 484dccf0a3..11c50cec16 100644
--- a/src/core/minions/handlers/shell.ts
+++ b/src/core/minions/handlers/shell.ts
@@ -34,7 +34,7 @@ import { deriveEnvKey, resolveInheritValue } from './shell-inherit.ts';
import { validateShellJobParams } from './shell-validate.ts';
import { redactSecretsInText } from './shell-redact.ts';
import { loadConfig } from '../../config.ts';
-import { killProcessGroup, processGroupAlive } from '../job-isolation.ts';
+import { killProcessGroup, processGroupAlive, signalProcessTree } from '../job-isolation.ts';
/** Environment variables passed through to shell children by default. Callers
* that need additional keys (e.g. a specific API token for a cron) must name
@@ -271,7 +271,8 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResul
// #5062: on POSIX the job runs in its own process group, so termination
// reaches every descendant (a shell's children and grandchildren), not
- // only the direct child. Windows keeps the direct-child kill path.
+ // only the direct child. Windows signals the tree under the direct child
+ // with taskkill (signalProcessTree), and liveness is the direct child's.
const ownGroup = process.platform !== 'win32';
let proc: ChildProcess;
try {
@@ -309,6 +310,7 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResul
killProcessGroup(pgid, signal);
return;
}
+ if (process.platform === 'win32' && (signalProcessTree(pid, signal) !== 'failed' || signal === 'SIGTERM')) return;
try { proc.kill(signal); } catch { /* proc already exited */ }
};
const stdoutTail = new TailBuffer(STDOUT_TAIL_MAX_BYTES);
diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.ts
index e0d5b30352..b3ba1fe019 100644
--- a/src/core/minions/job-isolation.ts
+++ b/src/core/minions/job-isolation.ts
@@ -40,7 +40,7 @@ import { JobDeferredError, UnrecoverableError } from './types.ts';
import { RateLeaseUnavailableError } from './handlers/subagent.ts';
import { SpendGroupRefusedError, type SpendRefusalEnvelope } from './spend-authorization.ts';
import { LocalConfigurationError, isLocalConfigurationError } from './configuration-error.ts';
-import { basename, delimiter, resolve } from 'node:path';
+import { basename, delimiter, resolve, win32 } from 'node:path';
/** Grace between group-SIGTERM and group-SIGKILL on abort. Deliberately
* inside the worker's 30s force-evict window so the evict path stays a
@@ -419,8 +419,23 @@ export function resolveChildCliInvocation(
return null;
}
+/** What signalling a process tree achieved: delivered to a live tree, the
+ * tree was already gone, or delivery failed (the tree's state is unknown). */
+export type ProcessTreeSignal = 'signalled' | 'gone' | 'failed';
+
+/** The Windows tree kill, by ABSOLUTE path like /bin/kill on POSIX:
+ * SIGTERM asks every process in the tree to close (`/T`), SIGKILL forces it
+ * (`/T /F`). A windowless console process refuses the polite form, so on
+ * Windows SIGTERM usually fails and the caller's SIGKILL escalation ends it. */
+export function taskkillCommand(pid: number, signal: 'SIGTERM' | 'SIGKILL'): [string, string[]] {
+ return [
+ win32.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe'),
+ ['/PID', String(pid), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])],
+ ];
+}
+
/**
- * Signal an entire process GROUP.
+ * Signal an entire process GROUP (POSIX) or process TREE (Windows).
*
* Children are spawned `detached: true`. Tini creates another group for its
* child, so callers must also signal that observed group. Neither group
@@ -428,33 +443,47 @@ export function resolveChildCliInvocation(
*
* Bun's process.kill() rejects negative pids (oven-sh/bun#15791), so on any
* throw other than ESRCH we fall back to POSIX /bin/kill, which
- * group-signals fine on darwin + linux. Returns true when the signal was
- * delivered to a live group; false when the group is already gone (ESRCH —
- * success for our purposes) or delivery failed.
+ * group-signals fine on darwin + linux.
+ *
+ * Windows has no process groups: taskkill `/T` walks the tree by parent pid
+ * from `pid`. A descendant whose parent already exited is no longer in that
+ * tree, so it survives (the orphaned-descendant limit); exit 128 means `pid`
+ * itself is gone.
*/
-export function killProcessGroup(pid: number, signal: 'SIGTERM' | 'SIGKILL'): boolean {
- if (!Number.isInteger(pid) || pid <= 1) return false;
+export function signalProcessTree(
+ pid: number, signal: 'SIGTERM' | 'SIGKILL', platform: NodeJS.Platform = process.platform,
+): ProcessTreeSignal {
+ if (!Number.isInteger(pid) || pid <= 1) return 'failed';
+ if (platform === 'win32') {
+ const [command, args] = taskkillCommand(pid, signal);
+ const res = spawnSync(command, args, { stdio: 'ignore', timeout: 10_000 });
+ return res.status === 0 ? 'signalled' : res.status === 128 ? 'gone' : 'failed';
+ }
try {
process.kill(-pid, signal);
- return true;
+ return 'signalled';
} catch (e) {
- const code = (e as NodeJS.ErrnoException).code;
- if (code === 'ESRCH') return false; // group already gone
+ if ((e as NodeJS.ErrnoException).code === 'ESRCH') return 'gone';
// RangeError on Bun (negative pid unsupported) or EPERM etc. — fall back
// to /bin/kill by ABSOLUTE path (a PATH-resolved binary in a kill path is
// an unnecessary indirection; security review). This is the NORMAL path
// in Bun-compiled production binaries; the sync exec is ~1-3ms and only
// runs on abort/shutdown, never in the claim/renewal hot loop.
try {
- const sigName = signal.replace(/^SIG/, '');
- const res = spawnSync('/bin/kill', ['-s', sigName, '--', `-${pid}`], { stdio: 'ignore' });
- return res.status === 0;
+ const res = spawnSync('/bin/kill', ['-s', signal.replace(/^SIG/, ''), '--', `-${pid}`], { stdio: 'ignore' });
+ return res.status === 0 ? 'signalled' : 'failed';
} catch {
- return false;
+ return 'failed';
}
}
}
+/** True when the signal was delivered to a live group or tree; false when it
+ * is already gone or delivery failed (`signalProcessTree` tells them apart). */
+export function killProcessGroup(pid: number, signal: 'SIGTERM' | 'SIGKILL'): boolean {
+ return signalProcessTree(pid, signal) === 'signalled';
+}
+
/**
* #5062: does any process remain in group `pgid`? Liveness, not
* `ChildProcess.killed` (which flips as soon as a signal is SENT), drives
diff --git a/test/spawn-windows-hide.test.ts b/test/spawn-windows-hide.test.ts
index 12a30b15ee..04b7cbca71 100644
--- a/test/spawn-windows-hide.test.ts
+++ b/test/spawn-windows-hide.test.ts
@@ -10,7 +10,7 @@
*/
import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import * as childProcess from 'node:child_process';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
@@ -18,6 +18,9 @@ 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';
+import { probeReleaseTag } from '../src/commands/upgrade.ts';
+import { checkDenyGlobs } from '../src/core/bootstrap/verify.ts';
+import { signalProcessTree, taskkillCommand } from '../src/core/minions/job-isolation.ts';
afterEach(() => { mock.restore(); });
@@ -135,4 +138,74 @@ describe('the spawn sites behind the reported windows pass windowsHide: true', (
rmSync(dir, { recursive: true, force: true });
}
});
+
+ test("upgrade's release-tag probe (git ls-remote)", () => {
+ const git = spyOn(childProcess, 'spawnSync').mockImplementation((() => ({ status: 2, stdout: '' })) as never);
+ expect(probeReleaseTag('0.0.0.1')).toBe('not_published');
+ expect(git.mock.calls[0]?.[0]).toBe('git');
+ expect(git.mock.calls[0]?.[2]).toMatchObject({ windowsHide: true });
+ });
+
+ test("bootstrap verify's deny-glob check (git ls-files)", () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-verify-git-'));
+ try {
+ const git = spyOn(childProcess, 'execFileSync').mockImplementation((() => '') as never);
+ checkDenyGlobs(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 });
+ }
+ });
+});
+
+describe('Windows process-tree termination (signalProcessTree)', () => {
+ const taskkill = taskkillCommand(4242, 'SIGTERM')[0];
+
+ test('SIGTERM asks the tree to close and SIGKILL forces it, by absolute taskkill path, hidden', () => {
+ const kill = spyOn(childProcess, 'spawnSync').mockImplementation((() => ({ status: 0 })) as never);
+ expect(signalProcessTree(4242, 'SIGTERM', 'win32')).toBe('signalled');
+ expect(signalProcessTree(4242, 'SIGKILL', 'win32')).toBe('signalled');
+ expect(taskkill).toMatch(/^[A-Za-z]:\\.+\\System32\\taskkill\.exe$/);
+ expect(kill.mock.calls.map(c => [c[0], c[1]])).toEqual([
+ [taskkill, ['/PID', '4242', '/T']],
+ [taskkill, ['/PID', '4242', '/T', '/F']],
+ ]);
+ expect(kill.mock.calls[0]?.[2]).toMatchObject({ windowsHide: true });
+ });
+
+ test.each([[0, 'signalled'], [128, 'gone'], [1, 'failed'], [null, 'failed']] as const)
+ ('taskkill exit %p is %s', (status, outcome) => {
+ spyOn(childProcess, 'spawnSync').mockImplementation((() => ({ status })) as never);
+ expect(signalProcessTree(4242, 'SIGKILL', 'win32')).toBe(outcome);
+ });
+
+ test('an invalid pid is never signalled', () => {
+ const kill = spyOn(childProcess, 'spawnSync');
+ for (const pid of [0, 1, -5, 1.5]) expect(signalProcessTree(pid, 'SIGKILL', 'win32')).toBe('failed');
+ expect(kill.mock.calls.length).toBe(0);
+ });
+
+ test.skipIf(process.platform !== 'win32')('natively, SIGKILL ends a grandchild and a second call reports the tree gone', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-taskkill-'));
+ const pidFile = join(dir, 'grandchild.pid');
+ const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+ try {
+ const script = `const c = require('child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', windowsHide: true });
+ require('fs').writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); setInterval(() => {}, 1000);`;
+ const parent = seam.spawn(process.execPath, ['-e', script], { stdio: 'ignore' });
+ let grandchild = 0;
+ for (let waited = 0; !grandchild && waited < 30_000; waited += 100) {
+ await Bun.sleep(100);
+ try { grandchild = Number(readFileSync(pidFile, 'utf8')) || 0; } catch { /* not written yet */ }
+ }
+ expect(grandchild).toBeGreaterThan(0);
+ expect(signalProcessTree(parent.pid!, 'SIGKILL')).toBe('signalled');
+ for (let waited = 0; alive(grandchild) && waited < 10_000; waited += 100) await Bun.sleep(100);
+ expect(alive(grandchild)).toBe(false);
+ expect(signalProcessTree(parent.pid!, 'SIGKILL')).toBe('gone');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 60_000);
});