Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(upgrade): skip interpreter flag values, keep the gbrain-path match without a cwd, redact the unrecognised parent (#8723 review)

garrytan3e60141fdef8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4cc41663a2..359b5a760d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
-- `src/core/upgrade-restart.ts`: `gbrainEntry` resolves a relative entry point against the process's working directory (`/proc/<pid>/cwd` on Linux) and treats `src/cli.ts` as gbrain when the package two levels up is named gbrain; an unreadable package falls back to the old path match. `bun run <file>` runs the file in its own process and is classified; `bunx`, `bun x` and `bun run <bin>` are wrappers whose child is the gbrain process, so they are no longer counted twice. A worker whose parent is not recognised as gbrain is refused with that parent's pid and command line. On macOS, where the working directory is not read, a relative launch is named in the refusal.
+- `src/core/upgrade-restart.ts`: `gbrainEntry` resolves a relative entry point against the process's working directory (`/proc/<pid>/cwd` on Linux), skips interpreter flags that take a value (`--preload x`, `--cwd x`, `-r x`) and treats `src/cli.ts` as gbrain when the package two levels up is named gbrain; an unreadable package falls back to the old path match. `bun run <file>` runs the file in its own process and is classified; `bunx`, `bun x` and `bun run <bin>` are wrappers whose child is the gbrain process, so they are no longer counted twice. A worker whose parent is not recognised as gbrain is refused with that parent's pid and command line. On macOS, where the working directory is not read, a relative entry still matches a gbrain path and is otherwise named in the refusal, with connection strings redacted.
- `scripts/eval-spend-guard.sh` (#8717): the lease's start time is read before the signal traps are armed, so no command substitution is parsed between arming them and `wait`. A TERM that landed there ran its trap while bash 5.2 still expected the lease line's `)`, the trap failed with "unexpected EOF while looking for matching `)'", the signal was lost and the guard waited out its command and exited 0. Under CPU load the original guard did that in 3 of 3000 forced TERMs and the fixed guard in 0 of 3000, interleaved. `test/eval-spend-guard.test.ts` pins that no command substitution sits in that window; the exit-143 assertion is unchanged.
- `.github/workflows/test.yml`, `e2e.yml`, `stress.yml` (#8700): the 15 `pglite-snapshot` cache keys hash `src/core/**/*.ts` (plus the snapshot builder and its test helper) instead of `src/core/*.ts` and a hand list of subdirectory files, so a schema input in a new `src/core` folder needs no workflow edit. A change anywhere under `src/core` now rebuilds the snapshot cache.
- `scripts/stress/run.ts` (#8702): a pooler-gated test is exempt from the stress gate only when the workflow job that names it, or the script lines beside it, set `GBRAIN_CI_REQUIRE_PGBOUNCER`; a flag elsewhere in the same file no longer counts. `test/e2e/graduation-cli-topologies.test.ts` is no longer exempt, and a script owner is reported as an "owning pooled runner".
diff --git a/src/commands/upgrade-restart.ts b/src/commands/upgrade-restart.ts
index 2504d0b156..5ccd0aa586 100644
--- a/src/commands/upgrade-restart.ts
+++ b/src/commands/upgrade-restart.ts
@@ -10,7 +10,7 @@
*/
import { existsSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
-import { delimiter, dirname, join } from 'node:path';
+import { delimiter, dirname, isAbsolute, join } from 'node:path';
import { spawnSync } from '../core/spawn.ts';
import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';
import { opError } from '../core/ops/contract.ts';
@@ -86,7 +86,7 @@ function installOf(command: string, cwd?: string | null): { root: string | null;
const entry = gbrainEntry(command, { cwd, packageName: packageNameAt })?.entry;
if (!entry) return { root: null, version: null };
try {
- const found = entry.includes('/') ? entry : (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, entry)).find(path => existsSync(path));
+ const found = entry.includes('/') ? (isAbsolute(entry) ? entry : undefined) : (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, entry)).find(path => existsSync(path));
if (!found) return { root: null, version: null };
let dir = dirname(realpathSync(found));
for (let i = 0; i < 4; i++, dir = dirname(dir)) {
diff --git a/src/core/upgrade-restart.ts b/src/core/upgrade-restart.ts
index a8b7028ebf..1d18e899c9 100644
--- a/src/core/upgrade-restart.ts
+++ b/src/core/upgrade-restart.ts
@@ -33,6 +33,7 @@
*/
import { basename, dirname, isAbsolute, resolve } from 'node:path';
import { parseGlobalFlags } from './cli-options.ts';
+import { redactConnectionInfo } from './audit/redact-connection-info.ts';
export type ProcessRole = 'serve' | 'autopilot' | 'supervisor' | 'worker' | 'mcp' | 'sync';
@@ -80,6 +81,8 @@ const SERVE_SUBCOMMANDS_TRANSIENT = new Set(['status', 'install', 'uninstall', '
/** `gbrain autopilot` forms that report or change the service and exit; anything else is the daemon (`--repo <path>`, `start`). */
const AUTOPILOT_TRANSIENT = new Set(['status', 'install', 'uninstall', 'pause', 'resume', 'help']);
const INTERPRETERS = new Set(['bun', 'node']);
+/** Interpreter flags whose value is the next token (gbrain's own sanitized re-run passes them this way: cli-preflight.ts PATH_RUNTIME_FLAGS). */
+const VALUE_FLAGS = new Set(['--preload', '-r', '--require', '--import', '--config', '-c', '--env-file', '--tsconfig-override', '--cwd']);
/**
* What decides whether a script entry point is gbrain: the process's working directory, which a relative entry
@@ -98,26 +101,26 @@ function isGbrainCli(path: string, packageName: EntryLookup['packageName']): boo
* The gbrain entry point of a command line and the arguments after it, or null when the command is not gbrain
* itself: a wrapper that starts gbrain as its child (tini, a shell, `timeout`, `bunx`, `bun x`, `bun run <bin>`)
* is not the gbrain process, while `bun run <file>` runs the file in its own process. A relative entry is
- * returned resolved against the process's working directory, and is null when that directory is unknown.
+ * returned resolved against the process's working directory; when that directory is unknown it stays relative and
+ * only a gbrain path matches.
*/
export function gbrainEntry(command: string, lookup: EntryLookup = {}): { entry: string; args: string[] } | null {
const tokens = command.trim().split(/\s+/);
const isPath = (token: string) => token.includes('/') || /\.[cm]?[jt]s$/.test(token);
let at = 0;
if (INTERPRETERS.has(basename(tokens[0]!))) {
- for (at = 1; tokens[at]?.startsWith('-'); at++);
+ for (at = 1; tokens[at]?.startsWith('-'); at++) if (VALUE_FLAGS.has(tokens[at]!)) at++;
if (basename(tokens[0]!) === 'bun') {
if (tokens[at] === 'x') return null;
- if (tokens[at] === 'run') for (at++; tokens[at]?.startsWith('-'); at++);
+ if (tokens[at] === 'run') for (at++; tokens[at]?.startsWith('-'); at++) if (VALUE_FLAGS.has(tokens[at]!)) at++;
if (tokens[at] !== undefined && !isPath(tokens[at]!)) return null;
}
}
const token = tokens[at];
if (token === undefined) return null;
- const relative = isPath(token) && !isAbsolute(token);
- if (relative && !lookup.cwd) return null;
- const entry = relative ? resolve(lookup.cwd!, token) : token;
- if (basename(entry) !== 'gbrain' && !isGbrainCli(entry, lookup.packageName)) return null;
+ const unresolved = isPath(token) && !isAbsolute(token) && !lookup.cwd;
+ const entry = isPath(token) && !isAbsolute(token) && lookup.cwd ? resolve(lookup.cwd, token) : token;
+ if (basename(entry) !== 'gbrain' && !isGbrainCli(entry, unresolved ? undefined : lookup.packageName)) return null;
return { entry, args: tokens.slice(at + 1) };
}
@@ -302,7 +305,7 @@ export function planRestart(processes: readonly HostProcess[], ctx: RestartConte
case 'worker':
if (parent?.role === 'supervisor' && parent.args) supervisors.set(parent.pid, [...(supervisors.get(parent.pid) ?? []), p.pid]);
else if (parent?.role === 'autopilot' && runsUnder(parent, ctx.autopilotService)) addService('autopilot', parent.pid);
- else kill(p, `${label(p)} is not run by a jobs supervisor this restart can relaunch${parent?.role === 'autopilot' ? ' (its autopilot runs under no installed service)' : ''}${p.unclassified_parent ? ` (its parent, pid ${p.unclassified_parent.pid} (\`${p.unclassified_parent.command}\`), is not a process this restart recognises as gbrain)` : ''}: stop it (\`kill ${p.pid}\`, SIGTERM drains its jobs) and start \`gbrain jobs work\` again the way it was launched, or run workers under \`gbrain jobs supervisor start --detach\`.`);
+ else kill(p, `${label(p)} is not run by a jobs supervisor this restart can relaunch${parent?.role === 'autopilot' ? ' (its autopilot runs under no installed service)' : ''}${p.unclassified_parent ? ` (its parent, pid ${p.unclassified_parent.pid} (\`${redactConnectionInfo(p.unclassified_parent.command)}\`), is not a process this restart recognises as gbrain)` : ''}: stop it (\`kill ${p.pid}\`, SIGTERM drains its jobs) and start \`gbrain jobs work\` again the way it was launched, or run workers under \`gbrain jobs supervisor start --detach\`.`);
break;
case 'mcp':
if (ctx.stopMcp && p.args) stops.push({ kind: 'stop', role: 'mcp', pid: p.pid, started_ms: p.started_ms });
diff --git a/test/upgrade-restart.test.ts b/test/upgrade-restart.test.ts
index ca89b7b24f..ab21c9b951 100644
--- a/test/upgrade-restart.test.ts
+++ b/test/upgrade-restart.test.ts
@@ -75,6 +75,18 @@ describe('gbrainEntry (#8723)', () => {
expect(classifyGbrainCommand('bun /srv/gbrain/src/cli.ts serve', { packageName })).toBe('mcp');
});
+ test('interpreter flags that take a value are skipped with their value, as gbrain\'s own sanitized re-run passes them', () => {
+ expect(classifyGbrainCommand('bun --preload ./p.ts /home/alice-example/.bun/bin/gbrain serve --http')).toBe('serve');
+ expect(classifyGbrainCommand(`bun --cwd /x ${CHECKOUT}/src/cli.ts serve`, { packageName })).toBe('mcp');
+ expect(classifyGbrainCommand('node --require /x/hook.js /home/alice-example/.bun/bin/gbrain jobs work')).toBe('worker');
+ expect(classifyGbrainCommand('bun run --env-file .env src/cli.ts jobs supervisor', { cwd: CHECKOUT, packageName })).toBe('supervisor');
+ });
+
+ test('with no working directory a relative entry still matches a gbrain path (macOS)', () => {
+ expect(classifyGbrainCommand('bun ../gbrain/src/cli.ts serve', { cwd: null })).toBe('mcp');
+ expect(gbrainEntry('bun ../gbrain/src/cli.ts serve', { cwd: null })?.entry).toBe('../gbrain/src/cli.ts');
+ });
+
test('bunx and bun run <bin> are wrappers; the child they start is the gbrain process', () => {
expect(gbrainEntry('/usr/local/bin/bun x gbrain jobs supervisor --queue q')).toBeNull();
expect(gbrainEntry('bunx gbrain jobs supervisor')).toBeNull();
@@ -103,12 +115,16 @@ describe('gbrainEntry (#8723)', () => {
heartbeats: async () => [], workers: () => [], supervisor: () => null, home: HOME, exclude: [], packageName,
processTable: () => [
{ pid: 20, ppid: 1, command: 'bun run src/cli.ts jobs supervisor', started_ms: 600, gbrain_home: HOME, cwd: null },
+ { pid: 30, ppid: 1, command: 'sh -c DATABASE_URL=postgres://alice-example:[email protected]:5432/brain bun run src/cli.ts jobs supervisor', started_ms: 600, gbrain_home: HOME, cwd: null },
+ { pid: 31, ppid: 30, command: `bun ${CHECKOUT}/src/cli.ts jobs work`, started_ms: 700, gbrain_home: HOME, cwd: null },
{ pid: 21, ppid: 20, command: `bun ${CHECKOUT}/src/cli.ts jobs work`, started_ms: 700, gbrain_home: HOME, cwd: null },
],
});
- expect(processes.map(p => [p.pid, p.role])).toEqual([[21, 'worker']]);
- const [manual] = planRestart(processes, ctx()).manual;
+ expect(processes.map(p => [p.pid, p.role])).toEqual([[21, 'worker'], [31, 'worker']]);
+ const [manual, redacted] = planRestart(processes, ctx()).manual;
expect(manual!.instruction).toContain('its parent, pid 20 (`bun run src/cli.ts jobs supervisor`), is not a process this restart recognises as gbrain');
+ expect(redacted!.instruction).toContain('its parent, pid 30 (');
+ expect(redacted!.instruction).not.toContain('hunter2');
});
});