Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): source_routing_health skips the dedicated skills source (#6076)
time-attackf04bca02f277
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.mdindex 11e966d333..b861c794ed 100644--- a/docs/architecture/key-files/commands-2.md+++ b/docs/architecture/key-files/commands-2.md@@ -42,7 +42,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.-- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts`, `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.+- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.- `src/commands/doctor/checks/default-source-path.ts` — the gathering wrapper on the doctor surface: reads the `default` sources row, page counts (live + file-backed), `sync.repo_path` resolution, and the leak-guard collision, then delegates the verdict to `assessDefaultSourcePath`. Only gathers the fallback-topology inputs when the pointer is actually null; returns null for the skip verdict.diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.tsindex 26f817c8e1..88ff20d050 100644--- a/src/commands/doctor/checks/routing-federation.ts+++ b/src/commands/doctor/checks/routing-federation.ts@@ -33,6 +33,10 @@ export const DCR_PRIVILEGED_SCOPES: ReadonlyArray<string> = Object.freeze(* `sync.respect_gitignore` is unset/false (info-line nudge for* Tier 4I's opt-in flag).*+ * A zero-page source that holds an adopted skill pack (a dedicated skills+ * source has no pages by design) is not warned about: see+ * `adoptedSkillPackSourceIds`.+ ** Cost-bounded: total cap of 200 means a 20-source CEO brain pays* 20*10 = 200 selects rather than 20*50 = 1000.*/@@ -45,16 +49,19 @@ export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Chereturn { name: 'source_routing_health', status: 'ok', message: 'Single-source brain (no federation to check)' };}const perSourceCap = Math.min(50, Math.ceil(200 / Math.max(1, sources.length)));- const emptySources: string[] = [];+ const zeroPageSources: string[] = [];for (const s of sources) {const rows = await engine.executeRaw<{ n: string }>(`SELECT COUNT(*)::text AS n FROM pages WHERE source_id = $1 LIMIT $2`,[s.id, perSourceCap],);if (Number(rows[0]?.n ?? 0) === 0) {- emptySources.push(s.id);+ zeroPageSources.push(s.id);}}+ const packSources = zeroPageSources.length > 0 ? await adoptedSkillPackSourceIds(engine) : new Set<string>();+ const skillPackSources = zeroPageSources.filter((id) => packSources.has(id));+ const emptySources = zeroPageSources.filter((id) => !packSources.has(id));if (emptySources.length > 0) {return {name: 'source_routing_health',@@ -69,7 +76,8 @@ export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Chereturn {name: 'source_routing_health',status: 'ok',- message: `Multi-source brain (${sources.length} non-default source(s)); all populated`,+ message: `Multi-source brain (${sources.length} non-default source(s)); all populated`+ + (skillPackSources.length ? ` (skill-pack sources hold no pages by design: ${skillPackSources.join(', ')})` : ''),};} catch (e) {const msg = e instanceof Error ? e.message : String(e);@@ -77,6 +85,30 @@ export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Che}}+/**+ * Non-default sources holding an adopted skill pack: a `shared_skill_packs`+ * row for the source's current incarnation with at least one live+ * (`NOT deleted`) `shared_skill_heads` row. A pack left behind by an earlier+ * incarnation does not count. A schema without the shared-skills tables (or+ * `sources.incarnation`) has no adopted packs.+ */+async function adoptedSkillPackSourceIds(engine: BrainEngine): Promise<Set<string>> {+ try {+ const rows = await engine.executeRaw<{ id: string }>(+ `SELECT s.id FROM sources s+ WHERE s.id <> 'default' AND EXISTS (+ SELECT 1 FROM shared_skill_packs p+ JOIN shared_skill_heads h ON h.source_id = p.source_id AND h.source_incarnation = p.source_incarnation+ AND h.pack_id = p.pack_id AND NOT h.deleted+ WHERE p.source_id = s.id AND p.source_incarnation = s.incarnation)`,+ );+ return new Set(rows.map((r) => r.id));+ } catch (e) {+ if (isUndefinedTableError(e) || isUndefinedColumnError(e, 'incarnation')) return new Set();+ throw e;+ }+}+/*** v0.40 Federated Sync v2 (T12) — federation_health.*diff --git a/test/doctor-routing-skill-pack-source.test.ts b/test/doctor-routing-skill-pack-source.test.tsnew file mode 100644index 0000000000..54e53091aa--- /dev/null+++ b/test/doctor-routing-skill-pack-source.test.ts@@ -0,0 +1,122 @@+/**+ * source_routing_health and the dedicated skills source (#6076).+ *+ * Protects: a non-default source with zero pages that holds an adopted skill+ * pack (a `shared_skill_packs` row for its current incarnation with a live+ * `shared_skill_heads` row) is not reported as a routing collapse, while every+ * other zero-page source still warns: no pack, a pack left by an earlier+ * incarnation, or a pack whose heads are all deleted. A schema without the+ * shared-skills tables keeps the old warning.+ * Fails when: the exemption is dropped (the skills source warns again) or+ * widened (a stale or empty pack hides a real collapse).+ * Seams: none; real PGLite (and Postgres through test/postgres-unit-arms.txt)+ * with the rows written directly (publication triggers suppressed in the+ * fixture transaction), plus a duck-typed engine for the pre-shared-skills+ * schema.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { checkSourceRoutingHealth } from '../src/commands/doctor.ts';+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++/** The fixture writes with the publication triggers off: real adoption runs through the persistence coordinator, and the check only reads these rows. */+async function withoutTriggers(engine: BrainEngine, run: (tx: BrainEngine) => Promise<void>): Promise<void> {+ await engine.transaction(async (tx) => {+ await tx.executeRaw('SET LOCAL session_replication_role = replica');+ await run(tx);+ });+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`${backend}: checkSourceRoutingHealth and skill-pack sources (#6076)`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));+ }, 120_000);++ afterAll(async () => {+ await close();+ });++ beforeEach(async () => {+ await withoutTriggers(engine, async (tx) => {+ await tx.executeRaw('DELETE FROM shared_skill_heads');+ await tx.executeRaw('DELETE FROM shared_skill_packs');+ await tx.executeRaw("DELETE FROM pages WHERE source_id <> 'default'");+ await tx.executeRaw("DELETE FROM sources WHERE id <> 'default'");+ });+ });++ async function addSource(id: string): Promise<string> {+ const [row] = await engine.executeRaw<{ incarnation: string }>(+ 'INSERT INTO sources (id, name) VALUES ($1, $1) RETURNING incarnation::text AS incarnation', [id]);+ return row!.incarnation;+ }++ async function adoptPack(sourceId: string, incarnation: string, heads: Array<{ name: string; deleted?: boolean }>): Promise<void> {+ await withoutTriggers(engine, async (tx) => {+ await tx.executeRaw(+ `INSERT INTO shared_skill_packs (source_id, source_incarnation, pack_id, revision, manifest, manifest_hash)+ VALUES ($1, $2::uuid, 'pack-example', $3::uuid, '{}'::jsonb, 'hash-example')`,+ [sourceId, incarnation, randomUUID()]);+ for (const head of heads) {+ await tx.executeRaw(+ `INSERT INTO shared_skill_heads (source_id, source_incarnation, pack_id, name, revision, metadata, deleted, policy_epoch)+ VALUES ($1, $2::uuid, 'pack-example', $3, $4::uuid, '{}'::jsonb, $5, 'epoch-example')`,+ [sourceId, incarnation, head.name, randomUUID(), head.deleted === true]);+ }+ });+ }++ test('a zero-page source holding an adopted pack on its current incarnation → ok, named in the message', async () => {+ await adoptPack('skills', await addSource('skills'), [{ name: 'example-skill' }]);+ const r = await checkSourceRoutingHealth(engine);+ expect(r.status).toBe('ok');+ expect(r.message).toBe('Multi-source brain (1 non-default source(s)); all populated (skill-pack sources hold no pages by design: skills)');+ });++ test('a zero-page source with no pack still warns', async () => {+ await adoptPack('skills', await addSource('skills'), [{ name: 'example-skill' }]);+ await addSource('lonely');+ const r = await checkSourceRoutingHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/^1 non-default source\(s\) have zero pages: lonely\./);+ });++ test('a pack left by an earlier incarnation still warns', async () => {+ await addSource('skills');+ await adoptPack('skills', randomUUID(), [{ name: 'example-skill' }]);+ const r = await checkSourceRoutingHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/zero pages: skills\./);+ });++ test('a pack whose heads are all deleted still warns', async () => {+ await adoptPack('skills', await addSource('skills'), [{ name: 'example-skill', deleted: true }]);+ const r = await checkSourceRoutingHealth(engine);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/zero pages: skills\./);+ });+ });+}++describe('checkSourceRoutingHealth on a schema without shared skills', () => {+ test('keeps the zero-page warning', async () => {+ const preSharedSkills = {+ executeRaw: async (sql: string) => {+ if (/shared_skill_packs/.test(sql)) throw Object.assign(new Error('relation "shared_skill_packs" does not exist'), { code: '42P01' });+ if (/FROM pages/.test(sql)) return [{ n: '0' }];+ return [{ id: 'skills' }];+ },+ } as unknown as BrainEngine;+ const r = await checkSourceRoutingHealth(preSharedSkills);+ expect(r.status).toBe('warn');+ expect(r.message).toMatch(/zero pages: skills\./);+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 235dbd84fe..67487f8b6d 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -24,6 +24,7 @@ test/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.tstest/doctor-frontmatter-holds.test.ts+test/doctor-routing-skill-pack-source.test.tstest/embedding-completion-atomic.serial.test.tstest/engine-sql-facts-keyset.test.tstest/extract-endpoint-revision.serial.test.ts