Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

segmented maintenance: integrity batch via engine, probe tests (wip)

garrytan1b56756e4f00
diff --git a/src/commands/integrity.ts b/src/commands/integrity.ts
index c267c078af..ab7fdb0c7b 100644
--- a/src/commands/integrity.ts
+++ b/src/commands/integrity.ts
@@ -30,7 +30,6 @@ import { dirname } from 'path';
import { loadConfig, toEngineConfig, gbrainPath } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
import type { BrainEngine } from '../core/engine.ts';
-import * as db from '../core/db.ts';
import { BrainWriter } from '../core/output/writer.ts';
import {
getDefaultRegistry,
@@ -170,7 +169,7 @@ export interface IntegritySkippedPage { slug: string; source_id: string; reason:
* with fence state and line numbers carried across blocks, so it gets the
* hits the same text held as one string gets.
*/
-export async function integrityHitsOf(engine: BrainEngine,
+async function integrityHitsOf(engine: BrainEngine,
page: { id: number; slug: string; source_id: string; body_storage?: BodyStorage | null; compiled_truth?: string | null }): Promise<{ bare: BareTweetHit[]; external: ExternalLinkHit[] }> {
if (!isSegmentedPage(page)) {
const text = page.compiled_truth ?? '';
@@ -388,9 +387,8 @@ export async function scanIntegrity(
// Fast path: single SQL query instead of N sequential getPage() calls.
// Eliminates ~500 round-trips through PgBouncer that caused doctor to
- // timeout on transaction-mode pooling. Postgres-only: PGLite has no
- // postgres.js connection, so the gate keeps the GBRAIN_DEBUG fallback
- // log clean for real Postgres errors instead of expected PGLite skips.
+ // timeout on transaction-mode pooling. Postgres-only: PGLite runs in
+ // process, where the sequential walk costs no network round-trips.
if (batchLoad && limit !== Infinity && engine.kind === 'postgres') {
try {
return await scanIntegrityBatch(engine, limit, typeFilter);
@@ -450,18 +448,19 @@ export async function scanIntegrity(
/**
* Batch-load integrity scan: fetches all candidate pages in a single SQL
* query, then scans in-memory. Reduces PgBouncer round-trips from ~500 to 1.
+ * A segmented page's body is read block by block from the same engine.
*/
async function scanIntegrityBatch(
engine: BrainEngine,
limit: number,
typeFilter?: string,
): Promise<IntegrityScanResult> {
- const sql = db.getConnection();
- const typeCondition = typeFilter ? sql`AND slug LIKE ${typeFilter + '/%'}` : sql``;
+ const params: unknown[] = [limit];
+ const typeCondition = typeFilter ? `AND slug LIKE $${params.push(`${typeFilter}/%`)}` : '';
// Boolean validate is the documented contract; stringly-typed 'false' (quoted
// YAML) diverges from the sequential path's strict === false check. Intentional
// — gbrain lint should reject stringly-typed validate at write time.
- const validateCondition = sql`AND (frontmatter->>'validate' IS NULL OR frontmatter->>'validate' != 'false')`;
+ const validateCondition = `AND (frontmatter->>'validate' IS NULL OR frontmatter->>'validate' != 'false')`;
// v0.32.8: scan ONE row per (source_id, slug) pair, not one per slug.
// Pre-fix used DISTINCT ON (slug) which collapsed multi-source rows into
@@ -472,13 +471,13 @@ async function scanIntegrityBatch(
// sees a soft-deleted page, so the batch must not either — otherwise the
// sampled doctor check reports hits from tombstones and, once they
// outnumber `limit`, stops reaching live pages.
- const rows = await sql`
+ const rows = await engine.executeRaw<Record<string, unknown>>(`
SELECT id, source_id, slug, compiled_truth, body_storage
FROM pages
WHERE deleted_at IS NULL ${typeCondition} ${validateCondition}
ORDER BY source_id, slug
- LIMIT ${limit}
- `;
+ LIMIT $1
+ `, params);
const bareHits: BareTweetHit[] = [];
const externalHits: ExternalLinkHit[] = [];
diff --git a/src/commands/reconcile-links.ts b/src/commands/reconcile-links.ts
index 02223b6199..1ac9c7c043 100644
--- a/src/commands/reconcile-links.ts
+++ b/src/commands/reconcile-links.ts
@@ -50,7 +50,7 @@ export interface ReconcileLinksResult {
* Code refs of a page's `${compiled_truth}\n${timeline}`, first occurrence of each path, in text order. A segmented
* page is read a block of lines at a time; `index` stays an offset into the joined text.
*/
-export async function pageCodeRefs(engine: BrainEngine, page: Page): Promise<CodeRef[]> {
+async function pageCodeRefs(engine: BrainEngine, page: Page): Promise<CodeRef[]> {
if (!isSegmentedPage(page)) return extractCodeRefs((page.compiled_truth || '') + '\n' + (page.timeline || ''));
const seen = new Set<string>();
const refs: CodeRef[] = [];
diff --git a/test/large-pages/segmented-maintenance-commands.test.ts b/test/large-pages/segmented-maintenance-commands.test.ts
new file mode 100644
index 0000000000..2addadfaeb
--- /dev/null
+++ b/test/large-pages/segmented-maintenance-commands.test.ts
@@ -0,0 +1,173 @@
+/**
+ * Wave B PR 2 lane 2r-maint: whole-brain maintenance commands over a
+ * segmented page (compiled_truth and timeline NULL, body in segments).
+ *
+ * 1. Protects: `gbrain integrity check` (sequential and the Postgres batch
+ * path) and `integrity auto` read a segmented page block by block and give
+ * the hits the same text stored inline gives (line numbers, fenced lines
+ * skipped); `reconcile-links` finds the same code refs; `reindex --aliases`
+ * writes the same alias rows (its body read back as strings within the
+ * single-string ceiling); `quarantine scan` lists the segmented page it
+ * does not re-check. None of them aborts at the segmented page.
+ * 2. Fails when: a command reads `page.compiled_truth` of a segmented page
+ * (the throwing getter aborts the whole run), a streamed scan loses a hit
+ * at a block boundary, restarts fence state or line numbers per block, or
+ * a command skips a segmented page without saying so.
+ * 3. Why existing coverage misses it: these commands' tests write inline
+ * pages only.
+ * Seams: none; the CLI arm runs the real `gbrain integrity auto` in a child.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
+import { scanIntegrity } from '../../src/commands/integrity.ts';
+import { runReconcileLinks } from '../../src/commands/reconcile-links.ts';
+import { extractCodeRefs } from '../../src/core/link-extraction.ts';
+import { runReindexAliases } from '../../src/commands/reindex-aliases.ts';
+import { runQuarantine } from '../../src/commands/quarantine.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { runCli } from '../helpers/cli-spawn.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-maint-'));
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const engines: Array<{ engine: BrainEngine; config: Record<string, string> }> = [];
+let diskEngine: PGLiteEngine;
+const diskPath = join(home, 'disk-brain');
+let closePostgres: (() => Promise<void>) | undefined;
+
+const INLINE = 'people/inline-twin';
+const SEGMENTED = 'people/segmented-twin';
+
+/** About 1.3 MiB: integrity hits, external links, code refs and an alias declaration early, mid-body (one inside a code fence) and late. */
+function twinPage(): string {
+ const early = 'Alice Example tweeted about pricing, see [docs](https://example.com/early) and src/core/sync.ts:42.';
+ const middle = '```text\nShe tweeted about the fenced example, [x](https://example.com/fenced) in lib/fenced.py\n```\n\n'
+ + 'Bob posted on X about the launch: [mid](https://example.com/mid) lib/mid.py and [cited](https://x.com/a/status/1) in a tweet.';
+ const late = 'Carol wrote a tweet about hiring. See [late](https://example.com/late) and src/core/late-ref.ts:7.\n\nAlice Example, also known as Ally Sample, joined the board.';
+ return `---\ntype: person\ntitle: Alice Example\naliases: [Al Example]\n---\n\n${early}\n\n${conversationBody(600_000, { seed: 5 })}\n\n${middle}\n\n`
+ + `${conversationBody(650_000, { seed: 6 })}\n\n${late}\n\n<!-- timeline -->\n\n- **2026-01-10** | Met about scripts/tl-ref.sh\n`;
+}
+
+async function twins(engine: BrainEngine): Promise<void> {
+ const content = twinPage();
+ await engine.setConfig('pages.segmented_storage', 'off');
+ expect(await importFromContent(engine, INLINE, content, { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ await engine.setConfig('pages.segmented_storage', 'on');
+ expect(await importFromContent(engine, SEGMENTED, content, { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ const rows = await engine.executeRaw<{ slug: string; body_storage: string }>('SELECT slug, body_storage FROM pages WHERE slug = ANY($1::text[]) ORDER BY slug', [[INLINE, SEGMENTED]]);
+ expect(rows).toEqual([{ slug: INLINE, body_storage: 'inline' }, { slug: SEGMENTED, body_storage: 'segmented' }]);
+}
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema();
+ engines.push({ engine: lite, config: {} });
+ diskEngine = new PGLiteEngine(); await diskEngine.connect({ database_path: diskPath }); await diskEngine.initSchema();
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push({ engine: pg.engine, config: { engine: 'postgres', database_url: pg.databaseUrl } });
+ closePostgres = pg.close;
+ }
+ await withEnv(env, async () => {
+ for (const { engine } of engines) await twins(engine);
+ await twins(diskEngine);
+ });
+ await diskEngine.disconnect();
+ engines[0]!.config = { engine: 'pglite', database_path: diskPath };
+}, 300_000);
+
+afterAll(async () => {
+ await withEnv(env, async () => {
+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await diskEngine.disconnect();
+ await closePostgres?.();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function capture(fn: () => Promise<unknown>): Promise<string> {
+ const orig = console.log;
+ const lines: string[] = [];
+ console.log = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };
+ try { await fn(); } finally { console.log = orig; }
+ return lines.join('\n');
+}
+
+const of = <T extends { slug: string }>(hits: T[], slug: string) => hits.filter(h => h.slug === slug).map(({ slug: _slug, ...rest }) => rest);
+
+describe('maintenance commands over a segmented page', () => {
+ test('integrity check: the segmented twin gets the inline twin\'s hits, read block by block (sequential and batch paths)', async () => withEnv(env, async () => {
+ for (const { engine } of engines) {
+ for (const limit of [Infinity, 500]) {
+ const before = { ...segmentedPassWork };
+ const res = await scanIntegrity(engine, { limit });
+ expect(res.skipped).toEqual([]);
+ const bare = of(res.bareHits, INLINE), external = of(res.externalHits, INLINE);
+ expect(bare.map(h => h.phrase)).toEqual(['tweeted about', 'wrote a tweet']);
+ expect(external.map(h => h.url)).toEqual(['https://example.com/early', 'https://example.com/mid', 'https://x.com/a/status/1', 'https://example.com/late']);
+ expect(bare.at(-1)!.line).toBeGreaterThan(5_000);
+ expect(of(res.bareHits, SEGMENTED)).toEqual(bare);
+ expect(of(res.externalHits, SEGMENTED)).toEqual(external);
+ expect(segmentedPassWork.blocks - before.blocks).toBeGreaterThan(1_000_000);
+ }
+ }
+ }), 300_000);
+
+ test('integrity auto --dry-run: the CLI walks past the segmented page and counts its hits like the inline twin\'s', async () => {
+ for (const { config } of engines) {
+ const cliHome = mkdtempSync(join(home, 'cli-'));
+ mkdirSync(join(cliHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(cliHome, '.gbrain', 'config.json'), JSON.stringify({ ...config, embedding_disabled: true }));
+ const out = await runCli(['integrity', 'auto', '--dry-run', '--skip-urls', '--fresh'], { home: cliHome, timeoutMs: 180_000 });
+ expect({ exit: out.exitCode, stderr: out.exitCode ? out.stderr : '' }).toEqual({ exit: 0, stderr: '' });
+ expect(out.stdout).toContain('Pages processed: 2');
+ expect(out.stdout).toContain('Skipped (<0.5): 4');
+ expect(out.stdout).not.toContain('Pages not scanned');
+ }
+ }, 600_000);
+
+ test('reconcile-links: the segmented twin yields the inline twin\'s code refs and the walk completes', async () => withEnv(env, async () => {
+ for (const { engine } of engines) {
+ const inline = (await engine.getPage(INLINE, { sourceId: 'default' }))!;
+ const expected = extractCodeRefs(`${inline.compiled_truth}\n${inline.timeline}`);
+ expect(expected.map(ref => ref.path)).toEqual(['src/core/sync.ts', 'lib/fenced.py', 'lib/mid.py', 'src/core/late-ref.ts', 'scripts/tl-ref.sh']);
+ const dry = await capture(() => runReconcileLinks(engine, { dryRun: true }).then(r => console.log(JSON.stringify(r))));
+ expect(JSON.parse(dry)).toMatchObject({ status: 'ok', codeRefsFound: 2 * expected.length });
+ expect(JSON.parse(dry).skipped).toBeUndefined();
+ const applied = await capture(() => runReconcileLinks(engine).then(r => console.log(JSON.stringify(r))));
+ expect(JSON.parse(applied)).toMatchObject({ status: 'ok', edgesAttempted: 2 * expected.length });
+ }
+ }), 300_000);
+
+ test('reindex --aliases: the segmented twin gets the inline twin\'s alias rows, declared ones included', async () => withEnv(env, async () => {
+ for (const { engine } of engines) {
+ const out = await capture(() => runReindexAliases(engine, ['--source', 'default', '--json']));
+ const result = JSON.parse(out);
+ expect(result.skipped).toBeUndefined();
+ expect(result.body_not_scanned).toBeUndefined();
+ const aliases = async (slug: string) => (await engine.executeRaw<{ alias_norm: string; origin: string }>(
+ 'SELECT alias_norm, origin FROM page_aliases WHERE source_id=$1 AND slug=$2 ORDER BY origin, alias_norm', ['default', slug]));
+ const inline = await aliases(INLINE);
+ expect(inline.map(a => a.origin)).toContain('declared');
+ expect(inline.map(a => a.origin)).toContain('frontmatter');
+ expect(await aliases(SEGMENTED)).toEqual(inline);
+ }
+ }), 300_000);
+
+ test('quarantine scan: the segmented page is listed as not re-checked and the scan goes on', async () => withEnv(env, async () => {
+ for (const { engine } of engines) {
+ for (const args of [['scan', '--json'], ['scan', '--apply', '--no-embed', '--json']]) {
+ const result = JSON.parse(await capture(() => runQuarantine(engine, args)));
+ expect(result.scanned).toBe(2);
+ expect(result.skipped).toEqual([{ slug: SEGMENTED, source_id: 'default', reason: 'page_body_segmented', message: expect.stringContaining('not re-checked') }]);
+ }
+ }
+ }), 300_000);
+});
diff --git a/test/large-pages/segmented-repair-scans.test.ts b/test/large-pages/segmented-repair-scans.test.ts
new file mode 100644
index 0000000000..8412f56dfd
--- /dev/null
+++ b/test/large-pages/segmented-repair-scans.test.ts
@@ -0,0 +1,199 @@
+/**
+ * Wave B PR 2 lane 2r-maint: the repair kinds and the doctor check whose scans
+ * read a page's body columns straight from SQL, against a segmented page
+ * (compiled_truth and timeline NULL, body in segments).
+ *
+ * 1. Protects: `gbrain repair timeline` (preview and apply) never crashes on a
+ * segmented page carrying database-only timeline rows: it repairs the
+ * inline pages and reports the segmented page as a residual (count + slug),
+ * and doctor timeline_history counts it separately without recommending a
+ * repair that cannot clear it. A per-item `page_body_segmented` refusal is
+ * recorded in failed[] and the run goes on. timeline-comments no longer
+ * plans an item it cannot apply (its apply aborted the run), and
+ * connector-fences, split-facts and conversation-labels report the
+ * segmented pages their SQL filters silently skipped.
+ * 2. Fails when: a scan reads `p.compiled_truth.length` of a segmented row,
+ * a segmented page is planned as an item whose apply refuses, or a scan
+ * drops a segmented page it should have handled without saying so.
+ * 3. Why existing coverage misses it: every repair test writes inline pages.
+ * Seams: none.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { upsertFactRow } from '../../src/core/facts-fence.ts';
+import { resolveRepairScope, runRepair, type RepairHandler } from '../../src/core/repair/core.ts';
+import { repairRunner } from '../../src/core/repair/registry.ts';
+import { timelineRepair } from '../../src/core/repair/timeline.ts';
+import { timelineHistoryCheck } from '../../src/commands/doctor/checks/timeline-history.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-repair-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const logger = { info() {}, warn() {}, error() {} };
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+
+beforeAll(async () => {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) await engine.setConfig('pages.segmented_storage', 'on');
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv(env, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+const ctx = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger }) as never;
+const fence = (rowNum: number, claim: string) => upsertFactRow('', { rowNum, claim, kind: 'fact', visibility: 'world', confidence: 1, notability: 'medium', source: 'fixture' }).body;
+
+async function source(engine: BrainEngine, id: string, kind?: string): Promise<string> {
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,$2::text::jsonb) ON CONFLICT DO NOTHING`, [id, JSON.stringify(kind ? { kind } : {})]);
+ return id;
+}
+
+/** A page over 1 MiB (segmented with the switch on): conversation prose, then `truth`, then the timeline. */
+async function bigPage(engine: BrainEngine, sourceId: string, slug: string, opts: { truth?: string; timeline?: string; type?: string } = {}): Promise<number> {
+ const content = `---\ntype: ${opts.type ?? 'note'}\ntitle: ${slug}\n---\n\n${conversationBody(1_200_000, { seed: slug.length })}\n\n${opts.truth ?? ''}\n\n<!-- timeline -->\n\n${opts.timeline ?? '- **2026-01-10** | Met about the launch'}\n`;
+ expect(await importFromContent(engine, slug, content, { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ const [row] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(row!.body_storage).toBe('segmented');
+ return Number(row!.id);
+}
+
+async function smallPage(engine: BrainEngine, sourceId: string, slug: string): Promise<number> {
+ await importFromContent(engine, slug, `---\ntype: note\ntitle: ${slug}\n---\n\nA short page.\n\n<!-- timeline -->\n\n- **2026-01-10** | Met about the launch\n`, { sourceId, noEmbed: true });
+ const [row] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ expect(row!.body_storage).toBe('inline');
+ return Number(row!.id);
+}
+
+const dbOnlyRow = (engine: BrainEngine, pageId: number, summary = 'A database-only event') =>
+ engine.executeRaw("INSERT INTO timeline_entries(page_id,date,source,summary,detail) VALUES($1,'2026-08-01','legacy',$2,'')", [pageId, summary]);
+const rowCount = async (engine: BrainEngine, pageId: number) =>
+ Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1', [pageId]))[0]!.n);
+
+describe('repair scans over segmented pages', () => {
+ test('repair timeline: preview and apply repair the inline page and report the segmented page as a residual', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'tl-mixed');
+ const segmented = await bigPage(engine, sourceId, 'notes/segmented-timeline');
+ const inline = await smallPage(engine, sourceId, 'notes/inline-timeline');
+ await dbOnlyRow(engine, segmented);
+ await dbOnlyRow(engine, inline);
+ const segmentedRows = await rowCount(engine, segmented);
+ const scope = await resolveRepairScope(engine, sourceId);
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('timeline', scope, { sourceFlag: sourceId });
+ expect(preview.sample).toEqual([`${sourceId}:notes/inline-timeline`]);
+ expect(preview.residuals).toMatchObject({ materializable_rows: 1, segmented_pages: 1, segmented_rows: segmentedRows });
+ expect(preview.warnings?.join('\n')).toContain(`segmented page(s) (${sourceId}:notes/segmented-timeline)`);
+ const applied = await runRepair(ctx(engine, sourceId), timelineRepair, scope, { apply: true });
+ expect({ applied: applied.applied, failed: applied.failed, complete: applied.complete }).toEqual({ applied: 1, failed: [], complete: true });
+ expect(applied.residuals).toMatchObject({ segmented_pages: 1 });
+ expect(await rowCount(engine, segmented)).toBe(segmentedRows);
+ }
+ }), 300_000);
+
+ test('doctor timeline_history counts a segmented page separately and does not recommend repair timeline for it', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'tl-doctor');
+ const segmented = await bigPage(engine, sourceId, 'notes/segmented-doctor');
+ await dbOnlyRow(engine, segmented);
+ const check = await timelineHistoryCheck(engine, sourceId);
+ expect(check.status).toBe('ok');
+ expect(check.message).not.toContain('gbrain repair timeline --apply');
+ expect(check.message).toContain(`${sourceId}:notes/segmented-doctor`);
+ expect(check.message).toContain('no command does yet');
+ expect(check.details).toMatchObject({ materializable_rows: 0, segmented_pages: 1, segmented_sample: [`${sourceId}:notes/segmented-doctor`] });
+ }
+ }), 300_000);
+
+ test('an item whose apply refuses page_body_segmented is recorded in failed[] and the run goes on', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'tl-failed');
+ const segmented = await bigPage(engine, sourceId, 'notes/segmented-item');
+ const attempts: string[] = [];
+ const handler: RepairHandler = {
+ kind: 'timeline', publication: 'projection', embeds: false,
+ async plan() {
+ return { residuals: {}, items: [
+ { cursor: { phase: 0, id: segmented }, source_id: sourceId, slug: 'notes/segmented-item', chars: 0, action: 'materialize 1 row(s)' },
+ { cursor: { phase: 0, id: segmented + 1_000_000 }, source_id: sourceId, slug: 'notes/after', chars: 0, action: 'stub' },
+ ] };
+ },
+ async apply(c, item) {
+ attempts.push(item.slug);
+ return item.slug === 'notes/after' ? true : timelineRepair.apply(c, item);
+ },
+ };
+ const result = await runRepair(ctx(engine, sourceId), handler, await resolveRepairScope(engine, sourceId), { apply: true });
+ expect(attempts).toEqual(['notes/segmented-item', 'notes/after']);
+ expect(result.applied).toBe(1);
+ expect(result.failed.map(f => [f.slug, f.reason])).toEqual([['notes/segmented-item', 'page_body_segmented']]);
+ }
+ }), 300_000);
+
+ test('repair timeline-comments: rows with markup on a segmented page are a residual, not an item whose apply aborts the run', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'tl-comments');
+ const segmented = await bigPage(engine, sourceId, 'notes/segmented-comments');
+ await dbOnlyRow(engine, segmented, 'Talked about the launch. <!-- AUTO:slack END -->');
+ const scope = await resolveRepairScope(engine, sourceId);
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('timeline-comments', scope, { explicit: true, sourceFlag: sourceId });
+ expect(preview.affected).toBe(0);
+ expect(preview.residuals).toMatchObject({ segmented_pages: 1, segmented_rows: 1 });
+ expect(preview.warnings?.join('\n')).toContain(`${sourceId}:notes/segmented-comments`);
+ const applied = await (await repairRunner(engine, { apply: true, logger })).run('timeline-comments', scope, { explicit: true, sourceFlag: sourceId });
+ expect({ complete: applied.complete, applied: applied.applied, failed: applied.failed }).toEqual({ complete: true, applied: 0, failed: [] });
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND summary LIKE '%<!--%'", [segmented]))[0]!.n).toBe(1);
+ }
+ }), 300_000);
+
+ test('repair connector-fences: a segmented connector page with a fence below the timeline is reported, not skipped silently', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'gh-fences', 'github');
+ await bigPage(engine, sourceId, 'notes/segmented-fence', { timeline: `- **2026-01-10** | Met about the launch\n\n${fence(1, 'Ships quarterly')}` });
+ await bigPage(engine, sourceId, 'notes/segmented-plain');
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('connector-fences', await resolveRepairScope(engine, sourceId), { sourceFlag: sourceId });
+ expect(preview.affected).toBe(0);
+ expect(preview.residuals).toMatchObject({ segmented_pages: 1 });
+ expect(preview.warnings?.join('\n')).toContain(`(${sourceId}:notes/segmented-fence)`);
+ }
+ }), 300_000);
+
+ test('repair split-facts: a segmented page with a facts fence in its body and its timeline is listed, not skipped silently', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'split-seg');
+ await bigPage(engine, sourceId, 'people/split-segmented', { type: 'person', truth: fence(1, 'Above claim'),
+ timeline: `- **2026-01-10** | Met about the launch\n\n${fence(2, 'Below claim')}` });
+ await bigPage(engine, sourceId, 'people/one-fence', { type: 'person', truth: fence(1, 'Only claim') });
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('split-facts', await resolveRepairScope(engine, sourceId), { explicit: true, sourceFlag: sourceId });
+ expect(preview.residuals).toMatchObject({ segmented: 1 });
+ expect(preview.listing?.filter(entry => entry.class === 'segmented').map(entry => entry.item)).toEqual([`${sourceId}:people/split-segmented`]);
+ }
+ }), 300_000);
+
+ test('repair conversation-labels: conversation facts on a segmented page are reported, not skipped silently', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const sourceId = await source(engine, 'labels-seg');
+ await bigPage(engine, sourceId, 'meetings/segmented-labels', { type: 'meeting', truth: '**Date:** 2026-01-10' });
+ await engine.insertFacts([{ fact: 'Date said the launch slips', entity_slug: null, source_markdown_slug: 'meetings/segmented-labels', kind: 'fact',
+ visibility: 'private', source: 'cli:extract-conversation-facts', context: 'segment 1970-01-01', confidence: 1 }], { source_id: sourceId });
+ const preview = await (await repairRunner(engine, { apply: false, logger })).run('conversation-labels', await resolveRepairScope(engine, sourceId), { explicit: true, sourceFlag: sourceId });
+ expect(preview.residuals).toMatchObject({ segmented_pages: 1, segmented_facts: 1 });
+ expect(preview.warnings?.join('\n')).toContain(`${sourceId}:meetings/segmented-labels`);
+ }
+ }), 300_000);
+});