Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor): legacy_job_authority check module and post-upgrade banner line (#5157, DX-O3(a))
garrytan64f6199b4c54
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 5503266a3a..3644826f6c 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -13,6 +13,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand`, `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`.+- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_SQL`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. Test: `test/doctor-legacy-job-authority.test.ts`.- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines. Test: `test/post-upgrade-banner.test.ts`.- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; details carry a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.test.ts`.diff --git a/src/commands/doctor/checks/legacy-job-authority.ts b/src/commands/doctor/checks/legacy-job-authority.tsnew file mode 100644index 0000000000..b56b5489a7--- /dev/null+++ b/src/commands/doctor/checks/legacy-job-authority.ts@@ -0,0 +1,93 @@+/**+ * legacy_job_authority (#5157, DX-O3(a)): the claim gate's population, read+ * with the gate's own query (`UNREVIEWED_LIVE_JOBS_SQL`) so the two counts+ * never drift. Live rows whose authority is SQL NULL (authorizable with+ * `gbrain jobs authorize-legacy --select`) or unsupported non-NULL block+ * every worker, so the check fails and names the recovery order. Terminal+ * keyed SQL NULL rows are reported separately: application callers coalesce+ * onto completed or failed ones and dead or cancelled keys are released on+ * resubmission, so they need no operator step.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import { ERROR_CATALOGUE } from '../../../core/error-catalogue.ts';+import { legacyRecoveryHint } from '../../../core/minions/legacy-selection.ts';+import { UNREVIEWED_LIVE_JOBS_SQL, parseSubmissionAuthority } from '../../../core/minions/submission-authority.ts';+import type { Check } from '../../doctor.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++export interface LegacyJobAuthorityState {+ /** Live rows with SQL NULL authority, by status. */+ authorizable: Record<string, number>;+ /** Live rows whose non-NULL authority is unsupported (first 10 ids). */+ unsupported_ids: number[];+ unsupported: number;+ /** Every active job (first 10 ids): legacy review needs none. */+ active_ids: number[];+ /** Terminal keyed SQL NULL rows, by status. */+ terminal_keyed: Record<string, number>;+}++export async function readLegacyJobAuthority(engine: BrainEngine): Promise<LegacyJobAuthorityState> {+ const live = (await engine.executeRaw<{ id: number; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(UNREVIEWED_LIVE_JOBS_SQL))+ .filter(row => !parseSubmissionAuthority(row.submission_authority));+ const authorizable: Record<string, number> = {};+ for (const row of live) if (row.legacy_authority_is_null === true) authorizable[row.status] = (authorizable[row.status] ?? 0) + 1;+ const unsupported = live.filter(row => row.legacy_authority_is_null !== true);+ const active = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 10");+ const terminal = await engine.executeRaw<{ status: string; count: number | string }>(+ `SELECT status, count(*) AS count FROM minion_jobs+ WHERE submission_authority IS NULL AND idempotency_key IS NOT NULL+ AND status IN ('completed','failed','dead','cancelled')+ GROUP BY status ORDER BY status`);+ return {+ authorizable,+ unsupported_ids: unsupported.slice(0, 10).map(row => Number(row.id)),+ unsupported: unsupported.length,+ active_ids: active.map(row => Number(row.id)),+ terminal_keyed: Object.fromEntries(terminal.map(row => [row.status, Number(row.count)])),+ };+}++const sum = (counts: Record<string, number>) => Object.values(counts).reduce((n, c) => n + c, 0);++export async function legacyJobAuthorityCheck(engine: BrainEngine): Promise<Check> {+ const state = await readLegacyJobAuthority(engine);+ const authorizable = sum(state.authorizable);+ const terminal = sum(state.terminal_keyed);+ const live = authorizable + state.unsupported;+ const details = { ...state, live, authorizable_total: authorizable, terminal_keyed_total: terminal, docs: ERROR_CATALOGUE.legacy_job_authority.docs };+ if (!live) {+ return {+ name: 'legacy_job_authority', status: 'ok', details,+ message: terminal+ ? `${terminal} finished job row(s) from before the upgrade still hold idempotency keys; resubmissions reuse completed or failed ones and release dead or cancelled ones, so no action is needed.`+ : 'No queued job predates submission authority.',+ };+ }+ const unsupported = state.unsupported+ ? ` ${state.unsupported} carry unsupported non-NULL authority: run matching application and database versions, or cancel them (${state.unsupported_ids.map(id => `gbrain jobs cancel ${id}`).join('; ')}).`+ : '';+ return {+ name: 'legacy_job_authority', status: 'fail', details,+ message: `${live} queued job(s) predate submission authority and block every worker (${authorizable} authorizable with SQL NULL authority, ${state.unsupported} unsupported). `+ + `${legacyRecoveryHint(Object.keys(state.authorizable), [], state.active_ids)}${unsupported} See ${ERROR_CATALOGUE.legacy_job_authority.docs}.`,+ };+}++export const legacyJobAuthorityEntry: DoctorEntry = {+ name: 'legacy_job_authority',+ emits: ['legacy_job_authority'],+ run: async (ctx: DoctorContext) => [await legacyJobAuthorityCheck(connectedEngine(ctx))],+};++/** `gbrain post-upgrade` banner line when live legacy rows block workers (read-only commands only). */+export async function legacyJobAuthorityBannerNote(engine: BrainEngine): Promise<string | null> {+ const state = await readLegacyJobAuthority(engine);+ const authorizable = sum(state.authorizable);+ if (!authorizable && !state.unsupported) return null;+ const statuses = Object.keys(state.authorizable).filter(status => status !== 'active');+ const preview = `gbrain jobs authorize-legacy --select "status=${(statuses.length ? statuses : ['waiting']).join('|')}"`;+ return `legacy_job_authority: ${authorizable + state.unsupported} queued job(s) from before v0.50 block every worker. `+ + `Stop producers (gbrain serve, gbrain autopilot) and workers, cancel active jobs, then preview with: ${preview}`+ + `${state.unsupported ? `; ${state.unsupported} unsupported row(s) need matching versions or gbrain jobs cancel <id>` : ''}. Recipe: ${ERROR_CATALOGUE.legacy_job_authority.docs}`;+}diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.tsindex 6b27ca1224..c2e0d2eca6 100644--- a/src/commands/doctor/upgrade-banner.ts+++ b/src/commands/doctor/upgrade-banner.ts@@ -13,6 +13,7 @@ import type { BrainEngine } from '../../core/engine.ts';import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';+import { legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */async function connectorRewalkNote(engine: BrainEngine): Promise<string | null> {@@ -29,7 +30,7 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>* of connector sources that will re-walk once after a checkpoint migration).* Each returns null when it has nothing to say.*/-export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote];+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote];/** One banner line for a non-ok wave finding. */export function bannerFindingLine({ spec, check, state }: WaveFinding): string {diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 7a41442fee..d137058240 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -220,6 +220,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['pool_budget','progressive_batch_audit_health','queue_health',+ // #5157: queued jobs from before the v0.50 authority cutover block every worker.+ 'legacy_job_authority','reranker_health','rls','rls_event_trigger',diff --git a/src/core/minions/legacy-selection.ts b/src/core/minions/legacy-selection.tsindex ef947ba709..81d2c06dcc 100644--- a/src/core/minions/legacy-selection.ts+++ b/src/core/minions/legacy-selection.ts@@ -83,10 +83,11 @@ export const STOP_PRODUCERS = 'Stop producers (gbrain serve, gbrain autopilot) a* and workers, cancel active jobs, preview with the filled `--select`, apply* with the printed hash, restart.*/-export function legacyRecoveryHint(statuses: Iterable<string>, names: string[] = []): string {+export function legacyRecoveryHint(statuses: Iterable<string>, names: string[] = [], activeIds: readonly number[] = []): string {const reviewable = [...new Set(statuses)].filter(status => SELECT_STATUSES['authorize-legacy'].includes(status));const preview = selectCommand('authorize-legacy', { statuses: reviewable.length ? reviewable : ['waiting'], names });- return `${STOP_PRODUCERS}, cancel active jobs (gbrain jobs cancel <id>), preview with ${preview}, apply with the printed --expect <hash> --yes, then restart them.`;+ const cancels = activeIds.length ? activeIds.slice(0, 10).map(id => `gbrain jobs cancel ${id}`).join('; ') : 'gbrain jobs cancel <id>';+ return `${STOP_PRODUCERS}, cancel active jobs (${cancels}), preview with ${preview}, apply with the printed --expect <hash> --yes, then restart them.`;}/** `legacy_jobs_active`: legacy rows are reviewed only with nothing active. Lists up to 10 ids to cancel. */diff --git a/test/doctor-legacy-job-authority.test.ts b/test/doctor-legacy-job-authority.test.tsnew file mode 100644index 0000000000..0827c6546b--- /dev/null+++ b/test/doctor-legacy-job-authority.test.ts@@ -0,0 +1,101 @@+/**+ * #5157 DX-O3(a): doctor `legacy_job_authority` counts exactly the claim+ * gate's population (live rows with SQL NULL or unsupported authority, keyed+ * or not), splits authorizable from unsupported, reports terminal keyed SQL+ * NULL rows separately, and the post-upgrade banner names the read-only+ * recovery preview when live rows exist.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { MinionQueue } from '../src/core/minions/queue.ts';+import { assertNoUnreviewedJobs } from '../src/core/minions/submission-authority.ts';+import { legacyJobAuthorityBannerNote, legacyJobAuthorityCheck, legacyJobAuthorityEntry } from '../src/commands/doctor/checks/legacy-job-authority.ts';+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';++let engine: PGLiteEngine;+let queue: MinionQueue;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ queue = new MinionQueue(engine);+}, 60_000);+afterAll(async () => { await engine?.disconnect(); }, 60_000);+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });++async function row(status: string, authority: string | null, key?: string): Promise<number> {+ const job = await queue.add('fixture', { n: Math.random() }, key ? { idempotency_key: key } : {});+ if (status === 'active') {+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [job.id]);+ } else if (status !== 'waiting') {+ await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [job.id, status]);+ }+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [job.id, authority]);+ return job.id;+}+async function gateCount(): Promise<number> {+ try { await assertNoUnreviewedJobs(engine); return 0; }+ catch (error) { return Number(/(\d+) legacy jobs/.exec((error as Error).message)![1]); }+}++describe('legacy_job_authority doctor check', () => {+ test('a brain without legacy rows is ok', async () => {+ await queue.add('fixture', {});+ const check = await legacyJobAuthorityCheck(engine);+ expect(check).toMatchObject({ name: 'legacy_job_authority', status: 'ok', message: 'No queued job predates submission authority.' });+ expect(await legacyJobAuthorityBannerNote(engine)).toBeNull();+ });++ test('terminal keyed SQL NULL rows are reported separately and need no operator step', async () => {+ await row('completed', null, 'k1');+ await row('dead', null, 'k2');+ await row('failed', null);+ const check = await legacyJobAuthorityCheck(engine);+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ live: 0, terminal_keyed: { completed: 1, dead: 1 }, terminal_keyed_total: 2 });+ expect(check.message).toContain('2 finished job row(s) from before the upgrade');+ expect(await gateCount()).toBe(0);+ expect(await legacyJobAuthorityBannerNote(engine)).toBeNull();+ });++ test('live rows fail with the gate count, the authorizable/unsupported split and the filled recovery', async () => {+ await row('waiting', null, 'keyed');+ await row('waiting', null);+ await row('paused', null);+ const active = await row('active', null);+ const jsonbNull = await row('delayed', 'null');+ const future = await row('waiting', '{"version":2,"kind":"application"}');+ await row('completed', null, 'old');+ await queue.add('fixture', { healthy: true });+ const check = await legacyJobAuthorityCheck(engine);+ expect(check.status).toBe('fail');+ expect(check.details).toMatchObject({+ live: 6, authorizable_total: 4, unsupported: 2, authorizable: { waiting: 2, paused: 1, active: 1 },+ unsupported_ids: [jsonbNull, future], active_ids: [active], terminal_keyed_total: 1,+ });+ expect(check.details!.live).toBe(await gateCount());+ expect(check.message).toContain('6 queued job(s) predate submission authority and block every worker (4 authorizable with SQL NULL authority, 2 unsupported)');+ expect(check.message).toContain('Stop producers (gbrain serve, gbrain autopilot) and workers');+ expect(check.message).toContain(`cancel active jobs (gbrain jobs cancel ${active})`);+ expect(check.message).toContain('preview with gbrain jobs authorize-legacy --select "status=waiting|paused"');+ expect(check.message).toContain('apply with the printed --expect <hash> --yes, then restart them');+ expect(check.message).toContain(`gbrain jobs cancel ${jsonbNull}; gbrain jobs cancel ${future}`);+ expect(check.message).toContain('docs/guides/repair.md#legacy-job-authority');+ const [fromEntry] = await legacyJobAuthorityEntry.run({ engine } as never) as Array<{ name: string }>;+ expect(fromEntry!.name).toBe('legacy_job_authority');+ });++ test('the post-upgrade banner names the read-only preview, never an applying command', async () => {+ await row('waiting', null, 'keyed');+ await row('paused', 'null');+ const lines = await postUpgradeRecoveryBanner(engine, 'host (pglite, id test-brain)');+ const text = lines.join('\n');+ expect(text).toContain('[AGENT] legacy_job_authority: 2 queued job(s) from before v0.50 block every worker.');+ expect(text).toContain('preview with: gbrain jobs authorize-legacy --select "status=waiting"');+ expect(text).toContain('1 unsupported row(s) need matching versions or gbrain jobs cancel <id>');+ expect(text).not.toContain('--yes');+ expect(text).not.toContain('--apply');+ for (const line of lines.filter(Boolean)) expect(line).toStartWith('[AGENT]');+ }, 120_000);+});