Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(onboard): record remediation impact so onboard --history shows it (#6109)
time-attack93719179f3b9
diff --git a/TODOS.md b/TODOS.mdindex f2faee36b5..2b81ad07b1 100644--- a/TODOS.md+++ b/TODOS.md@@ -497,8 +497,8 @@ 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.-- [ ] **P1 — `gbrain onboard --history` always returns nothing.**- **What:** `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.+- [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`.+ **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.- [ ] **P2 — Progressive-batch rewire or retire.**diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex a9cdc8eb6c..d69bb72fde 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -60,7 +60,6 @@ const PERMITTED_TEST_ONLY = [{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },- { path: 'src/core/onboard/impact-capture.ts', reason: 'held: sole writer of migration_impact_log, which the shipped `gbrain onboard --history` reads; wire-or-retract is a product decision' },{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },{ path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },{ path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },diff --git a/src/commands/onboard.ts b/src/commands/onboard.tsindex 32bb36a889..9eb83e2a30 100644--- a/src/commands/onboard.ts+++ b/src/commands/onboard.ts@@ -80,7 +80,7 @@ export async function runOnboard(engine: BrainEngine, args: string[]): Promise<vdelta: (r.metric_before === null || r.metric_after === null)? null: Number(r.metric_after) - Number(r.metric_before),- applied_at: r.applied_at,+ applied_at: new Date(r.applied_at).toISOString(),}));if (jsonOutput) {process.stdout.write(JSON.stringify({diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex 8c70a50bc4..2d5a3f0604 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -58,7 +58,8 @@ async function safeCount(engine: BrainEngine, sql: string, params: unknown[] = [}}-const VISIBLE_ENTITY_PREDICATE = `p.type IN ('person', 'company', 'organization', 'entity')+/** 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')AND p.deleted_at IS NULLAND ${QUARANTINE_FILTER_FRAGMENT}`;diff --git a/src/core/onboard/impact-capture.ts b/src/core/onboard/impact-capture.tsindex f1f622af78..b673fd7b5a 100644--- a/src/core/onboard/impact-capture.ts+++ b/src/core/onboard/impact-capture.ts@@ -3,20 +3,33 @@// 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 onboard-// remediation step so `gbrain onboard --history` can show "you reduced-// orphans 47% (88% → 41%)".+// 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.//-// Best-effort per A17: a stat-query throw must NOT block the extraction-// itself. The wrapper logs failures to stderr and records-// metric_before/after = null when the capture failed.+// 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`.+//+// Best-effort per A17: a stat-query throw must NOT block the remediation.+// Failures log to stderr and record metric_before/after = null.//// Attribution columns per A25 + codex finding #10: every row carries-// job_id (FK to minion_jobs), source_id, brain_id, started_at,-// idempotency_key so concurrent onboard/autopilot/manual runs can't-// misattribute deltas to the wrong remediation.+// 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.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';export type MetricName =| 'orphan_count'@@ -35,6 +48,16 @@ export interface ImpactAttribution {applied_by?: string;}+/** The metric each remediation job moves. A step whose job is not listed writes no row. */+const JOB_METRICS: Readonly<Record<string, MetricName>> = {+ embed: 'stale_count',+ 'embed-catch-up': 'stale_count',+ extract: 'orphan_count',+ 'extract-ner': 'entity_link_coverage',+ 'extract-timeline-from-meetings': 'timeline_coverage',+ 'extract-takes-from-pages': 'takes_count',+};+/*** Pure-ish: returns the current numeric value for `metric`. Returns null* on any throw (best-effort capture per A17).@@ -45,47 +68,34 @@ export async function captureMetric(): Promise<number | null> {try {switch (metric) {- case 'stale_count': {- const rows = await engine.executeRaw<{ count: string | number }>(- `SELECT COUNT(*) AS count FROM content_chunks WHERE embedding IS NULL`,- );- return rows.length > 0 ? Number(rows[0].count) : 0;- }+ case 'stale_count':+ return await engine.countStaleChunks();case 'orphan_count': {- const rows = await engine.executeRaw<{ count: string | number }>(- `SELECT COUNT(*) AS count- FROM pages p- WHERE p.deleted_at IS NULL- AND NOT EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`,- );- return rows.length > 0 ? Number(rows[0].count) : 0;+ // 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);}case 'entity_link_coverage':case 'timeline_coverage': {- // Compute as a fraction of entity pages with the relevant feature.- const total = await engine.executeRaw<{ count: string | number }>(- `SELECT COUNT(*) AS count FROM pages- WHERE type IN ('person', 'company', 'organization', 'entity')- AND deleted_at IS NULL`,- );- const totalN = total.length > 0 ? Number(total[0].count) : 0;- if (totalN === 0) return 1; // vacuous truth — empty brain has full coverage- if (metric === 'entity_link_coverage') {- const withLinks = await engine.executeRaw<{ count: string | number }>(- `SELECT COUNT(*) AS count FROM pages p- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = p.id)`,- );- return withLinks.length > 0 ? Number(withLinks[0].count) / totalN : 0;- }- const withTimeline = await engine.executeRaw<{ count: string | number }>(- `SELECT COUNT(*) AS count FROM pages p- WHERE p.type IN ('person', 'company', 'organization', 'entity')- AND p.deleted_at IS NULL- AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id)`,+ // 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}`,);- return withTimeline.length > 0 ? Number(withTimeline[0].count) / totalN : 0;+ const total = Number(row?.total ?? 0);+ if (total === 0) return 1; // vacuous truth — empty brain has full coverage+ return Number(row?.matched ?? 0) / total;}case 'takes_count': {const rows = await engine.executeRaw<{ count: string | number }>(@@ -143,46 +153,38 @@ export async function writeImpactLogRow(}/**- * Convenience wrapper: capture-before → run → capture-after → write log.- * The runner itself does the extraction; this fn handles the bookkeeping.+ * 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 runner. A null before/after- * is recorded; the row still lands so downstream consumers see a- * "ran but impact unknown" entry.+ * 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.*/-export async function withImpactCapture<T>(+export async function startStepImpact(engine: BrainEngine,- attribution: ImpactAttribution,- metric: MetricName,- runner: () => Promise<T>,- details?: Record<string, unknown>,-): Promise<T> {+ 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;const startedAt = new Date().toISOString();const before = await captureMetric(engine, metric);- let result: T;- try {- result = await runner();- } catch (err) {- // Capture "after" even on failure so the log row reflects the attempt.- const afterOnFail = await captureMetric(engine, metric);+ return async (jobId, details) => {+ const after = await captureMetric(engine, metric);+ const sourceId = step.params.sourceId;await writeImpactLogRow(engine,- { ...attribution, started_at: startedAt },+ {+ remediation_id: step.id,+ job_id: jobId,+ started_at: startedAt,+ idempotency_key: step.idempotency_key,+ ...(typeof sourceId === 'string' ? { source_id: sourceId } : {}),+ },metric,before,- afterOnFail,- { ...(details ?? {}), error: err instanceof Error ? err.message : String(err) },+ after,+ { job: step.job, ...details },);- throw err;- }- const after = await captureMetric(engine, metric);- await writeImpactLogRow(- engine,- { ...attribution, started_at: startedAt },- metric,- before,- after,- details,- );- return result;+ };}diff --git a/src/core/remediation/run.ts b/src/core/remediation/run.tsindex bd1e59866d..45102c0945 100644--- a/src/core/remediation/run.ts+++ b/src/core/remediation/run.ts@@ -257,6 +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 isPGLite = engine.kind === 'pglite';const queue = new MinionQueue(engine);const waitStep = stepWaiter(engine, queue, opts.inlineJobs === true);@@ -384,6 +385,7 @@ export async function runRemediation(hooks.onStepStart?.(stepCount, totalSteps, step);try {+ const finishImpact = await startStepImpact(engine, step);const isProtected = !!step.protected;const submitWith = (key: string) =>queue.add(@@ -421,9 +423,8 @@ export async function runRemediation(const terminal = await waitStep(job.id, { pollMs: isPGLite ? 250 : 1000, timeoutMs: (step.est_seconds + 60) * 1000 });submittedResult.status = terminal.status;- if (terminal.status !== 'completed') {- abortedIds.add(step.id);- }+ await finishImpact?.(job.id, { status: terminal.status, doctor_run_id: doctorRunId });+ if (terminal.status !== 'completed') abortedIds.add(step.id);hooks.onStepEnd?.(submittedResult);} catch (e) {if (e instanceof BudgetExhausted) {diff --git a/test/e2e/onboard-full-flow.test.ts b/test/e2e/onboard-full-flow.test.tsindex 88477ce4ba..365888f4c8 100644--- a/test/e2e/onboard-full-flow.test.ts+++ b/test/e2e/onboard-full-flow.test.ts@@ -3,18 +3,25 @@// 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+// - 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// - The runRemediation library refuses --auto without --max-usd// - The onboard CLI gates work as documented//-// Full DATABASE_URL-gated end-to-end (real Postgres, actual extractions-// firing through Minion handlers) is deferred to a v0.42.1 follow-up-// once the Minion worker test harness lands the per-handler stub seam.+// 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+// 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 { computeRemediationPlan } from '../../src/core/remediation/index.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 { hasDatabase, setupDB, teardownDB } from './helpers.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';@@ -53,6 +60,79 @@ 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);++ const result = await runRemediation(brain, { targetScore: 0, inlineJobs: true });+ const step = result.submitted.find((s) => s.id === 'extract.stale');+ expect(step?.status).toBe('completed');++ 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' } } });++ 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);+ });+ });+}+describe('onboard E2E — runAllOnboardChecks', () => {test('returns all 7 check shapes', async () => {// v0.42 (T13-T15): type-unification cathedral added 3 onboard checksdiff --git a/test/remediation-impact-capture.test.ts b/test/remediation-impact-capture.test.tsnew file mode 100644index 0000000000..f35553a17e--- /dev/null+++ b/test/remediation-impact-capture.test.ts@@ -0,0 +1,122 @@+/**+ * #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.+ *+ * 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).+ */+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 { runOnboard } from '../src/commands/onboard.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++let engine: PGLiteEngine;+let version: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ version = (await engine.getConfig('version'))!;+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', version);+});++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);+ try {+ await runOnboard(brain, ['--history', '--json']);+ } finally {+ write.mockRestore();+ }+ return (JSON.parse(out) as { history: Array<Record<string, unknown>> }).history;+}++/** 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.' });+}++const MAPPED_JOBS = new Set(['embed', 'embed-catch-up', 'extract', 'extract-ner', 'extract-timeline-from-meetings', 'extract-takes-from-pages']);++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 });+ });++ test('a dry run and an unmapped job record nothing', async () => {+ await seedLinkedPages();+ 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([]);+ });++ 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);+ try {+ const result = await runRemediation(failing, { targetScore: 0, inlineJobs: true });+ expect(result.submitted.find(s => s.id === 'extract.stale')?.status).toBe('completed');+ } finally {+ errors.mockRestore();+ }+ expect(await history(engine)).toEqual([]);+ });++ 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();+ expect(orphans).toBe((await engine.getHealth()).orphan_pages);+ expect(orphans).toBeGreaterThan(2);+ });+});