Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): junk_entity_hubs reports connector contact pages honestly (#6158)

garrytan69b24536ee97
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index c77071dbfe..4c26b27966 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -41,7 +41,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). `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).
+- `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). `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/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 3deeb1479e..1437a71f67 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -10,6 +10,7 @@ import { pricingSetCommand } from '../../../core/budget/no-pricing.ts';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { checkError } from '../check-fix.ts';
+import { isConnectorSourceKind } from '../../../core/persistence/connector-identity.ts';
/**
* v0.40.4 graph_signals_coverage doctor check.
@@ -459,6 +460,9 @@ export async function checkJunkEntityHubs(
source_id: string | null;
edges: number;
chunks: number;
+ connector_page: boolean;
+ source_kind: string | null;
+ default_twin: boolean;
}>(
`WITH edge_counts AS (
SELECT page_id, COUNT(*)::int AS edges FROM (
@@ -474,9 +478,14 @@ export async function checkJunkEntityHubs(
FROM content_chunks
GROUP BY page_id
)
- SELECT p.slug, p.source_id, ec.edges, COALESCE(cc.chunks, 0)::int AS chunks
+ SELECT p.slug, p.source_id, ec.edges, COALESCE(cc.chunks, 0)::int AS chunks,
+ (p.frontmatter ->> 'google_contact_id') IS NOT NULL AS connector_page,
+ s.config ->> 'kind' AS source_kind,
+ EXISTS (SELECT 1 FROM pages t WHERE t.source_id = 'default' AND t.slug = p.slug
+ AND t.deleted_at IS NULL AND p.source_id <> 'default') AS default_twin
FROM edge_counts ec
JOIN pages p ON p.id = ec.page_id AND p.deleted_at IS NULL
+ LEFT JOIN sources s ON s.id = p.source_id
LEFT JOIN chunk_counts cc ON cc.page_id = ec.page_id
WHERE COALESCE(cc.chunks, 0) <= $2
AND COALESCE(p.frontmatter ->> 'junk_hub_exempt', 'false') <> 'true'
@@ -493,25 +502,48 @@ export async function checkJunkEntityHubs(
};
}
- const list = rows
- .map(r => ` ${r.slug}${(r.source_id ?? 'default') !== 'default' ? ` [${r.source_id}]` : ''} — ${r.edges} edges, ${r.chunks} chunk(s)`)
- .join('\n');
- return {
- name: 'junk_entity_hubs',
- status: 'warn',
- message:
- `${rows.length} near-empty page(s) with >${edgeThreshold} edges — likely generic-token entities ` +
- `("Will", "Info") minted by an extractor and inflated by mention auto-links:\n${list}\n` +
+ const line = (r: typeof rows[number]) => ` ${r.slug}${(r.source_id ?? 'default') !== 'default' ? ` [${r.source_id}]` : ''} — ${r.edges} edges, ${r.chunks} chunk(s)`;
+ // #6158: a connector's own contact page (re-rendered by the connector) collects its source's
+ // mention links by design (the own-source twin wins); it is not an extractor-minted entity.
+ const isConnector = (r: typeof rows[number]) => r.connector_page || isConnectorSourceKind(r.source_kind);
+ const hubs = rows.filter(r => !isConnector(r));
+ const twins = rows.filter(isConnector);
+ const parts: string[] = [];
+ if (hubs.length > 0) {
+ parts.push(
+ `${hubs.length} near-empty page(s) with >${edgeThreshold} edges — likely generic-token entities ` +
+ `("Will", "Info") minted by an extractor and inflated by mention auto-links:\n${hubs.map(line).join('\n')}\n` +
`Review each page and merge/delete deliberately (nothing is auto-deleted). ` +
`New accretion is already gated: enrichEntity refuses generic single-token mints and ` +
`buildGazetteer drops single-generic-token person titles. If a page is an intentional thin ` +
- `hub/index page, opt it out with junk_hub_exempt: true in frontmatter.`,
+ `hub/index page, opt it out with junk_hub_exempt: true in frontmatter.`);
+ }
+ if (twins.length > 0) {
+ parts.push(
+ `${twins.length} connector contact page(s) with >${edgeThreshold} edges:\n${twins.map(line).join('\n')}\n` +
+ `These are not junk: a connector renders each contact as its own page, and mentions in that source link to it ` +
+ `before the main-brain page of the same name (by design). Frontmatter edits do not stick (the connector re-renders ` +
+ `the page) and gbrain has no merge command. Whether a contact page should defer to its main-brain twin is an open ` +
+ `policy question (issue #6158); nothing needs doing now, so ask the user before changing anything.`);
+ }
+ return {
+ name: 'junk_entity_hubs',
+ status: 'warn',
+ message: parts.join('\n'),
+ ...(twins.length > 0 ? { fix_unavailable_reason: 'operator_judgement' as const } : {}),
details: {
- hubs: rows.map(r => ({
+ hubs: hubs.map(r => ({
+ slug: r.slug,
+ source_id: r.source_id ?? 'default',
+ edges: r.edges,
+ chunks: r.chunks,
+ })),
+ connector_twins: twins.map(r => ({
slug: r.slug,
source_id: r.source_id ?? 'default',
edges: r.edges,
chunks: r.chunks,
+ canonical_twin: r.default_twin ? r.slug : null,
})),
},
};
diff --git a/test/junk-entity-guards.test.ts b/test/junk-entity-guards.test.ts
index d8b579455f..12325056f3 100644
--- a/test/junk-entity-guards.test.ts
+++ b/test/junk-entity-guards.test.ts
@@ -311,3 +311,34 @@ describe('junk_entity_hubs doctor check (#4222)', () => {
}
});
});
+
+// #6158: a connector's own contact page collects its source's mention links by design
+// (own-source twin first). Doctor must not call it an extractor-minted junk entity or offer
+// junk_hub_exempt (the connector re-renders the page), and must name the main-brain twin.
+describe('junk_entity_hubs connector contact pages (#6158)', () => {
+ beforeEach(truncateAll);
+
+ test('a connector contact page is reported as a connector twin, not a generic-token entity', async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('google-example', 'google-example', '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'stub', timeline: '' });
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'stub', timeline: '',
+ frontmatter: { google_contact_id: 'c123' } }, { sourceId: 'google-example' });
+ const batch: LinkBatchInput[] = [];
+ for (let i = 0; i < 4; i++) {
+ const slug = `mail/thread-${i}`;
+ await engine.putPage(slug, { type: 'note', title: `Thread ${i}`, compiled_truth: 'body', timeline: '' }, { sourceId: 'google-example' });
+ batch.push({ from_slug: slug, to_slug: 'people/alice-example', link_source: 'mentions', from_source_id: 'google-example', to_source_id: 'google-example' } as LinkBatchInput);
+ }
+ await engine.addLinksBatch(batch);
+
+ const check = await checkJunkEntityHubs(engine, { edgeThreshold: 3, maxChunks: 2 });
+ expect(check.status).toBe('warn');
+ expect(check.message).not.toContain('generic-token');
+ expect(check.message).not.toContain('junk_hub_exempt');
+ expect(check.message).toContain('people/alice-example [google-example]');
+ expect((check as { fix_unavailable_reason?: string }).fix_unavailable_reason).toBe('operator_judgement');
+ const details = check.details as { hubs: unknown[]; connector_twins: Array<Record<string, unknown>> };
+ expect(details.hubs).toEqual([]);
+ expect(details.connector_twins).toEqual([expect.objectContaining({ slug: 'people/alice-example', source_id: 'google-example', canonical_twin: 'people/alice-example' })]);
+ });
+});