Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(health): scoped get_health memo with computed_at (O-ENG-13)

garrytan1424edf5c484
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index a38224ca18..f54354cebe 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -33,6 +33,7 @@ test/e2e/engine-parity-salience.test.ts
test/e2e/engine-parity.test.ts
test/e2e/fact-embedding-backfill-parity.test.ts
test/e2e/fact-vector-repair-parity.test.ts
+test/e2e/engine-sql-health-parity.test.ts
test/e2e/health-parity-postgres.test.ts
test/e2e/minions-authority-parity.test.ts
test/e2e/ontology-merge-parity.test.ts
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 27c025bb62..920b6ea9eb 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -30,6 +30,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// Fix wave 8, Lane G: page revision rollout (#5216).
"src/core/page-state/revision-backfill-schema.ts": ["test/e2e/page-revision-rollout-5216-postgres.test.ts"],
"src/core/embedding-ann-build.ts": ["test/e2e/migrate-embeddings-ann-build-5088-postgres.test.ts", "test/e2e/migrate-embeddings-postgres.test.ts"],
+ // FOUNDATIONS 1 F4a: get_health SQL aggregate, shared orphan policy, op memo.
+ "src/core/engine-sql/health.ts": ["test/e2e/engine-sql-health-parity.test.ts", "test/e2e/health-parity-postgres.test.ts", "test/e2e/get-health-embedding-column-postgres.test.ts"],
+ "src/core/orphan-policy.ts": ["test/e2e/engine-sql-health-parity.test.ts", "test/e2e/health-parity-postgres.test.ts"],
+ "src/core/health-memo.ts": ["test/e2e/engine-sql-health-parity.test.ts", "test/e2e/get-health-embedding-column-postgres.test.ts"],
// Fix wave 8 lane D2 (#5828): the brain_score timeline grading helper.
"src/core/timeline-grading.ts": ["test/e2e/wave8-lane-d2-postgres.test.ts", "test/e2e/health-parity-postgres.test.ts"],
// GBRA-35 E10: the managed connector-source job contract drives these writers on an unbound connector source.
diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.ts
index 2366c6ecec..fdda05f0cc 100644
--- a/src/commands/doctor/remediate.ts
+++ b/src/commands/doctor/remediate.ts
@@ -24,6 +24,7 @@
*/
import type { BrainEngine } from '../../core/engine.ts';
import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
+import { clearHealthMemo } from '../../core/health-memo.ts';
import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';
import type { RepairPlanStep } from '../../core/remediation/repairs.ts';
import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';
@@ -298,6 +299,8 @@ export async function runRemediate(engine: BrainEngine, args: string[]): Promise
+ `of the cumulative cap $${snapshot.cap.toFixed(2)}. Checkpoint saved (cap, consent and remaining steps).`),
});
+ if (!dryRun) clearHealthMemo(engine);
+
if (result.budget_exhausted) {
const cap = result.budget?.max_usd ?? result.budget_exhausted.cap;
console.error(`Resume with:\n gbrain doctor --remediate --yes${result.budget?.include_repairs ? ' --include-repairs' : ''}`
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index eef9a876f9..b3bf591817 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -12,6 +12,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { clearHealthMemo } from '../core/health-memo.ts';
import { OperationError } from '../core/ops/contract.ts';
import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';
import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';
@@ -141,6 +142,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
if (result.stopped) break;
}
+ if (apply) clearHealthMemo(engine);
const paidKinds = results.filter(r => r.paid).map(r => r.kind);
if (json) {
console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds,
diff --git a/src/core/health-memo.ts b/src/core/health-memo.ts
new file mode 100644
index 0000000000..34c811d808
--- /dev/null
+++ b/src/core/health-memo.ts
@@ -0,0 +1,145 @@
+/**
+ * In-process memo for the `get_health` op (FOUNDATIONS 1, F4a, O-ENG-13).
+ *
+ * get_health aggregates the whole brain (or the caller's grant), and agents
+ * and health checks poll it. The op handler serves a repeat call from this
+ * memo when nothing it depends on moved. An entry is reused only when all of
+ * these match the current call:
+ *
+ * - engine identity: entries live in a WeakMap keyed by the engine object,
+ * and the brain id (`persistence_brain`) is part of the clock;
+ * - scope key: `all` (brain-wide), `scalar:<id>`, `set:<sorted unique ids>`,
+ * or `empty` (an empty grant or the no-sources sentinel; computes zeros
+ * and is never stored under `all`). The key is derived from the exact
+ * scope handed to `engine.getHealth`, so a scoped caller can never read
+ * an entry computed for another scope;
+ * - config generation: a hash of the orphan exclusions, the embedding
+ * column registry keys and the schema pack setting;
+ * - page clock: `page_generation_clock_seq.last_value`, which every page
+ * insert, update or delete advances;
+ * - age below the TTL: `GBRAIN_HEALTH_CACHE_TTL_MS`, else config
+ * `health.cache_ttl_ms`, else 30000 ms; 0 disables the memo. The TTL
+ * bounds staleness from writes that do not touch `pages` (links,
+ * timeline rows, chunks).
+ *
+ * The memo is not in the engine: doctor checks, remediation, maintain,
+ * embedding migration and repair verification call `engine.getHealth`
+ * directly and always see fresh numbers. `gbrain repair --apply` and
+ * `gbrain doctor --remediate` also clear it. If the clock or config read
+ * fails (for example a brain mid-upgrade), the call computes uncached.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from './engine.ts';
+import { NO_SOURCES } from './source-id.ts';
+import { ORPHAN_EXCLUDE_PREFIXES_KEY, ORPHAN_EXCLUDE_SLUGS_KEY } from './orphan-policy.ts';
+
+export const HEALTH_CACHE_TTL_KEY = 'health.cache_ttl_ms';
+export const HEALTH_CACHE_TTL_ENV = 'GBRAIN_HEALTH_CACHE_TTL_MS';
+export const DEFAULT_HEALTH_CACHE_TTL_MS = 30_000;
+
+const GENERATION_CONFIG_KEYS = [
+ ORPHAN_EXCLUDE_PREFIXES_KEY,
+ ORPHAN_EXCLUDE_SLUGS_KEY,
+ 'search_embedding_column',
+ 'embedding_columns',
+ 'schema_pack',
+] as const;
+const PAGE_CLOCK_ROW = '__page_clock__';
+const BRAIN_ID_ROW = '__brain_id__';
+const MAX_ENTRIES_PER_ENGINE = 256;
+
+interface Entry {
+ configGeneration: string;
+ pageClock: string;
+ storedAt: number;
+ computedAt: string;
+ value: unknown;
+}
+
+let memo = new WeakMap<object, Map<string, Entry>>();
+
+/** The memo key for the scope `engine.getHealth` receives (same normalization the engine applies). */
+export function healthScopeKey(scope: { sourceId?: string; sourceIds?: string[] }): string {
+ const ids = scope.sourceIds ?? (scope.sourceId ? [scope.sourceId] : null);
+ if (ids === null) return 'all';
+ const unique = [...new Set(ids)].sort();
+ if (unique.length === 0 || unique.includes(NO_SOURCES)) return 'empty';
+ if (scope.sourceIds === undefined) return `scalar:${unique[0]}`;
+ return `set:${unique.join(',')}`;
+}
+
+function parseTtl(raw: string | null | undefined): number | null {
+ if (raw === null || raw === undefined || raw.trim() === '') return null;
+ const n = Number(raw.trim());
+ return Number.isInteger(n) && n >= 0 ? n : null;
+}
+
+async function readGeneration(engine: BrainEngine): Promise<{ configGeneration: string; pageClock: string; configTtl: number | null } | null> {
+ try {
+ const rows = await engine.executeRaw<{ k: string; v: string | null }>(
+ `SELECT key AS k, value AS v FROM config
+ WHERE key IN (${[...GENERATION_CONFIG_KEYS, HEALTH_CACHE_TTL_KEY].map(k => `'${k}'`).join(', ')})
+ UNION ALL
+ SELECT '${PAGE_CLOCK_ROW}' AS k, COALESCE((SELECT last_value FROM page_generation_clock_seq), 0)::text AS v
+ UNION ALL
+ SELECT '${BRAIN_ID_ROW}' AS k, (SELECT brain_id::text FROM persistence_brain WHERE singleton = 1) AS v`,
+ );
+ const byKey = new Map(rows.map(r => [r.k, r.v]));
+ const generation = GENERATION_CONFIG_KEYS.map(k => [k, byKey.get(k) ?? null]);
+ generation.push(['env:GBRAIN_SCHEMA_PACK', process.env.GBRAIN_SCHEMA_PACK ?? null]);
+ return {
+ configGeneration: createHash('sha256').update(JSON.stringify(generation)).digest('hex').slice(0, 16),
+ pageClock: `${byKey.get(BRAIN_ID_ROW) ?? ''}:${byKey.get(PAGE_CLOCK_ROW) ?? ''}`,
+ configTtl: parseTtl(byKey.get(HEALTH_CACHE_TTL_KEY)),
+ };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Serve `compute()` from the memo when engine, scope, config generation and
+ * page clock match a fresh entry; otherwise compute, store and return it.
+ * The result carries `computed_at`, the ISO time its numbers were read.
+ */
+export async function memoizedHealth<T extends object>(
+ engine: BrainEngine,
+ scope: { sourceId?: string; sourceIds?: string[] },
+ compute: () => Promise<T>,
+): Promise<T & { computed_at: string }> {
+ const envTtl = parseTtl(process.env[HEALTH_CACHE_TTL_ENV]);
+ const startedAt = Date.now();
+ const generation = envTtl === 0 ? null : await readGeneration(engine);
+ const ttl = envTtl ?? generation?.configTtl ?? DEFAULT_HEALTH_CACHE_TTL_MS;
+ const key = healthScopeKey(scope);
+ const entries = memo.get(engine);
+ const hit = entries?.get(key);
+ if (generation && ttl > 0 && hit
+ && hit.configGeneration === generation.configGeneration
+ && hit.pageClock === generation.pageClock
+ && startedAt - hit.storedAt < ttl) {
+ return { ...structuredClone(hit.value as T), computed_at: hit.computedAt };
+ }
+ const value = await compute();
+ const computedAt = new Date(startedAt).toISOString();
+ if (generation && ttl > 0) {
+ const map = entries ?? new Map<string, Entry>();
+ if (!entries) memo.set(engine, map);
+ map.delete(key);
+ if (map.size >= MAX_ENTRIES_PER_ENGINE) map.delete(map.keys().next().value as string);
+ map.set(key, {
+ configGeneration: generation.configGeneration,
+ pageClock: generation.pageClock,
+ storedAt: startedAt,
+ computedAt,
+ value: structuredClone(value),
+ });
+ }
+ return { ...value, computed_at: computedAt };
+}
+
+/** Drop memoized health for one engine, or for every engine in this process. */
+export function clearHealthMemo(engine?: BrainEngine): void {
+ if (engine) memo.delete(engine);
+ else memo = new WeakMap();
+}
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index d0c12cecc8..38cd6b45f5 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -16,6 +16,7 @@ import type { Operation, OperationContext } from './contract.ts';
import { enforceClientSlugFence, sourceScopeOpts } from './context.ts';
import { VERSION } from '../../version.ts';
import { resolveActiveEmbeddingColumnFromEngine } from '../search/embedding-column.ts';
+import { memoizedHealth } from '../health-memo.ts';
// --- Admin ---
@@ -46,14 +47,24 @@ const get_stats: Operation = {
const get_health: Operation = {
name: 'get_health',
outputRedaction: 'no_stored_text',
- description: 'Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host.',
+ description: 'Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host. `computed_at` is when the counters were read: a repeat call within `health.cache_ttl_ms` (default 30000; env GBRAIN_HEALTH_CACHE_TTL_MS; 0 disables) with no page or config change returns the memoized numbers.',
params: {},
handler: async (ctx) => {
// The `migrations` block below stays GLOBAL for scoped callers by
// decision: it is a host filesystem ledger with no per-source semantics,
// and a wedged host migration is exactly what a remote agent needs to
// see to explain degraded behavior.
- const health = await ctx.engine.getHealth(diagnosticScope(ctx));
+ // F4a (O-ENG-13): memoized per engine, scope, config generation and page
+ // clock (src/core/health-memo.ts); engine.getHealth itself stays uncached.
+ const scope = diagnosticScope(ctx);
+ const health = await memoizedHealth(ctx.engine, scope, async () => {
+ const counters = await ctx.engine.getHealth(scope);
+ // #4732: name the column embed_coverage and missing_embeddings measured
+ // (the same resolution getHealth uses), so a 0% coverage on an embedded
+ // brain points at a mis-routed column instead of a paid re-embed.
+ const { name: embedding_column } = await resolveActiveEmbeddingColumnFromEngine(ctx.engine, { fallbackToLegacy: true });
+ return { ...counters, embedding_column };
+ });
// TODOS:4063 — composed at the OP layer (not BrainEngine.getHealth):
// the ledger is a filesystem JSONL, engine-agnostic; growing the engine
// interface would force both engines to duplicate a file read.
@@ -67,11 +78,7 @@ const get_health: Operation = {
} catch {
migrations = { error: 'ledger_unreadable' };
}
- // #4732: name the column embed_coverage and missing_embeddings measured
- // (the same resolution getHealth uses), so a 0% coverage on an embedded
- // brain points at a mis-routed column instead of a paid re-embed.
- const { name: embedding_column } = await resolveActiveEmbeddingColumnFromEngine(ctx.engine, { fallbackToLegacy: true });
- return { ...health, embedding_column, migrations };
+ return { ...health, migrations };
},
scope: 'admin',
cliHints: { name: 'health' },
diff --git a/test/e2e/engine-sql-health-parity.test.ts b/test/e2e/engine-sql-health-parity.test.ts
new file mode 100644
index 0000000000..96e412b86a
--- /dev/null
+++ b/test/e2e/engine-sql-health-parity.test.ts
@@ -0,0 +1,98 @@
+/**
+ * F4a on real Postgres (and PgBouncer in the backend matrix): the migrated
+ * single-statement getHealth equals the pre-F4a implementation field by field
+ * on the same fixtures and scopes as the PGLite suite
+ * (`test/engine-sql-health-equality.test.ts`); the SQL orphan predicate agrees
+ * with the TypeScript policy under Postgres's regex engine and collation
+ * (`test/orphan-policy-sql-parity.test.ts` is the PGLite twin); and the
+ * get_health memo's generation read (page clock, brain id, config) works on
+ * this backend, so the memo actually serves hits here instead of silently
+ * falling back to uncached reads.
+ *
+ * DATABASE_URL gated.
+ */
+import { afterAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { clearHealthMemo } from '../../src/core/health-memo.ts';
+import { _resetPackCacheForTests } from '../../src/core/schema-pack/registry.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import {
+ HEALTH_SRC_A,
+ expectHealthMatchesLegacy,
+ importE2eMarkdownFixtures,
+ seedRandomHealthGraph,
+ seedSourceScopeFixture,
+} from '../helpers/health-equality-fixtures.ts';
+import { expectOrphanPolicyParity } from '../helpers/orphan-policy-parity.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-f4a-health-pg-'));
+const env = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined }, fn);
+
+describe.skipIf(!hasDatabase())('F4a getHealth on Postgres', () => {
+ let engine: PostgresEngine;
+
+ beforeEach(async () => {
+ engine = await setupDB();
+ _resetPackCacheForTests();
+ clearHealthMemo();
+ }, 120_000);
+
+ afterAll(async () => {
+ await teardownDB();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('orphan policy: SQL and TS renderers agree on the generated corpus', async () => {
+ expect(await expectOrphanPolicyParity(engine)).toBeGreaterThan(2000);
+ });
+
+ test('empty brain and #4592 source-scope fixture match the pre-F4a implementation', async () => {
+ await env(() => expectHealthMatchesLegacy(engine, 'pg-empty'));
+ await seedSourceScopeFixture(engine);
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, 'pg-source-scope'));
+ expect(all.page_count).toBe(3);
+ });
+
+ test('E2E markdown fixture corpus matches the pre-F4a implementation', async () => {
+ expect(await importE2eMarkdownFixtures(engine)).toBeGreaterThan(10);
+ await env(() => expectHealthMatchesLegacy(engine, 'pg-e2e-corpus'));
+ });
+
+ for (const seed of [1, 7, 42]) {
+ test(`seeded random graph ${seed} matches the pre-F4a implementation`, async () => {
+ await seedRandomHealthGraph(engine, seed);
+ const [all] = await env(() => expectHealthMatchesLegacy(engine, `pg-random-${seed}`));
+ expect(all.most_connected.length).toBe(5);
+ });
+ }
+
+ test('seeded random graph under an active schema pack matches', async () => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await seedRandomHealthGraph(engine, 99);
+ await env(() => expectHealthMatchesLegacy(engine, 'pg-random-pack'));
+ });
+
+ test('the get_health memo serves hits on this backend and stays scope-confined', async () => {
+ await seedSourceScopeFixture(engine);
+ const op = (ctx: Partial<OperationContext>) =>
+ operationsByName.get_health.handler({ engine, takesHoldersAllowList: ['world'], ...ctx } as OperationContext, {}) as Promise<{ computed_at: string; page_count: number }>;
+ const trusted = { remote: false } as Partial<OperationContext>;
+ const scoped = { remote: true, transport: 'http', sourceId: HEALTH_SRC_A } as Partial<OperationContext>;
+ const first = await op(trusted);
+ await new Promise(r => setTimeout(r, 5));
+ const second = await op(trusted);
+ expect(second.computed_at).toBe(first.computed_at);
+ expect((await op(scoped)).page_count).toBe(2);
+ expect((await op(trusted)).page_count).toBe(3);
+ await engine.putPage('notes/new-page', { type: 'note', title: 'New', compiled_truth: 'new' });
+ const third = await op(trusted);
+ expect(third.computed_at).not.toBe(first.computed_at);
+ expect(third.page_count).toBe(4);
+ });
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 66d6b88848..06b874a5e8 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 208089,
- "stdoutSha256": "a63cbbb5e6793515080dcb661c072dc74b491e1ff8fb8c1b3c4bbc9ba9c9bfd0",
+ "stdoutBytes": 208298,
+ "stdoutSha256": "a88099238ea9e4a35f52664274cbebb2560787cd392af25448ed873874c80da9",
"toolNames": [
"remember",
"entity",
@@ -1606,7 +1606,7 @@
}
},
{
- "description": "Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host.",
+ "description": "Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host. `computed_at` is when the counters were read: a repeat call within `health.cache_ttl_ms` (default 30000; env GBRAIN_HEALTH_CACHE_TTL_MS; 0 disables) with no page or config change returns the memoized numbers.",
"name": "get_health",
"parameters": {},
"schema": {
diff --git a/test/health-memo.test.ts b/test/health-memo.test.ts
new file mode 100644
index 0000000000..ff20946821
--- /dev/null
+++ b/test/health-memo.test.ts
@@ -0,0 +1,202 @@
+/**
+ * F4a (O-ENG-13): the get_health op memo (`src/core/health-memo.ts`).
+ *
+ * Contracts protected:
+ * - a repeat call with no page/config change inside the TTL is served from
+ * the memo (`computed_at` unchanged); a page write, a config change, TTL
+ * expiry, `repair --apply` and `doctor --remediate` each force fresh
+ * numbers, so no caller sees a pre-repair score;
+ * - entries never cross scopes: warming as the trusted caller and then
+ * reading with disjoint source grants, in both orders, returns exactly
+ * what an uncached `engine.getHealth(scope)` returns for each grant, with
+ * `most_connected` confined to the grant;
+ * - an empty grant computes zeros and never reads the brain-wide entry;
+ * - TTL 0 (env or config) disables the memo.
+ * A links-only write does not advance the page clock, which is what lets
+ * these tests tell a memo hit from a recompute.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, setSystemTime, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import type { BrainHealth } from '../src/core/types.ts';
+import { clearHealthMemo, healthScopeKey, memoizedHealth, HEALTH_CACHE_TTL_KEY } from '../src/core/health-memo.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { runRemediate } from '../src/commands/doctor/remediate.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { HEALTH_SRC_A, HEALTH_SRC_B, seedSourceScopeFixture } from './helpers/health-equality-fixtures.ts';
+
+type OpHealth = BrainHealth & { computed_at: string; embedding_column: string; migrations: unknown };
+
+let engine: PGLiteEngine;
+let now = Date.parse('2026-10-03T12:00:00.000Z');
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ setSystemTime();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ clearHealthMemo();
+ now += 3_600_000;
+ setSystemTime(new Date(now));
+ await seedSourceScopeFixture(engine);
+});
+
+afterEach(() => setSystemTime());
+
+const advance = (ms: number) => { now += ms; setSystemTime(new Date(now)); };
+
+const trusted = () => ({ engine, remote: false }) as unknown as OperationContext;
+const remote = (extra: Partial<OperationContext>) =>
+ ({ engine, remote: true, transport: 'http', takesHoldersAllowList: ['world'], ...extra }) as unknown as OperationContext;
+const health = async (ctx: OperationContext) => (await operationsByName.get_health.handler(ctx, {})) as OpHealth;
+const counters = ({ computed_at, embedding_column, migrations, ...rest }: OpHealth) => rest;
+const degree = (h: BrainHealth) => h.most_connected.find(m => m.slug === 'people/alice-example')?.link_count ?? -1;
+const fresh = (scope?: { sourceId?: string; sourceIds?: string[] }) => engine.getHealth(scope);
+
+let probe = 0;
+async function linkOnlyWrite(): Promise<void> {
+ probe++;
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type)
+ SELECT b.id, a.id, 'memo-probe-${probe}' FROM pages a, pages b
+ WHERE a.slug = 'notes/alpha' AND b.slug = 'people/alice-example'`,
+ );
+}
+
+async function quietly<T>(fn: () => Promise<T>): Promise<T> {
+ const log = console.log;
+ const error = console.error;
+ console.log = () => {};
+ console.error = () => {};
+ try {
+ return await fn();
+ } finally {
+ console.log = log;
+ console.error = error;
+ }
+}
+
+describe('get_health memo (O-ENG-13)', () => {
+ test('a repeat call inside the TTL is memoized; a page write recomputes', async () => {
+ const first = await health(trusted());
+ expect(first.computed_at).toBe(new Date(now).toISOString());
+ expect(counters(first)).toEqual(await fresh());
+ await linkOnlyWrite();
+ advance(1_000);
+ const second = await health(trusted());
+ expect(second.computed_at).toBe(first.computed_at);
+ expect(degree(second)).toBe(degree(first));
+ await engine.putPage('notes/beta', { type: 'note', title: 'Beta', compiled_truth: 'beta' });
+ const third = await health(trusted());
+ expect(third.computed_at).toBe(new Date(now).toISOString());
+ expect(counters(third)).toEqual(await fresh());
+ expect(degree(third)).toBe(degree(first) + 1);
+ });
+
+ for (const order of ['trusted-first', 'grants-first'] as const) {
+ test(`disjoint grants stay confined when warmed ${order}`, async () => {
+ const calls: Array<[string, OperationContext, { sourceId?: string; sourceIds?: string[] } | undefined]> = [
+ ['trusted', trusted(), undefined],
+ ['scalar A', remote({ sourceId: HEALTH_SRC_A }), { sourceId: HEALTH_SRC_A }],
+ ['federated B', remote({ sourceId: 'default', auth: { token: 't', clientId: 'c', scopes: ['read', 'admin'], allowedSources: [HEALTH_SRC_B] } } as never), { sourceIds: [HEALTH_SRC_B] }],
+ ];
+ if (order === 'grants-first') calls.reverse();
+ for (const [, ctx] of calls) await health(ctx);
+ for (const [label, ctx, scope] of calls) {
+ const got = await health(ctx);
+ expect({ label, got: counters(got) }).toEqual({ label, got: await fresh(scope) });
+ }
+ const a = await health(remote({ sourceId: HEALTH_SRC_A }));
+ const b = await health(calls.find(c => c[0] === 'federated B')![1]);
+ expect(a.page_count).toBe(2);
+ expect(b.page_count).toBe(1);
+ expect(a.most_connected.map(m => m.slug)).toEqual(['people/alice-example']);
+ expect(b.most_connected.map(m => m.slug)).toEqual(['people/bob-example']);
+ expect(a.most_connected[0].link_count).toBe(1);
+ expect(b.most_connected[0].link_count).toBe(0);
+ });
+ }
+
+ test('an empty grant computes zeros and never reads the brain-wide entry', async () => {
+ const all = await health(trusted());
+ expect(all.page_count).toBe(3);
+ let computed = 0;
+ const empty = await memoizedHealth(engine, { sourceIds: [] }, async () => {
+ computed++;
+ return fresh({ sourceIds: [] });
+ });
+ expect(computed).toBe(1);
+ expect(empty.page_count).toBe(0);
+ expect(empty.most_connected).toEqual([]);
+ const sentinel = await health(remote({ sourceId: '__all__' }));
+ expect(sentinel.page_count).toBe(0);
+ expect(sentinel.most_connected).toEqual([]);
+ expect(healthScopeKey({})).toBe('all');
+ expect(healthScopeKey({ sourceIds: [] })).toBe('empty');
+ expect(healthScopeKey({ sourceId: '__none__' })).toBe('empty');
+ expect(healthScopeKey({ sourceId: '' })).toBe('all');
+ expect(healthScopeKey({ sourceId: 'a' })).toBe('scalar:a');
+ expect(healthScopeKey({ sourceIds: ['b', 'a', 'b'] })).toBe('set:a,b');
+ });
+
+ test('changing orphan exclusions recomputes with the new policy', async () => {
+ const before = await health(trusted());
+ expect(before.linkable_page_count).toBe(3);
+ await engine.setConfig('orphans.exclude_prefixes', 'notes/');
+ const after = await health(trusted());
+ expect(after.linkable_page_count).toBe(2);
+ expect(counters(after)).toEqual(await fresh());
+ });
+
+ test('repair --apply clears the memo: no pre-repair score', async () => {
+ const warm = await health(trusted());
+ await linkOnlyWrite();
+ expect(degree(await health(trusted()))).toBe(degree(warm));
+ await quietly(() => runRepairCommand(engine, ['timeline', '--apply', '--no-embed', '--json']));
+ const after = await health(trusted());
+ expect(degree(after)).toBe(degree(warm) + 1);
+ expect(counters(after)).toEqual(await fresh());
+ });
+
+ test('doctor --remediate clears the memo', async () => {
+ const warm = await health(trusted());
+ await linkOnlyWrite();
+ await quietly(() => runRemediate(engine, ['--yes', '--json', '--no-embed', '--max-jobs', '0']));
+ const after = await health(trusted());
+ expect(degree(after)).toBe(degree(warm) + 1);
+ });
+
+ test('the TTL expires entries; 0 disables the memo (env and config)', async () => {
+ await withEnv({ GBRAIN_HEALTH_CACHE_TTL_MS: '1000' }, async () => {
+ const warm = await health(trusted());
+ await linkOnlyWrite();
+ advance(999);
+ expect((await health(trusted())).computed_at).toBe(warm.computed_at);
+ advance(1);
+ const expired = await health(trusted());
+ expect(expired.computed_at).not.toBe(warm.computed_at);
+ expect(degree(expired)).toBe(degree(warm) + 1);
+ });
+ await withEnv({ GBRAIN_HEALTH_CACHE_TTL_MS: '0' }, async () => {
+ const a = await health(trusted());
+ await linkOnlyWrite();
+ expect(degree(await health(trusted()))).toBe(degree(a) + 1);
+ });
+ await withEnv({ GBRAIN_HEALTH_CACHE_TTL_MS: undefined }, async () => {
+ await engine.setConfig(HEALTH_CACHE_TTL_KEY, '0');
+ const a = await health(trusted());
+ await linkOnlyWrite();
+ expect(degree(await health(trusted()))).toBe(degree(a) + 1);
+ });
+ });
+});