Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): orphan_ratio hint runs, honest wording, connector renders reported apart (#5877)

garrytan2299bca9e647
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index dd72ef5278..4454a347c2 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
-- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter.
+- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
- `src/commands/pages.ts` — `gbrain pages purge-deleted [--older-than HOURS|Nd] [--dry-run] [--json]` operator escape hatch. Mirror of `gbrain sources purge` for the page-level lifecycle. Hard-deletes pages whose `deleted_at` is older than the cutoff; cascades to content_chunks/page_links/chunk_relations.
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 84ca85f94f..461e66de21 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -133,7 +133,7 @@ async function runOrphanRatio(ctx: DoctorContext): Promise<Check[]> {
// 9b. v0.41.18.0 — orphan_ratio check (migration #1 of #1409).
//
- // Surfaces the fraction of linkable pages with no inbound links.
+ // Surfaces the fraction of linkable pages with no links in either direction.
// Consumes the same canonical getOrphansData() pure fn as
// `gbrain orphans --count` (D1), so the two surfaces cannot disagree.
//
@@ -174,26 +174,30 @@ async function runOrphanRatio(ctx: DoctorContext): Promise<Check[]> {
entityCount < 100
? ` — low scale (${entityCount} entity pages <100), interpret with caution`
: '';
+ // #5877: --by-mention only runs against the database (`--source db`);
+ // the bare command exits 2 on the default fs source.
const hint =
- 'Run: gbrain extract links --by-mention (auto-links entity mentions in body text). ' +
- 'Run gbrain orphans for the list.';
- if (ratio > 0.8) {
+ `Run: gbrain extract links --by-mention --source db${srcId ? ` --source-id ${srcId}` : ''} (auto-links entity mentions in body text). ` +
+ `Run gbrain orphans${srcId ? ` --source ${srcId}` : ''} for the list.`;
+ const rendersExcluded = data.connector_renders_excluded ?? 0;
+ const renders = rendersExcluded > 0
+ ? ` ${rendersExcluded} connector email/meeting renders are reported apart and left out of the ratio.`
+ : '';
+ const details = { connector_renders_excluded: rendersExcluded };
+ const counts = `${data.total_orphans}/${data.total_linkable} linkable pages have no links in either direction`;
+ if (ratio > 0.5) {
checks.push({
name: 'orphan_ratio',
- status: 'fail',
- message: `Orphan ratio ${pct}%${inSource} (${data.total_orphans}/${data.total_linkable} linkable pages have no inbound links)${caveat}. ${hint}`,
- });
- } else if (ratio > 0.5) {
- checks.push({
- name: 'orphan_ratio',
- status: 'warn',
- message: `Orphan ratio ${pct}%${inSource} (${data.total_orphans}/${data.total_linkable} linkable pages have no inbound links)${caveat}. ${hint}`,
+ status: ratio > 0.8 ? 'fail' : 'warn',
+ message: `Orphan ratio ${pct}%${inSource} (${counts})${caveat}.${renders} ${hint}`,
+ details,
});
} else {
checks.push({
name: 'orphan_ratio',
status: 'ok',
- message: `Orphan ratio ${pct}%${inSource} (${data.total_orphans}/${data.total_linkable} linkable pages)${caveat}`,
+ message: `Orphan ratio ${pct}%${inSource} (${data.total_orphans}/${data.total_linkable} linkable pages)${caveat}${renders ? `.${renders}` : ''}`,
+ details,
});
}
}
diff --git a/src/commands/orphans.ts b/src/commands/orphans.ts
index 4758a32fac..6ef939baad 100644
--- a/src/commands/orphans.ts
+++ b/src/commands/orphans.ts
@@ -29,6 +29,8 @@ import {
type OrphanPageMeta,
} from '../core/orphan-policy.ts';
import { quarantineFilterFragment } from '../core/quarantine.ts';
+import { isConnectorSourceKind } from '../core/persistence/connector-identity.ts';
+import { parseSourceConfig } from '../core/sources-load.ts';
// --- Types ---
@@ -44,6 +46,20 @@ export interface OrphanResult {
total_linkable: number;
total_pages: number;
excluded: number;
+ /** #5877: orphaned connector renders (email/meeting pages of a google/github source), counted apart and left out of both totals. */
+ connector_renders_excluded?: number;
+}
+
+const CONNECTOR_RENDER_TYPES = new Set(['email', 'meeting']);
+
+/**
+ * #5877: ids of connector-kind sources. Their `email`/`meeting` pages are
+ * leaf renders (participants are raw addresses, never wikilinks), so an
+ * islanded render is expected and is reported apart rather than as an orphan.
+ */
+async function loadConnectorSourceIds(engine: BrainEngine): Promise<Set<string>> {
+ const rows = await engine.executeRaw<{ id: string; config: unknown }>(`SELECT id, config FROM sources`);
+ return new Set(rows.filter(r => isConnectorSourceKind(parseSourceConfig(r.config).kind)).map(r => r.id));
}
// --- Filter logic ---
@@ -82,7 +98,7 @@ export function deriveDomain(frontmatterDomain: string | null | undefined, slug:
*/
export async function queryOrphanPages(
engine: BrainEngine,
-): Promise<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }[]> {
+): Promise<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }[]> {
return engine.findOrphanPages();
}
@@ -124,10 +140,13 @@ export async function findOrphans(
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('orphans.scan');
const stopHb = startHeartbeat(progress, 'scanning pages for missing inbound links…');
- let allOrphans: { slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }[];
+ let allOrphans: { slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }[];
let total: number;
let excludedAll: number;
const overrides = includePseudo ? undefined : await loadOrphanPolicyOverrides(engine);
+ const connectorSources = includePseudo ? new Set<string>() : await loadConnectorSourceIds(engine);
+ const isConnectorRender = (row: { type?: string | null; source_id?: string }) =>
+ !!row.source_id && connectorSources.has(row.source_id) && !!row.type && CONNECTOR_RENDER_TYPES.has(row.type);
try {
allOrphans = await engine.findOrphanPages({
excludePrivate: opts.excludePrivate,
@@ -160,9 +179,11 @@ export async function findOrphans(
progress.finish();
}
- const filtered = includePseudo
+ const policyKept = includePseudo
? allOrphans
: allOrphans.filter(row => !shouldExclude(row.slug, overrides, row));
+ const filtered = policyKept.filter(row => !isConnectorRender(row));
+ const connectorRendersExcluded = policyKept.length - filtered.length;
const orphans: OrphanPage[] = filtered.map(row => ({
slug: row.slug,
@@ -170,7 +191,7 @@ export async function findOrphans(
domain: deriveDomain(row.domain, row.slug),
}));
- const excluded = allOrphans.length - filtered.length;
+ const excluded = allOrphans.length - policyKept.length;
return {
orphans,
@@ -178,9 +199,10 @@ export async function findOrphans(
// v0.41.29.0 (Codex F6): denominator = live pages minus ALL excluded
// pages (orphan or not), so excluded pages with inbound links no longer
// inflate it.
- total_linkable: total - excludedAll,
+ total_linkable: total - excludedAll - connectorRendersExcluded,
total_pages: total,
excluded,
+ connector_renders_excluded: connectorRendersExcluded,
};
}
@@ -198,9 +220,10 @@ export const getOrphansData = findOrphans;
export function formatOrphansText(result: OrphanResult): string {
const lines: string[] = [];
- const { orphans, total_orphans, total_linkable, total_pages, excluded } = result;
+ const { orphans, total_orphans, total_linkable, total_pages, excluded, connector_renders_excluded } = result;
+ const renders = connector_renders_excluded ? `; ${connector_renders_excluded} connector renders reported apart` : '';
lines.push(
- `${total_orphans} orphans out of ${total_linkable} linkable pages (${total_pages} total; ${excluded} excluded)\n`,
+ `${total_orphans} orphans out of ${total_linkable} linkable pages (${total_pages} total; ${excluded} excluded${renders})\n`,
);
if (orphans.length === 0) {
diff --git a/src/core/doctor-remote.ts b/src/core/doctor-remote.ts
index 40cf873817..9569c9359e 100644
--- a/src/core/doctor-remote.ts
+++ b/src/core/doctor-remote.ts
@@ -308,20 +308,20 @@ export async function runOrphanRatioCheck(config: GBrainConfig): Promise<RemoteC
// locally; point them at the brain server's operator.
const url = config.remote_mcp?.mcp_url ?? '<your brain server>';
const hint =
- `Ask the brain operator at ${url} to run: gbrain extract links --by-mention ` +
+ `Ask the brain operator at ${url} to run: gbrain extract links --by-mention --source db ` +
`(auto-links entity mentions in body text).`;
if (ratio > 0.8) {
return {
name: 'orphan_ratio',
status: 'fail',
- message: `Orphan ratio ${pct}% (${data.total_orphans}/${entityCount} linkable pages have no inbound links). ${hint}`,
+ message: `Orphan ratio ${pct}% (${data.total_orphans}/${entityCount} linkable pages have no links in either direction). ${hint}`,
};
}
if (ratio > 0.5) {
return {
name: 'orphan_ratio',
status: 'warn',
- message: `Orphan ratio ${pct}% (${data.total_orphans}/${entityCount} linkable pages have no inbound links). ${hint}`,
+ message: `Orphan ratio ${pct}% (${data.total_orphans}/${entityCount} linkable pages have no links in either direction). ${hint}`,
};
}
return {
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index 7750af9b0a..bb8c20e35f 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -371,7 +371,7 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {
sourceIds?: string[];
excludePrivate?: boolean;
mode?: 'inbound' | 'islanded';
- }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>> {
+ }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }>> {
// Soft-delete filter on BOTH sides:
// - candidate: p.deleted_at IS NULL — soft-deleted pages aren't orphan candidates
// - link source: src.deleted_at IS NULL — links FROM soft-deleted pages don't count as inbound
@@ -409,7 +409,8 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {
COALESCE(p.title, p.slug) AS title,
p.frontmatter->>'domain' AS domain,
p.type,
- (NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}) AS quarantined
+ (NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}) AS quarantined,
+ p.source_id
FROM pages p
WHERE p.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
${sourceFilter}
@@ -423,7 +424,7 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {
${outboundFilter}
ORDER BY p.slug
`)).rows;
- return rows as unknown as Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>;
+ return rows as unknown as Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }>;
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 0a2378553c..2e37800042 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1690,7 +1690,7 @@ export interface BrainEngine {
title: string;
domain: string | null;
type?: string | null;
- quarantined?: boolean;
+ quarantined?: boolean; source_id?: string;
}>>;
// Tags
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index bc8deb9061..cc161a00fb 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2039,7 +2039,7 @@ export class PGLiteEngine implements BrainEngine {
sourceIds?: string[];
excludePrivate?: boolean;
mode?: 'inbound' | 'islanded';
- }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>> {
+ }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }>> {
return linksImpl.findOrphanPages(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index db444ac93a..8f653e05fe 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1801,7 +1801,7 @@ export class PostgresEngine implements BrainEngine {
sourceIds?: string[];
excludePrivate?: boolean;
mode?: 'inbound' | 'islanded';
- }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean }>> {
+ }): Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string }>> {
return linksImpl.findOrphanPages(unscopedExecutor(this.engineSql, 'links: unscoped on master (EO4 inventory)'), opts);
}
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index 45d6f90911..fcfa781ad8 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -40,16 +40,16 @@
{
"lane": "pool",
"params": [],
- "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL ) ORDER BY p.slug",
- "textSha256": "0fa2045edf96c55157b109a673ea67cfde76f808c73c2285454ee33a6f634c88"
+ "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL ) ORDER BY p.slug",
+ "textSha256": "ccd54a0820a24043487ce62a2c9456979837f0bd06493aa541a3d980ffcf31fc"
}
],
"inbound": [
{
"lane": "pool",
"params": [],
- "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) ORDER BY p.slug",
- "textSha256": "3bfc66a02a00c96ed7dda81cad12b3f9b1791f6a5c7a3d44a05ca0e346da0432"
+ "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) ORDER BY p.slug",
+ "textSha256": "58eb67a7f7183533c6dbd2d8f472c35c36c90bbf5c00cbe1452eaa3e524b7097"
}
],
"sourceId": [
@@ -58,8 +58,8 @@
"params": [
"string"
],
- "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined FROM pages p WHERE p.deleted_at IS NULL AND p.source_id = $1 AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL ) ORDER BY p.slug",
- "textSha256": "8cae9b94e4071fae4702f46d9855d928337bbf7576486d86a562cc8c5cd15a9e"
+ "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND p.source_id = $1 AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL ) ORDER BY p.slug",
+ "textSha256": "adcf43bf67fb992a06d0837b478ce13fc924c8170f14f73039f30bb854b5670c"
}
],
"sourceIds+excludePrivate": [
@@ -68,8 +68,8 @@
"params": [
"array<string>"
],
- "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined FROM pages p WHERE p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND p.source_id = ANY($1::text[]) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL AND (COALESCE(src.frontmatter->>'visibility', CASE WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN src.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = src.source_id AND derived_origin.slug = src.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = src.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) )) ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL AND (COALESCE(tgt.frontmatter->>'visibility', CASE WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN tgt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = tgt.source_id AND derived_origin.slug = tgt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = tgt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) )) ) ORDER BY p.slug",
- "textSha256": "657e2b5a974e49468aa218c45b29ae0394a4985f988e0d9167e62d48fa000e16"
+ "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND p.source_id = ANY($1::text[]) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL AND (COALESCE(src.frontmatter->>'visibility', CASE WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN src.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = src.source_id AND derived_origin.slug = src.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = src.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) )) ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL AND (COALESCE(tgt.frontmatter->>'visibility', CASE WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN tgt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = tgt.source_id AND derived_origin.slug = tgt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = tgt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) ELSE false END)) )) ) ORDER BY p.slug",
+ "textSha256": "26fcae0f764b034ab8f98d2c1a0e8b764d69f86bd61b46878a740b8bbfa18b17"
}
]
},
diff --git a/test/orphan-ratio-connector-renders.test.ts b/test/orphan-ratio-connector-renders.test.ts
new file mode 100644
index 0000000000..f354a13c7d
--- /dev/null
+++ b/test/orphan-ratio-connector-renders.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #5877 (Cl8, D5): connector renders (email/meeting pages of a google or
+ * github source) are islanded by construction — participants are raw
+ * addresses, never wikilinks — so they leave the orphan ratio's numerator
+ * and denominator and are reported apart as `connector_renders_excluded`.
+ * The fix hint names `--source db` (and `--source-id` when scoped) and says
+ * what the metric measures: no links in either direction.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { findOrphans } from '../src/commands/orphans.ts';
+import { runDoctor, type DoctorReport } from '../src/commands/doctor.ts';
+import { setCliOptions } from '../src/core/cli-options.ts';
+
+let engine: PGLiteEngine;
+
+const page = (title: string, type: string) => ({ type: type as 'note', title, compiled_truth: 'body', timeline: '', frontmatter: {} });
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await resetPgliteState(engine);
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES
+ ('mail-example', 'mail-example', '{"kind":"google"}'::jsonb),
+ ('notes-example', 'notes-example', '{}'::jsonb) ON CONFLICT DO NOTHING`);
+ for (let i = 0; i < 5; i++) await engine.putPage(`emails/thread-${i}`, page(`Thread ${i}`, 'email'), { sourceId: 'mail-example' });
+ await engine.putPage('calendar/standup', page('Standup', 'meeting'), { sourceId: 'mail-example' });
+ // A connector-source page that is not a render still counts.
+ await engine.putPage('notes/mail-digest', page('Digest', 'note'), { sourceId: 'mail-example' });
+ // A git-source email page is not a connector render.
+ await engine.putPage('emails/hand-written', page('Hand written', 'email'), { sourceId: 'notes-example' });
+ await engine.putPage('notes/orphan', page('Orphan note', 'note'), { sourceId: 'notes-example' });
+ await engine.putPage('notes/orphan-2', page('Orphan note 2', 'note'), { sourceId: 'notes-example' });
+ await engine.putPage('notes/linked-a', page('Linked A', 'note'), { sourceId: 'notes-example' });
+ await engine.putPage('notes/linked-b', page('Linked B', 'note'), { sourceId: 'notes-example' });
+ await engine.addLinksBatch([{ from_slug: 'notes/linked-a', to_slug: 'notes/linked-b', link_type: 'mentions', link_source: 'markdown', context: '',
+ from_source_id: 'notes-example', to_source_id: 'notes-example', origin_source_id: 'notes-example' }]);
+}, 60_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+async function doctorCheck(args: string[]) {
+ const out: string[] = [];
+ const log = console.log;
+ const err = console.error;
+ const exit = process.exit;
+ console.log = (msg?: unknown) => { out.push(String(msg)); };
+ console.error = () => {};
+ (process as { exit: unknown }).exit = (() => { throw new Error('__exit'); }) as unknown as typeof process.exit;
+ try {
+ await runDoctor(engine, ['--json', ...args]);
+ } catch (e) {
+ if (!(e instanceof Error && e.message === '__exit')) throw e;
+ } finally {
+ console.log = log; console.error = err; (process as { exit: unknown }).exit = exit;
+ }
+ for (let i = out.length - 1; i >= 0; i--) {
+ try {
+ const parsed = JSON.parse(out[i]!) as DoctorReport;
+ if (parsed && 'checks' in parsed) return parsed.checks.find(c => c.name === 'orphan_ratio')!;
+ } catch { /* not the report */ }
+ }
+ throw new Error('no doctor report');
+}
+
+describe('#5877 connector renders', () => {
+ test('connector email/meeting renders are counted apart; only real orphans count', async () => {
+ const result = await findOrphans(engine, {});
+ expect(result.orphans.map(o => o.slug).sort()).toEqual(['emails/hand-written', 'notes/mail-digest', 'notes/orphan', 'notes/orphan-2']);
+ expect(result.connector_renders_excluded).toBe(6);
+ expect(result.total_pages).toBe(12);
+ expect(result.total_linkable).toBe(6);
+ });
+
+ test('--include-pseudo keeps every islanded page', async () => {
+ const result = await findOrphans(engine, { includePseudo: true });
+ expect(result.orphans).toHaveLength(10);
+ expect(result.connector_renders_excluded).toBe(0);
+ });
+
+ test('a connector source of only renders is not reported as a failing orphan ratio', async () => {
+ const result = await findOrphans(engine, { sourceId: 'mail-example' });
+ expect(result.orphans.map(o => o.slug)).toEqual(['notes/mail-digest']);
+ expect(result.connector_renders_excluded).toBe(6);
+ expect(result.total_linkable).toBe(1);
+ });
+
+ test('doctor orphan_ratio reports connector_renders_excluded and leaves them out of the ratio', async () => {
+ const check = await doctorCheck(['--source', 'mail-example']);
+ expect(check.details).toEqual({ connector_renders_excluded: 6 });
+ expect(check.message).toContain('Orphan ratio 100% in source \'mail-example\' (1/1 linkable pages have no links in either direction');
+ expect(check.message).toContain('6 connector email/meeting renders are reported apart');
+ }, 60_000);
+
+ test('scoped hint names --source db and --source-id; wording is honest', async () => {
+ const check = await doctorCheck(['--source', 'notes-example']);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('have no links in either direction');
+ expect(check.message).not.toContain('no inbound links');
+ expect(check.message).toContain('Run: gbrain extract links --by-mention --source db --source-id notes-example');
+ expect(check.message).toContain('Run gbrain orphans --source notes-example for the list.');
+ expect(check.details).toEqual({ connector_renders_excluded: 0 });
+ }, 60_000);
+});