Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): confine every remote doctor check to the caller's sources

time-attack47da62b19bae
diff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.ts
index 3ab8f30b30..09b0eb561f 100644
--- a/src/commands/doctor/checks/calibration.ts
+++ b/src/commands/doctor/checks/calibration.ts
@@ -87,7 +87,7 @@ export async function checkContextualRetrievalCoverage(
let failureSummaryLine = '';
try {
const audit = await import('../../../core/audit-synopsis.ts');
- const events = audit.readRecentSynopsisFailures(7);
+ const events = audit.readRecentSynopsisFailures(7).filter((e) => !opts.sourceIds || opts.sourceIds.includes(e.source_id));
const summary = audit.summarizeSynopsisFailures(events);
if (summary && summary.total > 0) {
const rate = (summary.page_level_fallback_rate * 100).toFixed(1);
@@ -160,7 +160,7 @@ export async function checkContextualRetrievalCoverage(
* NOTE: this does NOT verify `archive/` pages are embedded/graphed — after the
* #1777 fix `archive/` is no longer excluded, so it never appears here.
*/
-export async function checkHiddenBySearchPolicy(engine: BrainEngine): Promise<Check> {
+export async function checkHiddenBySearchPolicy(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
const name = 'hidden_by_search_policy';
try {
const prefixes = resolveHardExcludes();
@@ -177,14 +177,16 @@ export async function checkHiddenBySearchPolicy(engine: BrainEngine): Promise<Ch
const filters = prefixes
.map((_, i) => `COUNT(DISTINCT p.id) FILTER (WHERE p.slug LIKE $${i + 1} ESCAPE '\\')::int AS c${i}`)
.join(',\n ');
- const params = prefixes.map((pfx) => `${escapeLikePattern(pfx)}%`);
+ const params: unknown[] = prefixes.map((pfx) => `${escapeLikePattern(pfx)}%`);
+ // A remote caller's grant confines the counts to its own sources.
+ if (opts.sourceIds) params.push(opts.sourceIds);
const sql =
`SELECT
${filters}
FROM pages p
JOIN sources s ON s.id = p.source_id
WHERE EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)
- ${visibility}`;
+ ${visibility}${opts.sourceIds ? `\n AND p.source_id = ANY($${params.length}::text[])` : ''}`;
const rows = await engine.executeRaw<Record<string, number>>(sql, params);
const row = rows[0] ?? {};
@@ -238,13 +240,24 @@ export async function checkHiddenBySearchPolicy(engine: BrainEngine): Promise<Ch
export async function checkLinkResolutionOpportunity(
engine: BrainEngine,
progress?: ProgressReporter,
+ opts: { sourceIds?: string[] } = {},
): Promise<Check> {
const name = 'link_resolution_opportunity';
try {
if (await isGlobalBasenameEnabled(engine)) {
return { name, status: 'ok', message: 'global_basename mode already enabled' };
}
- const allSlugs = await engine.getAllSlugs();
+ // A remote caller's grant confines the slug index, the page total and the
+ // scanned sample to its own sources.
+ let allSlugs: Set<string>;
+ if (opts.sourceIds) {
+ allSlugs = new Set();
+ for (const sourceId of opts.sourceIds) for (const slug of await engine.getAllSlugs({ sourceId })) allSlugs.add(slug);
+ } else {
+ allSlugs = await engine.getAllSlugs();
+ }
+ const scope = opts.sourceIds ? ' AND source_id = ANY($1::text[])' : '';
+ const scopeParams = opts.sourceIds ? [opts.sourceIds] : undefined;
if (allSlugs.size === 0) {
return { name, status: 'ok', message: 'Brain is empty — nothing to scan' };
}
@@ -264,11 +277,13 @@ export async function checkLinkResolutionOpportunity(
// returned a perpetual partial; this bounds the work to a fixed sample.
const SAMPLE_LIMIT = 1000;
const sampled = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null }>(
- `SELECT compiled_truth, timeline FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}`,
+ `SELECT compiled_truth, timeline FROM pages WHERE deleted_at IS NULL${scope} ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}`,
+ scopeParams,
);
// Decision #10: a segmented page's body columns are NULL, so the sample scans it as an empty body.
const [segmented] = await engine.executeRaw<{ n: number }>(
- `SELECT COUNT(*)::int AS n FROM (SELECT body_storage FROM pages WHERE deleted_at IS NULL ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}) s WHERE s.body_storage = 'segmented'`,
+ `SELECT COUNT(*)::int AS n FROM (SELECT body_storage FROM pages WHERE deleted_at IS NULL${scope} ORDER BY id DESC LIMIT ${SAMPLE_LIMIT}) s WHERE s.body_storage = 'segmented'`,
+ scopeParams,
).catch(() => []);
const result = (check: Check) => withSkippedSegmented(check, Number(segmented?.n ?? 0));
const totalPages = allSlugs.size;
@@ -335,8 +350,9 @@ export async function checkLinkResolutionOpportunity(
}
}
-export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check> {
+export async function checkAbandonedThreads(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
+ // A remote caller's grant counts only takes on its own sources' pages.
const rows = await engine.executeRaw<{ count: number }>(
// since_date is TEXT and may be month-precision ('YYYY-MM'); 'YYYY-MM'::date
// throws "invalid input syntax for type date", so normalize to the 1st
@@ -350,7 +366,9 @@ export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check>
AND weight >= 0.7
AND since_date IS NOT NULL
AND (since_date || CASE WHEN length(since_date) = 7 THEN '-01' ELSE '' END)::date
- < (now() - INTERVAL '12 months')`,
+ < (now() - INTERVAL '12 months')` +
+ (opts.sourceIds ? `\n AND page_id IN (SELECT id FROM pages WHERE source_id = ANY($1::text[]))` : ''),
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const count = rows[0]?.count ?? 0;
if (count === 0) {
@@ -377,14 +395,15 @@ export async function checkAbandonedThreads(engine: BrainEngine): Promise<Check>
* brains see one row per source; this check uses the most recent across
* all sources.
*/
-export async function checkCalibrationFreshness(engine: BrainEngine): Promise<Check> {
+export async function checkCalibrationFreshness(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
const ownerHolder = resolveOwnerHolder({
configValue: await engine.getConfig('emotional_weight.user_holder'),
});
+ // A remote caller's grant reads only its own sources' profiles.
const rows = await engine.executeRaw<{ generated_at: Date | null }>(
- `SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = $1`,
- [ownerHolder],
+ `SELECT MAX(generated_at) AS generated_at FROM calibration_profiles WHERE holder = $1${opts.sourceIds ? ' AND source_id = ANY($2::text[])' : ''}`,
+ opts.sourceIds ? [ownerHolder, opts.sourceIds] : [ownerHolder],
);
const generated = rows[0]?.generated_at;
if (!generated) {
@@ -426,10 +445,15 @@ export async function checkCalibrationFreshness(engine: BrainEngine): Promise<Ch
* exists so the surface is wired; the math arrives once we have N >= 30
* auto-applied verdicts to compare.
*/
-export async function checkGradeConfidenceDrift(engine: BrainEngine): Promise<Check> {
+export async function checkGradeConfidenceDrift(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
+ // A remote caller's grant counts only verdicts on takes of its own sources' pages.
const rows = await engine.executeRaw<{ applied_count: number }>(
- `SELECT COUNT(*)::int AS applied_count FROM take_grade_cache WHERE applied = true`,
+ `SELECT COUNT(*)::int AS applied_count FROM take_grade_cache WHERE applied = true` +
+ (opts.sourceIds
+ ? ' AND take_id IN (SELECT t.id FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = ANY($1::text[]))'
+ : ''),
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const applied = rows[0]?.applied_count ?? 0;
if (applied < 30) {
@@ -531,13 +555,15 @@ export async function checkSubagentHealth(engine: BrainEngine): Promise<Check> {
}
}
-export async function checkVoiceGateHealth(engine: BrainEngine): Promise<Check> {
+export async function checkVoiceGateHealth(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
+ // A remote caller's grant reads only its own sources' profiles.
const rows = await engine.executeRaw<{ total: number; failures: number }>(
`SELECT COUNT(*)::int AS total,
COALESCE(SUM(CASE WHEN voice_gate_passed = false THEN 1 ELSE 0 END), 0)::int AS failures
FROM calibration_profiles
- WHERE generated_at >= (now() - INTERVAL '7 days')`,
+ WHERE generated_at >= (now() - INTERVAL '7 days')${opts.sourceIds ? ' AND source_id = ANY($1::text[])' : ''}`,
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const total = rows[0]?.total ?? 0;
const failures = rows[0]?.failures ?? 0;
diff --git a/src/commands/doctor/checks/consolidation-cycle.ts b/src/commands/doctor/checks/consolidation-cycle.ts
index de1d0d41c9..c04c3a0663 100644
--- a/src/commands/doctor/checks/consolidation-cycle.ts
+++ b/src/commands/doctor/checks/consolidation-cycle.ts
@@ -43,12 +43,15 @@ const _resolveSyncFreshnessHours = resolveHoursEnv;
* the deadline stays under the interval to keep ticks from overlapping. A
* schema without `persistence_brain` reads as unmanaged.
*/
-export async function checkSyncConsolidation(engine: BrainEngine): Promise<Check> {
+export async function checkSyncConsolidation(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
+ // A remote caller's grant bounds the count: the brain-wide source count
+ // would tell a source-bound token how many sources it cannot see.
const rows = await engine.executeRaw<{ id: string }>(
`SELECT id FROM sources
WHERE archived IS NOT TRUE
- AND local_path IS NOT NULL`,
+ AND local_path IS NOT NULL${opts.sourceIds ? '\n AND id = ANY($1::text[])' : ''}`,
+ opts.sourceIds ? [opts.sourceIds] : undefined,
);
const sourceCount = rows.length;
if (sourceCount < 2) {
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index c01d24d8a6..99ae32a21a 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -1172,10 +1172,10 @@ export async function computeExtractHealthCheck(
export async function checkSyncFreshness(
engine: BrainEngine,
- opts?: { nowMs?: number; localOnly?: boolean },
+ opts?: { nowMs?: number; localOnly?: boolean; sourceIds?: string[] },
): Promise<Check> {
try {
- const sources = await loadSyncFreshnessSources(engine);
+ const sources = await loadSyncFreshnessSources(engine, opts?.sourceIds);
if (sources.length === 0) {
return {
@@ -1217,7 +1217,7 @@ export async function checkSyncFreshness(
// #4960: sources with no successful sync carry their own state, fix and wording (no generic "run sync" suffix).
const outcomes: SyncOutcomeEntry[] = [];
let ownedContent = new Set<string>();
- try { ownedContent = new Set((await ownedContentFreshness(engine)).map(source => source.sourceId)); }
+ try { ownedContent = new Set((await ownedContentFreshness(engine, opts?.sourceIds)).map(source => source.sourceId)); }
catch (error) { if (!isOwnedContentSchemaMissing(error)) throw error; }
// #6076: an adopted read-only catalog pack (no commit history) has nothing to sync.
const catalogPacks = await readOnlyCatalogPackSourceIds(engine, sources, localOnly);
diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.ts
index 1789d8ac1e..fe0574e42b 100644
--- a/src/commands/doctor/checks/graph-embedding.ts
+++ b/src/commands/doctor/checks/graph-embedding.ts
@@ -39,7 +39,7 @@ import { isCrossSourceLinksEnabled } from '../../../core/link-extraction.ts';
* Errors during the SQL count → warn with the underlying message.
* Best-effort: this check never breaks doctor.
*/
-export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Check> {
+export async function checkGraphSignalsCoverage(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
// Resolve the active graph_signals setting. Read the config key
// explicitly; when unset, fall through to the mode bundle default.
@@ -72,8 +72,11 @@ export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Ch
}
// Compute global inbound-link density. Counts DISTINCT pages with
- // at least one inbound edge / total pages.
- const totalRows = await engine.executeRaw(`SELECT COUNT(*)::int AS n FROM pages WHERE deleted_at IS NULL`);
+ // at least one inbound edge / total pages. A remote caller's grant
+ // confines both sides to its sources (no brain-wide ratio).
+ const scope = opts.sourceIds ? ' AND p.source_id = ANY($1::text[])' : '';
+ const params = opts.sourceIds ? [opts.sourceIds] : undefined;
+ const totalRows = await engine.executeRaw(`SELECT COUNT(*)::int AS n FROM pages p WHERE deleted_at IS NULL${scope}`, params);
const totalPages = Number((totalRows as any)[0]?.n ?? 0);
if (totalPages === 0) {
@@ -88,7 +91,8 @@ export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Ch
`SELECT COUNT(DISTINCT l.to_page_id)::int AS n
FROM links l
JOIN pages p ON p.id = l.to_page_id
- WHERE p.deleted_at IS NULL`
+ WHERE p.deleted_at IS NULL${scope}`,
+ params,
);
const linkedPages = Number((linkedRows as any)[0]?.n ?? 0);
const pct = (linkedPages / totalPages) * 100;
@@ -146,7 +150,7 @@ export async function checkGraphSignalsCoverage(engine: BrainEngine): Promise<Ch
* are non-blocking warnings; brainstorm + LSD still work, just with degraded
* signal.
*/
-export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check> {
+export async function checkBrainstormHealth(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
// (1) Column probe — fast, single-query.
try {
const probeRows = await engine.executeRaw<{ exists: boolean }>(
@@ -208,14 +212,15 @@ export async function checkBrainstormHealth(engine: BrainEngine): Promise<Check>
};
}
- // (4) Calibration cold-start — empty active_bias_tags.
+ // (4) Calibration cold-start — empty active_bias_tags. Profiles are per
+ // source; a remote caller's grant reads only its own sources' profiles.
try {
const calibRows = await engine.executeRaw<{ active_bias_tags: string[] | null }>(
`SELECT active_bias_tags
- FROM calibration_profiles
+ FROM calibration_profiles${opts.sourceIds ? '\n WHERE source_id = ANY($1::text[])' : ''}
ORDER BY generated_at DESC
LIMIT 1`,
- []
+ opts.sourceIds ? [opts.sourceIds] : []
);
if (calibRows.length === 0) {
return {
diff --git a/src/commands/doctor/checks/routing-federation.ts b/src/commands/doctor/checks/routing-federation.ts
index 4ed1e5d441..07346d0622 100644
--- a/src/commands/doctor/checks/routing-federation.ts
+++ b/src/commands/doctor/checks/routing-federation.ts
@@ -100,13 +100,22 @@ export async function checkSourceRoutingHealth(engine: BrainEngine): Promise<Che
*
* Single-source brain short-circuits to ok (no federation to check).
* Each warning carries a paste-ready remediation hint.
+ *
+ * `opts.sourceIds` (the remote caller's grant) confines the dashboard to
+ * those sources: a source-bound token never reads another source's id, lag,
+ * coverage or failed-job count, and the single-source short-circuit is
+ * judged on brain-wide state only for unscoped callers.
*/
-export async function checkFederationHealth(engine: BrainEngine): Promise<Check> {
+export async function checkFederationHealth(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
const { loadAllSources } = await import('../../../core/sources-load.ts');
const { computeAllSourceMetrics } = await import('../../../core/source-health.ts');
- const sources = await loadAllSources(engine, { includeArchived: false });
- if (sources.length <= 1) {
+ const allSources = await loadAllSources(engine, { includeArchived: false });
+ const sources = opts.sourceIds ? allSources.filter((s) => opts.sourceIds!.includes(s.id)) : allSources;
+ if (opts.sourceIds && sources.length === 0) {
+ return { name: 'federation_health', status: 'ok', message: 'No sources in scope to check' };
+ }
+ if (!opts.sourceIds && sources.length <= 1) {
return {
name: 'federation_health',
status: 'ok',
diff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.ts
index 7c282e6fca..a8c2c4acf6 100644
--- a/src/commands/doctor/checks/search-eval.ts
+++ b/src/commands/doctor/checks/search-eval.ts
@@ -199,7 +199,7 @@ export async function checkEmbeddingEnvOverride(engine: BrainEngine): Promise<Ch
* is mid-transition and retrieval may be degraded until it drains. Warn with
* the exact resume + status commands.
*/
-export async function checkEmbeddingMigrationState(engine: BrainEngine): Promise<Check> {
+export async function checkEmbeddingMigrationState(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
const { readMigrationState, migrationSignature, renderResumeCommand } = await import('../../../core/embedding-migration.ts');
const marker = await readMigrationState(engine);
@@ -216,10 +216,14 @@ export async function checkEmbeddingMigrationState(engine: BrainEngine): Promise
const s = marker.state;
let staleNote = '';
try {
- const stale = await engine.countStaleChunks({
- signature: migrationSignature(s.to_model, s.to_dims),
- includeNullSignature: true,
- });
+ const signature = migrationSignature(s.to_model, s.to_dims);
+ // A remote caller's grant counts only its own sources' chunks.
+ let stale = 0;
+ if (opts.sourceIds) {
+ for (const sourceId of opts.sourceIds) stale += await engine.countStaleChunks({ sourceId, signature, includeNullSignature: true });
+ } else {
+ stale = await engine.countStaleChunks({ signature, includeNullSignature: true });
+ }
staleNote = `; ${stale} chunk(s) not yet in the target space`;
} catch { /* count is best-effort */ }
return {
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 4a7ba2436b..e3a4f49147 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -343,7 +343,7 @@ export async function doctorReportRemote(
// Surface the migration state marker (previously write-only): a live
// marker = mid-migration brain, with the exact resume + status commands.
- checks.push(await checkEmbeddingMigrationState(engine));
+ checks.push(await checkEmbeddingMigrationState(engine, { sourceIds: opts.sourceIds }));
// v0.31.12 subagent runtime enforcement (Layer 3 of 3 — Codex F13).
// The subagent loop requires native tool-calling. If models.subagent,
@@ -359,13 +359,15 @@ export async function doctorReportRemote(
// other sources' activity counts/timestamps.
checks.push(await checkVolunteerChannels(engine, { sourceIds: opts.sourceIds }));
- // 6. Sync freshness check
- checks.push(await checkSyncFreshness(engine));
+ // 6. Sync freshness check. Every check below that takes { sourceIds } is
+ // confined to the caller's grant (#4592 class): a source-bound token never
+ // reads another source's id, name, counts or timestamps.
+ checks.push(await checkSyncFreshness(engine, { sourceIds: opts.sourceIds }));
const contentWrites = await (await import('./checks/canonical-content.ts')).checkCanonicalContentWrites(engine, opts.sourceIds);
if (contentWrites) checks.push(contentWrites);
// v0.41.19.0 (Issue 5): sync --all consolidation nudge for multi-source brains.
- checks.push(await checkSyncConsolidation(engine));
+ checks.push(await checkSyncConsolidation(engine, { sourceIds: opts.sourceIds }));
// v0.42.x (#1794, 4A): pool-budget nudge when GBRAIN_MAX_CONNECTIONS is set.
checks.push(await checkPoolBudget(engine));
@@ -373,8 +375,8 @@ export async function doctorReportRemote(
// v0.42.7 (#1696): link-extraction lag. Strictly SQL (single indexed COUNT),
// safe on the thin-client/remote path — remote operators on checkout-less
// Postgres brains are exactly who can't otherwise see the extraction backlog.
- // Brain-wide here (remote --source scoping is a separate TODO, like orphan_ratio).
- checks.push(await checkLinksExtractionLag(engine, { remote: true }));
+ // A scoped caller gets each granted source graded on its own (the worst wins).
+ checks.push(await remoteLinksExtractionLag(engine, opts.sourceIds));
// #4576 (related gap): extract_atoms_backlog was absent from the
// thin-client surface, so an MCP-only caller couldn't see the backlog at
@@ -389,7 +391,7 @@ export async function doctorReportRemote(
// schema_pack_source_drift — per-source pack divergence
checks.push(await checkSchemaPackActive(engine));
checks.push(await checkSchemaPackConsistency(engine, { sourceIds: opts.sourceIds }));
- checks.push(await checkSchemaPackSourceDrift(engine));
+ checks.push(await checkSchemaPackSourceDrift(engine, { sourceIds: opts.sourceIds }));
// 7. v0.32.3 search-lite mode + per-key drift surface.
checks.push(await checkSearchMode(engine));
@@ -410,24 +412,24 @@ export async function doctorReportRemote(
// (via mode bundle default or explicit config override), surface
// whether link density is high enough for the signal to fire
// meaningfully. <10% inbound coverage warns; >=30% ok with metric.
- checks.push(await checkGraphSignalsCoverage(engine));
+ checks.push(await checkGraphSignalsCoverage(engine, { sourceIds: opts.sourceIds }));
// 9b. v0.37.0 brainstorm_health: surfaces three brainstorm/lsd readiness
// signals: (a) migration v79 applied (last_retrieved_at column exists),
// (b) calibration cold-start status (active_bias_tags empty), (c)
// search.track_retrieval enabled/disabled. Each surfaces a paste-ready
// fix hint.
- checks.push(await checkBrainstormHealth(engine));
+ checks.push(await checkBrainstormHealth(engine, { sourceIds: opts.sourceIds }));
// 10. v0.36.1.0 Hindsight calibration wave (T12) — four new checks:
// - abandoned_threads: high-conviction takes never revisited
// - calibration_freshness: profile is older than 7 days
// - grade_confidence_drift: judge self-reported confidence vs actual accuracy (CDX-11 mitigation)
// - voice_gate_health: voice gate failure rate over the last 7 days
- checks.push(await checkAbandonedThreads(engine));
- checks.push(await checkCalibrationFreshness(engine));
- checks.push(await checkGradeConfidenceDrift(engine));
- checks.push(await checkVoiceGateHealth(engine));
+ checks.push(await checkAbandonedThreads(engine, { sourceIds: opts.sourceIds }));
+ checks.push(await checkCalibrationFreshness(engine, { sourceIds: opts.sourceIds }));
+ checks.push(await checkGradeConfidenceDrift(engine, { sourceIds: opts.sourceIds }));
+ checks.push(await checkVoiceGateHealth(engine, { sourceIds: opts.sourceIds }));
// 11. v0.40.3.0 contextual_retrieval_coverage — surfaces pages with
// - chunker_version drift (pre-v40 pages not yet re-embedded)
@@ -442,18 +444,18 @@ export async function doctorReportRemote(
// issue #1777 — hidden_by_search_policy: chunked pages withheld from default
// search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
// remote/thin-client path.
- checks.push(await checkHiddenBySearchPolicy(engine));
+ checks.push(await checkHiddenBySearchPolicy(engine, { sourceIds: opts.sourceIds }));
// 11a. issue #972 link_resolution_opportunity — same check the local
// doctor runs at the equivalent slot in buildChecks. Mirrored for
// thin-client parity so `gbrain remote doctor` sees the same hint.
- checks.push(await checkLinkResolutionOpportunity(engine));
+ checks.push(await checkLinkResolutionOpportunity(engine, undefined, { sourceIds: opts.sourceIds }));
// 12. v0.40.5.0 Federated Sync v2 (T12) — federation_health:
- // - Per-source lag, embed coverage, failed-job rate.
- // - Single-source brain short-circuits to ok.
+ // - Per-source lag, embed coverage, failed-job rate, for the granted sources only.
+ // - Single-source brain short-circuits to ok (unscoped callers).
// - Three-state: ok / warn / fail.
- checks.push(await checkFederationHealth(engine));
+ checks.push(await checkFederationHealth(engine, { sourceIds: opts.sourceIds }));
// 13. v0.42 self_upgrade_health: mode, whether behind, recent failures.
// File-plane only (no engine) — works on thin clients too. Then #5836 unlinked_facts inside the caller's grant.
@@ -467,3 +469,17 @@ export async function doctorReportRemote(
return computeDoctorReport(checks, { render: opts.render });
}
+
+/**
+ * links_extraction_lag for the remote doctor: brain-wide when unscoped;
+ * otherwise each granted source is graded on its own (the `--source` path)
+ * and the worst is reported, so no count, held slug or source id outside the
+ * grant reaches the result.
+ */
+async function remoteLinksExtractionLag(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ if (!sourceIds) return checkLinksExtractionLag(engine, { remote: true });
+ const checks: Check[] = [];
+ for (const sourceId of sourceIds) checks.push(await checkLinksExtractionLag(engine, { sourceId, remote: true }));
+ return checks.find(c => c.status === 'fail') ?? checks.find(c => c.status === 'warn') ?? checks[0]
+ ?? { name: 'links_extraction_lag', status: 'ok', message: 'Extraction lag not applicable (no pages)' };
+}
diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.ts
index df7ced9a23..6cb68542a8 100644
--- a/src/commands/doctor/schema-pack-checks.ts
+++ b/src/commands/doctor/schema-pack-checks.ts
@@ -181,13 +181,20 @@ export async function checkSchemaPackConsistency(
};
}
-export async function checkSchemaPackSourceDrift(engine: BrainEngine): Promise<Check> {
+export async function checkSchemaPackSourceDrift(engine: BrainEngine, opts: { sourceIds?: string[] } = {}): Promise<Check> {
try {
// Compare per-source schema_pack overrides (tier 3 DB config) to detect
// multi-source brains where different sources point at conflicting packs.
- const rows = await engine.executeRaw<{ key: string; value: string }>(
- `SELECT key, value FROM config WHERE key LIKE 'schema_pack.source.%'`,
- );
+ // A remote caller's grant confines the comparison to its own sources'
+ // override keys, so it never counts another source's override.
+ const rows = opts.sourceIds
+ ? await engine.executeRaw<{ key: string; value: string }>(
+ `SELECT key, value FROM config WHERE key = ANY($1::text[])`,
+ [opts.sourceIds.map((id) => `schema_pack.source.${id}`)],
+ )
+ : await engine.executeRaw<{ key: string; value: string }>(
+ `SELECT key, value FROM config WHERE key LIKE 'schema_pack.source.%'`,
+ );
if (rows.length === 0) {
return { name: 'schema_pack_source_drift', status: 'ok', message: 'No per-source pack overrides — drift N/A.' };
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3d3753be42..57db7e06b9 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -903,6 +903,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Doctor `segmented_storage` no longer tells you to upgrade this host when the only writes holding segmented storage off are this host\'s own from before its upgrade and the upgraded gbrain has since made the same kind of write (the same import or sync type, resident kind or managed principal), after the last of them: it reports the hold as information with the time it clears. Another host, an older `serve` or worker still running on this host, or an older write this build has not matched (a cron job or `npx` run on this host) keeps the warning and the `gbrain upgrade` fix.' },
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
+ { since: '0.60.305.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/source-health.ts b/src/core/source-health.ts
index 6199d73b07..43aedf4b3d 100644
--- a/src/core/source-health.ts
+++ b/src/core/source-health.ts
@@ -417,8 +417,9 @@ async function jobCountsBySource(engine: BrainEngine): Promise<Map<string, JobSt
* Sync-eligible sources with a local path, for doctor `sync_freshness`,
* including the upstream observation sync records (#5255, O-DX-8). Older
* brains without those columns (or without `archived`) still load.
+ * `sourceIds` (a remote caller's grant) confines the roster in SQL.
*/
-export async function loadSyncFreshnessSources(engine: BrainEngine) {
+export async function loadSyncFreshnessSources(engine: BrainEngine, sourceIds?: string[]) {
type FreshnessSourceRow = {
id: string;
name: string;
@@ -433,20 +434,25 @@ export async function loadSyncFreshnessSources(engine: BrainEngine) {
upstream_behind: number | null;
};
const columns = 'id, name, local_path, last_sync_at, last_commit, chunker_version, newest_content_at, config';
+ const scope = sourceIds ? ' AND id = ANY($1::text[])' : '';
+ const params = sourceIds ? [sourceIds] : undefined;
let sources: FreshnessSourceRow[];
try {
sources = await engine.executeRaw<FreshnessSourceRow>(
- `SELECT ${columns}, upstream_checked_at, upstream_commit, upstream_behind FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ `SELECT ${columns}, upstream_checked_at, upstream_commit, upstream_behind FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE${scope}`,
+ params,
);
} catch {
const noUpstream = 'NULL AS upstream_checked_at, NULL AS upstream_commit, NULL AS upstream_behind';
try {
sources = await engine.executeRaw<FreshnessSourceRow>(
- `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE`,
+ `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL AND archived IS NOT TRUE${scope}`,
+ params,
);
} catch {
sources = await engine.executeRaw<FreshnessSourceRow>(
- `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL`,
+ `SELECT ${columns}, ${noUpstream} FROM sources WHERE local_path IS NOT NULL${scope}`,
+ params,
);
}
}
diff --git a/test/doctor-report-remote-scope.test.ts b/test/doctor-report-remote-scope.test.ts
new file mode 100644
index 0000000000..6af1e2ce86
--- /dev/null
+++ b/test/doctor-report-remote-scope.test.ts
@@ -0,0 +1,213 @@
+/**
+ * Source isolation of the remote doctor (run_doctor): a caller whose grant
+ * names one source must not read another source's id, name, slugs, counts or
+ * timestamps out of any check. Each test seeds the excluded source so the
+ * unscoped (local/admin) report shows the leak, then asserts the scoped report
+ * does not. Shared by both engines: PGLite here, PostgreSQL through
+ * test/e2e/doctor-report-remote-scope-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { doctorReportRemote, type Check, type DoctorReport } from '../src/commands/doctor.ts';
+import { logSynopsisFailure } from '../src/core/audit-synopsis.ts';
+import { MIGRATION_STATE_KEY, migrationSignature } from '../src/core/embedding-migration.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const MINE = 'scope-mine-src';
+const OTHER = 'scope-other-src';
+const OTHER_NAME = 'Other Hidden Example';
+const MINE_PAGES = ['notes/mine-a', 'notes/mine-b'];
+const OTHER_PAGES = ['test/other-leak-hidden', 'notes/other-leak-target', 'notes/other-leak-linker', 'notes/other-leak-take', 'notes/other-leak-filler'];
+const ALL_PAGES = MINE_PAGES.length + OTHER_PAGES.length;
+
+for (const kind of testBackends()) {
+ describe(`doctorReportRemote source scope (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let home: string;
+ let dirs: string[] = [];
+
+ const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: undefined }, fn);
+ const report = (sourceIds?: string[]) => inHome(() => doctorReportRemote(engine, { sourceIds, remote: true }));
+ const check = (r: DoctorReport, name: string): Check => {
+ const found = r.checks.find(c => c.name === name);
+ if (!found) throw new Error(`no ${name} check`);
+ return found;
+ };
+ const text = (c: Check) => JSON.stringify(c);
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-doctor-scope-'));
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ dirs = [mkdtempSync(join(tmpdir(), 'gbrain-scope-mine-')), mkdtempSync(join(tmpdir(), 'gbrain-scope-other-'))];
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, last_sync_at) VALUES
+ ($1, 'Mine Example', $3, now()),
+ ($2, $4, $5, now() - interval '100 hours')`,
+ [MINE, OTHER, dirs[0], OTHER_NAME, dirs[1]],
+ );
+ for (const slug of MINE_PAGES) {
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: `# ${slug}\n\nbody\n` }, { sourceId: MINE });
+ }
+ await engine.addLink('notes/mine-a', 'notes/mine-b', 'ctx', 'mentions', 'markdown', undefined, undefined, { fromSourceId: MINE, toSourceId: MINE });
+ for (const slug of OTHER_PAGES) {
+ const body = slug === 'notes/other-leak-linker' ? 'See [[other-leak-target]] for details.\n' : `# ${slug}\n\nbody\n`;
+ await engine.putPage(slug, { title: slug, type: 'note', compiled_truth: body }, { sourceId: OTHER });
+ }
+ await engine.upsertChunks('test/other-leak-hidden', [{ chunk_index: 0, chunk_text: 'hidden body', chunk_source: 'compiled_truth' }], { sourceId: OTHER });
+ await engine.executeRaw("UPDATE pages SET text_projection_revision = knowledge_revision WHERE source_id = $1 AND slug = 'test/other-leak-hidden'", [OTHER]);
+ }, 120_000);
+
+ afterAll(async () => {
+ await close?.();
+ for (const dir of [home, ...dirs]) rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('federation_health names and grades only granted sources', async () => {
+ expect(text(check(await report(), 'federation_health'))).toContain(`${OTHER}: stale`);
+ const scoped = check(await report([MINE]), 'federation_health');
+ expect(text(scoped)).not.toContain(OTHER);
+ expect(scoped.status).toBe('ok');
+ expect(scoped.message).toBe('1 source(s) healthy (parallel sync, async embed)');
+ });
+
+ test('sync_freshness never names, counts or fixes an excluded source', async () => {
+ expect(text(check(await report(), 'sync_freshness'))).toContain(OTHER_NAME);
+ const scoped = check(await report([MINE]), 'sync_freshness');
+ expect(text(scoped)).not.toContain(OTHER);
+ expect(text(scoped)).not.toContain(OTHER_NAME);
+ expect(scoped.status).toBe('ok');
+ expect(scoped.details).toMatchObject({ synced_recently_count: 1, stale_count: 0 });
+ });
+
+ test('sync_consolidation counts only granted sources', async () => {
+ expect(check(await report(), 'sync_consolidation').message).toContain('2 active sources');
+ expect(check(await report([MINE]), 'sync_consolidation').message).toBe('Single-source brain — sync --all consolidation not applicable.');
+ });
+
+ test('links_extraction_lag grades the granted source, not the brain-wide total', async () => {
+ expect(check(await report(), 'links_extraction_lag').message).toContain(`(${ALL_PAGES} pages`);
+ const scoped = check(await report([MINE]), 'links_extraction_lag');
+ expect(scoped.details).toMatchObject({ total: MINE_PAGES.length, source_id: MINE });
+ expect(scoped.message).not.toContain(`${ALL_PAGES} pages`);
+ });
+
+ test('graph_signals_coverage measures link density inside the grant', async () => {
+ expect(check(await report(), 'graph_signals_coverage').message).toContain(`${(100 / ALL_PAGES).toFixed(1)}%`);
+ expect(check(await report([MINE]), 'graph_signals_coverage').message).toContain('50.0% of pages have inbound links');
+ });
+
+ test('hidden_by_search_policy counts only the granted sources', async () => {
+ expect(check(await report(), 'hidden_by_search_policy').message).toContain("1 under 'test/'");
+ const scoped = check(await report([MINE]), 'hidden_by_search_policy');
+ expect(scoped.message).toBe('No pages hidden by search-exclude policy.');
+ expect(scoped.details).toMatchObject({ counts: {} });
+ });
+
+ test('link_resolution_opportunity scans only the granted sources', async () => {
+ expect(check(await report(), 'link_resolution_opportunity').message).toContain('1/1 bare wikilinks');
+ expect(check(await report([MINE]), 'link_resolution_opportunity').message).toBe('No bare wikilinks found');
+ });
+
+ test('contextual_retrieval_coverage counts synopsis failures of granted sources only', async () => {
+ await inHome(async () => logSynopsisFailure({ pageSlug: 'notes/other-leak-filler', sourceId: OTHER, chunkIndex: 0, kind: 'timeout', pageLevelFallback: true }));
+ expect(check(await report(), 'contextual_retrieval_coverage').message).toContain('1 synopsis failure(s) in last 7d');
+ expect(check(await report([MINE]), 'contextual_retrieval_coverage').message).not.toContain('synopsis failure');
+ });
+
+ test("schema_pack_source_drift compares only the granted sources' overrides", async () => {
+ await engine.setConfig(`schema_pack.source.${MINE}`, 'gbrain-base');
+ await engine.setConfig(`schema_pack.source.${OTHER}`, 'gbrain-recommended');
+ try {
+ expect(check(await report(), 'schema_pack_source_drift').message).toContain('2 distinct packs across 2 sources');
+ const scoped = check(await report([MINE]), 'schema_pack_source_drift');
+ expect(scoped.status).toBe('ok');
+ expect(scoped.message).toBe('1 per-source overrides; all point at the same pack.');
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key LIKE 'schema_pack.source.%'`);
+ }
+ });
+
+ test('embedding_migration_state counts stale chunks of granted sources only', async () => {
+ const state = { to_model: 'openai:text-embedding-3-small', to_dims: 1536, from_model: 'openai:text-embedding-3-large', from_dims: 1536, started_at: '2026-01-01T00:00:00.000Z' };
+ const signature = migrationSignature(state.to_model, state.to_dims);
+ const mineStale = await engine.countStaleChunks({ sourceId: MINE, signature, includeNullSignature: true });
+ const wideStale = await engine.countStaleChunks({ signature, includeNullSignature: true });
+ expect(wideStale).toBeGreaterThan(mineStale);
+ await engine.setConfig(MIGRATION_STATE_KEY, JSON.stringify(state));
+ try {
+ expect(check(await report(), 'embedding_migration_state').message).toContain(`; ${wideStale} chunk(s) not yet in the target space`);
+ expect(check(await report([MINE]), 'embedding_migration_state').message).toContain(`; ${mineStale} chunk(s) not yet in the target space`);
+ } finally {
+ await engine.executeRaw('DELETE FROM config WHERE key = $1', [MIGRATION_STATE_KEY]);
+ }
+ });
+
+ describe("calibration checks read only the granted sources' profiles and takes", () => {
+ beforeAll(async () => {
+ const profile = `INSERT INTO calibration_profiles (source_id, holder, generated_at, total_resolved, domain_scorecards,
+ pattern_statements, voice_gate_passed, voice_gate_attempts, active_bias_tags, model_id)
+ VALUES ($1, $2, now() - ($3 || ' days')::interval, 9, '{}'::jsonb, ARRAY['p']::text[], $4, 1,
+ ARRAY['bias-a', 'bias-b', 'bias-c']::text[], 'test-model')`;
+ await engine.executeRaw(profile, [OTHER, 'self', '30', true]);
+ await engine.executeRaw(profile, [OTHER, 'other-holder', '0', false]);
+ const takes = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, since_date)
+ SELECT id, 1, 'claim', 'take', 'self', 0.9, '2020-01' FROM pages WHERE source_id = $1 AND slug = 'notes/other-leak-take'
+ RETURNING id`,
+ [OTHER],
+ );
+ for (const version of ['v1', 'v2', 'v3']) {
+ await engine.executeRaw(
+ `INSERT INTO take_grade_cache (take_id, prompt_version, judge_model_id, evidence_signature, verdict, confidence, applied)
+ VALUES ($1, $2, 'judge', 'sig', 'correct', 0.9, true)`,
+ [Number(takes[0]!.id), version],
+ );
+ }
+ });
+
+ test('abandoned_threads', async () => {
+ expect(check(await report(), 'abandoned_threads').message).toContain('1 high-conviction take(s)');
+ expect(check(await report([MINE]), 'abandoned_threads').message).toBe('No abandoned high-conviction threads');
+ });
+
+ test('calibration_freshness', async () => {
+ expect(check(await report(), 'calibration_freshness').message).toContain('Calibration profile is 30 days old');
+ expect(check(await report([MINE]), 'calibration_freshness').message).toBe('No calibration profile yet (builds after 5+ resolved takes)');
+ });
+
+ test('grade_confidence_drift', async () => {
+ expect(check(await report(), 'grade_confidence_drift').message).toContain('Only 3 auto-applied verdicts');
+ expect(check(await report([MINE]), 'grade_confidence_drift').message).toContain('Only 0 auto-applied verdicts');
+ });
+
+ test('voice_gate_health', async () => {
+ expect(check(await report(), 'voice_gate_health').message).toContain('Voice gate failed 1/1');
+ expect(check(await report([MINE]), 'voice_gate_health').message).toBe('No calibration profile generation in the last 7 days');
+ });
+
+ test('brainstorm_health', async () => {
+ expect(check(await report(), 'brainstorm_health').message).toContain('3 bias tag(s)');
+ expect(check(await report([MINE]), 'brainstorm_health').message).toContain('Calibration profile not yet generated');
+ });
+ });
+
+ test('the whole scoped report carries no trace of the excluded source', async () => {
+ expect(JSON.stringify(await report())).toContain(OTHER);
+ const scoped = JSON.stringify(await report([MINE]));
+ expect(scoped).not.toContain(OTHER);
+ expect(scoped).not.toContain(OTHER_NAME);
+ expect(scoped).not.toContain('other-leak');
+ });
+ });
+}
diff --git a/test/doctor.test.ts b/test/doctor.test.ts
index b73ee61e5b..74615fca66 100644
--- a/test/doctor.test.ts
+++ b/test/doctor.test.ts
@@ -1734,8 +1734,8 @@ describe('issue #972 — link_resolution_opportunity check', () => {
const source = doctorSource();
// Local buildChecks path.
expect(source).toMatch(/await checkLinkResolutionOpportunity\(engine, progress\)/);
- // Thin-client doctorReportRemote path.
- expect(source).toMatch(/await checkLinkResolutionOpportunity\(engine\)/);
+ // Thin-client doctorReportRemote path, confined to the caller's grant.
+ expect(source).toMatch(/await checkLinkResolutionOpportunity\(engine, undefined, \{ sourceIds: opts\.sourceIds \}\)/);
// Heartbeat label registered.
expect(source).toContain("progress.heartbeat('link_resolution_opportunity')");
// Issue #972 (T3): scan is bounded to a most-recent sample, not a full
diff --git a/test/e2e/doctor-report-remote-scope-postgres.test.ts b/test/e2e/doctor-report-remote-scope-postgres.test.ts
new file mode 100644
index 0000000000..b3710bad50
--- /dev/null
+++ b/test/e2e/doctor-report-remote-scope-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../doctor-report-remote-scope.test.ts'));