Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor: capped lists report their count as a floor, and a failed scan is not a clean result (#7145)
garrytan323a8778ca10
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex b84c92d53a..85e8aab982 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -15,6 +15,9 @@ import { connectedEngine, type DoctorContext, type DoctorEntry } from '../conteximport { agentFix, checkError, doctorVerify, withSkippedSegmented } from '../check-fix.ts';import { scanDeadline } from '../budget.ts';+/** Oversized pages `oversized_pages` lists before it reports a floor. */+const OVERSIZED_LIST_LIMIT = 100;+async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const { args, progress } = ctx;const engine = connectedEngine(ctx);@@ -63,9 +66,11 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {AND ${EMBED_SKIP_FILTER_FRAGMENT}AND (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, ''))) > $1ORDER BY bytes DESC- LIMIT 100`,+ LIMIT ${OVERSIZED_LIST_LIMIT + 1}`,[bytesBlock],);+ // #7145: a full list means more pages exceed the block; the count is then a floor.+ const capped = rows.length > OVERSIZED_LIST_LIMIT;// Pages an older gbrain stored chunkless for size that now fit under the block: the free backfill re-indexes them.const [skipped] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages pWHERE p.deleted_at IS NULL AND p.frontmatter->'embed_skip'->>'reason' = 'oversized'@@ -97,17 +102,14 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {oversizedCheck({name: 'oversized_pages',status: 'warn',- message: `${rows.length} page(s) exceed the ${bytesBlock}-byte content_sanity.bytes_block. Top: ${top}. A page over the block is stored without chunks on its next write. `+ details: { count: Math.min(rows.length, OVERSIZED_LIST_LIMIT), exact: !capped, ...(capped ? { limit: OVERSIZED_LIST_LIMIT } : {}) },+ message: `${capped ? `At least ${OVERSIZED_LIST_LIMIT}` : rows.length} page(s) exceed the ${bytesBlock}-byte content_sanity.bytes_block. Top: ${top}. A page over the block is stored without chunks on its next write. `+ 'Raise content_sanity.bytes_block (up to the 24 MiB page ceiling) to make them searchable, or exclude them from the source.',});}} catch (err) {- const msg = err instanceof Error ? err.message : String(err);- checks.push({- name: 'oversized_pages',- status: 'ok',- message: `Skipped (${msg})`,- });+ // #7145: a scan that failed found nothing either way.+ checks.push(checkError('oversized_pages', 'check for oversized pages', err, { details: { health: 'unknown' } }));}progress.heartbeat('scraper_junk_pages');diff --git a/src/commands/doctor/checks/data-integrity.ts b/src/commands/doctor/checks/data-integrity.tsindex d9879006c0..7462b25249 100644--- a/src/commands/doctor/checks/data-integrity.ts+++ b/src/commands/doctor/checks/data-integrity.ts@@ -18,7 +18,11 @@ import {} from './core-health.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { withSkippedSegmented } from '../check-fix.ts';+import { checkError, withSkippedSegmented } from '../check-fix.ts';+import { isMissingSchemaObject } from '../../../core/utils.ts';++/** Pages `markdown_body_completeness` lists before it reports a floor. */+const LISTED_PAGE_LIMIT = 100;async function runIntegrity(ctx: DoctorContext): Promise<Check[]> {const { progress } = ctx;@@ -330,8 +334,10 @@ async function runMarkdownBody(ctx: DoctorContext): Promise<Check[]> {AND length(rd.data ->> 'content') > 1000AND length(p.compiled_truth) < length(rd.data ->> 'content') * 0.3AND (rd.data ->> 'content') ~ '(^|\n)##+ '- LIMIT 100`,+ LIMIT ${LISTED_PAGE_LIMIT + 1}`,);+ // #7145: a full list means more pages match; the count is then a floor.+ const capped = rows.length > LISTED_PAGE_LIMIT;// Decision #10: a segmented page's compiled_truth is NULL, so the length comparison above passes it by.const [segmented] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(DISTINCT p.id)::int AS n@@ -350,12 +356,15 @@ async function runMarkdownBody(ctx: DoctorContext): Promise<Check[]> {checks.push(withSkippedSegmented({name: 'markdown_body_completeness',status: 'warn',- message: `${rows.length} page(s) appear truncated (sample: ${sample}). Re-import: edit each page body, then run gbrain sync (see docs/integrations/reliability-repair.md)`,+ details: { count: Math.min(rows.length, LISTED_PAGE_LIMIT), exact: !capped, ...(capped ? { limit: LISTED_PAGE_LIMIT } : {}) },+ message: `${capped ? `At least ${LISTED_PAGE_LIMIT}` : rows.length} page(s) appear truncated (sample: ${sample}). Re-import: edit each page body, then run gbrain sync (see docs/integrations/reliability-repair.md)`,}, skipped));}- } catch {- // pages_raw.raw_data may not exist on older schemas; best-effort.- checks.push({ name: 'markdown_body_completeness', status: 'ok', message: 'Skipped (raw_data unavailable)' });+ } catch (error) {+ // raw_data may not exist on older schemas; any other failure (#7145) is not a clean result.+ checks.push(isMissingSchemaObject(error, 'table', 'raw_data')+ ? { name: 'markdown_body_completeness', status: 'ok', message: 'Skipped (raw_data unavailable)' }+ : checkError('markdown_body_completeness', 'check for truncated bodies', error, { details: { health: 'unknown' } }));} finally {mbcHb();}diff --git a/src/commands/doctor/checks/edge-validity.ts b/src/commands/doctor/checks/edge-validity.tsindex daecd9458b..a54743e5e4 100644--- a/src/commands/doctor/checks/edge-validity.ts+++ b/src/commands/doctor/checks/edge-validity.ts@@ -16,12 +16,17 @@ import { connectedEngine, type DoctorContext, type DoctorEntry } from '../conteximport { edgeValidityEnabled } from '../../../core/link-validity.ts';import { staleRelationshipKeys } from '../../../core/link-relationships.ts';+/** Stale-assertion pages `edge_validity` lists before it reports a floor. */+const STALE_ASSERTION_LIMIT = 20;+export interface EdgeValidityStats {read_policy: 'on' | 'off';contradiction_mode: string;relationships: Record<string, number>;lagging: number;stale_assertions: Array<{ slug: string; target: string; link_type: string; ended: string | null }>;+ /** #7145: more pages than the listed ones still state an ended relationship. */+ stale_assertions_capped?: true;proposals: { proposed: number; undated: number; applied: number };}@@ -41,7 +46,7 @@ export async function edgeValidityStats(engine: BrainEngine, sourceIds?: readonlAND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = lr.from_page_id AND l.to_page_id = lr.to_page_idAND l.link_type = lr.link_type AND COALESCE(l.origin_page_id, l.from_page_id) = lr.from_page_idAND COALESCE(l.assertion_tense, 'present') = 'present')- ORDER BY lr.last_end DESC LIMIT 20`, [scope]);+ ORDER BY lr.last_end DESC LIMIT ${STALE_ASSERTION_LIMIT + 1}`, [scope]);const [p] = await engine.executeRaw<{ proposed: number; undated: number; applied: number }>(`SELECT COUNT(*) FILTER (WHERE status = 'proposed')::int AS proposed, COUNT(*) FILTER (WHERE status = 'undated_unresolved')::int AS undated,COUNT(*) FILTER (WHERE status = 'applied')::int AS applied@@ -52,7 +57,8 @@ export async function edgeValidityStats(engine: BrainEngine, sourceIds?: readonlcontradiction_mode: (await engine.getConfig('dream.edge_contradictions.mode')) ?? 'propose (default)',relationships: Object.fromEntries(byStatus.map(r => [r.status, Number(r.n)])),lagging,- stale_assertions: stale,+ stale_assertions: stale.slice(0, STALE_ASSERTION_LIMIT),+ ...(stale.length > STALE_ASSERTION_LIMIT ? { stale_assertions_capped: true } : {}),proposals: { proposed: Number(p?.proposed ?? 0), undated: Number(p?.undated ?? 0), applied: Number(p?.applied ?? 0) },};}@@ -66,7 +72,7 @@ export function edgeValidityVerdict(stats: EdgeValidityStats | null, opts: { thiif (stats.lagging > 0) { parts.push(`${stats.lagging}${stats.lagging >= 1000 ? '+' : ''} lag their evidence`); fixes.push(host('gbrain extract --stale (the dream cycle also sweeps them)')); }if (stats.stale_assertions.length) {const first = stats.stale_assertions[0];- parts.push(`${stats.stale_assertions.length} page(s) still state a relationship their timeline ended (e.g. ${first.slug}: ${first.link_type} ${first.target}, ended ${first.ended})`);+ parts.push(`${stats.stale_assertions.length}${stats.stale_assertions_capped ? '+' : ''} page(s) still state a relationship their timeline ended (e.g. ${first.slug}: ${first.link_type} ${first.target}, ended ${first.ended})`);fixes.push(`ask the user before rewriting: ${first.slug} still says ${first.link_type} ${first.target}; the timeline says it ended ${first.ended}`);}if (stats.proposals.proposed || stats.proposals.undated) {diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 99ae32a21a..e99171bafe 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -40,6 +40,8 @@ import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from/** Local alias; the shared warn-once memo lives in core so it can't fork per module. */const _resolveSyncFreshnessHours = resolveHoursEnv;+/** Duplicate content-hash groups `content_hash_duplicates` reads. */+const HASH_GROUP_LIMIT = 50;/*** The extraction-lag threshold and vacuous-skip floor live with the shared read and verdict@@ -222,8 +224,11 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<CWHERE deleted_at IS NULL AND content_hash IS NOT NULL AND content_hash <> ''GROUP BY source_id, content_hashHAVING count(*) > 1- LIMIT 50`,+ LIMIT ${HASH_GROUP_LIMIT + 1}`,);+ // #7145: a full page of groups means more exist; the counts below are then floors.+ const capped = rows.length > HASH_GROUP_LIMIT;+ const atLeast = capped ? 'At least ' : '';if (rows.length === 0) {return { name, status: 'ok', message: 'No same-source content-hash duplicate groups' };}@@ -232,7 +237,7 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<Cconst samples: string[] = [];let otherGroupCount = 0;const otherSamples: string[] = [];- for (const r of rows) {+ for (const r of rows.slice(0, HASH_GROUP_LIMIT)) {const slugs = String(r.slugs).split('|');const bare = slugs.filter(s => !s.includes('/'));const prefixed = slugs.filter(s => s.includes('/'));@@ -257,14 +262,14 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<Cconst sourceNote = pairSources.size === 1 ? '' : ` (pairs span sources ${[...pairSources].sort().join(', ')}; run it once per pair with that pair's source)`;const fix = `Fix: GBRAIN_SOURCE=${source} gbrain delete <bare-slug> --force for each pair${sourceNote}.`;parts.push(- `${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — ` ++ `${atLeast}${pairCount} content-hash duplicate pair(s) detected (same content, differing slug forms — ` +`usually an import run from the wrong root, which drops the path prefix). ` +`Sample: ${samples.join('; ')}. ${fix}`,);}if (otherGroupCount > 0) {parts.push(- `${otherGroupCount} duplicate-content group(s) with distinct slugs (no bare/nested wrong-root shape). ` ++ `${atLeast}${otherGroupCount} duplicate-content group(s) with distinct slugs (no bare/nested wrong-root shape). ` +`Sample: ${otherSamples.join('; ')}. Review which slug is canonical and consolidate manually — ` +`no automatic delete hint (either copy may be the one links point at).`,);@@ -272,10 +277,12 @@ export async function checkContentHashDuplicates(engine: BrainEngine): Promise<Creturn {name,status: 'warn',- message: parts.join(' '),+ message: parts.join(' ') + (capped ? ` Only the first ${HASH_GROUP_LIMIT} duplicate groups were read (no setting); fix these and rerun to see the rest.` : ''),details: {pair_count: pairCount,- hash_groups: rows.length,+ hash_groups: Math.min(rows.length, HASH_GROUP_LIMIT),+ exact: !capped,+ ...(capped ? { limit: HASH_GROUP_LIMIT } : {}),sample_pairs: samples,distinct_slug_group_count: otherGroupCount,sample_distinct_slug_groups: otherSamples,diff --git a/src/commands/doctor/checks/graph-embedding.ts b/src/commands/doctor/checks/graph-embedding.tsindex fe0574e42b..4cec1c8f79 100644--- a/src/commands/doctor/checks/graph-embedding.ts+++ b/src/commands/doctor/checks/graph-embedding.ts@@ -429,6 +429,8 @@ export async function checkFactsEmbeddingWidthConsistency(engine: BrainEngine):*/export const JUNK_HUB_EDGE_THRESHOLD = 1000;export const JUNK_HUB_MAX_CHUNKS = 2;+/** Pages `junk_entity_hubs` lists before it reports a floor. */+const JUNK_HUB_LIMIT = 20;/*** #4222 junk_entity_hubs doctor check.@@ -461,7 +463,7 @@ export async function checkJunkEntityHubs(const edgeThreshold = opts?.edgeThreshold ?? JUNK_HUB_EDGE_THRESHOLD;const maxChunks = opts?.maxChunks ?? JUNK_HUB_MAX_CHUNKS;try {- const rows = await engine.executeRaw<{+ const listed = await engine.executeRaw<{slug: string;source_id: string | null;edges: number;@@ -499,9 +501,13 @@ export async function checkJunkEntityHubs(WHERE COALESCE(cc.chunks, 0) <= $2AND COALESCE(p.frontmatter ->> 'junk_hub_exempt', 'false') <> 'true'ORDER BY ec.edges DESC- LIMIT 20`,+ LIMIT ${JUNK_HUB_LIMIT + 1}`,[edgeThreshold, maxChunks],);+ // #7145: a full list means more pages match; the counts below are then floors.+ const capped = listed.length > JUNK_HUB_LIMIT;+ const rows = listed.slice(0, JUNK_HUB_LIMIT);+ const plus = capped ? '+' : '';if (rows.length === 0) {return {@@ -520,7 +526,7 @@ export async function checkJunkEntityHubs(const parts: string[] = [];if (hubs.length > 0) {parts.push(- `${hubs.length} near-empty page(s) with >${edgeThreshold} edges — likely generic-token entities ` ++ `${hubs.length}${plus} 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 ` +@@ -536,7 +542,7 @@ export async function checkJunkEntityHubs(const withTwin = twins.filter(r => r.canonical_twin_source !== null).length;if (twins.length > 0) {parts.push(- `${twins.length} connector contact page(s) with >${edgeThreshold} edges:\n${twins.map(line).join('\n')}\n` ++ `${twins.length}${plus} 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 a page of the same name elsewhere unless link_resolution.cross_source is on. ` +`${withTwin} of them ${withTwin === 1 ? 'has' : 'have'} a canonical twin in another source. ` +@@ -561,6 +567,8 @@ export async function checkJunkEntityHubs(message: parts.join('\n'),...twinFix,details: {+ exact: !capped,+ ...(capped ? { limit: JUNK_HUB_LIMIT } : {}),hubs: hubs.map(r => ({slug: r.slug,source_id: r.source_id ?? 'default',diff --git a/src/commands/doctor/checks/queue-assets.ts b/src/commands/doctor/checks/queue-assets.tsindex 7a33549593..00599dd775 100644--- a/src/commands/doctor/checks/queue-assets.ts+++ b/src/commands/doctor/checks/queue-assets.ts@@ -121,16 +121,18 @@ async function runIndexAudit(ctx: DoctorContext): Promise<Check[]> {WHERE schemaname = 'public'AND idx_scan = 0ORDER BY pg_relation_size(indexrelid) DESC- LIMIT 20+ LIMIT 21`;if (rows.length === 0) {checks.push({ name: 'index_audit', status: 'ok', message: 'All public indexes have recorded scans' });} else {- const list = rows.map((r: any) => `${r.index}(${r.size})`).join(', ');+ // #7145: 21 rows means more than the 20 listed.+ const list = rows.slice(0, 20).map((r: any) => `${r.index}(${r.size})`).join(', ');checks.push({name: 'index_audit',status: 'warn',- message: `${rows.length} zero-scan index(es): ${list}. ` ++ details: { exact: rows.length <= 20 },+ message: `${rows.length > 20 ? '20+' : rows.length} zero-scan index(es): ${list}. ` +`Consider investigating whether they're used on YOUR workload (fresh brains naturally show zero scans until queries accumulate). ` +`Do not drop without confirming.`,});diff --git a/src/commands/doctor/checks/queue-jobs.ts b/src/commands/doctor/checks/queue-jobs.tsindex 5664cbc840..a2501da087 100644--- a/src/commands/doctor/checks/queue-jobs.ts+++ b/src/commands/doctor/checks/queue-jobs.ts@@ -70,9 +70,10 @@ export async function computeQueueHealthCheck(try {// issue #1801: column is `status`, not `state` (schema.sql:780).- const stalledRows: Array<{ id: number; name: string; started_at: string }> =+ // #7145: total counts every stalled job, not only the five listed.+ const stalledRows: Array<{ id: number; name: string; started_at: string; total: number }> =await engine.executeRaw(- `SELECT id, name, started_at::text AS started_at+ `SELECT id, name, started_at::text AS started_at, count(*) OVER ()::int AS totalFROM minion_jobsWHERE status = 'active'AND started_at IS NOT NULL@@ -136,8 +137,7 @@ export async function computeQueueHealthCheck(AND name = 'embed-backfill'GROUP BY name, queueHAVING min(created_at) < now() - ($1::text::interval)- ORDER BY oldest_age_seconds DESC- LIMIT 5`,+ ORDER BY oldest_age_seconds DESC`,[`${oldWaitingHours} hours`],);@@ -196,7 +196,7 @@ export async function computeQueueHealthCheck(.map(r => `#${r.id}(${r.name})`).join(', ');problems.push(- `${stalledRows.length} stalled-forever job(s): ${sample}. ` ++ `${Number(stalledRows[0]!.total)} stalled-forever job(s)${Number(stalledRows[0]!.total) > stalledRows.length ? ` (oldest ${stalledRows.length} listed)` : ''}: ${sample}. ` +`Fix: gbrain jobs get <id> to inspect; gbrain jobs cancel <id> to force-kill.`);}@@ -209,8 +209,8 @@ export async function computeQueueHealthCheck(`Fix: set maxWaiting on the submitter (or raise GBRAIN_QUEUE_WAITING_THRESHOLD).`);}- for (const row of oldWaitingRows) {- if (liveWorkerQueues?.has(row.queue)) continue;+ // #7145: queues with a live worker are dropped before the five-queue cap, so they cannot hide one without.+ for (const row of oldWaitingRows.filter(r => !liveWorkerQueues?.has(r.queue)).slice(0, 5)) {const hours = Math.max(1, Math.round(Number(row.oldest_age_seconds ?? 0) / 3600));if (registryFailure) {problems.push(diff --git a/test/doctor-capped-counts-7145.test.ts b/test/doctor-capped-counts-7145.test.tsnew file mode 100644index 0000000000..392ac2a625--- /dev/null+++ b/test/doctor-capped-counts-7145.test.ts@@ -0,0 +1,88 @@+/**+ * #7145: a doctor check that lists at most N rows reports N as a floor when more exist ("At least N", "N+",+ * exact: false), never as the exact count, and a scan that failed is not a clean result. PGLite in-memory, and+ * an isolated Postgres database when DATABASE_URL is set (test/postgres-unit-arms.txt); queue_health's+ * stalled and no-worker lists are Postgres-only (PGLite has its own queue summary).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { checkContentHashDuplicates } from '../src/commands/doctor/checks/extraction-sync.ts';+import { markdownBodyEntry } from '../src/commands/doctor/checks/data-integrity.ts';+import { contentSanityEntry } from '../src/commands/doctor/checks/content-quality.ts';+import { checkJunkEntityHubs } from '../src/commands/doctor/checks/graph-embedding.ts';+import { computeQueueHealthCheck } from '../src/commands/doctor/checks/queue-jobs.ts';+import { edgeValidityVerdict } from '../src/commands/doctor/checks/edge-validity.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const progress = new Proxy({}, { get: () => () => undefined });++for (const kind of testBackends()) describe(`doctor capped counts are floors (${kind})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }+ }, 120_000);+ afterAll(async () => { await close?.(); });++ async function withPages(prefix: string, n: number, body: string, extra: string, run: () => Promise<void>): Promise<void> {+ await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth, content_hash)+ SELECT '${prefix}/' || lpad(i::text, 3, '0'), 'note', 'Example ' || i, $1, ${extra} FROM generate_series(1, $2::int) i`, [body, n]);+ try { await run(); } finally { await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE '${prefix}/%'`); }+ }++ test('content_hash_duplicates past its 50-group read says at least 50', () => withPages('dup-a', 51, 'Same.', `'h-' || i`, () =>+ withPages('dup-b', 51, 'Same.', `'h-' || i`, async () => {+ const check = await checkContentHashDuplicates(engine);+ expect(check).toMatchObject({ status: 'warn', details: { hash_groups: 50, exact: false, limit: 50 } });+ expect(check.message).toContain('At least 50 duplicate-content group(s)');+ })));++ test('markdown_body_completeness past its 100-page list says at least 100', () => withPages('cut', 101, 'Short.', 'NULL', async () => {+ const content = `# Title\n\n## Part one\n\n${'Long body text. '.repeat(100)}`;+ await engine.executeRaw(`INSERT INTO raw_data (page_id, source, data) SELECT id, 'test', jsonb_build_object('content', $1::text) FROM pages WHERE slug LIKE 'cut/%'`, [content]);+ const [check] = (await markdownBodyEntry.run({ engine, progress } as never) as Array<Record<string, any>>).filter(c => c.name === 'markdown_body_completeness');+ expect(check).toMatchObject({ status: 'warn', details: { count: 100, exact: false, limit: 100 } });+ expect(check.message).toContain('At least 100 page(s) appear truncated');+ }));++ test('oversized_pages past its 100-page list says at least 100', () => withPages('big', 101, 'x'.repeat(400), 'NULL', async () => {+ await engine.setConfig('content_sanity.bytes_block', '200');+ try {+ const [check] = (await contentSanityEntry.run({ engine, progress, args: [] } as never) as Array<Record<string, any>>).filter(c => c.name === 'oversized_pages');+ expect(check).toMatchObject({ status: 'warn', details: { count: 100, exact: false, limit: 100 } });+ expect(check.message).toContain('At least 100 page(s) exceed the 200-byte');+ } finally { await engine.unsetConfig('content_sanity.bytes_block'); }+ }));++ test('junk_entity_hubs past its 20-page list says 20+', () => withPages('hub', 22, 'Hub.', 'NULL', async () => {+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type)+ SELECT p.id, q.id, 'mentions' FROM pages p JOIN pages q ON q.slug = 'hub/022' WHERE p.slug LIKE 'hub/%' AND p.slug <> 'hub/022'`);+ const check = await checkJunkEntityHubs(engine, { edgeThreshold: 0, maxChunks: 0 });+ expect(check).toMatchObject({ status: 'warn', details: { exact: false, limit: 20 } });+ expect(check.message).toContain('20+ near-empty page(s)');+ }));++ if (kind === 'postgres') {+ test('queue_health counts every stalled job and finds the no-worker queue behind five with workers', async () => {+ await engine.executeRaw(`INSERT INTO minion_jobs (submission_authority, name, queue, status, started_at) SELECT '{}'::jsonb, 'example-job', 'q-stall', 'active', now() - interval '2 hours' FROM generate_series(1, 7)`);+ await engine.executeRaw(`INSERT INTO minion_jobs (submission_authority, name, queue, status, created_at)+ SELECT '{}'::jsonb, 'embed-backfill', 'q-' || i, 'waiting', now() - make_interval(hours => 10 - i) FROM generate_series(1, 6) i`);+ try {+ const check = await computeQueueHealthCheck(engine, { oldWaitingHours: 1, readWorkers: () => [1, 2, 3, 4, 5].map(i => ({ queue: `q-${i}` })) });+ expect(check.status).not.toBe('ok');+ expect(check.message).toContain('7 stalled-forever job(s) (oldest 5 listed)');+ expect(check.message).toContain("queue 'q-6'");+ } finally { await engine.executeRaw("DELETE FROM minion_jobs WHERE queue = 'q-stall' OR queue LIKE 'q-%'"); }+ });+ }+});++test('edge_validity marks a capped stale-assertion list as a floor', () => {+ const verdict = edgeValidityVerdict({ read_policy: 'on', contradiction_mode: 'propose', relationships: {}, lagging: 0,+ stale_assertions: [{ slug: 'people/alice-example', target: 'companies/acme-example', link_type: 'works_at', ended: '2025-01-01' }],+ stale_assertions_capped: true, proposals: { proposed: 0, undated: 0, applied: 0 } } as never);+ expect(verdict.message).toContain('1+ page(s) still state a relationship');+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 3f07882637..343fabdd69 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -47,6 +47,7 @@ test/cycle/synthesize-concepts-merge.test.tstest/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tstest/derived-link-reconciliation.test.ts+test/doctor-capped-counts-7145.test.tstest/doctor-frontmatter-holds.test.tstest/doctor-image-embedding-coverage.test.tstest/doctor-keyword-plan-6495.test.ts