Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(onboard): our own implementation of the #6109 fix (#6109)

time-attackedcf8d637c4b
diff --git a/TODOS.md b/TODOS.md
index bca0bf1388..bacb8afdcf 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -500,7 +500,7 @@ Evidence for each item is in `docs/test-audit/2026-09-29/`.
**What:** after the third consecutive health failure the supervisor warns and calls `engine.reconnect()`. A failed reconnect leaves the failure counter at 3 or more, so every later failing health tick warns `db_connection_degraded` and reconnects again (pinned as current behavior in `test/supervisor-health-reconnect.test.ts`). No doc or CHANGELOG entry says whether that per-tick retry is intended. **Fix:** confirm it is intended and document it, or add a backoff between reconnect attempts and update the test. **Effort:** S. **Priority:** P3.
- [x] **P1 — `auto_chronicle` does nothing since v0.51.0.0.** **Completed (verified 2026-10-04, GBRA-47 F15):** `src/core/chronicle/config.ts` owns the switch, the chronicle cycle phase (`src/core/cycle/chronicle.ts`) reads it, and `backstop.ts` is gone; `test/chronicle-auto-phase.test.ts` writes a meeting, runs the phase and reads the events, and its "opt-out between decision and run" case makes zero model calls (31/31 pass with `test/chronicle-auto-decision.test.ts`).
**What (original):** v0.51.0.0 moved the facts backstop onto the effects queue and dropped the chronicle backstop, so `gbrain config set auto_chronicle true` has no reader (`isAutoChronicleEnabled` is only called from the unwired `src/core/chronicle/backstop.ts`), yet the advisor still tells users to enable it. **Fix:** restore the chronicle backstop on the effects queue, or retract the setting and the advisor text. `backstop.ts` is held in the orphan guard's permitted set until then.
-- [x] **P1 — `gbrain onboard --history` always returns nothing.** **Completed (fix wave 10, #6109):** `runRemediation` (`src/core/remediation/run.ts`) records each executed job step's mapped metric before submit and after its job is terminal through `startStepImpact` in `src/core/onboard/impact-capture.ts`, which reads the canonical predicates (countStaleChunks, get_health's orphan definition, the coverage checks' entity population); the orphan guard no longer holds the module. `test/remediation-impact-capture.test.ts` (PGLite) and `test/e2e/onboard-full-flow.test.ts` (PGLite and Postgres) run a real extract step and read the row back through `onboard --history`.
+- [x] **P1 — `gbrain onboard --history` always returns nothing.** **Completed (fix wave 10, #6109):** `runRemediation` (`src/core/remediation/run.ts`) opens an impact probe before submitting each job step whose job moves a tracked metric and closes it once the job is terminal (`openStepImpact` / `closeStepImpact` in `src/core/onboard/impact-capture.ts`), reading each metric through the brain's own definition (countStaleChunks, findOrphanPages under the orphan-reporting policy, the coverage checks' query); the orphan guard no longer holds the module. `test/remediation-impact-capture.test.ts` (PGLite) runs real extract steps and reads the rows back through `onboard --history`; `test/e2e/onboard-full-flow.test.ts` checks the row's JSONB details on Postgres.
**What (original):** `src/core/onboard/impact-capture.ts` is the only writer of `migration_impact_log`, which `onboard --history` reads, and it has no runtime caller. **Fix:** wire impact capture into the migration path or retract `--history`. Held in the orphan guard's permitted set.
- [ ] **P2 — archive-crawler `scan_paths` safety fence is documented as enforced but is not.**
**What:** `skills/archive-crawler/SKILL.md` says the fence is enforced by `src/core/storage-config.ts`; the enforcing module `src/core/archive-crawler-config.ts` is unwired. **Fix:** wire the check or correct the skill text. Held in the permitted set.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 9c00197f42..0566324479 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -62,4 +62,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.
- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI: `brain_id` (a resume against another brain refuses), `max_usd` (reused by `--resume` without `--max-usd`), `include_repairs`, cumulative `spent_usd` and the original step `manifest` (`job_ids`, `repair_kinds`); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus `test/recovery-layer.test.ts`.
-- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. A kind whose preview throws is reported through `onPreviewError` as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted and capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (embed / embed-catch-up: `countStaleChunks`; extract: get_health's orphan definition counted directly, never a full `getHealth()`; extract-ner / extract-timeline-from-meetings: visible-entity coverage; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `startStepImpact`, best-effort: a failed capture records null and never changes the step result), which `gbrain onboard --history` reads; dry runs, skipped steps and unmapped jobs record nothing.
+- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. A kind whose preview throws is reported through `onPreviewError` as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted and capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.
diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.ts
index 8ed0a490b8..de60ff9030 100644
--- a/src/core/onboard/checks.ts
+++ b/src/core/onboard/checks.ts
@@ -58,8 +58,7 @@ async function safeCount(engine: BrainEngine, sql: string, params: unknown[] = [
}
}
-/** The coverage checks' entity population (`p` = pages); impact capture counts the same pages. */
-export const VISIBLE_ENTITY_PREDICATE = `p.type IN ('person', 'company', 'organization', 'entity')
+const VISIBLE_ENTITY_PREDICATE = `p.type IN ('person', 'company', 'organization', 'entity')
AND p.deleted_at IS NULL
AND ${QUARANTINE_FILTER_FRAGMENT}`;
@@ -78,10 +77,38 @@ function ungradedCoverageResult(name: string, entityPages: number): OnboardCheck
return { check: { name, status: 'ok', message }, remediations: [] };
}
-type CoverageFeature =
+export type CoverageFeature =
| { table: 'links'; pageIdColumn: 'to_page_id' }
| { table: 'timeline_entries'; pageIdColumn: 'page_id' };
+/** entity_link_coverage counts inbound links; timeline_coverage counts timeline entries. */
+export const LINK_COVERAGE_FEATURE: CoverageFeature = { table: 'links', pageIdColumn: 'to_page_id' };
+export const TIMELINE_COVERAGE_FEATURE: CoverageFeature = { table: 'timeline_entries', pageIdColumn: 'page_id' };
+
+/**
+ * One row `{ sample_size, matched }`: the visible entity pages (optionally
+ * TABLESAMPLEd) and how many of them have `feature`. The coverage checks and
+ * remediation impact capture both read coverage through this query, so a
+ * `gbrain onboard --history` row measures the population the check grades.
+ */
+export function visibleEntityCoverageSql(feature: CoverageFeature, sampleClause = ''): string {
+ return `WITH sampled_entities AS (
+ SELECT p.id
+ FROM pages p ${sampleClause}
+ WHERE ${VISIBLE_ENTITY_PREDICATE}
+ )
+ SELECT
+ COUNT(*)::int AS sample_size,
+ COUNT(*) FILTER (
+ WHERE EXISTS (
+ SELECT 1
+ FROM ${feature.table} f
+ WHERE f.${feature.pageIdColumn} = s.id
+ )
+ )::int AS matched
+ FROM sampled_entities s`;
+}
+
interface EntityCoverageSample {
matched: number;
sampleSize: number;
@@ -105,23 +132,7 @@ async function sampleVisibleEntityCoverage(
feature: CoverageFeature,
): Promise<EntityCoverageSample> {
try {
- const result = await engine.executeRaw(
- `WITH sampled_entities AS (
- SELECT p.id
- FROM pages p ${sampleClause}
- WHERE ${VISIBLE_ENTITY_PREDICATE}
- )
- SELECT
- COUNT(*)::int AS sample_size,
- COUNT(*) FILTER (
- WHERE EXISTS (
- SELECT 1
- FROM ${feature.table} f
- WHERE f.${feature.pageIdColumn} = s.id
- )
- )::int AS matched
- FROM sampled_entities s`,
- );
+ const result = await engine.executeRaw(visibleEntityCoverageSql(feature, sampleClause));
const rows = (result as { rows?: Array<Record<string, unknown>> } | undefined)?.rows
?? (result as Array<Record<string, unknown>> | undefined)
?? [];
@@ -297,7 +308,7 @@ export async function checkEntityLinkCoverage(
const sample = await sampleVisibleEntityCoverage(
engine,
sampleClause,
- { table: 'links', pageIdColumn: 'to_page_id' },
+ LINK_COVERAGE_FEATURE,
);
const { coverage, ci } = coverageWithConfidence(sample);
@@ -379,7 +390,7 @@ export async function checkTimelineCoverage(
const sample = await sampleVisibleEntityCoverage(
engine,
sampleClause,
- { table: 'timeline_entries', pageIdColumn: 'page_id' },
+ TIMELINE_COVERAGE_FEATURE,
);
const { coverage, ci } = coverageWithConfidence(sample);
const pct = Math.round(coverage * 100);
diff --git a/src/core/onboard/impact-capture.ts b/src/core/onboard/impact-capture.ts
index b673fd7b5a..8206513582 100644
--- a/src/core/onboard/impact-capture.ts
+++ b/src/core/onboard/impact-capture.ts
@@ -3,33 +3,30 @@
// aggregates (orphan_count, stale_count, coverage fractions) by design.
// Per A26 lint opt-out.
//
-// v0.41.18.0 (A6 + A25 + A17, T11). Capture before/after stats per
-// remediation job step so `gbrain onboard --history` can show "you reduced
-// orphans 47% (88% → 41%)". runRemediation (doctor --remediate, onboard
-// --auto, MCP run_onboard) calls startStepImpact before it submits a step's
-// job and finishes it once the job is terminal. Only the metric the step's
-// job moves is read, and a step that is skipped or never reaches a terminal
-// job records nothing.
+// v0.41.18.0 (A6 + A25 + A17, T11). Before/after stats for remediation job
+// steps, the rows `gbrain onboard --history` reads ("you reduced orphans
+// 47% (88% → 41%)"). runRemediation is the writer: it opens a probe before
+// it submits a step's job and closes it once that job is terminal. Steps
+// whose job moves no tracked metric, dry runs, and steps that throw before
+// their job is terminal leave no row.
//
-// Each metric reads the predicate the brain already reports it with (the
-// embed worker's stale count, get_health's orphan count, the onboard
-// coverage checks' entity population), so a history row agrees with
-// `gbrain onboard --check` and `gbrain doctor`.
+// Every metric is read through the brain's own definition of it, so a row
+// agrees with doctor and `onboard --check`: the embed worker's stale-chunk
+// count, findOrphanPages under the shared orphan-reporting policy (what
+// get_health counts), and the onboard coverage checks' own query.
//
-// Best-effort per A17: a stat-query throw must NOT block the remediation.
-// Failures log to stderr and record metric_before/after = null.
+// Best-effort per A17: a stat-query or log-write failure must NOT change the
+// step's outcome. Failures log to stderr; a failed capture records null.
//
-// Attribution columns per A25 + codex finding #10: every row carries
-// job_id (FK to minion_jobs), source_id, started_at, idempotency_key so
-// concurrent onboard/autopilot/manual runs can't misattribute deltas to the
-// wrong remediation.
+// Attribution columns per A25 + codex finding #10: rows carry job_id (FK to
+// minion_jobs), source_id, started_at and idempotency_key so concurrent
+// onboard/autopilot/manual runs can't misattribute deltas to the wrong
+// remediation.
import type { BrainEngine } from './../engine.ts';
import type { RemediationStep } from '../remediation-step.ts';
-import { VISIBLE_ENTITY_PREDICATE } from './checks.ts';
-import { loadOrphanPolicyOverrides, orphanExclusionSql } from '../orphan-policy.ts';
-import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
-import { renderFragment, sqlFragment, trustedSql } from '../engine-sql/fragment.ts';
+import { loadOrphanPolicyOverrides, shouldExcludeFromOrphanReporting } from '../orphan-policy.ts';
+import { LINK_COVERAGE_FEATURE, TIMELINE_COVERAGE_FEATURE, visibleEntityCoverageSql } from './checks.ts';
export type MetricName =
| 'orphan_count'
@@ -58,6 +55,28 @@ const JOB_METRICS: Readonly<Record<string, MetricName>> = {
'extract-takes-from-pages': 'takes_count',
};
+/**
+ * The tracked metric a remediation job is expected to move, or null when its
+ * effect has no single metric (its steps then record no history row).
+ */
+export function impactMetricForJob(job: string): MetricName | null {
+ switch (job) {
+ case 'embed':
+ case 'embed-catch-up':
+ return 'stale_count';
+ case 'extract':
+ return 'orphan_count';
+ case 'extract-ner':
+ return 'entity_link_coverage';
+ case 'extract-timeline-from-meetings':
+ return 'timeline_coverage';
+ case 'extract-takes-from-pages':
+ return 'takes_count';
+ default:
+ return null;
+ }
+}
+
/**
* Pure-ish: returns the current numeric value for `metric`. Returns null
* on any throw (best-effort capture per A17).
@@ -71,31 +90,19 @@ export async function captureMetric(
case 'stale_count':
return await engine.countStaleChunks();
case 'orphan_count': {
- // get_health's orphan_pages without the rest of its aggregates: live,
- // unquarantined pages outside the orphan policy with no live inbound
- // and no live outbound link.
- const { text, params } = renderFragment(sqlFragment`SELECT count(*)::int AS count FROM pages p
- WHERE p.deleted_at IS NULL AND ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}
- AND NOT ${orphanExclusionSql('p', await loadOrphanPolicyOverrides(engine))}
- AND NOT EXISTS (SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL)
- AND NOT EXISTS (SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL)`);
- const [row] = await engine.executeRaw<{ count: number }>(text, params);
- return Number(row?.count ?? 0);
+ const [candidates, overrides] = await Promise.all([
+ engine.findOrphanPages(),
+ loadOrphanPolicyOverrides(engine),
+ ]);
+ return candidates.filter((page) => !shouldExcludeFromOrphanReporting(page.slug, overrides, page)).length;
}
case 'entity_link_coverage':
case 'timeline_coverage': {
- // Exact (unsampled) fraction of visible entity pages with the feature.
- const feature = metric === 'entity_link_coverage'
- ? 'SELECT 1 FROM links l WHERE l.to_page_id = p.id'
- : 'SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id';
- const [row] = await engine.executeRaw<{ total: number; matched: number }>(
- `SELECT COUNT(*)::int AS total, COUNT(*) FILTER (WHERE EXISTS (${feature}))::int AS matched
- FROM pages p
- WHERE ${VISIBLE_ENTITY_PREDICATE}`,
- );
- const total = Number(row?.total ?? 0);
- if (total === 0) return 1; // vacuous truth — empty brain has full coverage
- return Number(row?.matched ?? 0) / total;
+ const feature = metric === 'entity_link_coverage' ? LINK_COVERAGE_FEATURE : TIMELINE_COVERAGE_FEATURE;
+ const [row] = await engine.executeRaw<{ sample_size: number; matched: number }>(visibleEntityCoverageSql(feature));
+ const population = Number(row?.sample_size ?? 0);
+ // An empty population is vacuously covered.
+ return population === 0 ? 1 : Number(row?.matched ?? 0) / population;
}
case 'takes_count': {
const rows = await engine.executeRaw<{ count: string | number }>(
@@ -152,39 +159,51 @@ export async function writeImpactLogRow(
}
}
+/** A step's metric as read just before its job was submitted. */
+export interface StepImpactProbe {
+ metric: MetricName;
+ before: number | null;
+ startedAt: string;
+}
+
+type ImpactStep = Pick<RemediationStep, 'id' | 'job' | 'idempotency_key' | 'params'>;
+
/**
- * Capture a remediation step's metric before its job is submitted. Returns
- * the finisher that captures it again once the job is terminal and writes
- * the row, or null when the step's job moves no tracked metric.
- *
- * Per A17: capture failures DO NOT block the step. A null before/after is
- * recorded; the row still lands so downstream consumers see a "ran but
- * impact unknown" entry.
+ * Read the metric `step`'s job moves, before the job is submitted. Returns
+ * null (and reads nothing) when the job has no tracked metric.
*/
-export async function startStepImpact(
- engine: BrainEngine,
- step: Pick<RemediationStep, 'id' | 'job' | 'idempotency_key' | 'params'>,
-): Promise<((jobId: number, details: Record<string, unknown>) => Promise<void>) | null> {
- const metric = JOB_METRICS[step.job];
- if (!metric) return null;
+export async function openStepImpact(engine: BrainEngine, step: ImpactStep): Promise<StepImpactProbe | null> {
+ const metric = impactMetricForJob(step.job);
+ if (metric === null) return null;
const startedAt = new Date().toISOString();
- const before = await captureMetric(engine, metric);
- return async (jobId, details) => {
- const after = await captureMetric(engine, metric);
- const sourceId = step.params.sourceId;
- await writeImpactLogRow(
- engine,
- {
- remediation_id: step.id,
- job_id: jobId,
- started_at: startedAt,
- idempotency_key: step.idempotency_key,
- ...(typeof sourceId === 'string' ? { source_id: sourceId } : {}),
- },
- metric,
- before,
- after,
- { job: step.job, ...details },
- );
- };
+ return { metric, startedAt, before: await captureMetric(engine, metric) };
+}
+
+/**
+ * Read the metric again now that the step's job is terminal and write the
+ * step's history row. Never throws: a failed read records null and a failed
+ * write only logs (A17).
+ */
+export async function closeStepImpact(
+ engine: BrainEngine,
+ probe: StepImpactProbe,
+ step: ImpactStep,
+ outcome: { jobId: number; status: string; doctorRunId: string },
+): Promise<void> {
+ const after = await captureMetric(engine, probe.metric);
+ const sourceId = typeof step.params.sourceId === 'string' ? step.params.sourceId : undefined;
+ await writeImpactLogRow(
+ engine,
+ {
+ remediation_id: step.id,
+ job_id: outcome.jobId,
+ started_at: probe.startedAt,
+ idempotency_key: step.idempotency_key,
+ source_id: sourceId,
+ },
+ probe.metric,
+ probe.before,
+ after,
+ { job: step.job, status: outcome.status, doctor_run_id: outcome.doctorRunId },
+ );
}
diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.ts
index 45102c0945..086c20e54f 100644
--- a/src/core/remediation/run.ts
+++ b/src/core/remediation/run.ts
@@ -257,7 +257,7 @@ export async function runRemediation(
const repairResults: RepairStepResult[] = [];
const { MinionQueue } = await import('../minions/queue.ts');
- const { startStepImpact } = await import('../onboard/impact-capture.ts');
+ const { openStepImpact, closeStepImpact } = await import('../onboard/impact-capture.ts');
const isPGLite = engine.kind === 'pglite';
const queue = new MinionQueue(engine);
const waitStep = stepWaiter(engine, queue, opts.inlineJobs === true);
@@ -385,7 +385,7 @@ export async function runRemediation(
hooks.onStepStart?.(stepCount, totalSteps, step);
try {
- const finishImpact = await startStepImpact(engine, step);
+ const impact = await openStepImpact(engine, step);
const isProtected = !!step.protected;
const submitWith = (key: string) =>
queue.add(
@@ -423,7 +423,7 @@ export async function runRemediation(
const terminal = await waitStep(job.id, { pollMs: isPGLite ? 250 : 1000, timeoutMs: (step.est_seconds + 60) * 1000 });
submittedResult.status = terminal.status;
- await finishImpact?.(job.id, { status: terminal.status, doctor_run_id: doctorRunId });
+ if (impact) await closeStepImpact(engine, impact, step, { jobId: job.id, status: terminal.status, doctorRunId });
if (terminal.status !== 'completed') abortedIds.add(step.id);
hooks.onStepEnd?.(submittedResult);
} catch (e) {
diff --git a/test/e2e/onboard-full-flow.test.ts b/test/e2e/onboard-full-flow.test.ts
index 365888f4c8..c4f0b8ccf2 100644
--- a/test/e2e/onboard-full-flow.test.ts
+++ b/test/e2e/onboard-full-flow.test.ts
@@ -3,25 +3,21 @@
// DATABASE_URL needed. Exercises the key contracts end-to-end:
// - computeRemediationPlan with extras returns the expected shape
// - buildOnboardReport produces a stable JSON envelope
-// - captureMetric returns numeric values for each of 5 metrics, read
-// with the predicates the onboard checks and get_health report
-// - A remediation job step writes its before/after impact row, which
-// `gbrain onboard --history` shows
+// - captureMetric returns numeric values for each of 5 metrics
// - The runRemediation library refuses --auto without --max-usd
// - The onboard CLI gates work as documented
//
-// The impact-history block also runs on real Postgres when DATABASE_URL is
-// set (a real extract job, run inline through the Minion worker). Other
+// One block needs DATABASE_URL: a real extract job run inline on Postgres,
+// which proves the remediation impact row (#6109) lands with its JSONB
+// details as an object (PGLite cannot show a double-encoded string). Other
// handlers firing on Postgres still wait on the per-handler stub seam.
import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
-import type { BrainEngine } from '../../src/core/engine.ts';
import { computeRemediationPlan, runRemediation } from '../../src/core/remediation/index.ts';
-import { captureMetric } from '../../src/core/onboard/impact-capture.ts';
-import { runOnboard } from '../../src/commands/onboard.ts';
-import { installFixtureChunks } from '../helpers/page-projection.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { captureMetric } from '../../src/core/onboard/impact-capture.ts';
import { buildOnboardReport, toOnboardRecommendation } from '../../src/core/onboard/render.ts';
import { runAllOnboardChecks } from '../../src/core/onboard/checks.ts';
import { makeRemediationStep } from '../../src/core/remediation-step.ts';
@@ -60,78 +56,49 @@ describe('onboard E2E — captureMetric', () => {
});
});
-// The impact row's JSONB details only prove out on real Postgres (PGLite hides
-// double-encoding), so this block also runs there when DATABASE_URL is set.
-for (const backend of ['pglite', 'postgres'] as const) {
- (backend === 'postgres' && !hasDatabase() ? describe.skip : describe)(`onboard E2E — impact history (${backend})`, () => {
- let brain: BrainEngine;
-
- beforeAll(async () => {
- if (backend === 'postgres') {
- brain = await setupDB();
- return;
- }
- const pglite = new PGLiteEngine();
- await pglite.connect({});
- await pglite.initSchema();
- brain = pglite;
- }, 60_000);
-
- afterAll(async () => {
- if (backend === 'postgres') await teardownDB();
- else await brain.disconnect();
- });
-
- test('a remediation job step records its metric before and after; onboard --history shows it', async () => {
- // Two unextracted pages, one linking the other: the planner adds
- // extract.stale, whose link leaves get_health with no orphan pages.
- await brain.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice works at [[companies/acme-example]].' });
- await brain.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'A widget company.' });
- expect((await brain.getHealth()).orphan_pages).toBe(2);
+(hasDatabase() ? describe : describe.skip)('onboard E2E — remediation impact row on Postgres (#6109)', () => {
+ let pg: PostgresEngine;
- const result = await runRemediation(brain, { targetScore: 0, inlineJobs: true });
- const step = result.submitted.find((s) => s.id === 'extract.stale');
- expect(step?.status).toBe('completed');
+ beforeAll(async () => {
+ pg = await setupDB();
+ }, 60_000);
- const onboardOutput = async (args: string[]) => {
- let out = '';
- const write = process.stdout.write;
- process.stdout.write = ((chunk: string | Uint8Array) => { out += String(chunk); return true; }) as typeof process.stdout.write;
- try {
- await runOnboard(brain, args);
- } finally {
- process.stdout.write = write;
- }
- return out;
- };
- const { history } = JSON.parse(await onboardOutput(['--history', '--json'])) as { history: Array<Record<string, unknown>> };
- expect(history).toHaveLength(1);
- expect(history[0]).toMatchObject({ remediation_id: 'extract.stale', metric_name: 'orphan_count', metric_before: 2, metric_after: 0, delta: -2 });
- expect(await onboardOutput(['--history'])).toMatch(
- /^Onboard history \(last 1\):\n {2}\d{4}-\d\d-\d\dT[\d:.]+Z {2}extract\.stale {2}orphan_count: 2 → 0 \(-2\)\n$/);
-
- const [row] = await brain.executeRaw<{ job_id: string | number; details: Record<string, unknown> }>(
- 'SELECT job_id, details FROM migration_impact_log');
- expect(Number(row.job_id)).toBe(step!.job_id!);
- expect(row.details).toMatchObject({ job: 'extract', status: 'completed', doctor_run_id: result.doctor_run_id });
- });
-
- test('stale and coverage metrics leave out the pages the onboard checks leave out', async () => {
- // An embed_skip page's unembedded chunk is not stale work, and a
- // quarantined entity page is outside the coverage population.
- await brain.putPage('notes/plain-example', { type: 'note', title: 'Plain', compiled_truth: 'Waiting for a vector.' });
- await installFixtureChunks(brain, 'notes/plain-example', [{ chunk_index: 0, chunk_text: 'Waiting for a vector.', chunk_source: 'compiled_truth' }]);
- await brain.putPage('notes/skipped-example', { type: 'note', title: 'Skipped', compiled_truth: 'Never embedded.', frontmatter: { embed_skip: true } });
- await installFixtureChunks(brain, 'notes/skipped-example', [{ chunk_index: 0, chunk_text: 'Never embedded.', chunk_source: 'compiled_truth' }]);
- await brain.putPage('people/hidden-example', { type: 'person', title: 'Hidden', compiled_truth: 'Quarantined.', frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'fixture' } } });
+ afterAll(async () => {
+ await teardownDB();
+ });
- expect(await captureMetric(brain, 'stale_count')).toBe(1);
- expect(await brain.countStaleChunks()).toBe(1);
- // acme-example has an inbound link, alice-example has none.
- expect(await captureMetric(brain, 'entity_link_coverage')).toBe(0.5);
+ test('an executed extract step stores its orphan delta with object-shaped details', async () => {
+ await pg.putPage('notes/kickoff-example', {
+ type: 'note', title: 'Kickoff', compiled_truth: 'Met [[people/carol-example]] and [[companies/delta-example]].',
});
+ await pg.putPage('people/carol-example', { type: 'person', title: 'Carol Example', compiled_truth: 'An engineer.' });
+ await pg.putPage('companies/delta-example', { type: 'company', title: 'Delta Example', compiled_truth: 'A company.' });
+
+ const result = await runRemediation(pg, { targetScore: 0, inlineJobs: true });
+ const step = result.submitted.find((s) => s.id === 'extract.stale');
+ expect(step?.status).toBe('completed');
+
+ // migration_impact_log is not in the E2E truncate list; scope to this run.
+ const rows = await pg.executeRaw<{
+ remediation_id: string; metric_name: string; metric_before: string; metric_after: string;
+ job_id: string; details_type: string; details: Record<string, unknown>;
+ }>(
+ `SELECT remediation_id, metric_name, metric_before, metric_after, job_id,
+ jsonb_typeof(details) AS details_type, details
+ FROM migration_impact_log
+ WHERE details->>'doctor_run_id' = $1`,
+ [result.doctor_run_id],
+ );
+ expect(rows).toHaveLength(1);
+ const [row] = rows;
+ expect(row!.remediation_id).toBe('extract.stale');
+ expect(row!.metric_name).toBe('orphan_count');
+ expect([Number(row!.metric_before), Number(row!.metric_after)]).toEqual([3, 0]);
+ expect(Number(row!.job_id)).toBe(step!.job_id!);
+ expect(row!.details_type).toBe('object');
+ expect(row!.details).toEqual({ job: 'extract', status: 'completed', doctor_run_id: result.doctor_run_id });
});
-}
+});
describe('onboard E2E — runAllOnboardChecks', () => {
test('returns all 7 check shapes', async () => {
diff --git a/test/remediation-impact-capture.test.ts b/test/remediation-impact-capture.test.ts
index f35553a17e..79944dd1e5 100644
--- a/test/remediation-impact-capture.test.ts
+++ b/test/remediation-impact-capture.test.ts
@@ -1,34 +1,40 @@
/**
- * #6109: `gbrain onboard --history` reads migration_impact_log, and
- * runRemediation is its writer. Each executed job step whose job moves a
- * tracked metric records that metric before submit and after its job is
- * terminal; a dry run, an unmapped job or a failed capture never changes the
- * step's result, and the orphan metric is get_health's orphan_pages without
- * running the full health aggregate.
+ * Remediation impact history (#6109).
*
- * Protects: onboard history reflecting what remediation actually did.
- * Fails when: the capture is unwired (history stays empty), a step writes
- * more or fewer rows than it executed, the orphan metric drifts from
- * get_health, or telemetry failure changes a job's status.
- * Seams: none; real remediation with inline jobs on PGLite (the Postgres arm
- * is test/e2e/onboard-full-flow.test.ts).
+ * `gbrain onboard --history` reads migration_impact_log. runRemediation is
+ * its writer: every executed step whose job moves a tracked metric records
+ * that metric just before its job is submitted and again once the job is
+ * terminal. Each metric must be the number the rest of the brain reports
+ * (get_health's orphan_pages, the onboard coverage checks' population, the
+ * embed worker's stale count), and history bookkeeping must never change a
+ * step's outcome.
+ *
+ * Protects: the history rows a real remediation run leaves, and the
+ * definitions of the captured metrics. Fails when the capture is unwired
+ * (history stays empty), a step writes a row it should not (dry run,
+ * unmapped job), a capture or log-write failure changes the step result, or
+ * a metric drifts from the check it is meant to measure.
+ * Seams: none; real remediation with inline jobs on PGLite. The Postgres arm
+ * of the JSONB details write is test/e2e/onboard-full-flow.test.ts.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import type { BrainEngine } from '../src/core/engine.ts';
import { runRemediation } from '../src/core/remediation/index.ts';
-import * as impactCapture from '../src/core/onboard/impact-capture.ts';
+import { makeRemediationStep } from '../src/core/remediation-step.ts';
+import { captureMetric } from '../src/core/onboard/impact-capture.ts';
+import { buildQuarantineMarker } from '../src/core/quarantine.ts';
import { runOnboard } from '../src/commands/onboard.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
let engine: PGLiteEngine;
-let version: string;
+let schemaVersion: string;
beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- version = (await engine.getConfig('version'))!;
+ schemaVersion = (await engine.getConfig('version'))!;
});
afterAll(async () => {
@@ -37,86 +43,190 @@ afterAll(async () => {
beforeEach(async () => {
await resetPgliteState(engine);
- await engine.setConfig('version', version);
+ await engine.setConfig('version', schemaVersion);
});
-async function history(brain: BrainEngine): Promise<Array<Record<string, unknown>>> {
- let out = '';
- const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => { out += String(chunk); return true; }) as never);
+interface HistoryEntry {
+ remediation_id: string;
+ metric_name: string;
+ metric_before: number | null;
+ metric_after: number | null;
+ delta: number | null;
+ applied_at: string;
+}
+
+async function onboardStdout(args: string[]): Promise<string> {
+ let captured = '';
+ const write = spyOn(process.stdout, 'write').mockImplementation(((chunk: string | Uint8Array) => {
+ captured += String(chunk);
+ return true;
+ }) as never);
try {
- await runOnboard(brain, ['--history', '--json']);
+ await runOnboard(engine, args);
} finally {
write.mockRestore();
}
- return (JSON.parse(out) as { history: Array<Record<string, unknown>> }).history;
+ return captured;
}
-/** Two unextracted pages, one linking the other: the planner adds extract.stale, which leaves no orphan pages. */
-async function seedLinkedPages(): Promise<void> {
- await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice works at [[companies/acme-example]].' });
- await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'A widget company.' });
+async function historyEntries(): Promise<HistoryEntry[]> {
+ return (JSON.parse(await onboardStdout(['--history', '--json'])) as { history: HistoryEntry[] }).history;
}
-const MAPPED_JOBS = new Set(['embed', 'embed-catch-up', 'extract', 'extract-ner', 'extract-timeline-from-meetings', 'extract-takes-from-pages']);
+async function withStderr<T>(fn: () => Promise<T>): Promise<{ result: T; stderr: string }> {
+ let stderr = '';
+ const write = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => {
+ stderr += String(chunk);
+ return true;
+ }) as never);
+ try {
+ return { result: await fn(), stderr };
+ } finally {
+ write.mockRestore();
+ }
+}
+
+/**
+ * Three unextracted pages: a note wikilinking two entities. All three are
+ * orphans until extraction runs, so the planner schedules extract.stale and
+ * its job takes the orphan count from 3 to 0.
+ */
+async function seedUnextractedNote(): Promise<void> {
+ await engine.putPage('notes/kickoff-example', {
+ type: 'note', title: 'Kickoff', compiled_truth: 'Met [[people/carol-example]] and [[companies/delta-example]].',
+ });
+ await engine.putPage('people/carol-example', { type: 'person', title: 'Carol Example', compiled_truth: 'An engineer.' });
+ await engine.putPage('companies/delta-example', { type: 'company', title: 'Delta Example', compiled_truth: 'A company.' });
+}
+
+describe('remediation writes onboard history (#6109)', () => {
+ test('an executed step records its metric before and after its job', async () => {
+ await seedUnextractedNote();
+ expect(await historyEntries()).toEqual([]);
-describe('remediation impact capture (#6109)', () => {
- test('onboard --history returns one row per executed mapped step, with the metric before and after', async () => {
- await seedLinkedPages();
const result = await runRemediation(engine, { targetScore: 0, inlineJobs: true });
- const executed = result.submitted.filter(s => s.job_id !== null);
- expect(executed.map(s => s.id)).toContain('extract.stale');
- const rows = await history(engine);
- const jobs = await engine.executeRaw<{ id: number; name: string }>('SELECT id, name FROM minion_jobs');
- const jobName = new Map(jobs.map(j => [Number(j.id), j.name]));
- expect(rows.map(r => r.remediation_id).sort()).toEqual(executed.filter(s => MAPPED_JOBS.has(jobName.get(s.job_id!)!)).map(s => s.id).sort());
- expect(rows.find(r => r.remediation_id === 'extract.stale')).toMatchObject({ metric_name: 'orphan_count', metric_before: 2, metric_after: 0, delta: -2 });
+ const step = result.submitted.find((s) => s.id === 'extract.stale');
+ expect(step?.status).toBe('completed');
+
+ const entries = await historyEntries();
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({
+ remediation_id: 'extract.stale', metric_name: 'orphan_count', metric_before: 3, metric_after: 0, delta: -3,
+ });
+ expect(entries[0]!.applied_at).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/);
+ expect(await onboardStdout(['--history'])).toBe(
+ `Onboard history (last 1):\n ${entries[0]!.applied_at} extract.stale orphan_count: 3 → 0 (-3)\n`);
+
+ const [row] = await engine.executeRaw<{ job_id: number; idempotency_key: string; details: Record<string, unknown> }>(
+ 'SELECT job_id, idempotency_key, details FROM migration_impact_log');
+ const [job] = await engine.executeRaw<{ idempotency_key: string }>(
+ 'SELECT idempotency_key FROM minion_jobs WHERE id = $1', [step!.job_id]);
+ expect(Number(row!.job_id)).toBe(step!.job_id!);
+ expect(row!.idempotency_key).toBe(job!.idempotency_key);
+ expect(row!.details).toEqual({ job: 'extract', status: 'completed', doctor_run_id: result.doctor_run_id });
+ });
+
+ test("a step whose job moves no tracked metric records nothing, even once it is terminal", async () => {
+ await seedUnextractedNote();
+ const unmapped = makeRemediationStep({
+ id: 'onboard.unmapped-example', job: 'unify-types', params: { apply: false },
+ severity: 'low', est_seconds: 30, est_usd_cost: 0, protected: true, rationale: 'synthetic unmapped job',
+ });
+ const { result } = await withStderr(() => runRemediation(engine, { targetScore: 0, inlineJobs: true, extraRemediations: [unmapped] }));
+ const unmappedStep = result.submitted.find((s) => s.id === 'onboard.unmapped-example');
+ expect(unmappedStep?.job_id).not.toBeNull();
+ expect(['completed', 'failed', 'dead']).toContain(unmappedStep!.status);
+ expect((await historyEntries()).map((e) => e.remediation_id)).toEqual(['extract.stale']);
});
- test('a dry run and an unmapped job record nothing', async () => {
- await seedLinkedPages();
+ test('a dry run records nothing', async () => {
+ await seedUnextractedNote();
const dry = await runRemediation(engine, { targetScore: 0, dryRun: true });
- expect(dry.submitted.every(s => s.status === 'dry_run')).toBe(true);
- expect(await impactCapture.startStepImpact(engine, { id: 'x.unmapped', job: 'reindex-frontmatter', idempotency_key: 'k', params: {} })).toBeNull();
- expect(await history(engine)).toEqual([]);
+ expect(dry.submitted.map((s) => s.status)).toContain('dry_run');
+ expect(await historyEntries()).toEqual([]);
});
- test('a failed capture or log write never changes the step result', async () => {
- await seedLinkedPages();
- const failing = new Proxy(engine, {
- get(target, prop) {
- if (prop === 'executeRaw') return async (sql: string, params?: unknown[]) => {
- if (sql.includes('migration_impact_log') || sql.includes('FROM links l JOIN pages src')) throw new Error('telemetry unavailable');
- return target.executeRaw(sql, params as never);
- };
- const value = Reflect.get(target, prop);
- return typeof value === 'function' ? value.bind(target) : value;
- },
- });
- const errors = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);
+ test('an unreadable metric still records the attempt, with unknown values', async () => {
+ await seedUnextractedNote();
+ const orphans = spyOn(engine, 'findOrphanPages').mockRejectedValue(new Error('synthetic read failure'));
+ try {
+ const { result, stderr } = await withStderr(() => runRemediation(engine, { targetScore: 0, inlineJobs: true }));
+ expect(result.submitted.find((s) => s.id === 'extract.stale')?.status).toBe('completed');
+ expect(stderr).toContain('[impact-capture] failed to capture orphan_count: synthetic read failure');
+ } finally {
+ orphans.mockRestore();
+ }
+ expect(await historyEntries()).toMatchObject([
+ { remediation_id: 'extract.stale', metric_before: null, metric_after: null, delta: null },
+ ]);
+ });
+
+ test('a failed history write leaves the step completed', async () => {
+ await seedUnextractedNote();
+ // A real write failure: every new history row violates this constraint.
+ await engine.executeRaw('ALTER TABLE migration_impact_log ADD CONSTRAINT impact_log_rejects_writes CHECK (false) NOT VALID');
try {
- const result = await runRemediation(failing, { targetScore: 0, inlineJobs: true });
- expect(result.submitted.find(s => s.id === 'extract.stale')?.status).toBe('completed');
+ const { result, stderr } = await withStderr(() => runRemediation(engine, { targetScore: 0, inlineJobs: true }));
+ expect(result.submitted.find((s) => s.id === 'extract.stale')?.status).toBe('completed');
+ expect(stderr).toContain('[impact-capture] failed to write log row for extract.stale');
} finally {
- errors.mockRestore();
+ await engine.executeRaw('ALTER TABLE migration_impact_log DROP CONSTRAINT impact_log_rejects_writes');
}
- expect(await history(engine)).toEqual([]);
+ expect(await historyEntries()).toEqual([]);
});
+});
+
+describe('captured metrics match the numbers the brain reports (#6109)', () => {
+ test("orphan_count is get_health's orphan_pages, read without get_health", async () => {
+ await engine.putPage('notes/alone-example', { type: 'note', title: 'Alone', compiled_truth: 'Nothing links here.' });
+ await engine.putPage('notes/outbound-example', { type: 'note', title: 'Outbound', compiled_truth: 'Links out.' });
+ await engine.putPage('notes/target-example', { type: 'note', title: 'Target', compiled_truth: 'Linked from outbound.' });
+ await engine.putPage('notes/ghost-linked-example', { type: 'note', title: 'Ghost linked', compiled_truth: 'Only a deleted page links here.' });
+ await engine.putPage('notes/ghost-example', { type: 'note', title: 'Ghost', compiled_truth: 'Soft-deleted.' });
+ await engine.putPage('templates/new-person', { type: 'note', title: 'Template', compiled_truth: 'Excluded by the orphan policy.' });
+ await engine.putPage('notes/hidden-example', {
+ type: 'note', title: 'Hidden', compiled_truth: 'Quarantined.',
+ frontmatter: { quarantine: buildQuarantineMarker('junk_pattern', 'synthetic fixture') },
+ });
+ await engine.addLink('notes/outbound-example', 'notes/target-example', '', 'mentions', 'manual');
+ await engine.addLink('notes/ghost-example', 'notes/ghost-linked-example', '', 'mentions', 'manual');
+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/ghost-example'`);
- test('orphan_count equals get_health orphan_pages without running get_health', async () => {
- await seedLinkedPages();
- await engine.putPage('notes/lonely-example', { type: 'note', title: 'Lonely', compiled_truth: 'No links.' });
- await engine.putPage('notes/quarantined-example', { type: 'note', title: 'Hidden', compiled_truth: 'Junk.', frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'fixture' } } });
- await engine.putPage('templates/new-person', { type: 'note', title: 'Template', compiled_truth: 'A template page.' });
- await engine.putPage('notes/gone-example', { type: 'note', title: 'Gone', compiled_truth: 'Links to [[notes/kept-example]].' });
- await engine.putPage('notes/kept-example', { type: 'note', title: 'Kept', compiled_truth: 'Only a deleted page links here.' });
- await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type)
- SELECT f.id, t.id, 'mention' FROM pages f, pages t WHERE f.slug = 'notes/gone-example' AND t.slug = 'notes/kept-example'`);
- await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/gone-example'`);
const health = spyOn(engine, 'getHealth');
- const orphans = await impactCapture.captureMetric(engine, 'orphan_count');
- expect(health).not.toHaveBeenCalled();
- health.mockRestore();
+ let orphans: number | null;
+ try {
+ orphans = await captureMetric(engine, 'orphan_count');
+ expect(health).not.toHaveBeenCalled();
+ } finally {
+ health.mockRestore();
+ }
+ // alone + ghost-linked; the linked pair, the template and the quarantined page are not orphans.
+ expect(orphans).toBe(2);
expect(orphans).toBe((await engine.getHealth()).orphan_pages);
- expect(orphans).toBeGreaterThan(2);
+ });
+
+ test("coverage metrics leave out the entity pages the onboard checks leave out", async () => {
+ const quarantine = { quarantine: buildQuarantineMarker('junk_pattern', 'synthetic fixture') };
+ await engine.putPage('notes/source-example', { type: 'note', title: 'Source', compiled_truth: 'A note.' });
+ await engine.putPage('people/linked-example', { type: 'person', title: 'Linked', compiled_truth: 'Visible.' });
+ await engine.putPage('people/plain-example', { type: 'person', title: 'Plain', compiled_truth: 'Visible.' });
+ await engine.putPage('people/hidden-example', { type: 'person', title: 'Hidden', compiled_truth: 'Quarantined.', frontmatter: quarantine });
+ await engine.addLink('notes/source-example', 'people/linked-example', '', 'mentions', 'manual');
+ await engine.addLink('notes/source-example', 'people/hidden-example', '', 'mentions', 'manual');
+ await engine.addTimelineEntry('people/linked-example', { date: '2026-01-02', source: 'synthetic', summary: 'Met' });
+ await engine.addTimelineEntry('people/hidden-example', { date: '2026-01-02', source: 'synthetic', summary: 'Met' });
+
+ expect(await captureMetric(engine, 'entity_link_coverage')).toBe(0.5);
+ expect(await captureMetric(engine, 'timeline_coverage')).toBe(0.5);
+ });
+
+ test("stale_count is the embed worker's stale count, so embed_skip chunks are not stale", async () => {
+ await engine.putPage('notes/waiting-example', { type: 'note', title: 'Waiting', compiled_truth: 'Needs a vector.' });
+ await installFixtureChunks(engine, 'notes/waiting-example', [{ chunk_index: 0, chunk_text: 'Needs a vector.', chunk_source: 'compiled_truth' }]);
+ await engine.putPage('notes/skip-example', { type: 'note', title: 'Skip', compiled_truth: 'Never embedded.', frontmatter: { embed_skip: true } });
+ await installFixtureChunks(engine, 'notes/skip-example', [{ chunk_index: 0, chunk_text: 'Never embedded.', chunk_source: 'compiled_truth' }]);
+
+ expect(await engine.countStaleChunks()).toBe(1);
+ expect(await captureMetric(engine, 'stale_count')).toBe(1);
});
});