Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
repair, integrity, reconcile-links, reindex aliases: handle segmented pages (wip)
garrytanf8320ab6dbb3
diff --git a/src/commands/doctor/checks/data-integrity.ts b/src/commands/doctor/checks/data-integrity.tsindex af77f5bd50..c157e0a961 100644--- a/src/commands/doctor/checks/data-integrity.ts+++ b/src/commands/doctor/checks/data-integrity.ts@@ -34,11 +34,12 @@ async function runIntegrity(ctx: DoctorContext): Promise<Check[]> {const { scanIntegrity } = await import('../../integrity.ts');const res = await scanIntegrity(engine, { limit: 500 });const total = res.bareHits.length + res.externalHits.length;+ const unread = res.skipped.length ? ` ${res.skipped.length} page(s) could not be scanned (first: ${res.skipped[0]!.source_id}:${res.skipped[0]!.slug}, ${res.skipped[0]!.reason}); gbrain integrity check lists them.` : '';if (total === 0) {checks.push({name: 'integrity',status: 'ok',- message: `Sampled ${res.pagesScanned} pages; no bare-tweet phrases or external links.`,+ message: `Sampled ${res.pagesScanned} pages; no bare-tweet phrases or external links.${unread}`,});} else if (res.bareHits.length > 0) {// v0.40.3.0 T8b (D8): emit integrity-auto RemediationStep.@@ -61,7 +62,7 @@ async function runIntegrity(ctx: DoctorContext): Promise<Check[]> {checks.push({name: 'integrity',status: 'warn',- message: `Sampled ${res.pagesScanned} pages; ${res.bareHits.length} bare-tweet phrase(s), ${res.externalHits.length} external link(s). Run: gbrain integrity check (or integrity auto to repair).`,+ message: `Sampled ${res.pagesScanned} pages; ${res.bareHits.length} bare-tweet phrase(s), ${res.externalHits.length} external link(s). Run: gbrain integrity check (or integrity auto to repair).${unread}`,remediation: [integrityStep],remediation_status: 'remediable',});@@ -69,7 +70,7 @@ async function runIntegrity(ctx: DoctorContext): Promise<Check[]> {checks.push({name: 'integrity',status: 'ok',- message: `Sampled ${res.pagesScanned} pages; ${res.externalHits.length} external link(s) (no bare tweets).`,+ message: `Sampled ${res.pagesScanned} pages; ${res.externalHits.length} external link(s) (no bare tweets).${unread}`,});}} catch (e) {diff --git a/src/commands/doctor/checks/timeline-history.ts b/src/commands/doctor/checks/timeline-history.tsindex 3cc7d64c72..75777e2409 100644--- a/src/commands/doctor/checks/timeline-history.ts+++ b/src/commands/doctor/checks/timeline-history.ts@@ -12,10 +12,15 @@* between runs is seen and a pass that ends reports current counts. While a later pass is in progress, a clean* finished pass is trusted until a newer timeline row is written. A truncated* run with neither is a lower bound and is never reported as clean.+ *+ * Segmented pages (Wave B) are not classified: `gbrain repair timeline` cannot+ * re-publish them, so their database-side rows are counted separately+ * (`segmented_pages`, `segmented_rows`), named, reported as kept, and never+ * drive the warning or the repair recommendation.*/import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';-import { recountTimelinePages, scanTimelineHistory } from '../../../core/repair/timeline.ts';+import { recountTimelinePages, scanTimelineHistory, segmentedTimelineNote, segmentedTimelinePages } from '../../../core/repair/timeline.ts';const PAGE_CAP = 2_000;const TIME_BUDGET_MS = 10_000;@@ -68,6 +73,9 @@ export async function timelineHistoryCheck(engine: BrainEngine, sourceId?: strinruns: state.runs + 1,};const multiRun = pass.runs > 1;+ const segmented = await segmentedTimelinePages(engine, sources);+ const segmentedDetails = segmented.pages ? { segmented_pages: segmented.pages, segmented_rows: segmented.rows, segmented_sample: segmented.sample } : {};+ const segmentedNote = segmented.pages ? ` Also: ${segmentedTimelineNote(segmented)}` : '';if (!scan.truncated) {if (prior) {@@ -75,31 +83,32 @@ export async function timelineHistoryCheck(engine: BrainEngine, sourceId?: strinlast: { ...pass, max_entry: state.started_max_entry, completed_at: new Date().toISOString() } });}const details = { materializable_rows: pass.materializable, kept_unrenderable_rows: pass.unrenderable, pages_affected: pass.affected,- pages_inspected: pass.inspected, count: 'exact', truncated: false, repair: 'timeline', ...(multiRun ? { pass_runs: pass.runs } : {}) };+ pages_inspected: pass.inspected, count: 'exact', truncated: false, repair: 'timeline', ...(multiRun ? { pass_runs: pass.runs } : {}), ...segmentedDetails };const across = multiRun ? ` (full pass across ${pass.runs} doctor runs)` : '';if (pass.materializable > 0) {return { name, status: 'warn', details, message: `${pass.materializable} timeline row(s) on ${pass.affected} page(s) exist only in the database${across}. `- + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };+ + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') + segmentedNote };}- return { name, status: 'ok', details, message: pass.unrenderable+ return { name, status: 'ok', details, message: (pass.unrenderable? `No materializable database-only timeline rows${across}; ${pass.unrenderable} row(s) cannot round-trip through their page and are kept as-is (informational).`- : `Every timeline row has a bullet in its page (${pass.inspected} page(s) inspected${multiRun ? ` across ${pass.runs} doctor runs` : ''}).` };+ : segmented.pages ? `No materializable database-only timeline rows on inline pages (${pass.inspected} page(s) inspected${multiRun ? ` across ${pass.runs} doctor runs` : ''}).`+ : `Every timeline row has a bullet in its page (${pass.inspected} page(s) inspected${multiRun ? ` across ${pass.runs} doctor runs` : ''}).`) + segmentedNote };}await saveState(engine, key, { ...state, ...pass, cursor: scan.cursor, found: counted.map(p => p.id).slice(0, FOUND_CAP) });const details = { materializable_rows: pass.materializable, kept_unrenderable_rows: pass.unrenderable, pages_affected: pass.affected,- pages_inspected: pass.inspected, count: 'lower_bound', truncated: true, repair: 'timeline', pass_runs: pass.runs, resumes_after_page_id: scan.cursor };+ pages_inspected: pass.inspected, count: 'lower_bound', truncated: true, repair: 'timeline', pass_runs: pass.runs, resumes_after_page_id: scan.cursor, ...segmentedDetails };const coverage = ` (this pass has inspected ${pass.inspected} page(s) over ${pass.runs} run(s) and resumes on the next doctor run; counts are a lower bound)`;if (pass.materializable > 0) {return { name, status: 'warn', details, message: `at least ${pass.materializable} timeline row(s) on ${pass.affected} page(s) exist only in the database${coverage}. `- + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') };+ + `Preview: gbrain repair timeline — apply: gbrain repair timeline --apply` + (pass.unrenderable ? `. ${pass.unrenderable} other row(s) cannot round-trip and are kept as-is.` : '') + segmentedNote };}const last = state.last;if (last && last.materializable === 0 && maxEntry <= last.max_entry) {return { name, status: 'ok', details: { ...details, last_full_pass: { pages_inspected: last.inspected, runs: last.runs, completed_at: last.completed_at } },- message: `No materializable database-only timeline rows: the last full pass (${last.inspected} page(s), completed ${last.completed_at}) found none and no timeline row has been written since; the next pass is in progress.` };+ message: `No materializable database-only timeline rows: the last full pass (${last.inspected} page(s), completed ${last.completed_at}) found none and no timeline row has been written since; the next pass is in progress.${segmentedNote}` };}- return { name, status: 'warn', details, message: `Timeline history scan incomplete${coverage}; run \`gbrain repair timeline\` for the full count now.` };+ return { name, status: 'warn', details, message: `Timeline history scan incomplete${coverage}; run \`gbrain repair timeline\` for the full count now.${segmentedNote}` };} catch (e) {return { name, status: 'warn', message: `timeline history check skipped: ${e instanceof Error ? e.message : String(e)}`,details: { count: 'lower_bound', truncated: true, health: 'unknown' } };diff --git a/src/commands/integrity.ts b/src/commands/integrity.tsindex 2e525d11f1..c267c078af 100644--- a/src/commands/integrity.ts+++ b/src/commands/integrity.ts@@ -40,6 +40,12 @@ import {import { registerBuiltinResolvers } from './resolvers.ts';import { tweetCitation } from '../core/output/scaffold.ts';import { INTEGRITY_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';+import { OperationError } from '../core/ops/contract.ts';+import { isSegmentedPage } from '../core/page-body/page-shape.ts';+import type { Page } from '../core/types.ts';+import type { BodyStorage } from '../core/page-body/types.ts';+import { bodyLines } from '../core/page-body/segment-lines.ts';+import { detachedValue } from '../core/page-body/segment-blocks.ts';// ---------------------------------------------------------------------------// Paths@@ -81,41 +87,51 @@ export interface BareTweetHit {phrase: string;}-export function findBareTweetHits(compiledTruth: string, slug: string): BareTweetHit[] {- const hits: BareTweetHit[] = [];- const lines = compiledTruth.split('\n');- let insideFence = false;- let fenceMarker = '';- for (let i = 0; i < lines.length; i++) {- const line = lines[i];- if (insideFence) {- if (line.startsWith(fenceMarker)) insideFence = false;+interface FenceState { inside: boolean; marker: string; line: number }+const fenceState = (): FenceState => ({ inside: false, marker: '', line: 0 });++/** Calls `visit` with each line outside a ``` or ~~~ fence and its 1-based number; `state` carries across calls, so lines may arrive in runs. */+function unfencedLines(lines: readonly string[], state: FenceState, visit: (line: string, n: number) => void): void {+ for (const line of lines) {+ state.line++;+ if (state.inside) {+ if (line.startsWith(state.marker)) state.inside = false;continue;}if (line.startsWith('```') || line.startsWith('~~~')) {- insideFence = true;- fenceMarker = line.startsWith('```') ? '```' : '~~~';+ state.inside = true;+ state.marker = line.startsWith('```') ? '```' : '~~~';continue;}- // If the line already contains a tweet URL, it's cited — skip- if (URL_NEARBY_RE.test(line)) continue;- // If the line carries an explicit source citation (e.g.- // "[Source: X, @handle, 2026-05-28]"), it's already attributed — skip.- // Catches instructional/example lines in recipe docs that demonstrate- // the CORRECT citation format. (v0.42.x)- if (/\[\s*source:/i.test(line)) continue;- // Strip inline-code spans (`...`) before matching: phrases shown as- // inline-code templates in docs are examples, not bare claims. The- // fenced-code skip above only covers ``` blocks, not inline backticks.- const lineForMatch = line.replace(/`[^`]*`/g, '');- for (const re of BARE_TWEET_PHRASES) {- const m = lineForMatch.match(re);- if (m) {- hits.push({ slug, line: i + 1, rawLine: line.trim(), phrase: m[0] });- break; // one finding per line is enough- }- }+ visit(line, state.line);+ }+}++function bareTweetHit(line: string, n: number, slug: string): BareTweetHit | null {+ // If the line already contains a tweet URL, it's cited — skip+ if (URL_NEARBY_RE.test(line)) return null;+ // If the line carries an explicit source citation (e.g.+ // "[Source: X, @handle, 2026-05-28]"), it's already attributed — skip.+ // Catches instructional/example lines in recipe docs that demonstrate+ // the CORRECT citation format. (v0.42.x)+ if (/\[\s*source:/i.test(line)) return null;+ // Strip inline-code spans (`...`) before matching: phrases shown as+ // inline-code templates in docs are examples, not bare claims. The+ // fenced-code skip above only covers ``` blocks, not inline backticks.+ const lineForMatch = line.replace(/`[^`]*`/g, '');+ for (const re of BARE_TWEET_PHRASES) {+ const m = lineForMatch.match(re);+ if (m) return { slug, line: n, rawLine: line.trim(), phrase: m[0] }; // one finding per line is enough}+ return null;+}++export function findBareTweetHits(compiledTruth: string, slug: string): BareTweetHit[] {+ const hits: BareTweetHit[] = [];+ unfencedLines(compiledTruth.split('\n'), fenceState(), (line, n) => {+ const hit = bareTweetHit(line, n, slug);+ if (hit) hits.push(hit);+ });return hits;}@@ -131,31 +147,64 @@ export interface ExternalLinkHit {url: string;}+function externalLinkHits(line: string, n: number, slug: string, hits: ExternalLinkHit[]): void {+ MD_LINK_EXTERNAL_RE.lastIndex = 0;+ let m: RegExpExecArray | null;+ while ((m = MD_LINK_EXTERNAL_RE.exec(line)) !== null) {+ hits.push({ slug, line: n, url: m[1] });+ }+}+export function findExternalLinks(compiledTruth: string, slug: string): ExternalLinkHit[] {const hits: ExternalLinkHit[] = [];- const lines = compiledTruth.split('\n');- let insideFence = false;- let fenceMarker = '';- for (let i = 0; i < lines.length; i++) {- const line = lines[i];- if (insideFence) {- if (line.startsWith(fenceMarker)) insideFence = false;- continue;- }- if (line.startsWith('```') || line.startsWith('~~~')) {- insideFence = true;- fenceMarker = line.startsWith('```') ? '```' : '~~~';- continue;- }- MD_LINK_EXTERNAL_RE.lastIndex = 0;- let m: RegExpExecArray | null;- while ((m = MD_LINK_EXTERNAL_RE.exec(line)) !== null) {- hits.push({ slug, line: i + 1, url: m[1] });- }- }+ unfencedLines(compiledTruth.split('\n'), fenceState(), (line, n) => externalLinkHits(line, n, slug, hits));return hits;}+/** A page the scan could not read; the run goes on without it. */+export interface IntegritySkippedPage { slug: string; source_id: string; reason: string; message: string }++/**+ * Bare-tweet and external-link hits of a page's compiled truth. A segmented+ * page (Wave B) is read block by block (`bodyLines` over its truth region),+ * 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,+ 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 ?? '';+ return { bare: findBareTweetHits(text, page.slug), external: findExternalLinks(text, page.slug) };+ }+ const bare: BareTweetHit[] = [];+ const external: ExternalLinkHit[] = [];+ const bareState = fenceState(), externalState = fenceState();+ for await (const lines of bodyLines(engine, page, { regions: ['truth'] })) {+ unfencedLines(lines, bareState, (line, n) => {+ const hit = bareTweetHit(line, n, page.slug);+ if (hit) bare.push(detachedValue(hit));+ });+ unfencedLines(lines, externalState, (line, n) => {+ const found: ExternalLinkHit[] = [];+ externalLinkHits(line, n, page.slug, found);+ external.push(...found.map(detachedValue));+ });+ }+ return { bare, external };+}++/** The page as `integrityHitsOf` reads it: a segmented page without its body (its body fields throw). */+function pageRef(page: Page, sourceId: string) {+ const segmented = isSegmentedPage(page);+ return { id: Number(page.id), slug: page.slug, source_id: sourceId, body_storage: page.body_storage, compiled_truth: segmented ? null : page.compiled_truth };+}++/** A per-page refusal (a segmented page whose run is too long to read as one block) becomes a skipped page; anything else propagates. */+function skippedPage(error: unknown, page: { slug: string; source_id: string }): IntegritySkippedPage {+ if (error instanceof OperationError && error.code === 'page_body_segmented') return { slug: page.slug, source_id: page.source_id, reason: error.code, message: error.message };+ throw error;+}+// ---------------------------------------------------------------------------// Progress tracking// ---------------------------------------------------------------------------@@ -274,6 +323,7 @@ async function cmdCheck(args: string[]): Promise<void> {pagesScanned: res.pagesScanned,bareTweetHits: res.bareHits,externalLinkCount: res.externalHits.length,+ ...(res.skipped.length ? { skipped: res.skipped } : {}),}, null, 2));return;}@@ -281,6 +331,10 @@ async function cmdCheck(args: string[]): Promise<void> {console.log(`Scanned ${res.pagesScanned} pages.`);console.log(`Bare-tweet phrases: ${res.bareHits.length}`);console.log(`External links (for optional dead-link check): ${res.externalHits.length}`);+ if (res.skipped.length > 0) {+ console.log(`Pages not scanned: ${res.skipped.length}`);+ for (const skipped of res.skipped) console.log(` ${skipped.source_id}:${skipped.slug} (${skipped.reason}): ${skipped.message}`);+ }if (res.topPages.length > 0) {console.log('\nTop 10 pages with bare-tweet references:');for (const { slug, count } of res.topPages) {@@ -315,6 +369,8 @@ export interface IntegrityScanResult {externalHits: ExternalLinkHit[];/** Top 10 pages sorted by bare-tweet hit count, descending. */topPages: Array<{ slug: string; count: number }>;+ /** Pages the scan could not read (a per-page refusal); counted in pagesScanned, no hits. */+ skipped: IntegritySkippedPage[];}/**@@ -337,7 +393,7 @@ export async function scanIntegrity(// log clean for real Postgres errors instead of expected PGLite skips.if (batchLoad && limit !== Infinity && engine.kind === 'postgres') {try {- return await scanIntegrityBatch(limit, typeFilter);+ return await scanIntegrityBatch(engine, limit, typeFilter);} catch (err) {// GBRAIN_DEBUG=1 surfaces real Postgres errors (deadlock, connection// drop, SQL bug) that would otherwise vanish into the sequential@@ -362,6 +418,8 @@ export async function scanIntegrity(const externalHits: ExternalLinkHit[] = [];let pagesScanned = 0;+ const skipped: IntegritySkippedPage[] = [];+for (const { slug, source_id } of allRefs) {if (typeFilter && !slug.startsWith(`${typeFilter}/`)) continue;if (pagesScanned >= limit) break;@@ -370,8 +428,13 @@ export async function scanIntegrity(// Skip grandfathered pages (opted out of brain-integrity enforcement)if ((page.frontmatter as Record<string, unknown> | undefined)?.validate === false) continue;pagesScanned++;- bareHits.push(...findBareTweetHits(page.compiled_truth, slug));- externalHits.push(...findExternalLinks(page.compiled_truth, slug));+ try {+ const hits = await integrityHitsOf(engine, pageRef(page, source_id));+ bareHits.push(...hits.bare);+ externalHits.push(...hits.external);+ } catch (error) {+ skipped.push(skippedPage(error, { slug, source_id }));+ }}const byPage = new Map<string, number>();@@ -381,7 +444,7 @@ export async function scanIntegrity(.slice(0, 10).map(([slug, count]) => ({ slug, count }));- return { pagesScanned, bareHits, externalHits, topPages };+ return { pagesScanned, bareHits, externalHits, topPages, skipped };}/**@@ -389,6 +452,7 @@ export async function scanIntegrity(* query, then scans in-memory. Reduces PgBouncer round-trips from ~500 to 1.*/async function scanIntegrityBatch(+ engine: BrainEngine,limit: number,typeFilter?: string,): Promise<IntegrityScanResult> {@@ -409,7 +473,7 @@ async function scanIntegrityBatch(// sampled doctor check reports hits from tombstones and, once they// outnumber `limit`, stops reaching live pages.const rows = await sql`- SELECT slug, compiled_truth, frontmatter+ SELECT id, source_id, slug, compiled_truth, body_storageFROM pagesWHERE deleted_at IS NULL ${typeCondition} ${validateCondition}ORDER BY source_id, slug@@ -419,11 +483,18 @@ async function scanIntegrityBatch(const bareHits: BareTweetHit[] = [];const externalHits: ExternalLinkHit[] = [];+ const skipped: IntegritySkippedPage[] = [];+for (const row of rows) {- const slug = row.slug as string;- const compiledTruth = row.compiled_truth as string;- bareHits.push(...findBareTweetHits(compiledTruth, slug));- externalHits.push(...findExternalLinks(compiledTruth, slug));+ const page = { id: Number(row.id), source_id: row.source_id as string, slug: row.slug as string,+ compiled_truth: row.compiled_truth as string | null, body_storage: row.body_storage as BodyStorage };+ try {+ const hits = await integrityHitsOf(engine, page);+ bareHits.push(...hits.bare);+ externalHits.push(...hits.external);+ } catch (error) {+ skipped.push(skippedPage(error, page));+ }}const byPage = new Map<string, number>();@@ -433,7 +504,7 @@ async function scanIntegrityBatch(.slice(0, 10).map(([slug, count]) => ({ slug, count }));- return { pagesScanned: rows.length, bareHits, externalHits, topPages };+ return { pagesScanned: rows.length, bareHits, externalHits, topPages, skipped };}// ---------------------------------------------------------------------------@@ -492,6 +563,7 @@ async function cmdAuto(args: string[]): Promise<void> {let bucketErr = 0;let bucketDeadLink = 0;let pagesProcessed = 0;+ const skippedPages: IntegritySkippedPage[] = [];const { createProgress } = await import('../core/progress.ts');const { getCliOptions, cliOptsToProgressOptions } = await import('../core/cli-options.ts');@@ -517,9 +589,17 @@ async function cmdAuto(args: string[]): Promise<void> {pagesProcessed++;progress.tick(1, slug);+ let found: Awaited<ReturnType<typeof integrityHitsOf>>;+ try {+ found = await integrityHitsOf(engine, pageRef(page, source_id));+ } catch (error) {+ skippedPages.push(skippedPage(error, { slug, source_id }));+ continue;+ }+// Bare-tweet handlingif (!skipTweet) {- const hits = findBareTweetHits(page.compiled_truth, slug);+ const hits = found.bare;const handle = extractXHandleFromFrontmatter(page.frontmatter);if (hits.length > 0 && handle) {for (const hit of hits) {@@ -577,7 +657,7 @@ async function cmdAuto(args: string[]): Promise<void> {// Dead-link handling (no auto-repair; just surface)if (!skipUrls) {- const externalHits = findExternalLinks(page.compiled_truth, slug);+ const externalHits = found.external;// Limit to first few per page to keep the default run fast; --check// gives the full picture.for (const hit of externalHits.slice(0, 3)) {@@ -618,6 +698,10 @@ async function cmdAuto(args: string[]): Promise<void> {console.log(`Skipped (<${reviewLower}): ${bucketSkip}`);if (bucketErr > 0) console.log(`Resolver errors: ${bucketErr}`);if (bucketDeadLink > 0) console.log(`Dead links surfaced (see skipped log): ${bucketDeadLink}`);+ if (skippedPages.length > 0) {+ console.log(`Pages not scanned: ${skippedPages.length}`);+ for (const skipped of skippedPages) console.log(` ${skipped.source_id}:${skipped.slug} (${skipped.reason}): ${skipped.message}`);+ }console.log(`\nReview queue: ${getReviewFile()}`);console.log(`Skipped log: ${getLogFile()}`);console.log(`Progress: ${getProgressFile()}`);diff --git a/src/commands/reconcile-links.ts b/src/commands/reconcile-links.tsindex d94d2bcb6d..02223b6199 100644--- a/src/commands/reconcile-links.ts+++ b/src/commands/reconcile-links.ts@@ -20,10 +20,18 @@* files, that's 5K ILIKE scans. A user-triggered batch pass on an* already-synced brain is one walk, fully indexed via the existing* slug lookup in addLink.+ *+ * A segmented page (Wave B) is read block by block (`bodyLines`): a code ref+ * never spans a line, so it gets the refs the same text held as one string+ * gets. A page a block read refuses is listed in `skipped` and the walk goes on.*/import type { BrainEngine } from '../core/engine.ts';-import { extractCodeRefs } from '../core/link-extraction.ts';+import type { Page } from '../core/types.ts';+import { extractCodeRefs, type CodeRef } from '../core/link-extraction.ts';+import { OperationError } from '../core/ops/contract.ts';+import { isSegmentedPage } from '../core/page-body/page-shape.ts';+import { bodyLines } from '../core/page-body/segment-lines.ts';import { slugifyCodePath } from '../core/sync.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -34,6 +42,29 @@ export interface ReconcileLinksResult {codeRefsFound: number;edgesAttempted: number;edgesTargetsMissing: number;+ /** Pages a per-page refusal kept out of the scan (present only when there are any). */+ skipped?: Array<{ slug: string; reason: string; message: string }>;+}++/**+ * 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[]> {+ if (!isSegmentedPage(page)) return extractCodeRefs((page.compiled_truth || '') + '\n' + (page.timeline || ''));+ const seen = new Set<string>();+ const refs: CodeRef[] = [];+ let at = 0;+ for await (const lines of bodyLines(engine, page)) {+ const text = lines.join('\n');+ for (const ref of extractCodeRefs(text)) {+ if (seen.has(ref.path)) continue;+ seen.add(ref.path);+ refs.push({ path: Buffer.from(ref.path, 'utf8').toString('utf8'), line: ref.line, index: ref.index + at });+ }+ at += text.length + 1;+ }+ return refs;}export interface ReconcileLinksOpts {@@ -85,6 +116,7 @@ export async function runReconcileLinks(let codeRefsFound = 0;let edgesAttempted = 0;let edgesTargetsMissing = 0;+ const skipped: NonNullable<ReconcileLinksResult['skipped']> = [];// Fetch pages one at a time via getPage (no bulk read helper exists yet).// On a 47K-page brain this is the slow path; a v0.20.x follow-up can add@@ -103,8 +135,15 @@ export async function runReconcileLinks(progress.tick(1, mdSlug);continue;}- const haystack = (page.compiled_truth || '') + '\n' + (page.timeline || '');- const refs = extractCodeRefs(haystack);+ let refs: CodeRef[];+ try {+ refs = await pageCodeRefs(engine, page);+ } catch (e: unknown) {+ if (!(e instanceof OperationError && e.code === 'page_body_segmented')) throw e;+ skipped.push({ slug: mdSlug, reason: e.code, message: e.message });+ progress.tick(1, `${mdSlug} (skipped)`);+ continue;+ }if (refs.length === 0) {progress.tick(1, mdSlug);continue;@@ -149,6 +188,7 @@ export async function runReconcileLinks(codeRefsFound,edgesAttempted,edgesTargetsMissing,+ ...(skipped.length ? { skipped } : {}),};}@@ -184,4 +224,5 @@ export async function runReconcileLinksCli(engine: BrainEngine, args: string[]):? ` (${result.edgesTargetsMissing} targets missing code page)`: ''),);+ for (const page of result.skipped ?? []) console.log(`[reconcile-links] skipped ${page.slug} (${page.reason}): ${page.message}`);}diff --git a/src/commands/reindex-aliases.ts b/src/commands/reindex-aliases.tsindex bfb250ccc4..531d9205c3 100644--- a/src/commands/reindex-aliases.ts+++ b/src/commands/reindex-aliases.ts@@ -13,16 +13,26 @@* Walks listAllPageRefs (cheap (source_id, slug) enumeration) so it's* cross-source by default; --source narrows it. On a managed brain the* derived rows are written through the coordinated writer.+ *+ * A segmented page (Wave B) derives its aliases from its body read back as+ * strings (`materializedPage`), as its import did. A body over the+ * single-string ceiling is never read as one string: like its streamed+ * import, the page gets its frontmatter and subject aliases only, and is+ * listed in `body_not_scanned`. A per-page refusal is listed in `skipped`+ * and the walk goes on.*/import type { BrainEngine } from '../core/engine.ts';import { normalizeAliasList } from '../core/search/alias-normalize.ts';import { writeDerivedAliases } from '../core/mentions/pass.ts';-import { readMentionPolicy } from '../core/mentions/policy.ts';+import { linkableTypesFor, loadSourcePack, readMentionPolicy, type PackTypes } from '../core/mentions/policy.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { maintenanceAttribution } from '../core/persistence/attribution.ts';import { withCoordinatedWrite } from '../core/persistence/context.ts';import { createProgress } from '../core/progress.ts';+import { OperationError } from '../core/ops/contract.ts';+import { bodyUnread, isSegmentedPage } from '../core/page-body/page-shape.ts';+import { materializedPage } from '../core/persistence/segmented-apply.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';export interface ReindexAliasesResult {@@ -30,6 +40,10 @@ export interface ReindexAliasesResult {pages_with_aliases: number;aliases_written: number;dry_run: boolean;+ /** Segmented pages over the single-string ceiling whose body was not scanned for declared aliases (present only when there are any). */+ body_not_scanned?: Array<{ slug: string; source_id: string; reason: string }>;+ /** Pages a per-page refusal kept out of the walk (present only when there are any). */+ skipped?: Array<{ slug: string; source_id: string; reason: string; message: string }>;}export async function runReindexAliases(engine: BrainEngine, args: string[]): Promise<ReindexAliasesResult> {@@ -56,6 +70,8 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Prattribution ? withCoordinatedWrite(tx, [sourceId], () => fn(tx), attribution) : fn(tx));const mentionPolicy = dryRun ? null : await readMentionPolicy(engine);+ const bodyNotScanned: NonNullable<ReindexAliasesResult['body_not_scanned']> = [];+ const skipped: NonNullable<ReindexAliasesResult['skipped']> = [];for (const ref of refs) {scanned++;reporter.tick();@@ -71,10 +87,29 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Prif (aliasNorms.length) { pagesWithAliases++; aliasesWritten += aliasNorms.length; }continue;}+ let body: { compiled_truth: string | null; timeline: string | null } = { compiled_truth: '', timeline: '' };+ let pack: PackTypes | null | undefined;+ if (!isSegmentedPage(page)) body = { compiled_truth: page.compiled_truth, timeline: page.timeline };+ else if (mentionPolicy?.enabled) {+ pack = await loadSourcePack(engine, ref.source_id);+ if (linkableTypesFor(pack, mentionPolicy).includes(page.type ?? '')) {+ try {+ const read = await materializedPage(engine, page);+ if (!bodyUnread(read)) body = { compiled_truth: read.compiled_truth, timeline: read.timeline };+ else bodyNotScanned.push({ slug: ref.slug, source_id: ref.source_id,+ reason: 'its body is over the single-string ceiling, so declared aliases are not derived from it (frontmatter and subject aliases are written)' });+ } catch (e) {+ if (!(e instanceof OperationError && e.code === 'page_body_segmented')) throw e;+ skipped.push({ slug: ref.slug, source_id: ref.source_id, reason: e.code, message: e.message });+ continue;+ }+ }+ }try {if (aliasNorms.length) await engine.setPageAliases(ref.slug, ref.source_id, aliasNorms);const derived = await derivedWrite(ref.source_id, tx => writeDerivedAliases(tx, ref.source_id,- { slug: ref.slug, title: page.title, type: page.type, compiled_truth: page.compiled_truth, timeline: page.timeline, frontmatter: page.frontmatter as Record<string, unknown> | undefined }, { policy: mentionPolicy }));+ { slug: ref.slug, title: page.title, type: page.type, ...body, frontmatter: page.frontmatter as Record<string, unknown> | undefined },+ { policy: mentionPolicy, ...(pack !== undefined ? { pack } : {}) }));if (aliasNorms.length || derived) pagesWithAliases++;aliasesWritten += aliasNorms.length + derived;} catch (e) {@@ -89,6 +124,8 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Prpages_with_aliases: pagesWithAliases,aliases_written: aliasesWritten,dry_run: dryRun,+ ...(bodyNotScanned.length ? { body_not_scanned: bodyNotScanned } : {}),+ ...(skipped.length ? { skipped } : {}),};if (json) {@@ -96,6 +133,8 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Pr} else {const verb = dryRun ? 'would write' : 'wrote';console.log(`reindex --aliases: scanned ${scanned} pages, ${verb} ${aliasesWritten} aliases across ${pagesWithAliases} pages.`);+ for (const page of bodyNotScanned) console.log(` body not scanned: ${page.source_id}:${page.slug}: ${page.reason}`);+ for (const page of skipped) console.log(` skipped ${page.source_id}:${page.slug} (${page.reason}): ${page.message}`);}return result;}diff --git a/src/core/page-body/segment-lines.ts b/src/core/page-body/segment-lines.tsnew file mode 100644index 0000000000..0374f5f9cb--- /dev/null+++ b/src/core/page-body/segment-lines.ts@@ -0,0 +1,45 @@+/**+ * Segmented page storage (Wave B, PR 2 full-pass mode): line-oriented scans of+ * a segmented page's trusted body for the maintenance commands (integrity,+ * reconcile-links, connector-fences), block by block over `bodyBlocks`, never+ * the whole body as one string.+ *+ * A block can end inside a line (a forced cut joined into the block ends where+ * the next segment starts, and a region ends without a newline), so the part+ * of a line after a block's last newline is carried into the next block+ * (`segmentedPassWork.carry` counts the carried units). A line-local parser fed+ * these lines in order sees exactly the lines of the joined text.+ */+import type { BrainEngine } from '../engine.ts';+import { bodyBlocks, segmentedPassWork, type BodyBlockOptions } from './segment-blocks.ts';++/**+ * The lines of the joined text (`${compiled_truth}\n${timeline}`, or the regions+ * and separator `opts` names), a block's worth at a time: joining every yielded+ * array with '\n', and the arrays with '\n', gives the joined text.+ */+export async function* bodyLines(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },+ opts: BodyBlockOptions = {}): AsyncIterable<string[]> {+ let carry = '';+ for await (const block of bodyBlocks(engine, page, opts)) {+ const lines = (carry + block.text).split('\n');+ carry = lines.pop()!;+ segmentedPassWork.carry += carry.length;+ if (lines.length) yield lines;+ }+ yield [carry];+}++/** Whether one region of a segmented page holds any of `needles` (case-sensitive, as SQL LIKE), a needle cut by a block boundary included. */+export async function segmentedRegionContains(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },+ region: 'truth' | 'timeline', needles: readonly string[]): Promise<boolean> {+ const keep = Math.max(0, ...needles.map(n => n.length - 1));+ let carry = '';+ for await (const block of bodyBlocks(engine, page, { regions: [region] })) {+ const text = carry + block.text;+ if (needles.some(needle => text.includes(needle))) return true;+ carry = keep ? text.slice(-keep) : '';+ segmentedPassWork.carry += carry.length;+ }+ return false;+}diff --git a/src/core/repair/connector-fences.ts b/src/core/repair/connector-fences.tsindex 5284ccd4ad..9f5ad058c5 100644--- a/src/core/repair/connector-fences.ts+++ b/src/core/repair/connector-fences.ts@@ -6,6 +6,10 @@* republished with its own rows through a revision-bound `put_page`; a page* whose fences are ambiguous (duplicated, unbalanced or unparseable) is kept* and counted for a manual edit, never guessed at.+ *+ * A segmented page (Wave B) is not moved: this repair rewrites the whole body+ * as one string. Its timeline region is searched block by block for a fence+ * marker, and each such page is counted (`segmented_pages`) and named.*/import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';@@ -13,6 +17,8 @@ import { submitPageMutation } from '../persistence/page-mutations.ts';import { conceptPreservationHold } from '../cycle/concept-publication.ts';import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, replaceOrInsertFactsFence } from '../facts-fence.ts';import { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';+import { segmentedRegionContains } from '../page-body/segment-lines.ts';+import { SEGMENTED_SAMPLE } from './timeline.ts';import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';const count = (text: string, marker: string) => text.split(marker).length - 1;@@ -46,12 +52,26 @@ export function relocateTimelineFences(page: { compiled_truth: string | null; tiinterface FencePage { id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }+const FENCE_MARKERS = ['gbrain:facts:', 'gbrain:takes:'];+async function candidates(engine: BrainEngine, sourceIds: string[]): Promise<FencePage[]> {return engine.executeRaw<FencePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages p JOIN sources s ON s.id=p.source_idWHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN ('google','github')AND (p.timeline LIKE '%gbrain:facts:%' OR p.timeline LIKE '%gbrain:takes:%') ORDER BY p.id`, [sourceIds]);}+/** Segmented connector pages whose timeline region holds a facts or takes fence marker, as `source:slug`. */+async function segmentedCandidates(engine: BrainEngine, sourceIds: string[], after: RepairCursor | null): Promise<string[]> {+ const pages = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT p.id,p.source_id,p.slug FROM pages p JOIN sources s ON s.id=p.source_id+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND s.config->>'kind' IN ('google','github') AND p.body_storage='segmented' ORDER BY p.id`, [sourceIds]);+ const found: string[] = [];+ for (const page of pages) {+ if (!afterCursor({ phase: 0, id: Number(page.id) }, after)) continue;+ if (await segmentedRegionContains(engine, page, 'timeline', FENCE_MARKERS)) found.push(`${page.source_id}:${page.slug}`);+ }+ return found;+}+export const connectorFencesRepair: RepairHandler = {kind: 'connector-fences',async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {@@ -63,7 +83,11 @@ export const connectorFencesRepair: RepairHandler = {items.push({ cursor: { phase: 0, id: page.id }, source_id: page.source_id, slug: page.slug,chars: page.compiled_truth.length + (page.timeline ?? '').length, action: 'move fences above the timeline' });}- return { items, residuals: { kept_ambiguous_pages: ambiguous } };+ const segmented = await segmentedCandidates(engine, scope.source_ids, after);+ const warnings = segmented.length ? [`segmented_pages: ${segmented.length} segmented connector page(s) (${segmented.slice(0, SEGMENTED_SAMPLE).join(', ')}`+ + `${segmented.length > SEGMENTED_SAMPLE ? ', …' : ''}) hold a facts or takes fence below the timeline and are left as they are: this repair rewrites a whole body `+ + 'as one string, so it does not handle segmented pages, and no command does yet.'] : [];+ return { ...(warnings.length ? { warnings } : {}), items, residuals: { kept_ambiguous_pages: ambiguous, ...(segmented.length ? { segmented_pages: segmented.length } : {}) } };},async apply(ctx, item) {const snapshot = await ctx.engine.readPageSnapshot(item.slug, { sourceId: item.source_id });diff --git a/src/core/repair/conversation-labels.ts b/src/core/repair/conversation-labels.tsindex 08b4e22145..4272dcb3e6 100644--- a/src/core/repair/conversation-labels.ts+++ b/src/core/repair/conversation-labels.ts@@ -34,6 +34,12 @@* `--max-cost-usd`). A managed brain publishes one database-only* `managed_maintenance_conversation_label_retire` request per page; an* unmanaged brain writes under the page lock. Never automatic.+ *+ * Segmented pages (Wave B) are not classified: the candidate filter matches+ * the label line against the page row's body columns, which a segmented page+ * leaves empty. Their active per-segment extractor facts, on pages the fixed+ * extractor has not stamped, are counted+ * (`segmented_pages`, `segmented_facts`) and the pages named in a warning.*/import type { BrainEngine, NewFact } from '../engine.ts';import type { Page } from '../types.ts';@@ -56,6 +62,7 @@ import { readConversationBodyForParsing } from '../conversation-parser/body.ts';import { conversationSkip } from '../facts/conversation-skip.ts';import { LABEL_RETIRED_MARKER } from '../facts/conversation-publication.ts';import { LEGACY_TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE, TERMINAL_AUDIT_SOURCE, stampExtractorVersion } from '../facts/audit-sources.ts';+import { SEGMENTED_SAMPLE } from './timeline.ts';import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';export const CONVERSATION_LABELS_INTENT = 'managed_maintenance_conversation_label_retire';@@ -247,6 +254,12 @@ export const conversationLabelsRepair: RepairHandler = {details: { handoff: handoffCommands(approved.items) } };}const facts = await classifyLabelFacts(engine, scope.source_ids);+ const segmented = await engine.executeRaw<{ source_id: string; slug: string; n: number }>(`SELECT p.source_id, p.slug, count(*)::int AS n+ FROM facts f JOIN pages p ON p.source_id=f.source_id AND p.slug=f.source_markdown_slug AND p.deleted_at IS NULL+ WHERE f.source_id=ANY($1::text[]) AND f.source=$2 AND f.expired_at IS NULL AND p.body_storage='segmented'+ AND NOT EXISTS (SELECT 1 FROM facts o WHERE o.source_id=f.source_id AND o.source_markdown_slug=f.source_markdown_slug+ AND o.source IN ($3, $4) AND o.expired_at IS NULL AND o.context ~ 'extractor_version=[0-9]+$')+ GROUP BY p.id, p.source_id, p.slug ORDER BY p.id`, [scope.source_ids, SEGMENT_SOURCE, TERMINAL_AUDIT_SOURCE, NON_EXTRACTABLE_AUDIT_SOURCE]);const selected = facts.filter(fact => fact.class === 'evidenced' || fact.class === 'ambiguous' && includeAmbiguous);const pages = new Map<string, LabelPage>();for (const fact of selected) {@@ -276,8 +289,12 @@ export const conversationLabelsRepair: RepairHandler = {items: batchItems(approved, hash), preview_hash: hash, listing,residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),non_extractable_pages: approved.filter(p => p.outcome === 'non_extractable').length, awaiting_reextraction_pages: awaiting.length,- awaiting_segments: awaiting.reduce((n, p) => n + p.segments, 0) },- warnings: ['This command makes no model calls.'],+ awaiting_segments: awaiting.reduce((n, p) => n + p.segments, 0),+ ...(segmented.length ? { segmented_pages: segmented.length, segmented_facts: segmented.reduce((n, p) => n + Number(p.n), 0) } : {}) },+ warnings: ['This command makes no model calls.', ...(segmented.length ? [`segmented_pages: ${segmented.length} segmented page(s) `+ + `(${segmented.slice(0, SEGMENTED_SAMPLE).map(p => `${p.source_id}:${p.slug}`).join(', ')}${segmented.length > SEGMENTED_SAMPLE ? ', …' : ''}) `+ + 'carry conversation facts that are not checked for misattributed labels: the candidate filter reads the page body as one string, '+ + 'so this repair does not handle segmented pages, and no command does yet.'] : [])],details: { pages: approved.map(({ source_id, slug, outcome, facts: rows, segments, non_extractable_reason }) =>({ source_id, slug, outcome, facts: rows.length, segments, ...(non_extractable_reason ? { reason: non_extractable_reason } : {}) })),handoff: handoffCommands(approved) },diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex aafb1d5277..de1a862bc5 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -12,8 +12,8 @@* `op_checkpoints` under a fingerprint of (kind, brain, sources): a rerun with* the same scope resumes after it, and a finished scan clears it.*- * An item whose apply refuses `invalid_params` or `source_changed` is a- * per-item verdict, not a run failure: it is recorded in `failed[]`, left as+ * An item whose apply refuses `invalid_params`, `source_changed` or+ * `page_body_segmented` is a per-item verdict, not a run failure: it is recorded in `failed[]`, left as* it was, and the loop continues without a cursor write for it. A later* success writes a higher cursor, so a resumed run does not retry it; the next* full scan (a run with no stored cursor, which every completed run leaves@@ -132,8 +132,11 @@ export interface RepairHandler {export interface RepairItemOutcome { applied: boolean; outcome: string; reason?: string; detail?: Record<string, unknown>; llm_usd?: number;stop?: { reason: string; message: string; fix?: Action } }-/** Refusal codes that are one item's verdict: the item is recorded in `failed[]` and the run goes on. */-export const REPAIR_ITEM_FAILURE_CODES: ReadonlySet<string> = new Set(['invalid_params', 'source_changed']);+/**+ * Refusal codes that are one item's verdict: the item is recorded in `failed[]` and the run goes on.+ * `page_body_segmented`: the item's page stores its body in segments and the kind rewrites the whole body as one string.+ */+export const REPAIR_ITEM_FAILURE_CODES: ReadonlySet<string> = new Set(['invalid_params', 'source_changed', 'page_body_segmented']);/** An item whose apply refused with a per-item code; its page, file and rows are exactly as before. The next full scan retries it. */export interface RepairFailedItem { item: string; source_id: string; slug: string; reason: string; message: string; retry: 'next_full_scan' }diff --git a/src/core/repair/split-facts.ts b/src/core/repair/split-facts.tsindex 97e620aee8..1546eeb2cc 100644--- a/src/core/repair/split-facts.ts+++ b/src/core/repair/split-facts.ts@@ -16,6 +16,10 @@* that set through revision-bound `put_page`s (`changed_since_preview` when a* page moved). It never runs from `--all`, the remediation plan, the* maintenance cycle or an upgrade.+ *+ * A segmented page (Wave B) is not merged: this repair rewrites the whole body+ * as one string. A segmented page whose stored segments record a facts fence+ * in both its body and its timeline is listed (`segmented`) and kept.*/import type { BrainEngine } from '../engine.ts';import type { Page } from '../types.ts';@@ -101,6 +105,18 @@ export const splitFactsRepair: RepairHandler = {[scope.source_ids]);const residuals: Record<string, number> = {};const listing: NonNullable<RepairPlan['listing']> = [];+ const segmented = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id, p.slug FROM pages p+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.body_storage='segmented'+ AND EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id=p.id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.region='truth'+ AND m.protected_regions @> '[{"kind":"facts"}]'::jsonb)+ AND EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.page_id=p.id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.region='timeline'+ AND m.protected_regions @> '[{"kind":"facts"}]'::jsonb)+ ORDER BY p.id`, [scope.source_ids]);+ for (const page of segmented) {+ residuals.segmented = (residuals.segmented ?? 0) + 1;+ listing.push({ item: `${page.source_id}:${page.slug}`, class: 'segmented',+ detail: 'the page stores its body in segments and this repair rewrites the whole body as one string; no command merges its fences yet' });+ }const merge: ApprovedPage[] = [];for (const page of pages) {const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });diff --git a/src/core/repair/timeline-comments.ts b/src/core/repair/timeline-comments.tsindex bc6065d796..0ab56a5984 100644--- a/src/core/repair/timeline-comments.ts+++ b/src/core/repair/timeline-comments.ts@@ -22,9 +22,10 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { materializedMarkerHash } from '../timeline-marker.ts';import { stripHtmlComments } from '../timeline-citations.ts';+import { SEGMENTED_SAMPLE } from './timeline.ts';import { repairRequestId, type RepairHandler, type RepairItem, type RepairScope, type RepairCursor } from './core.ts';-interface MarkupRow { id: number; page_id: number; source_id: string; slug: string; date: string; source: string; summary: string; detail: string }+interface MarkupRow { id: number; page_id: number; source_id: string; slug: string; date: string; source: string; summary: string; detail: string; body_storage: string }const MARKUP_SQL = `(t.summary LIKE '%<!--%' OR t.summary LIKE '%-->%' OR t.source LIKE '%<!--%' OR t.source LIKE '%-->%'OR t.detail LIKE '%<!--%' OR t.detail LIKE '%-->%')`;@@ -46,7 +47,7 @@ export function dropCommentBullets(body: string): string {}async function markupRows(engine: BrainEngine, where: string, params: unknown[]): Promise<MarkupRow[]> {- return engine.executeRaw<MarkupRow>(`SELECT t.id, t.page_id, p.source_id, p.slug, t.date::text AS date, t.source, t.summary, t.detail+ return engine.executeRaw<MarkupRow>(`SELECT t.id, t.page_id, p.source_id, p.slug, t.date::text AS date, t.source, t.summary, t.detail, p.body_storageFROM timeline_entries t JOIN pages p ON p.id=t.page_idWHERE t.event_page_id IS NULL AND p.deleted_at IS NULL AND ${MARKUP_SQL} AND ${where} ORDER BY t.page_id, t.id`, params);}@@ -75,7 +76,9 @@ async function cleanRows(engine: BrainEngine, page: { id: number; slug: string;export const timelineCommentsRepair: RepairHandler = {kind: 'timeline-comments',async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {- const rows = await markupRows(engine, 'p.source_id=ANY($1::text[]) AND p.id>$2', [scope.source_ids, after?.id ?? 0]);+ const all = await markupRows(engine, 'p.source_id=ANY($1::text[]) AND p.id>$2', [scope.source_ids, after?.id ?? 0]);+ const rows = all.filter(row => row.body_storage !== 'segmented');+ const segmented = [...new Map(all.filter(row => row.body_storage === 'segmented').map(row => [row.page_id, `${row.source_id}:${row.slug}`])).values()];const pages = await engine.executeRaw<{ id: number; source_id: string; slug: string; compiled_truth: string; timeline: string | null }>(`SELECT id, source_id, slug, compiled_truth, timeline FROM pages WHERE source_id=ANY($1::text[]) AND deleted_at IS NULL AND id>$2AND (compiled_truth LIKE '%gbrain:materialized%' OR timeline LIKE '%gbrain:materialized%') ORDER BY id`, [scope.source_ids, after?.id ?? 0]);@@ -93,10 +96,14 @@ export const timelineCommentsRepair: RepairHandler = {}const items: RepairItem[] = [...byPage.values()].sort((a, b) => a.id - b.id).map(p => ({ cursor: { phase: 0, id: p.id }, source_id: p.source_id, slug: p.slug,chars: p.chars, action: [p.bullets ? 'drop comment bullets' : '', p.rows.length ? `clean ${p.rows.length} row(s)` : ''].filter(Boolean).join(', ') }));- return { items, residuals: {+ const warnings = segmented.length ? [`segmented_pages: ${all.length - rows.length} timeline row(s) with comment markup on ${segmented.length} segmented page(s) `+ + `(${segmented.slice(0, SEGMENTED_SAMPLE).join(', ')}${segmented.length > SEGMENTED_SAMPLE ? ', …' : ''}) are left as they are: this repair rewrites a whole body as one string, `+ + 'so it does not handle segmented pages, and no command does yet.'] : [];+ return { ...(warnings.length ? { warnings } : {}), items, residuals: {comment_only_rows: rows.filter(r => !clean(r.summary)).length,comment_bearing_rows: rows.filter(r => !!clean(r.summary)).length,pages_with_comment_bullets: [...byPage.values()].filter(p => p.bullets).length,+ ...(segmented.length ? { segmented_pages: segmented.length, segmented_rows: all.length - rows.length } : {}),} };},async apply(ctx, item) {diff --git a/src/core/repair/timeline.ts b/src/core/repair/timeline.tsindex 628cd6a4b0..4649192a68 100644--- a/src/core/repair/timeline.ts+++ b/src/core/repair/timeline.ts@@ -7,6 +7,11 @@* earlier stored version of the page produced and its current text dropped* are removals, not history (`timeline_orphans`, `extract timeline* --prune-orphans`), so they are not counted or materialized here.+ *+ * Only inline pages are classified and repaired: a segmented page (Wave B)+ * keeps its body in segments and this repair re-publishes the whole body as+ * one string. Segmented pages carrying timeline rows are counted and named+ * as a residual (`segmentedTimelinePages`) instead.*/import type { BrainEngine } from '../engine.ts';import { serializePageToMarkdown } from '../markdown.ts';@@ -43,7 +48,7 @@ async function classifyTimelinePage(engine: BrainEngine, page: TimelinePage, stoexport async function recountTimelinePages(engine: BrainEngine, sourceIds: string[], ids: number[]) {if (ids.length === 0) return [];const pages = await engine.executeRaw<TimelinePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages p- WHERE p.id = ANY($1::bigint[]) AND p.source_id=ANY($2::text[]) AND p.deleted_at IS NULL`, [ids, sourceIds]);+ WHERE p.id = ANY($1::bigint[]) AND p.source_id=ANY($2::text[]) AND p.deleted_at IS NULL AND p.body_storage='inline'`, [ids, sourceIds]);const stored = await storedRowsByPage(engine, pages);const counted = [];for (const page of pages) counted.push({ id: page.id, ...await classifyTimelinePage(engine, page, stored.get(Number(page.id))) });@@ -60,7 +65,7 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: stringlet cursor = afterId, inspected = 0, truncated = false;for (;;) {const batch = await engine.executeRaw<TimelinePage>(`SELECT p.id,p.source_id,p.slug,p.compiled_truth,p.timeline FROM pages p- WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.id>$2+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.id>$2 AND p.body_storage='inline'AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id=p.id AND t.event_page_id IS NULL)ORDER BY p.id LIMIT ${BATCH}`, [sourceIds, cursor]);const stored = await storedRowsByPage(engine, batch);@@ -78,6 +83,33 @@ export async function scanTimelineHistory(engine: BrainEngine, sourceIds: string}}+/** Slugs a segmented-page residual names (the counts cover every page). */+export const SEGMENTED_SAMPLE = 10;++/**+ * Segmented pages carrying non-event timeline rows: this repair cannot classify or+ * materialize them (it re-publishes the whole body as one string), so they are+ * counted, with their rows, and the first SEGMENTED_SAMPLE are named.+ */+export async function segmentedTimelinePages(engine: BrainEngine, sourceIds: string[]): Promise<{ pages: number; rows: number; sample: string[] }> {+ const [counts] = await engine.executeRaw<{ pages: number; rows: number }>(`SELECT count(DISTINCT p.id)::int AS pages, count(*)::int AS rows+ FROM timeline_entries t JOIN pages p ON p.id=t.page_id+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.body_storage='segmented' AND t.event_page_id IS NULL`, [sourceIds]);+ if (!counts?.pages) return { pages: 0, rows: 0, sample: [] };+ const named = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT p.source_id, p.slug FROM pages p+ WHERE p.source_id=ANY($1::text[]) AND p.deleted_at IS NULL AND p.body_storage='segmented'+ AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id=p.id AND t.event_page_id IS NULL)+ ORDER BY p.id LIMIT ${SEGMENTED_SAMPLE}`, [sourceIds]);+ return { pages: Number(counts.pages), rows: Number(counts.rows), sample: named.map(page => `${page.source_id}:${page.slug}`) };+}++/** The sentence a preview or doctor prints for segmented pages carrying timeline rows. */+export function segmentedTimelineNote(segmented: { pages: number; rows: number; sample: string[] }): string {+ return `${segmented.rows} timeline row(s) on ${segmented.pages} segmented page(s) (${segmented.sample.join(', ')}${segmented.pages > segmented.sample.length ? ', …' : ''}) `+ + 'are not checked for a bullet in their page or materialized: gbrain repair timeline re-publishes a whole body as one string, so it does not handle segmented pages, '+ + 'and no command does yet. The rows are kept as-is.';+}+export const timelineRepair: RepairHandler = {kind: 'timeline',async plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null) {@@ -90,9 +122,12 @@ export const timelineRepair: RepairHandler = {// #6184: such rows are never rendered back (they would duplicate a section END marker); name the cleanup.const warnings = markup ? [`timeline_comment_markup: ${markup} timeline row(s) carry HTML comment markup and stay database-side; `+ `preview the cleanup with gbrain repair timeline-comments${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}.`] : [];+ const segmented = await segmentedTimelinePages(engine, scope.source_ids);+ if (segmented.pages) warnings.push(`segmented_pages: ${segmentedTimelineNote(segmented)}`);return { ...(warnings.length ? { warnings } : {}), items, residuals: {materializable_rows: pages.reduce((n, p) => n + p.materializable, 0),kept_unrenderable_rows: pages.reduce((n, p) => n + p.unrenderable, 0),+ ...(segmented.pages ? { segmented_pages: segmented.pages, segmented_rows: segmented.rows } : {}),} };},async apply(ctx, item) {