Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): keep the claim gate's query shape; share its population predicate with doctor
garrytan8fb1c7788b15
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 3644826f6c..a4505a62f1 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -13,7 +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/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), 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/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 8c3ba51c78..9a0b587872 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).-- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_SQL` is the claim gate's query, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under its snapshot hash with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.+- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_WHERE` is the claim gate's predicate, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under its snapshot hash with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.diff --git a/src/commands/doctor/checks/legacy-job-authority.ts b/src/commands/doctor/checks/legacy-job-authority.tsindex bc64f85abc..e85023aa6c 100644--- a/src/commands/doctor/checks/legacy-job-authority.ts+++ b/src/commands/doctor/checks/legacy-job-authority.ts@@ -1,6 +1,6 @@/*** 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+ * with the gate's own predicate (`UNREVIEWED_LIVE_JOBS_WHERE`) 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@@ -11,7 +11,7 @@import type { BrainEngine } from '../../../core/engine.ts';import { ERROR_CATALOGUE } from '../../../core/error-catalogue.ts';import { LIVE_LEGACY_PREVIEW, legacyRecoveryHint } from '../../../core/minions/legacy-selection.ts';-import { UNREVIEWED_LIVE_JOBS_SQL, parseSubmissionAuthority } from '../../../core/minions/submission-authority.ts';+import { UNREVIEWED_LIVE_JOBS_WHERE, parseSubmissionAuthority } from '../../../core/minions/submission-authority.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -28,7 +28,9 @@ export interface LegacyJobAuthorityState {}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))+ const live = (await engine.executeRaw<{ id: number; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(+ `SELECT id, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null+ FROM minion_jobs WHERE ${UNREVIEWED_LIVE_JOBS_WHERE} ORDER BY id`)).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;diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.tsindex 57cf1bed99..f7c0b51b56 100644--- a/src/core/minions/submission-authority.ts+++ b/src/core/minions/submission-authority.ts@@ -272,16 +272,12 @@ export async function assertRemoteJobControl(ctx: OperationContext, job: MinionJexport const LIVE_JOB_STATUSES = ['waiting', 'active', 'delayed', 'waiting-children', 'paused'] as const;/**- * The claim gate's candidate rows, shared by `assertNoUnreviewedJobs` and the- * doctor `legacy_job_authority` check so their counts can never drift. Callers- * keep the rows `parseSubmissionAuthority` rejects; `legacy_authority_is_null`- * splits them into authorizable SQL NULL rows and unsupported non-NULL rows.+ * The claim gate's population predicate, shared by `assertNoUnreviewedJobs`+ * and the doctor `legacy_job_authority` check so their counts can never drift.+ * Callers keep the rows `parseSubmissionAuthority` rejects.*/-export const UNREVIEWED_LIVE_JOBS_SQL = `SELECT id, name, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null- FROM minion_jobs- WHERE status IN (${LIVE_JOB_STATUSES.map(s => `'${s}'`).join(',')})- AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb- ORDER BY id`;+export const UNREVIEWED_LIVE_JOBS_WHERE = `status IN (${LIVE_JOB_STATUSES.map(s => `'${s}'`).join(',')})+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb`;/** Select-list column every coalesce read adds so SQL NULL stays distinguishable from JSONB null. */export const LEGACY_AUTHORITY_COLUMN = 'submission_authority IS NULL AS legacy_authority_is_null';@@ -327,12 +323,12 @@ export function coalesceDecision(row: Record<string, unknown>, authority: Submis/** Startup and claim gate: do not let sweeps silently destroy unresolved legacy dependency graphs. */export async function assertNoUnreviewedJobs(engine: BrainEngine): Promise<void> {- const rows = await engine.executeRaw<{ id: number; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(UNREVIEWED_LIVE_JOBS_SQL);+ const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(+ `SELECT id, submission_authority FROM minion_jobs+ WHERE ${UNREVIEWED_LIVE_JOBS_WHERE}`);const invalid = rows.filter(row => !parseSubmissionAuthority(row.submission_authority));if (!invalid.length) return;- const unsupported = invalid.filter(row => row.legacy_authority_is_null !== true).length;throw catalogueError('legacy_job_authority',`Queued job authorization: ${invalid.length} legacy jobs have missing or unsupported authority, so workers cannot start until they are reviewed.`,- `${legacyRecoveryHint()}${unsupported- ? ` ${unsupported} job(s) carry unsupported non-NULL authority: run matching application and database versions, or cancel them with gbrain jobs cancel <id> (gbrain doctor lists them).` : ''}`);+ `${legacyRecoveryHint()} Rows with unsupported non-NULL authority need matching application and database versions, or gbrain jobs cancel <id>; gbrain doctor lists them.`);}