Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): verify guards on #7252 (structured legacy-review fix, spawn.ts for the terminal hook, function-size helpers, plugin tree), wait_job in the token-redaction sweep
garrytan19d79fc3a3bd
diff --git a/plugin/README.md b/plugin/README.mdindex a0161f9bff..28644fd647 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -8,7 +8,7 @@ addition/exclusion).## MCP surface note (read once)-The plugin's MCP server runs `gbrain serve --surface full` — 179+The plugin's MCP server runs `gbrain serve --surface full` — 180operations, the same surface every stdio registration gbrain writes pins.Every gbrain operation the bundled skills name is on it. A harness that capsits tool count can narrow this machine's plugin surface withdiff --git a/src/commands/jobs/get.ts b/src/commands/jobs/get.tsindex 5ff8bec564..7c5b3bf167 100644--- a/src/commands/jobs/get.ts+++ b/src/commands/jobs/get.ts@@ -7,6 +7,7 @@ import { spendBasis } from '../../core/minions/spend-record.ts';import { jobGroupAmounts } from '../../core/minions/spend-authorization.ts';import { describeJobs, withInsight, type JobInsight } from '../../core/minions/job-insight.ts';import type { BrainEngine } from '../../core/engine.ts';+import { shellQuote } from '../../core/agent-output.ts';export async function runJobsGet({ args, queue, engine }: JobsCommandContext): Promise<void> {const id = parseInt(args[1], 10);@@ -62,7 +63,7 @@ function insightLines(doc: Partial<JobInsight>): string[] {else if (b.kind === 'waiting_children') lines.push(` Blocked by: ${b.pending} unfinished children${b.child_ids.length ? ` (${b.child_ids.map(c => '#' + c).join(', ')})` : ''}`);else if (b.kind === 'delayed') lines.push(` Blocked by: delayed until ${b.delay_until ?? '?'} (${b.reason})`);else if (b.kind === 'lock') lines.push(` Blocked by: lock ${b.lock ?? ''} held${b.holder_job_id != null ? ` by job #${b.holder_job_id}` : b.holder ? ` by a ${b.holder.kind} holder` : ''}`);- else if (b.kind === 'unreviewed_authority') lines.push(` Blocked by: unreviewed legacy authority (${b.fix})`);+ else if (b.kind === 'unreviewed_authority') lines.push(` Blocked by: unreviewed legacy authority (${shellQuote(b.fix.argv ?? [])})`);else lines.push(` Blocked by: ${b.kind}`);}if (doc.lock_expires_in_ms != null) {diff --git a/src/commands/jobs/stats.ts b/src/commands/jobs/stats.tsindex f1d7d9a433..b47f95b20f 100644--- a/src/commands/jobs/stats.ts+++ b/src/commands/jobs/stats.ts@@ -2,6 +2,7 @@import { hasFlag, parseFlag, type JobsCommandContext } from './shared.ts';import { formatNice, getEffectiveNiceness } from '../../core/minions/niceness.ts';import { DREAM_INLINE_PRIVATE_QUEUE_PREFIX, deriveWedgeSignal } from '../../core/minions/queue.ts';+import type { QueueFamilyStats } from '../../core/minions/queue-families.ts';export async function runJobsStats({ args, engine, queue }: JobsCommandContext): Promise<void> {try { await queue.ensureSchema(); }@@ -84,11 +85,7 @@ export async function runJobsStats({ args, engine, queue }: JobsCommandContext):console.log(' No jobs in the last 24 hours.');}console.log(`\n Queue health: ${stats.queue_health.waiting} waiting, ${stats.queue_health.active} active, ${stats.queue_health.stalled} stalled`);- // #7241: one line per queue; the per-run dream-inline-* queues share one line (`--queue <name>` scopes the wedge lines to one).- for (const q of stats.by_queue) {- const label = `${q.queue}-` === DREAM_INLINE_PRIVATE_QUEUE_PREFIX ? `${q.queue} (${q.queues} queue${q.queues === 1 ? '' : 's'})` : sanitizeName(q.queue);- console.log(` ${label.padEnd(26)} ${q.waiting_now} waiting, ${q.active_now} active, ${q.total} total, ${q.completed} done, ${q.failed} failed, ${q.dead} dead`);- }+ printQueueFamilies(stats.by_queue, sanitizeName);// DIVERGENT-queue scream: intake structurally exceeds useful drain and a// real backlog is sitting there. This is the default-on protection layer@@ -317,3 +314,11 @@ async function printNoWorker(engineKind: string, queue: string, waiting: number)` Fix: ${shellQuote(fix.argv ?? [])} # ${fix.why}`,);}++/** #7241: one line per queue; the per-run dream-inline-* queues share one line (`--queue <name>` scopes the wedge lines to one). */+function printQueueFamilies(families: QueueFamilyStats[], sanitizeName: (name: string) => string): void {+ for (const q of families) {+ const label = `${q.queue}-` === DREAM_INLINE_PRIVATE_QUEUE_PREFIX ? `${q.queue} (${q.queues} queue${q.queues === 1 ? '' : 's'})` : sanitizeName(q.queue);+ console.log(` ${label.padEnd(26)} ${q.waiting_now} waiting, ${q.active_now} active, ${q.total} total, ${q.completed} done, ${q.failed} failed, ${q.dead} dead`);+ }+}diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 6918443b75..dbded5130e 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -1927,6 +1927,9 @@ export async function runCycle(return notices.length ? { ...report, notices } : report;}+/** #7241: tell `opts.onPhaseStart` a selected phase is starting; a hook error is logged, never fatal. */+const notifyPhaseStart = (opts: CycleOpts, phase: CyclePhase, phases: readonly CyclePhase[]): Promise<void> => Promise.resolve().then(() => opts.onPhaseStart?.(phase, phases.indexOf(phase), phases.length)).then(() => undefined, (e: unknown) => { console.warn(`[cycle] onPhaseStart hook error (non-fatal): ${e instanceof Error ? e.message : String(e)}`); });+async function runCycleUnscoped(engine: BrainEngine | null,opts: CycleOpts,@@ -2187,11 +2190,7 @@ async function runCycleUnscoped(// synthesize_concepts still can't carry one (W6). Steal-free cycles behave// byte-identically to timePhase.// Phase containment (#5484): a failing phase returns a `fail` result so later phases run; abort, lease loss and budget exhaustion still stop the job.- const timePhase = async <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => {- try { await opts.onPhaseStart?.(phase, phases.indexOf(phase), phases.length); }- catch (e) { console.warn(`[cycle] onPhaseStart hook error (non-fatal): ${e instanceof Error ? e.message : String(e)}`); }- return timeContainedPhase({ engine, sourceId: cycleSourceId ?? 'default', signal: cycleSignal }, phase, fn);- };+ const timePhase = async <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => { await notifyPhaseStart(opts, phase, phases); return timeContainedPhase({ engine, sourceId: cycleSourceId ?? 'default', signal: cycleSignal }, phase, fn); };const racedTimePhase = <T extends PhaseResult,>(fn: () => Promise<T>, phase: CyclePhase) => raceStolen(timePhase(fn, phase));// #1972: reap dead-holder sync/cycle locks at cycle start — before the syncdiff --git a/src/core/minions/job-insight.ts b/src/core/minions/job-insight.tsindex 43d3cdcf1c..877ea27c60 100644--- a/src/core/minions/job-insight.ts+++ b/src/core/minions/job-insight.ts@@ -9,6 +9,7 @@*/import type { BrainEngine } from '../engine.ts';import { parseGlobalFlags } from '../cli-options.ts';+import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from './submission-authority.ts';import { currentChatPhase } from '../ai/chat-usage.ts';import type { MinionJob } from './types.ts';@@ -63,7 +64,7 @@ export type BlockedBy =| { kind: 'waiting_children'; pending: number; child_ids: number[] }| { kind: 'delayed'; delay_until: string | null; reason: DelayReason; detail?: string }| { kind: 'paused' }- | { kind: 'unreviewed_authority'; fix: string }+ | { kind: 'unreviewed_authority'; fix: Action }| { kind: 'queue'; queue: string; queue_position: number; ahead: number; active: number; active_jobs: Array<{ id: number; name: string }>; private_queue?: true }| { kind: 'lock'; held: true; lock?: string; holder_job_id?: number; holder?: { kind: string; pid?: number; host?: string; acquired_at: string | null; ttl_expires_at: string | null } };@@ -269,7 +270,9 @@ function blockedBy(job: MinionJob, c: BlockCtx): BlockedBy[] | null {} else if (job.status === 'paused') {reasons.push({ kind: 'paused' });} else if (job.status === 'waiting') {- if (!job.submission_authority) reasons.push({ kind: 'unreviewed_authority', fix: `gbrain jobs authorize-legacy --ids ${job.id}` });+ if (!job.submission_authority) reasons.push({ kind: 'unreviewed_authority', fix: {+ argv: ['gbrain', 'jobs', 'authorize-legacy', '--ids', String(job.id)], consent: [], actor: 'user', requires_exclusive: false,+ why: 'This job was queued before submission authority existed; the host operator previews it here and then authorizes it to run.' } });const active = c.holders.get(job.queue) ?? [];const ahead = c.positions.get(job.id) ?? 0;reasons.push({ kind: 'queue', queue: job.queue, queue_position: ahead + 1, ahead, active: active.length,diff --git a/src/core/minions/terminal-hook.ts b/src/core/minions/terminal-hook.tsindex a0b963c883..2e850f8d40 100644--- a/src/core/minions/terminal-hook.ts+++ b/src/core/minions/terminal-hook.ts@@ -11,7 +11,7 @@* user with that process's environment, is killed after timeout_ms (default 10 s), and a failure is logged* once and never retried, never changing the job.*/-import { spawn } from 'node:child_process';+import { spawn } from '../spawn.ts';import { isAbsolute } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';diff --git a/test/jobs-ops-token-redaction.test.ts b/test/jobs-ops-token-redaction.test.tsindex ec835e5cd8..a18875bd66 100644--- a/test/jobs-ops-token-redaction.test.ts+++ b/test/jobs-ops-token-redaction.test.ts@@ -200,6 +200,7 @@ describe('registry sweep ratchet — no jobs op envelope may carry the raw tokenconst id = await seedPrivateJobWithStatus(status);const args: Record<string, unknown> = { id };if ((op.params as Record<string, unknown>).message) args.message = 'sweep-probe';+ if ((op.params as Record<string, unknown>).timeout_s) args.timeout_s = 0;// Success OR error envelope — the raw capability must appear in neither.const res = await dispatchToolCall(engine, op.name, args, { ...STDIO });expect(res.content[0].text).not.toContain(RAW_TOKEN);diff --git a/test/minions/job-insight.test.ts b/test/minions/job-insight.test.tsindex 8434baf416..f26bc630a0 100644--- a/test/minions/job-insight.test.ts+++ b/test/minions/job-insight.test.ts@@ -127,6 +127,16 @@ describe('blocked_by', () => {expect(queueOf(b.id)).toMatchObject({ queue_position: 3, ahead: 2, active_jobs: [{ id: running.id, name: 'long-runner' }] });});+ test('a legacy job with no authority names the review command as argv', async () => {+ const job = await add('noop');+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [job.id]);+ const [row] = await queue.getJobs({ status: 'waiting' }).then(rows => rows.filter(r => r.id === job.id));+ const insight = await describeJobs(engine, [row]);+ expect(insight.get(job.id)!.blocked_by![0]).toMatchObject({ kind: 'unreviewed_authority',+ fix: { argv: ['gbrain', 'jobs', 'authorize-legacy', '--ids', String(job.id)], actor: 'user', consent: [] } });+ expect(insight.get(job.id)!.submitted_by).toEqual({ kind: 'unreviewed' });+ });+test('waiting-children, delayed and paused jobs say why', async () => {const parent = await add('noop');const kid = await add('noop', {}, { parent_job_id: parent.id });