Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(advisor): built-in collector read failures report collector_failed, not healthy (#6936)

time-attack82656b42ace7
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 99dde6cb1a..812f222c59 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv via `spawnCliChild`, never a shell; local-only; asks through `requireConsent` with per-dispatch-id effects and cost text, so `--apply <id> --yes` is the non-interactive approval and a refusal exits 3 with the consent payload naming the command and its cost). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (`readPublishGate`: on by default for the owner's stdio server, off for HTTP unless set; an explicit `false` or a failed read hides it) and strictly read-only on remote. The `writeback-consent` collector reaches MCP callers and stays until the user answers (`memory.auto_writeback` set to any value). CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
+- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [tolerates only missing `minion_jobs`, `sources` or `sources.last_sync_at`], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch that reports a thrown collector as the static `collector_failed:<id>` warn; built-in collectors rethrow read failures instead of returning no findings; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv via `spawnCliChild`, never a shell; local-only; asks through `requireConsent` with per-dispatch-id effects and cost text, so `--apply <id> --yes` is the non-interactive approval and a refusal exits 3 with the consent payload naming the command and its cost). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (`readPublishGate`: on by default for the owner's stdio server, off for HTTP unless set; an explicit `false` or a failed read hides it) and strictly read-only on remote. The `writeback-consent` collector reaches MCP callers and stays until the user answers (`memory.auto_writeback` set to any value). CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.
- `src/core/audit/audit-writer.ts` — shared JSONL audit primitive behind the audit modules. Exports `createAuditWriter({kind, recordSchema})` returning `{log, readRecent}` plus shared helpers `computeIsoWeekFilename(kind, now?)` and `resolveAuditDir()` (honors `GBRAIN_AUDIT_DIR`). ISO-week file rotation; best-effort writes (stderr warn on failure, never throws); read-path scans current-week + previous-week files for boundary spans. Built on it: `src/core/rerank-audit.ts`, `src/core/audit-slug-fallback.ts`, `src/core/minions/handlers/shell-audit.ts`, `src/core/minions/handlers/supervisor-audit.ts`, `src/core/facts/phantom-audit.ts`. The `graph-signals-failures` audit (`logGraphSignalsFailure`) uses the same primitive. `src/core/skillpack/audit.ts` is the one audit that does not use it. Pinned by `test/audit/audit-writer.test.ts`.
diff --git a/src/core/advisor/collect-stalled-jobs.ts b/src/core/advisor/collect-stalled-jobs.ts
index a84041ec64..8f917c9628 100644
--- a/src/core/advisor/collect-stalled-jobs.ts
+++ b/src/core/advisor/collect-stalled-jobs.ts
@@ -1,13 +1,16 @@
/**
* advisor/collect-stalled-jobs.ts — stuck background work + stale sync.
*
- * #14: `minion_jobs` may be ABSENT on older/partial brains — the query is
- * wrapped so a missing table yields no finding (never an error). Engine-agnostic
+ * #14: `minion_jobs` may be ABSENT on older/partial brains, and very old
+ * brains lack `sources` or `sources.last_sync_at`: exactly those missing
+ * objects yield no finding. Any other read failure is rethrown so runAdvisor
+ * reports `collector_failed:stalled-jobs` instead of a clean check. Engine-agnostic
* SQL via executeRaw (works on Postgres + PGLite); timestamps compared with
* `now()` which both engines provide. No PG-only constructs.
*/
import type { AdvisorCollector, AdvisorFinding } from './types.ts';
+import { isMissingSchemaObject } from '../utils.ts';
export const collectStalledJobs: AdvisorCollector = {
id: 'stalled-jobs',
@@ -38,8 +41,8 @@ export const collectStalledJobs: AdvisorCollector = {
ask_user: true,
});
}
- } catch {
- /* minion_jobs absent / engine quirk → no stalled-jobs finding */
+ } catch (err) {
+ if (!isMissingSchemaObject(err, 'table', 'minion_jobs')) throw err;
}
// Stale federated sources: synced sources that haven't advanced in a week.
@@ -62,8 +65,8 @@ export const collectStalledJobs: AdvisorCollector = {
ask_user: true,
});
}
- } catch {
- /* sources table missing last_sync_at on a very old brain → skip */
+ } catch (err) {
+ if (!isMissingSchemaObject(err, 'table', 'sources') && !isMissingSchemaObject(err, 'column', 'last_sync_at')) throw err;
}
return findings;
diff --git a/src/core/advisor/collect-usage-shape.ts b/src/core/advisor/collect-usage-shape.ts
index 660e873391..aa96c60d23 100644
--- a/src/core/advisor/collect-usage-shape.ts
+++ b/src/core/advisor/collect-usage-shape.ts
@@ -9,6 +9,9 @@
* than getStats. The advisor calls it on explicit `gbrain advisor` / weekly
* cron; the sync-cadence path uses getStats only (commands/advisor.ts /
* the sync hook decide which collectors to run).
+ *
+ * A failed read is not an empty brain: getStats/getHealth errors propagate so
+ * runAdvisor reports `collector_failed:usage-shape`.
*/
import type { AdvisorCollector, AdvisorFinding } from './types.ts';
@@ -18,52 +21,42 @@ export const collectUsageShape: AdvisorCollector = {
collect: async (ctx) => {
const findings: AdvisorFinding[] = [];
- let pageCount = 0;
- try {
- const stats = await ctx.engine.getStats();
- pageCount = stats.page_count;
- } catch {
- return []; // no stats → empty brain or unreachable; nothing to advise
- }
- if (pageCount === 0) return [];
+ const stats = await ctx.engine.getStats();
+ if (stats.page_count === 0) return [];
- try {
- const health = await ctx.engine.getHealth();
- // A keyless-by-choice brain has no vectors by design; `embed --all` refuses there (setup-smells covers it).
- if (health.embed_coverage < 0.7 && health.missing_embeddings > 0 && ctx.config?.embedding_disabled !== true) {
- findings.push({
- id: 'low_embed_coverage',
- severity: 'warn',
- title: `Only ${Math.round(health.embed_coverage * 100)}% of content is embedded — semantic search is degraded.`,
- detail: `${health.missing_embeddings} pages are missing embeddings. Backfill to restore full recall.`,
- fix: { command_argv: ['gbrain', 'embed', '--all'] },
- collector: 'usage-shape',
- ask_user: true,
- });
- }
- if (health.orphan_pages > 0) {
- findings.push({
- id: 'orphan_pages',
- severity: 'info',
- title: `${health.orphan_pages} page${health.orphan_pages === 1 ? ' has' : 's have'} no links in or out.`,
- detail: 'Orphaned pages do not surface through graph traversal — connect or review them.',
- fix: { command_argv: ['gbrain', 'orphans'] },
- collector: 'usage-shape',
- ask_user: true,
- });
- }
- if (health.dead_links > 0) {
- findings.push({
- id: 'dead_links',
- severity: 'info',
- title: `${health.dead_links} link${health.dead_links === 1 ? '' : 's'} point to a page that no longer exists.`,
- fix: { command_argv: ['gbrain', 'doctor'] },
- collector: 'usage-shape',
- ask_user: true,
- });
- }
- } catch {
- /* getHealth unavailable → skip the health-derived findings */
+ const health = await ctx.engine.getHealth();
+ // A keyless-by-choice brain has no vectors by design; `embed --all` refuses there (setup-smells covers it).
+ if (health.embed_coverage < 0.7 && health.missing_embeddings > 0 && ctx.config?.embedding_disabled !== true) {
+ findings.push({
+ id: 'low_embed_coverage',
+ severity: 'warn',
+ title: `Only ${Math.round(health.embed_coverage * 100)}% of content is embedded — semantic search is degraded.`,
+ detail: `${health.missing_embeddings} pages are missing embeddings. Backfill to restore full recall.`,
+ fix: { command_argv: ['gbrain', 'embed', '--all'] },
+ collector: 'usage-shape',
+ ask_user: true,
+ });
+ }
+ if (health.orphan_pages > 0) {
+ findings.push({
+ id: 'orphan_pages',
+ severity: 'info',
+ title: `${health.orphan_pages} page${health.orphan_pages === 1 ? ' has' : 's have'} no links in or out.`,
+ detail: 'Orphaned pages do not surface through graph traversal — connect or review them.',
+ fix: { command_argv: ['gbrain', 'orphans'] },
+ collector: 'usage-shape',
+ ask_user: true,
+ });
+ }
+ if (health.dead_links > 0) {
+ findings.push({
+ id: 'dead_links',
+ severity: 'info',
+ title: `${health.dead_links} link${health.dead_links === 1 ? '' : 's'} point to a page that no longer exists.`,
+ fix: { command_argv: ['gbrain', 'doctor'] },
+ collector: 'usage-shape',
+ ask_user: true,
+ });
}
return findings;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d5d83a49ef..fb55e4f54f 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -907,6 +907,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// Fix wave 20 lane 3.
{ since: '0.60.307.0', text: 'The bundled `gbrain-base-v2` schema pack (the `init` default, also inherited by `company-brain`) is now version 1.5.0 and declares the `code` page type the code importer stamps and the `extract_receipt` page type the extract receipt writer stamps under `extracts/` (#6818), so neither makes doctor `schema_pack_consistency` warn `page_type_undeclared` and `unify-types` no longer retypes those pages to `note`. Existing pages keep their type; no data changes. The active pack identity reads `[email protected]+<hash>`.' },
{ since: '0.60.307.0', text: 'The `advisor` MCP operation now judges the cached backup verdict the way the doctor does: a remote readback older than one hour, a future-dated cache or a degraded compute reports the `backup_coverage_aggregate` warning instead of no finding. It still reads the cache only and names reason counts, never source ids.' },
+ { since: '0.60.307.0', text: '`gbrain advisor` (and the `advisor` MCP operation) reports a database read that fails inside the `usage-shape` or `stalled-jobs` check as `collector_failed:<check>` and exits 1, instead of returning no findings for that check and possibly reporting a healthy brain. A brain with no pages, and an older brain without `minion_jobs`, `sources` or `sources.last_sync_at`, still report nothing for those checks.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/advisor-core.test.ts b/test/advisor-core.test.ts
index 7e023754c1..659f1cbbda 100644
--- a/test/advisor-core.test.ts
+++ b/test/advisor-core.test.ts
@@ -74,6 +74,19 @@ describe('runAdvisor resilience', () => {
expect(Array.isArray(report.findings)).toBe(true);
});
+ test('an unreachable engine is reported as collector_failed, never as healthy, without the error text', async () => {
+ const secret = 'postgres://alice-example:[email protected]:5432/brain';
+ const fail = async () => { throw new Error(`connect ECONNREFUSED ${secret}`); };
+ const engine = { getStats: fail, getHealth: fail, getConfig: fail, executeRaw: fail };
+ const report = await runAdvisor(ctx(engine));
+ const ids = report.findings.map((f) => f.id);
+ expect(ids).toContain('collector_failed:usage-shape');
+ expect(ids).toContain('collector_failed:stalled-jobs');
+ expect(report.worst).not.toBeNull();
+ expect(renderAdvisorReport(report)).not.toContain('looks healthy');
+ expect(JSON.stringify(report)).not.toContain('hunter2');
+ });
+
test('drops workspace_dependent findings when remote', async () => {
const wd = finding({ id: 'wd', workspace_dependent: true });
// simulate by ranking + the remote filter logic via runAdvisor is internal;
@@ -167,6 +180,19 @@ describe('collect-usage-shape', () => {
expect(ids).toContain('orphan_pages');
});
+ test('getStats failure → throws for runAdvisor, not an empty-brain pass', async () => {
+ const engine = { getStats: async () => { throw new Error('password authentication failed for user "x"'); } };
+ await expect(collectUsageShape.collect(ctx(engine as never))).rejects.toThrow('password authentication failed');
+ });
+
+ test('getHealth failure on a non-empty brain → throws for runAdvisor', async () => {
+ const engine = {
+ getStats: async () => ({ page_count: 100, chunk_count: 0, embedded_count: 0, link_count: 0, tag_count: 0, timeline_entry_count: 0, pages_by_type: {} }),
+ getHealth: async () => { throw new Error('statement timeout'); },
+ };
+ await expect(collectUsageShape.collect(ctx(engine as never))).rejects.toThrow('statement timeout');
+ });
+
test('empty brain → no findings', async () => {
const engine = { getStats: async () => ({ page_count: 0, chunk_count: 0, embedded_count: 0, link_count: 0, tag_count: 0, timeline_entry_count: 0, pages_by_type: {} }) };
expect(await collectUsageShape.collect(ctx(engine as never))).toEqual([]);
@@ -174,11 +200,38 @@ describe('collect-usage-shape', () => {
});
describe('collect-stalled-jobs', () => {
+ // Fails only the query that reads `table`; every other query returns no rows.
+ function failingOn(table: string, err: unknown) {
+ return {
+ executeRaw: async (sql: string) => {
+ if (new RegExp(`FROM ${table}\\b`).test(sql)) throw err;
+ return [];
+ },
+ };
+ }
+
test('absent minion_jobs table → no error, no finding', async () => {
- const engine = { executeRaw: async () => { throw new Error('relation "minion_jobs" does not exist'); } };
+ const engine = failingOn('minion_jobs', new Error('relation "minion_jobs" does not exist'));
expect(await collectStalledJobs.collect(ctx(engine as never))).toEqual([]);
});
+ test('old brain without sources.last_sync_at or sources → no finding', async () => {
+ const noColumn = failingOn('sources', Object.assign(new Error('column "last_sync_at" does not exist'), { code: '42703' }));
+ expect(await collectStalledJobs.collect(ctx(noColumn as never))).toEqual([]);
+ const noTable = failingOn('sources', Object.assign(new Error('relation "sources" does not exist'), { code: '42P01' }));
+ expect(await collectStalledJobs.collect(ctx(noTable as never))).toEqual([]);
+ });
+
+ test('unexpected jobs-query failure → throws for runAdvisor', async () => {
+ const engine = failingOn('minion_jobs', Object.assign(new Error('permission denied for table minion_jobs'), { code: '42501' }));
+ await expect(collectStalledJobs.collect(ctx(engine as never))).rejects.toThrow('permission denied');
+ });
+
+ test('a different missing relation is not mistaken for an old brain', async () => {
+ const engine = failingOn('sources', Object.assign(new Error('relation "sources_v2" does not exist'), { code: '42P01', table_name: 'sources_v2' }));
+ await expect(collectStalledJobs.collect(ctx(engine as never))).rejects.toThrow('sources_v2');
+ });
+
test('reports stalled jobs and stale sync', async () => {
let call = 0;
const engine = {