Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): Wave B PR 4 recall: segmented forced cuts on sentence or line ends (SEGMENTED_CHUNKER_VERSION 5) and gbrain reindex --segmented preview/apply re-chunk
garrytanc72acc24e5a1
diff --git a/src/cli/commands/reindex.ts b/src/cli/commands/reindex.tsindex 5cdc42c4b9..7e9a99275d 100644--- a/src/cli/commands/reindex.ts+++ b/src/cli/commands/reindex.ts@@ -48,6 +48,10 @@ export async function run(engine: BrainEngine, args: string[]): Promise<void> {}return;}+ if (args.includes('--segmented')) {+ await reindex.runReindexSegmented(engine, args);+ return;+ }if (args.includes('--oversized')) {const { runOversizedBackfill, formatOversizedBackfillReceipt } = await import('../../core/oversized-backfill.ts');const value = (flag: string) => { const at = args.indexOf(flag); return at >= 0 ? args[at + 1] : undefined; };diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex 15f0b6ec67..52bdb16ec2 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -38,6 +38,7 @@ import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { loadConfig } from '../core/config.ts';import { BudgetExhausted, BudgetTracker } from '../core/budget/budget-tracker.ts';import { withBudgetTracker } from '../core/ai/gateway.ts';+import type { SegmentedRechunkReceipt } from '../core/page-body/rechunk.ts';interface ReindexOpts {/** Cap total pages reindexed. Useful for triage runs on huge brains. */@@ -90,6 +91,7 @@ USAGEgbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]gbrain reindex --vectors [--dry-run] [--json]gbrain reindex --oversized [--limit N] [--dry-run] [--json] [--source <id>]+ gbrain reindex --segmented [--source <id>] [--slug <slug>] [--apply] [--json]TARGETS (exactly one required)--markdown Re-chunk markdown pages whose chunker_version lags the@@ -112,6 +114,13 @@ TARGETS (exactly one required)with embeddings off and makes them keyword-searchablenow. Pages over 1 MiB wait for approval before any paidembedding (gbrain embed --held). Resumable.+ --segmented Re-chunk pages over 1 MiB (segmented storage) whose chunks+ an older segmented chunker made: long passages now cut at+ sentence or line ends. Previews by default (pages, chunk+ counts, new chunk texts; writes nothing). --apply re-chunks+ only the segments that change, keeps the vectors of+ unchanged chunk texts and leaves new texts to the embed+ sweep (gbrain embed --stale). Never runs on upgrade.OPTIONS--type <t> --markdown only: restrict to one page type@@ -128,7 +137,9 @@ OPTIONS--dry-run, --no-embed and a keyless brain never ask);--multimodal skips its cost confirm--max-usd USD --markdown: approve the paid run with this cost cap- --source <id> --aliases and --oversized: restrict to one source+ --source <id> --aliases, --oversized and --segmented: restrict to one source+ --slug <slug> --segmented only: one page+ --apply --segmented only: apply the previewed re-chunk--repo PATH --markdown only: brain repo override--json Machine-readable output--help, -h Show this help@@ -173,6 +184,7 @@ export function validateReindexModeScope(args: string[]): string | null {if (args.includes('--multimodal')) return '--type is only supported with reindex --markdown, not --multimodal';if (args.includes('--aliases')) return '--type is only supported with reindex --markdown, not --aliases';if (args.includes('--oversized')) return '--type is only supported with reindex --markdown, not --oversized';+ if (args.includes('--segmented')) return '--type is only supported with reindex --markdown, not --segmented';return null;}@@ -628,3 +640,27 @@ async function reindexManaged(engine: BrainEngine, opts: ReindexOpts, type: stri}return { ...base, pendingAfter, reindexed, skipped: 0, failed };}++/**+ * `gbrain reindex --segmented`: preview (default) or `--apply` the re-chunk of sealed segmented pages an older+ * segmented chunker made (core/page-body/rechunk.ts). Nothing on upgrade or migration runs it.+ */+export async function runReindexSegmented(engine: BrainEngine, args: string[]): Promise<SegmentedRechunkReceipt | null> {+ args = normalizeReindexArgs(args);+ const json = args.includes('--json');+ const invalid = ['--source', '--slug'].find(flag => invalidRequiredValueFlag(args, flag));+ if (invalid) {+ const error = `invalid ${invalid}: expected a value`;+ if (json) process.stdout.write(JSON.stringify({ error }) + '\n');+ else process.stderr.write(`[reindex] ${error}\n`);+ setCliExitVerdict(2);+ return null;+ }+ const value = (flag: string) => { const at = args.indexOf(flag); return at >= 0 ? args[at + 1] : undefined; };+ const { runSegmentedRechunk, formatSegmentedRechunkReceipt } = await import('../core/page-body/rechunk.ts');+ const receipt = await runSegmentedRechunk(engine, { apply: args.includes('--apply'), sourceId: value('--source'), slug: value('--slug') });+ if (json) process.stdout.write(JSON.stringify(receipt, null, 2) + '\n');+ else for (const line of formatSegmentedRechunkReceipt(receipt)) console.log(line);+ if (receipt.pages.some(page => page.state === 'failed')) setCliExitVerdict(1);+ return receipt;+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f3dbaeb083..a885ece251 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1022,6 +1022,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },+ // PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.+ { since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex 8a419fbfb8..3871ee62e9 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -78,6 +78,12 @@ export interface ChunkOptions {* a section appended after a full last chunk then leaves that chunk's text, and its vector, unchanged.*/headingsLead?: boolean;+ /**+ * The hard cap's forced cuts (capByChars) land on a sentence end, else a line end, else whitespace, else a code point,+ * searched backward from the bound over at most CUT_LOOKBACK_CHARS, and the next window starts one overlap before+ * that cut. Segmented pages only (segment-chunks.ts, SEGMENTED_CHUNKER_VERSION): inline chunks are unchanged.+ */+ boundaryCuts?: boolean;}export interface TextChunk {@@ -137,12 +143,13 @@ export function chunkProjectedText(stripped: string, opts?: ChunkOptions): TextC: DEFAULT_MAX_CHUNK_TOKENS;if (!stripped || stripped.trim().length === 0) return [];+ const boundaryCuts = opts?.boundaryCuts === true;const wordCount = countWords(stripped);if (wordCount <= chunkSize) {// Single-chunk path: still apply the maxChars cap.const whole = trimmedRun({ text: stripped, segs: [{ t: 0, s: 0, n: stripped.length }] });- return finish(stripped, capByChars(whole.text, maxChars, maxTokens).map(c => placed(whole, c)), opts?.spans === true);+ return finish(stripped, capByChars(whole.text, maxChars, maxTokens, undefined, boundaryCuts).map(c => placed(whole, c)), opts?.spans === true);}// Recursively split, then greedily merge to target size@@ -155,7 +162,7 @@ export function chunkProjectedText(stripped: string, opts?: ChunkOptions): TextCconst capped: Placed[] = [];for (const chunk of withOverlap) {const run = trimmedRun(chunk);- for (const c of capByChars(run.text, maxChars, maxTokens)) capped.push(placed(run, c));+ for (const c of capByChars(run.text, maxChars, maxTokens, undefined, boundaryCuts)) capped.push(placed(run, c));}return finish(stripped, capped, opts?.spans === true);}@@ -286,6 +293,7 @@ function capByChars(maxChars: number,maxTokens: number = DEFAULT_MAX_CHUNK_TOKENS,knownEst?: number,+ boundaryCuts = false,): Slice[] {if (text.length === 0) return [];if (knownEst === undefined && text.length <= maxChars && fitsEmbedTokens(text, maxTokens)) return [{ text, at: 0 }];@@ -299,7 +307,7 @@ function capByChars(// a sparse ASCII head can under-read a dense CJK tail.if (knownEst !== undefined || text.length <= DENSITY_PROBE_CHARS) return [{ text, at: 0 }];const exact = estimateEmbedTokens(text);- return exact <= maxTokens ? [{ text, at: 0 }] : capByChars(text, maxChars, maxTokens, exact);+ return exact <= maxTokens ? [{ text, at: 0 }] : capByChars(text, maxChars, maxTokens, exact, boundaryCuts);}// The stride keeps its nominal window-minus-overlap value. Evening the// windows out (as the header-budget hard split does) is WRONG here: that@@ -310,10 +318,12 @@ function capByChars(// that trade and is the behavior this loop has always had.const overlap = Math.min(500, Math.floor(window / 10));const stride = Math.max(1, window - overlap);+ const lookback = Math.min(CUT_LOOKBACK_CHARS, Math.floor(window / 4));const out: Slice[] = [];let i = 0;while (i < text.length) {- const end = safeSplitIndex(text, Math.min(text.length, i + window));+ const bound = safeSplitIndex(text, Math.min(text.length, i + window));+ const end = boundaryCuts && bound < text.length ? forcedCut(text, bound, lookback) : bound;const raw = text.slice(i, end);const slice = raw.trim();const at = i + raw.length - raw.trimStart().length;@@ -323,18 +333,50 @@ function capByChars(// Denser than the text average — re-derive locally, reusing the exact// figure just measured (it also guarantees window < slice.length, so// the recursion strictly shrinks).- for (const part of capByChars(slice, maxChars, maxTokens, sliceEst)) out.push({ text: part.text, at: at + part.at });+ for (const part of capByChars(slice, maxChars, maxTokens, sliceEst, boundaryCuts)) out.push({ text: part.text, at: at + part.at });} else {out.push({ text: slice, at });}}if (end >= text.length) break;- const next = safeSplitIndex(text, Math.min(text.length, i + stride));+ const next = safeSplitIndex(text, Math.min(text.length, boundaryCuts ? end - overlap : i + stride));i = next > i ? next : i + 1;}return out;}+/**+ * Chars a forced cut may move back from the hard bound to reach a sentence or line end. A constant, so the cut search+ * adds at most this much work per window and chunking stays linear; capped at a quarter of the window, so a window+ * keeps three quarters of its length and the next one (one overlap, at most a tenth, before the cut) moves forward.+ */+export const CUT_LOOKBACK_CHARS = 512;++/** @internal Code units the forced-cut search visits, for the linearity test (counts, not time). */+export const cutWork = { scanned: 0 };++const SENTENCE_END_CHARS = new Set(['.', '!', '?']);+const CJK_SENTENCE_END_CHARS = new Set(CJK_SENTENCE_DELIMITERS);+const isSpace = (c: string | undefined) => c !== undefined && /\s/.test(c);++/**+ * Where a forced cut at `bound` lands: after the last sentence end at most `lookback` code units back, else after the+ * last line end, else at the last whitespace, else at `bound` (already a code-point boundary). One backward pass.+ * Every candidate sits between code points (a delimiter or whitespace is one BMP unit) and never between CR and LF.+ */+function forcedCut(text: string, bound: number, lookback: number): number {+ let line = -1, space = -1;+ for (let c = bound; c > bound - lookback && c > 0; c--) {+ cutWork.scanned++;+ const before = text[c - 1]!, at = text[c];+ if (before === '\r' && at === '\n') continue;+ if (CJK_SENTENCE_END_CHARS.has(before) || (isSpace(at) && SENTENCE_END_CHARS.has(before))) return c;+ if (line < 0 && (before === '\n' || at === '\n' || at === '\r')) line = c;+ if (space < 0 && (isSpace(before) || isSpace(at))) space = c;+ }+ return line >= 0 ? line : space >= 0 ? space : bound;+}+/*** Chars measured to derive the window. estimateEmbedTokens is SUPERLINEAR on* CJK — measured on this repo's encoder: 2K chars 11ms, 6K 99ms, 20K 1,138ms —diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex a634a2ef0f..a52c59b67e 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -49,7 +49,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--cursor', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -75,10 +75,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--request-id', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--catch-up', '--chat-model', '--check', '--class', '--clear-never-installed', '--client', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--cursor', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--install', '--issuer-url', '--json', '--keep', '--keep-checkout', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-filters', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--statement-timeout', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--adopt-slug-path', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],@@ -93,7 +93,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--older-than', '--retry-parked', '--source', '--state', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],- 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],'protocol': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],@@ -103,7 +103,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],- 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],@@ -135,7 +135,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],- 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],+ 'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--resume', '--retry-global', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsindex d6b332309c..81c93f6647 100644--- a/src/core/page-body/ingest.ts+++ b/src/core/page-body/ingest.ts@@ -30,7 +30,7 @@ import { initialEntryState, readEntryState, timelineEntryState, type EntryStateimport { ContentHashStream } from './content-hash-stream.ts';import { prepareSegmentChunks } from './segment-chunks.ts';import { reuseSegmentChunkVectors } from '../import-chunk-reuse.ts';-import { newFenceChunkBudget } from '../markdown-chunks.ts';+import { newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';import { loadFenceChunkOverlay } from '../eligibility/fence-overlay.ts';import { withdrawalFenceBlocks } from '../facts/withdrawal-overlay.ts';import { overlaySegmentText, readBodyLedger, type BodyLedger } from './segment-ledger.ts';@@ -384,10 +384,12 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageIdhold?: SegmentChunkInput[];/** Guarded: runs in each batch's transaction before its insert (the projection renews its claim on the page's queue row);* false when the caller lost its claim: that batch inserts nothing and the staging stops. */- renew?: (tx: BrainEngine) => Promise<boolean> }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {+ renew?: (tx: BrainEngine) => Promise<boolean>;+ /** The page's fence-chunk budget when one page is chunked over several calls (the re-chunk, page-body/rechunk.ts); default a new one. */+ fenceBudget?: FenceChunkBudget }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };const batchBytes = STAGE_BATCH_BYTES[engine.kind];- const fenceBudget = newFenceChunkBudget();+ const fenceBudget = input.fenceBudget ?? newFenceChunkBudget();let ledger: BodyLedger | undefined;let rows = 0, done = 0;const indexes: number[] = [];diff --git a/src/core/page-body/rechunk.ts b/src/core/page-body/rechunk.tsnew file mode 100644index 0000000000..7884379f1d--- /dev/null+++ b/src/core/page-body/rechunk.ts@@ -0,0 +1,267 @@+/**+ * Re-chunk sealed segmented pages stored under an older SEGMENTED_CHUNKER_VERSION (`gbrain reindex --segmented`).+ *+ * Preview first: the preview chunks each page's live occurrences with today's segmented chunker, compares the result+ * with the stored rows, and writes nothing. `--apply` re-stages only the occurrences whose chunks change, one staging+ * batch (STAGE_BATCH_BYTES of segments) per transaction under the page lock: the batch's new rows are staged above the+ * live generation (staging kind `resegment`), vectors of unchanged chunk texts are copied from the same occurrence's+ * stored rows (text-keyed reuse), and the generation flip retires the occurrence's old rows. Occurrence ids, segment+ * texts, the manifest and the knowledge revision stay as they are (the body did not change), so per-segment+ * derivations stay settled and nothing is re-extracted; new chunk texts carry no vector until the embed sweep. The page+ * keeps serving its old rows until each batch flips, and is stamped at SEGMENTED_CHUNKER_VERSION only when every batch+ * landed. No migration or upgrade step runs this.+ */+import type { BrainEngine } from '../engine.ts';+import { isQuarantined } from '../quarantine.ts';+import { chunkGenerationFilter } from '../search/safe-chunks.ts';+import { newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';+import { reuseSegmentChunkVectors } from '../import-chunk-reuse.ts';+import { maintenanceAttribution } from '../persistence/attribution.ts';+import { applySegmentedBody, sealSegmentedPage } from '../persistence/segmented-apply.ts';+import { withPageTierKept } from '../trust/fence-append.ts';+import { openSegmentedStaging, segmentWriteScope, stageOccurrenceChunks } from './ingest.ts';+import { readPageBodyPolicy, STAGE_BATCH_BYTES } from './limits.ts';+import { SEGMENTED_CHUNKER_VERSION } from './segment-chunks.ts';+import type { JsonObject, ManifestRow, SegmentChunkInput } from './types.ts';++export interface SegmentedRechunkPage {+ source_id: string;+ slug: string;+ /** The page's chunker version when the run read it. */+ chunker_version: number;+ segments: number;+ /** Stored chunk rows of the live occurrences, and the rows today's chunker makes of them. */+ chunks: number;+ chunks_after: number;+ /** Occurrences whose chunks change, and chunk texts no stored row of the same occurrence holds (they need a vector). */+ segments_changed: number;+ new_chunk_texts: number;+ /** Apply only. `moved`: another write published while this page was re-chunked; it keeps its version, run again. */+ state?: 'rechunked' | 'stamped' | 'moved' | 'failed';+ vectors_reused?: number;+ error?: string;+}++export interface SegmentedRechunkReceipt {+ dry_run: boolean;+ chunker_version: number;+ pages: SegmentedRechunkPage[];+ commands: { apply: string[] | null; embed: string[] | null; preview: string[] };+}++/** @internal Work counts for the re-chunk tests: staging batches chunked, batches that flipped, rows staged and vectors reused. */+export const rechunkWork = { batches: 0, flips: 0, staged: 0, reused: 0 };++interface RechunkPageRow {+ id: number; slug: string; source_id: string; title: string; type: string; page_kind: string; frontmatter: JsonObject | null;+ body_generation: number | string; body_flags: JsonObject | null; chunker_version: number | null; contextual_retrieval_mode: string | null;+ corpus_generation: string | null; knowledge_revision: string; sealed: boolean; updated_us: string; deleted_at: string | null;+ content_hash: string; body_bytes: number | string; truth_bytes: number | string; body_lines: number | string; segment_count: number;+ segmenter_version: number; truth_lead: string | null; timeline_lead: string | null;+}++class PageMoved extends Error {}++const PAGE_SQL = `SELECT id, slug, source_id, title, type, page_kind, frontmatter, body_generation, body_flags, chunker_version,+ contextual_retrieval_mode, corpus_generation, knowledge_revision::text AS knowledge_revision,+ (text_projection_revision = knowledge_revision) IS TRUE AS sealed, (extract(epoch FROM updated_at) * 1000000)::bigint::text AS updated_us, deleted_at, content_hash, body_bytes, truth_bytes,+ body_lines, segment_count, segmenter_version, truth_lead, timeline_lead+ FROM pages WHERE id=$1 AND body_storage='segmented'`;++/** Sealed, live segmented pages below the current segmented chunker, in a stable order. */+async function candidates(engine: BrainEngine, scope: { sourceId?: string; slug?: string }): Promise<Array<{ id: number }>> {+ const params: unknown[] = [SEGMENTED_CHUNKER_VERSION];+ let where = '';+ if (scope.sourceId) { params.push(scope.sourceId); where += ` AND source_id=$${params.length}`; }+ if (scope.slug) { params.push(scope.slug); where += ` AND slug=$${params.length}`; }+ return engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE body_storage='segmented' AND deleted_at IS NULL+ AND chunker_version < $1 AND (text_projection_revision = knowledge_revision) IS TRUE${where} ORDER BY source_id, slug`, params);+}++/** The tier and corpus generation the page's stored vectors were embedded under, so reuse admits them as a write would. */+const reuseTier = (page: RechunkPageRow) => page.contextual_retrieval_mode === 'title'+ ? { tier: 'title' as const, corpusGeneration: page.corpus_generation } : { tier: 'none' as const, corpusGeneration: null };++const chunkKey = (c: { chunk_source: string; chunk_text: string; raw_byte_start: number; raw_byte_end: number;+ projected_byte_start?: number | null; projected_byte_end?: number | null }) =>+ JSON.stringify([c.chunk_source, c.chunk_text, c.raw_byte_start, c.raw_byte_end, c.projected_byte_start ?? null, c.projected_byte_end ?? null]);+const num = (v: unknown) => (v === null || v === undefined ? null : Number(v));++interface BatchPlan {+ /** Today's chunks of the changed occurrences. */+ held: SegmentChunkInput[];+ changed: number[];+ /** Stored rows of the changed occurrences (the flip retires them), of the whole batch, and today's chunk count. */+ retiring: number;+ stored: number;+ chunksAfter: number;+ newTexts: number;+}++/** Chunk one batch of occurrences with today's chunker (nothing staged) and compare with the stored rows. */+async function planBatch(exec: BrainEngine, page: RechunkPageRow, batch: readonly ManifestRow[], fenceBudget: FenceChunkBudget): Promise<BatchPlan> {+ const held: SegmentChunkInput[] = [];+ const frontmatter = page.frontmatter ?? {};+ await stageOccurrenceChunks(exec, { pageId: page.id, sourceId: page.source_id, slug: page.slug, generation: Number(page.body_generation),+ occurrences: batch, title: page.title, frontmatter, flags: page.body_flags ?? {},+ chunking: { quarantined: isQuarantined(frontmatter), ...reuseTier(page) }, retiredOccurrences: [], hold: held, fenceBudget });+ const ids = batch.map(row => Number(row.occurrenceId));+ const stored = await exec.executeRaw<{ occurrence_id: unknown; chunk_source: string; chunk_text: string; raw_byte_start: unknown; raw_byte_end: unknown;+ projected_byte_start: unknown; projected_byte_end: unknown }>(`SELECT c.occurrence_id, c.chunk_source, c.chunk_text, c.raw_byte_start, c.raw_byte_end,+ c.projected_byte_start, c.projected_byte_end FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE c.page_id = $1 AND c.occurrence_id = ANY($2::bigint[]) AND ${chunkGenerationFilter('p', 'c')}+ ORDER BY c.occurrence_id, c.local_ordinal`, [page.id, ids]);+ const before = new Map<number, Array<{ key: string; text: string }>>();+ for (const row of stored) {+ const id = Number(row.occurrence_id);+ const entry = { key: chunkKey({ chunk_source: row.chunk_source, chunk_text: row.chunk_text, raw_byte_start: Number(row.raw_byte_start),+ raw_byte_end: Number(row.raw_byte_end), projected_byte_start: num(row.projected_byte_start), projected_byte_end: num(row.projected_byte_end) }),+ text: `${row.chunk_source}\0${row.chunk_text}` };+ const list = before.get(id);+ if (list) list.push(entry); else before.set(id, [entry]);+ }+ const after = new Map<number, SegmentChunkInput[]>();+ for (const c of held) { const list = after.get(c.occurrence_id); if (list) list.push(c); else after.set(c.occurrence_id, [c]); }+ const plan: BatchPlan = { held: [], changed: [], retiring: 0, stored: stored.length, chunksAfter: held.length, newTexts: 0 };+ for (const id of ids) {+ const old = before.get(id) ?? [];+ const next = after.get(id) ?? [];+ if (old.length === next.length && next.every((c, i) => chunkKey(c) === old[i]!.key)) continue;+ plan.changed.push(id);+ plan.retiring += old.length;+ plan.held.push(...next);+ const texts = new Set(old.map(o => o.text));+ plan.newTexts += next.filter(c => !texts.has(`${c.chunk_source}\0${c.chunk_text}`)).length;+ }+ rechunkWork.batches++;+ return plan;+}++async function readPage(exec: Pick<BrainEngine, 'executeRaw'>, id: number): Promise<RechunkPageRow | null> {+ return (await exec.executeRaw<RechunkPageRow>(PAGE_SQL, [id]))[0] ?? null;+}++/** Under the page lock: the page is still the sealed, live generation this run expects, else it moved. */+async function lockedPage(tx: BrainEngine, ref: { id: number; sourceId: string; slug: string }, generation: number): Promise<RechunkPageRow> {+ await tx.lockPageKeys([{ sourceId: ref.sourceId, slug: ref.slug }]);+ const page = await readPage(tx, ref.id);+ if (!page || Number(page.body_generation) !== generation || !page.sealed || page.deleted_at) throw new PageMoved();+ return page;+}++/** Re-stage one batch's changed occurrences and flip, in the caller's transaction; returns the vectors reused. */+async function flipBatch(tx: BrainEngine, page: RechunkPageRow, plan: BatchPlan, owner: { kind: string; id: string }, retireMaxRows: number): Promise<number> {+ if (plan.retiring > retireMaxRows) {+ throw new Error(`A staging batch of ${page.slug} retires ${plan.retiring} chunk rows, over the flip's limit of ${retireMaxRows}.`);+ }+ const generation = Number(page.body_generation);+ const next = generation + 1;+ const stagingId = await openSegmentedStaging(tx, { sourceId: page.source_id, slug: page.slug, declaredBytes: Number(page.body_bytes),+ live: { id: page.id, generation, storage: 'segmented', title: page.title, type: page.type, flags: page.body_flags },+ owner: { kind: 'resegment', principalKind: owner.kind, principalId: owner.id, baseRevision: page.knowledge_revision } });+ const reused = await reuseSegmentChunkVectors(tx, { pageId: page.id, retiredOccurrences: plan.changed, chunks: plan.held, title: page.title, ...reuseTier(page) });+ const indexes = await tx.stageSegmentChunks(page.id, next, plan.held);+ await tx.setBodyStagingState(stagingId, 'prepared');+ // The body is unchanged: the flip keeps the knowledge revision (and so the seal), as a materialization does.+ const [prior] = await tx.executeRaw<{ revision: string | null }>("SELECT current_setting('gbrain.materializing_revision', true) AS revision");+ await tx.executeRaw("SELECT set_config('gbrain.materializing_revision', $1, true)", [page.knowledge_revision]);+ const applied = await withPageTierKept(tx, { sourceId: page.source_id, slug: page.slug }, () => applySegmentedBody(tx, {+ slug: page.slug, sourceId: page.source_id, pageId: page.id, promotion: false, retireMaxRows,+ meta: { title: page.title, type: page.type as never, frontmatter: page.frontmatter ?? {}, page_kind: page.page_kind as never },+ prepared: { stagingId, expectedGeneration: generation, newGeneration: next, createRows: null, createChunks: null, closeOccurrences: [],+ retireChunkOccurrences: plan.changed, unchunked: 0, priorStale: false, bodyUnchanged: false, stagedChunkIndexes: indexes,+ rows: { texts: 0, manifest: 0, chunks: indexes.length },+ body: { content_hash: page.content_hash, body_bytes: Number(page.body_bytes), truth_bytes: Number(page.truth_bytes),+ body_lines: Number(page.body_lines), segment_count: page.segment_count, segmenter_version: page.segmenter_version,+ truth_lead: page.truth_lead ?? '', timeline_lead: page.timeline_lead ?? '', body_flags: page.body_flags ?? {} } } }));+ if (!applied.complete) throw new Error(`The re-chunk flip of ${page.slug} left rows to retire after its transaction.`);+ // A re-chunk is not an edit: the page keeps its updated_at, restored exactly (microseconds survive no driver date round trip).+ await tx.executeRaw(`UPDATE pages SET updated_at = 'epoch'::timestamptz + $2::bigint * interval '1 microsecond' WHERE id=$1`, [page.id, page.updated_us]);+ await sealSegmentedPage(tx, page.id);+ await tx.executeRaw("SELECT set_config('gbrain.materializing_revision', $1, true)", [prior?.revision ?? '']);+ rechunkWork.flips++;+ rechunkWork.staged += indexes.length;+ rechunkWork.reused += reused;+ return reused;+}++async function rechunkPage(engine: BrainEngine, id: number, apply: boolean, retireMaxRows: number): Promise<SegmentedRechunkPage | null> {+ const first = await readPage(engine, id);+ if (!first) return null;+ const rows = await engine.readManifest(first.id);+ const out: SegmentedRechunkPage = { source_id: first.source_id, slug: first.slug, chunker_version: Number(first.chunker_version ?? 0),+ segments: rows.length, chunks: 0, chunks_after: 0, segments_changed: 0, new_chunk_texts: 0 };+ const tally = (plan: BatchPlan) => {+ out.chunks += plan.stored;+ out.chunks_after += plan.chunksAfter;+ out.segments_changed += plan.changed.length;+ out.new_chunk_texts += plan.newTexts;+ };+ const ref = { id: first.id, sourceId: first.source_id, slug: first.slug };+ const fenceBudget = newFenceChunkBudget();+ const batchBytes = STAGE_BATCH_BYTES[engine.kind];+ const batches: ManifestRow[][] = [];+ for (let start = 0; start < rows.length;) {+ let end = start, bytes = 0;+ while (end < rows.length && (end === start || bytes + rows[end]!.byteLen <= batchBytes)) bytes += rows[end++]!.byteLen;+ batches.push(rows.slice(start, end));+ start = end;+ }+ if (!apply) {+ for (const batch of batches) tally(await planBatch(engine, first, batch, fenceBudget));+ return out;+ }+ const scope = await segmentWriteScope(engine, first.source_id);+ const { principal } = await maintenanceAttribution(engine);+ let generation = Number(first.body_generation);+ let reused = 0;+ try {+ for (const batch of batches) {+ await scope(exec => exec.transaction(async tx => {+ const page = await lockedPage(tx, ref, generation);+ const plan = await planBatch(tx, page, batch, fenceBudget);+ tally(plan);+ if (!plan.changed.length) return;+ reused += await flipBatch(tx, page, plan, principal, retireMaxRows);+ generation++;+ }));+ }+ await scope(exec => exec.transaction(async tx => {+ const page = await lockedPage(tx, ref, generation);+ await tx.executeRaw('UPDATE pages SET chunker_version=$2 WHERE id=$1', [page.id, SEGMENTED_CHUNKER_VERSION]);+ }));+ return { ...out, state: out.segments_changed ? 'rechunked' : 'stamped', vectors_reused: reused };+ } catch (error) {+ if (error instanceof PageMoved) return { ...out, state: 'moved', vectors_reused: reused };+ return { ...out, state: 'failed', vectors_reused: reused, error: error instanceof Error ? error.message : String(error) };+ }+}++/** Preview (default) or apply the re-chunk of every sealed segmented page below SEGMENTED_CHUNKER_VERSION in scope. */+export async function runSegmentedRechunk(engine: BrainEngine, opts: { apply?: boolean; sourceId?: string; slug?: string } = {}): Promise<SegmentedRechunkReceipt> {+ const apply = opts.apply === true;+ const { flipRetireMaxRows } = await readPageBodyPolicy(engine);+ const pages: SegmentedRechunkPage[] = [];+ for (const { id } of await candidates(engine, opts)) {+ const page = await rechunkPage(engine, Number(id), apply, flipRetireMaxRows);+ if (page) pages.push(page);+ }+ const scope = [...(opts.sourceId ? ['--source', opts.sourceId] : []), ...(opts.slug ? ['--slug', opts.slug] : [])];+ const embed = apply && pages.some(p => p.state === 'rechunked' && p.new_chunk_texts > 0);+ return { dry_run: !apply, chunker_version: SEGMENTED_CHUNKER_VERSION, pages,+ commands: { apply: !apply && pages.length ? ['gbrain', 'reindex', '--segmented', ...scope, '--apply'] : null,+ embed: embed ? ['gbrain', 'embed', '--stale'] : null, preview: ['gbrain', 'reindex', '--segmented', ...scope] } };+}++export function formatSegmentedRechunkReceipt(r: SegmentedRechunkReceipt): string[] {+ const lines = [`reindex --segmented${r.dry_run ? ' (preview, nothing written)' : ''}: ${r.pages.length} page(s) below segmented chunker ${r.chunker_version}`];+ for (const p of r.pages) {+ lines.push(` ${p.source_id}/${p.slug} v${p.chunker_version} ${p.segments} segments, ${p.chunks} -> ${p.chunks_after} chunks, `+ + `${p.segments_changed} segment(s) change, ${p.new_chunk_texts} new chunk text(s)${p.state ? ` ${p.state}` : ''}`+ + `${p.vectors_reused ? `, ${p.vectors_reused} vector(s) reused` : ''}${p.error ? `: ${p.error}` : ''}`);+ }+ if (r.commands.apply) lines.push(`Apply: ${r.commands.apply.join(' ')}`);+ if (r.commands.embed) lines.push(`New chunk texts get vectors from the embed sweep: ${r.commands.embed.join(' ')}`);+ if (r.pages.some(p => p.state === 'moved')) lines.push(`A page changed while it was re-chunked; run again: ${r.commands.preview.join(' ')} --apply`);+ return lines;+}diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.tsindex fb91b6537b..8793ea1cc6 100644--- a/src/core/page-body/segment-chunks.ts+++ b/src/core/page-body/segment-chunks.ts@@ -20,7 +20,7 @@* reads serve its chunks.* Inline pages keep prepareMarkdownChunks; this is a separate chunker identity.*/-import { chunkProjectedText, chunkText, MARKDOWN_CHUNKER_VERSION } from '../chunkers/recursive.ts';+import { chunkProjectedText, chunkText } from '../chunkers/recursive.ts';import { estimateEmbedTokens } from '../chunkers/token-estimate.ts';import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';import { fencedCodeChunks, newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';@@ -32,11 +32,16 @@ import type { StoredRegion } from './segmenter.ts';import { projectSegment } from './segment-projection.ts';/**- * `pages.chunker_version` of a sealed segmented page: segments are chunked by the markdown pipeline- * (chunkProjectedText, fencedCodeChunks) under the same safe-fence contract, so they share its version, at or above- * SAFE_FENCE_CHUNKER_VERSION. A change to the cuts or the stored per-segment metadata bumps SEGMENTER_VERSION.+ * `pages.chunker_version` of a sealed segmented page whose live chunks were all made by this chunker. Segments are+ * chunked by the markdown pipeline (chunkProjectedText, fencedCodeChunks) under the same safe-fence contract, so it+ * stays at or above SAFE_FENCE_CHUNKER_VERSION, but it is its own identity: inline pages keep MARKDOWN_CHUNKER_VERSION.+ *+ * 5: the hard cap's forced cuts land on a sentence or line end (chunkProjectedText `boundaryCuts`), so a sentence the+ * cap used to split now sits whole in one chunk. Pages sealed at 4 keep serving their chunks until+ * `gbrain reindex --segmented --apply` re-chunks them (page-body/rechunk.ts). A change to the cuts or the stored+ * per-segment metadata bumps SEGMENTER_VERSION instead.*/-export const SEGMENTED_CHUNKER_VERSION = MARKDOWN_CHUNKER_VERSION;+export const SEGMENTED_CHUNKER_VERSION = 5;export type SegmentChunk = Omit<SegmentChunkInput, 'occurrence_id'>;@@ -85,7 +90,7 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segmconst wholeSegment = { raw_byte_start: 0, raw_byte_end: segment.bytes.length };if (projection.trim()) {- for (const c of chunkProjectedText(projection, { maxTokens, spans: true, headingsLead: true })) {+ for (const c of chunkProjectedText(projection, { maxTokens, spans: true, headingsLead: true, boundaryCuts: true })) {if (c.byte_start === undefined || c.byte_end === undefined) {push({ chunk_text: c.text, chunk_source: source, ...wholeSegment });continue;diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex eeeff11b3c..c18ba4a4e4 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -29,6 +29,7 @@ import { buildSegmentedProjection } from '../page-body/projection.ts';import { maintenanceAttribution } from './attribution.ts';import { readPageBodyPolicy, chooseBodyStorage, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, type PageBodyPolicy } from '../page-body/limits.ts';import { SEGMENTED_CHUNKER_VERSION } from '../page-body/segment-chunks.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { pageSearchVectorSql } from '../fts-language.ts';import { sanitizeRemoteBody } from '../remote-body.ts';@@ -145,16 +146,24 @@ export interface SegmentedApplied { pageId: number; complete: boolean; retireDef/*** Seal a segmented page's text projection at its current revision (chunks visible, title + timeline lead searchable).* The lead is indexed as the inline seal indexes a snapshot's timeline: after the page's withdrawal overlay, sanitized.+ * `chunker_version` is the oldest segmented chunker among the live chunks: a page sealed at an older one keeps it while+ * any chunk row from before this generation is still stored (a write re-chunks only the occurrences it changed), so+ * `gbrain reindex --segmented` still lists it.*/export async function sealSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number, timelineLead?: string): Promise<void> {- const [page] = await tx.executeRaw<{ slug: string; source_id: string; timeline_lead: string | null }>('SELECT slug, source_id, timeline_lead FROM pages WHERE id=$1', [pageId]);+ const [page] = await tx.executeRaw<{ slug: string; source_id: string; timeline_lead: string | null; chunker_version: number | null; body_generation: number | string }>(+ 'SELECT slug, source_id, timeline_lead, chunker_version, body_generation FROM pages WHERE id=$1', [pageId]);if (!page) return;+ const stamped = Number(page.chunker_version ?? 0);+ const older = stamped >= SAFE_FENCE_CHUNKER_VERSION && stamped < SEGMENTED_CHUNKER_VERSION && (await tx.executeRaw(+ `-- chunk-visibility-ok: a sealing page stores only live rows; any one older than this generation predates the write+ SELECT 1 FROM content_chunks WHERE page_id=$1 AND body_generation < $2 LIMIT 1`, [pageId, page.body_generation])).length > 0;const query = <T>(sql: string, params?: unknown[]) => tx.executeRaw<T>(sql, params);const ledger = await readPageSnapshot(query, page.slug, { sourceId: page.source_id, includeDeleted: true });const { timeline } = await overlayCanonicalBodies(query, '', timelineLead ?? page.timeline_lead ?? '', ledger?.withdrawals ?? [],{ sourceId: page.source_id, marker: ledger?.globalPurges });await tx.executeRaw(`UPDATE pages SET text_projection_revision=knowledge_revision, chunker_version=$3,- search_vector=${pageSearchVectorSql('title', '$2')} WHERE id=$1`, [pageId, sanitizeRemoteBody(timeline), SEGMENTED_CHUNKER_VERSION]);+ search_vector=${pageSearchVectorSql('title', '$2')} WHERE id=$1`, [pageId, sanitizeRemoteBody(timeline), older ? stamped : SEGMENTED_CHUNKER_VERSION]);}/** The segmented branch of a page write's apply, inside the publication transaction. */diff --git a/test/e2e/rechunk-segmented-postgres.test.ts b/test/e2e/rechunk-segmented-postgres.test.tsnew file mode 100644index 0000000000..fddced9c89--- /dev/null+++ b/test/e2e/rechunk-segmented-postgres.test.ts@@ -0,0 +1,15 @@+/**+ * The re-chunk of segmented pages sealed at an older segmented chunker on Postgres (Wave B PR 4, lane recall): the+ * shared cases. PGLite arm: test/large-pages/rechunk-segmented.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { defineRechunkSegmentedCases } from '../helpers/rechunk-segmented-cases.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('reindex --segmented [postgres]', () => {+ let engine: PostgresEngine;+ beforeAll(async () => { engine = await setupDB(); }, 120_000);+ afterAll(async () => { await teardownDB(); });+ defineRechunkSegmentedCases({ getEngine: () => engine });+});diff --git a/test/helpers/needle-chat.ts b/test/helpers/needle-chat.tsnew file mode 100644index 0000000000..d011caacc1--- /dev/null+++ b/test/helpers/needle-chat.ts@@ -0,0 +1,30 @@+/**+ * N14's 24 MiB needle layout reduced to a one-day chat (placeholder speakers, invented place name): the chat line shape+ * of the N14 conversation generator, and the seed and message position at which the version-4 segmented chunker's hard+ * cap split the needle sentence across two chunks. Used by test/large-pages/needle-sentence-chunk.test.ts and+ * test/helpers/rechunk-segmented-cases.ts.+ */+import { mulberry32 } from './seeded-random.ts';++const SPEAKERS = ['alice-example', 'bob-example', 'carol-example', 'dave-example'];+const WORDS = ('soon fine call sure coffee into book pretty tonight off apparently walk by good know lunch bakery short tell great from need '+ + 'definitely bike finish see basically to on today big maybe umbrella feel just even café naïve crème über 日曜日 🙂 👍 ☕ déjà').split(' ');+export const NEEDLE = 'the Fennmere harbor pilot is carol-example';++/** A one-day chat in N14's line shape: `lines` messages four minutes apart, the needle sentence as message `at` (-1: none). */+export function needleChat(seed: number, lines: number, at: number, day = '2018-12-29'): string {+ const r = mulberry32(seed);+ const out = [`## ${day}`, ''];+ for (let i = 0; i < lines; i++) {+ const who = SPEAKERS[Math.floor(r() * SPEAKERS.length)];+ const min = 7 * 60 + i * 4;+ const stamp = `(${day} ${((Math.floor(min / 60) + 11) % 12) + 1}:${String(min % 60).padStart(2, '0')} ${min < 720 ? 'AM' : 'PM'})`;+ const text = i === at ? `noting here that ${NEEDLE}` : Array.from({ length: 2 + Math.floor(r() * 18) }, () => WORDS[Math.floor(r() * WORDS.length)]).join(' ');+ out.push(`**${who}** ${stamp}: ${text}`);+ }+ return out.join('\n') + '\n';+}++/** N14's reduction: under the old cuts the hard cap's window ends inside the needle line. */+export const N14_REDUCED = needleChat(1, 62, 60);+diff --git a/test/helpers/rechunk-segmented-cases.ts b/test/helpers/rechunk-segmented-cases.tsnew file mode 100644index 0000000000..e3d7aa30a5--- /dev/null+++ b/test/helpers/rechunk-segmented-cases.ts@@ -0,0 +1,184 @@+/**+ * The re-chunk of segmented pages sealed at an older segmented chunker (`gbrain reindex --segmented`,+ * core/page-body/rechunk.ts), shared by the PGLite arm (test/large-pages/rechunk-segmented.test.ts) and the Postgres arm+ * (test/e2e/rechunk-segmented-postgres.test.ts). The page is N14's 24 MiB needle layout reduced to a 1.3 MB chat whose+ * first day is the reduction test/large-pages/needle-sentence-chunk.test.ts pins: under the old cuts its needle+ * sentence is split across two chunks. "Sealed at the old chunker" is built the way version 4 stored it: the same+ * per-segment pipeline without `boundaryCuts`, stamped chunker_version 4. Embeddings come from a counting fake.+ */+import { expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { runEmbedCore } from '../../src/commands/embed.ts';+import { runReindex } from '../../src/commands/reindex.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { chunkProjectedText } from '../../src/core/chunkers/recursive.ts';+import { resolveMaxChunkTokens } from '../../src/core/embedding-input-limit.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';+import { SEGMENTED_CHUNKER_VERSION } from '../../src/core/page-body/segment-chunks.ts';+import { rechunkWork, runSegmentedRechunk } from '../../src/core/page-body/rechunk.ts';+import type { SegmentChunkInput } from '../../src/core/page-body/types.ts';+import { N14_REDUCED, NEEDLE, needleChat } from './needle-chat.ts';++/** The chunker version segmented pages were sealed at before the forced-cut change. */+export const OLD_SEGMENTED_CHUNKER_VERSION = 4;++const dayOf = (n: number) => new Date(Date.UTC(2018, 11, 29 + n)).toISOString().slice(0, 10);+/** The needle day first, then filler days up to `bytes`. */+export function needlePageBody(bytes = 1_300_000, firstFiller = 1): string {+ let body = N14_REDUCED;+ for (let d = firstFiller; Buffer.byteLength(body) < bytes; d++) body += '\n' + needleChat(100 + d, 400, -1, dayOf(d));+ return body;+}+export const needlePage = (body: string) => `---\ntitle: Group chat\ntype: note\n---\n\n${body}`;++interface ChunkRow { id: number; occurrence_id: number; chunk_source: string; chunk_text: string }++async function pageId(engine: BrainEngine, slug: string): Promise<number> {+ return Number((await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0]!.id);+}++/** The page's chunk rows (all stored rows: a sealed page stores only live ones). */+async function chunkRows(engine: BrainEngine, id: number): Promise<ChunkRow[]> {+ return (await engine.executeRaw<ChunkRow>(`-- chunk-visibility-ok: test probe of every stored row of one sealed page+ SELECT id, occurrence_id, chunk_source, chunk_text FROM content_chunks WHERE page_id=$1 ORDER BY occurrence_id, local_ordinal`, [id]))+ .map(row => ({ ...row, id: Number(row.id), occurrence_id: Number(row.occurrence_id) }));+}++async function pageState(engine: BrainEngine, id: number) {+ const [page] = await engine.executeRaw<Record<string, unknown>>(`SELECT chunker_version, body_generation::text AS body_generation,+ knowledge_revision::text AS knowledge_revision, (text_projection_revision = knowledge_revision) IS TRUE AS sealed, content_hash,+ updated_at::text AS updated_at FROM pages WHERE id=$1`, [id]);+ const counts = await engine.executeRaw<Record<string, unknown>>(`SELECT+ (SELECT count(*)::int FROM page_body_manifest WHERE page_id=$1) AS manifest,+ (SELECT count(*)::int FROM page_body_stagings WHERE page_id=$1) AS stagings,+ (SELECT string_agg(occurrence_id::text, ',' ORDER BY seq) FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL) AS occurrences`, [id]);+ return { ...page, ...counts[0] };+}++/** Store the page's chunks as the version-4 segmented chunker made them (plain text: the projection is the segment). */+export async function sealAtOldChunker(engine: BrainEngine, slug: string): Promise<number> {+ const id = await pageId(engine, slug);+ const [page] = await engine.executeRaw<{ body_generation: number | string }>('SELECT body_generation FROM pages WHERE id=$1', [id]);+ const rows = await engine.readManifest(id);+ const texts = await engine.readSegmentTexts('default', rows.map(row => row.sha256));+ const chunks: SegmentChunkInput[] = [];+ for (const row of rows) {+ expect(row.protectedRegions).toEqual([]);+ const text = new TextDecoder().decode(texts.get(Buffer.from(row.sha256).toString('hex'))!);+ chunkProjectedText(text, { maxTokens: resolveMaxChunkTokens(), spans: true, headingsLead: true }).forEach((c, i) => chunks.push({+ chunk_text: c.text, chunk_source: row.region === 'truth' ? 'compiled_truth' : 'timeline', occurrence_id: Number(row.occurrenceId), local_ordinal: i,+ projected_byte_start: c.byte_start, projected_byte_end: c.byte_end, raw_byte_start: c.byte_start!, raw_byte_end: c.byte_end! }));+ }+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id=$1', [id]);+ await engine.stageSegmentChunks(id, Number(page!.body_generation), chunks);+ await engine.executeRaw('UPDATE pages SET chunker_version=$2 WHERE id=$1', [id, OLD_SEGMENTED_CHUNKER_VERSION]);+ return id;+}++const split = (rows: readonly ChunkRow[]) => rows.filter(r => r.chunk_text.includes('Fennmere') && !r.chunk_text.includes(NEEDLE));++/** Chunk texts of `after` that no row of the same occurrence in `before` holds. */+function newTexts(before: readonly ChunkRow[], after: readonly ChunkRow[]): number {+ const old = new Set(before.map(r => `${r.occurrence_id}\0${r.chunk_source}\0${r.chunk_text}`));+ return after.filter(r => !old.has(`${r.occurrence_id}\0${r.chunk_source}\0${r.chunk_text}`)).length;+}++export function defineRechunkSegmentedCases(opts: { getEngine: () => BrainEngine }): void {+ const embedded: string[] = [];+ const setup = async () => {+ const engine = opts.getEngine();+ const dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;+ await engine.setConfig('pages.segmented_storage', 'on');+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embedded.push(...values);+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };+ }) as never);+ embedded.length = 0;+ return engine;+ };+ const teardown = () => { __setEmbedTransportForTests(null); resetGateway(); };++ test('a page sealed at the old chunker: the preview lists it and writes nothing; --apply re-chunks it, keeps the vectors of unchanged texts, embeds only new texts and search finds the needle whole', async () => {+ const engine = await setup();+ try {+ const slug = 'chats/rechunk-needle';+ await importFromContent(engine, slug, needlePage(needlePageBody()), { noEmbed: true });+ const id = await sealAtOldChunker(engine, slug);+ await runEmbedCore(engine, { stale: true, quiet: true });+ expect(embedded.length).toBeGreaterThan(100);+ const before = await chunkRows(engine, id);+ const stateBefore = await pageState(engine, id);+ expect(stateBefore).toMatchObject({ chunker_version: OLD_SEGMENTED_CHUNKER_VERSION, sealed: true });+ expect(split(before).length).toBeGreaterThan(0);++ const preview = await runSegmentedRechunk(engine);+ expect(preview.dry_run).toBe(true);+ expect(preview.pages.map(p => [p.slug, p.chunker_version])).toEqual([[slug, OLD_SEGMENTED_CHUNKER_VERSION]]);+ const listed = preview.pages[0]!;+ expect(listed.chunks).toBe(before.length);+ expect(listed.segments_changed).toBeGreaterThan(0);+ expect(listed.new_chunk_texts).toBeGreaterThan(0);+ expect(preview.commands.apply).toEqual(['gbrain', 'reindex', '--segmented', '--apply']);+ expect(await chunkRows(engine, id)).toEqual(before);+ expect(await pageState(engine, id)).toEqual(stateBefore);++ embedded.length = 0;+ const work = { ...rechunkWork };+ const applied = await runSegmentedRechunk(engine, { apply: true });+ const page = applied.pages[0]!;+ expect(page).toMatchObject({ slug, state: 'rechunked', chunks: listed.chunks, chunks_after: listed.chunks_after,+ segments_changed: listed.segments_changed, new_chunk_texts: listed.new_chunk_texts });+ const after = await chunkRows(engine, id);+ const stateAfter = await pageState(engine, id);+ expect(stateAfter).toMatchObject({ chunker_version: SEGMENTED_CHUNKER_VERSION, sealed: true, knowledge_revision: stateBefore.knowledge_revision,+ content_hash: stateBefore.content_hash, updated_at: stateBefore.updated_at, manifest: stateBefore.manifest, occurrences: stateBefore.occurrences });+ expect(after.length).toBe(listed.chunks_after);+ const fresh = newTexts(before, after);+ expect(page.new_chunk_texts).toBe(fresh);+ const staged = rechunkWork.staged - work.staged;+ expect(rechunkWork.flips - work.flips).toBe(1);+ expect(page.vectors_reused).toBe(staged - fresh);+ expect(applied.commands.embed).toEqual(['gbrain', 'embed', '--stale']);++ expect(split(after)).toEqual([]);+ expect(after.some(r => r.chunk_text.includes(NEEDLE))).toBe(true);+ for (const requireSafeChunks of [false, true]) {+ const hit = (await engine.searchKeyword('Fennmere harbor pilot', { requireSafeChunks })).find(h => h.slug === slug);+ expect(hit?.chunk_text).toContain(NEEDLE);+ }+ await runEmbedCore(engine, { stale: true, quiet: true });+ expect(embedded.length).toBe(fresh);+ expect((await runSegmentedRechunk(engine)).pages).toEqual([]);+ } finally { teardown(); }+ }, 300_000);++ test('an append to a page sealed at the old chunker re-chunks only its tail, so the page stays at the old version and listed', async () => {+ const engine = await setup();+ try {+ const slug = 'chats/rechunk-append';+ const body = needlePageBody(1_300_000, 200);+ await importFromContent(engine, slug, needlePage(body), { noEmbed: true });+ const id = await sealAtOldChunker(engine, slug);+ await importFromContent(engine, slug, needlePage(body + '\n' + needleChat(7, 40, -1, '2019-03-01')), { noEmbed: true });+ expect(await pageState(engine, id)).toMatchObject({ chunker_version: OLD_SEGMENTED_CHUNKER_VERSION, sealed: true });+ expect((await runSegmentedRechunk(engine, { slug })).pages.map(p => p.slug)).toEqual([slug]);+ } finally { teardown(); }+ }, 300_000);++ test('replaying the schema migrations or the markdown reindex never re-chunks a segmented page', async () => {+ const engine = await setup();+ try {+ const slug = 'chats/rechunk-upgrade';+ await importFromContent(engine, slug, needlePage(needlePageBody(1_300_000, 400)), { noEmbed: true });+ const id = await sealAtOldChunker(engine, slug);+ const before = await chunkRows(engine, id);+ const state = await pageState(engine, id);+ await engine.initSchema();+ await runReindex(engine, ['--markdown', '--no-embed', '--json']);+ expect(await chunkRows(engine, id)).toEqual(before);+ expect(await pageState(engine, id)).toEqual(state);+ } finally { teardown(); }+ }, 300_000);+}diff --git a/test/large-pages/needle-sentence-chunk.test.ts b/test/large-pages/needle-sentence-chunk.test.tsnew file mode 100644index 0000000000..676253a6b1--- /dev/null+++ b/test/large-pages/needle-sentence-chunk.test.ts@@ -0,0 +1,103 @@+/**+ * Forced chunk cuts on sentence or line ends (Wave B PR 4, lane recall; N14 large-page fidelity).+ *+ * 1. Protects: when the chunker's hard cap (capByChars) has to cut a merged run, the segmented chunker cuts at a+ * sentence end, else a line end, else whitespace, searched back from the bound over at most CUT_LOOKBACK_CHARS, so a+ * needle sentence sits whole in one chunk. N14's 24 MiB chat missed one needle because chunk 7138 ended+ * "...the <place> harbor pilot is <first name>" and the surname opened the next chunk: the run was just over the+ * 2,000-token budget, the window derived from its density ended mid-line and the next window started 310 characters+ * back. This file reduces that layout to a 5.9 KB one-day chat (placeholder speakers) whose old cut lands inside the+ * needle sentence.+ * 2. Fails when: a segmented chunk ends inside a line of a chat (old cuts), a chunk exceeds maxChunkTokens, chunk spans+ * stop tiling the text, the cut search stops being bounded per window (a newline-free or whitespace-free segment+ * would chunk in quadratic work), or SEGMENTED_CHUNKER_VERSION stops naming the new cuts.+ * 3. Existing coverage: test/large-pages/inline-chunks-golden.test.ts pins inline chunks byte for byte (the option is+ * off there); test/chunker-spans-linear.slow.test.ts bounds the span bookkeeping.+ * 4. No production seam: pure functions.+ */+import { describe, expect, test } from 'bun:test';+import * as recursive from '../../src/core/chunkers/recursive.ts';+import { estimateEmbedTokens } from '../../src/core/chunkers/token-estimate.ts';+import { initialEntryState } from '../../src/core/page-body/entry-state.ts';+import { segmentString } from '../../src/core/page-body/segmenter.ts';+import * as segmentChunks from '../../src/core/page-body/segment-chunks.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../../src/core/search/safe-chunks.ts';+import { N14_REDUCED, NEEDLE, needleChat } from '../helpers/needle-chat.ts';+import { segmentOptions } from '../helpers/segment-bodies.ts';++const MAX_TOKENS = 2000;+const OLD = { maxTokens: MAX_TOKENS, spans: true, headingsLead: true } as const;++async function segmentedChunks(text: string, maxChunkTokens = MAX_TOKENS) {+ const segments = segmentString(text, initialEntryState({ region: 'truth' }), segmentOptions('trusted'));+ expect(segments.length).toBe(1);+ return segmentChunks.prepareSegmentChunks(segments[0]!, { fenceTrust: 'trusted', maxChunkTokens });+}++/** Chunk spans (UTF-8 byte offsets into `text`) cover its non-whitespace content with no gap. */+function expectTiles(text: string, spans: Array<{ start: number; end: number }>): void {+ const bytes = Buffer.from(text);+ const first = bytes.findIndex(b => b > 0x20);+ let last = bytes.length;+ while (last > 0 && bytes[last - 1]! <= 0x20) last--;+ expect(spans[0]!.start).toBeLessThanOrEqual(first);+ for (let i = 1; i < spans.length; i++) {+ const gap = bytes.subarray(spans[i - 1]!.end, Math.max(spans[i - 1]!.end, spans[i]!.start));+ expect(gap.every(b => b <= 0x20)).toBe(true);+ }+ expect(Math.max(...spans.map(s => s.end))).toBeGreaterThanOrEqual(last);+}++describe('forced cuts in the segmented chunker', () => {+ test('N14 24 MiB needle: the old cut splits the sentence across two chunks; the segmented chunker keeps it whole in one', async () => {+ const old = recursive.chunkProjectedText(N14_REDUCED, OLD).map(c => c.text);+ const split = old.find(t => t.includes('Fennmere') && !t.includes(NEEDLE));+ expect(split).toBeDefined();+ const tail = split!.slice(split!.lastIndexOf('noting here that ') + 'noting here that '.length);+ expect(tail.length).toBeGreaterThan(0);+ expect(tail.length).toBeLessThan(NEEDLE.length);+ expect(NEEDLE.startsWith(tail)).toBe(true);++ const chunks = await segmentedChunks(N14_REDUCED);+ const holding = chunks.filter(c => c.chunk_text.includes('Fennmere'));+ expect(holding.length).toBeGreaterThan(0);+ for (const c of holding) expect(c.chunk_text).toContain(NEEDLE);+ expect(segmentChunks.SEGMENTED_CHUNKER_VERSION).toBeGreaterThan(recursive.MARKDOWN_CHUNKER_VERSION);+ expect(segmentChunks.SEGMENTED_CHUNKER_VERSION).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);+ });++ test('in a chat every segmented chunk ends at a line end (a word end when a line outgrows the look-back), fits maxChunkTokens and the spans tile the segment', async () => {+ const text = [3, 5, 7].map(seed => needleChat(seed, 400, -1)).join('\n');+ const bytes = Buffer.from(text);+ // At 128 tokens the window is about 190 characters, so its look-back (a quarter) is shorter than a chat line.+ for (const [max, ends] of [[MAX_TOKENS, [0x0a]], [512, [0x0a]], [128, [0x0a, 0x20]]] as const) {+ const chunks = await segmentedChunks(text, max);+ for (const c of chunks) {+ expect(estimateEmbedTokens(c.chunk_text)).toBeLessThanOrEqual(max);+ expect(c.projected_byte_end === bytes.length || (ends as readonly number[]).includes(bytes[c.projected_byte_end!]!)).toBe(true);+ }+ expectTiles(text, chunks.map(c => ({ start: c.projected_byte_start!, end: c.projected_byte_end! })));+ }+ }, 60_000);++ for (const [name, make] of [+ ['newline-free prose', (chars: number) => 'the harbor pilot checks the tide tables. '.repeat(Math.ceil(chars / 41)).slice(0, chars)],+ ['whitespace-free text', (chars: number) => 'Qx7'.repeat(Math.ceil(chars / 3)).slice(0, chars)],+ ] as const) {+ test(`a ${name} 1 MiB segment chunks in linear work: the cut search visits at most CUT_LOOKBACK_CHARS per chunk`, () => {+ const work = (chars: number) => {+ const text = make(chars);+ recursive.cutWork.scanned = 0;+ const chunks = recursive.chunkProjectedText(text, { ...OLD, boundaryCuts: true });+ for (const c of chunks) expect(estimateEmbedTokens(c.text)).toBeLessThanOrEqual(MAX_TOKENS);+ expectTiles(text, chunks.map(c => ({ start: c.byte_start!, end: c.byte_end! })));+ expect(recursive.cutWork.scanned).toBeLessThanOrEqual(recursive.CUT_LOOKBACK_CHARS * chunks.length);+ return { chunks: chunks.length, scanned: recursive.cutWork.scanned };+ };+ const half = work(512 * 1024);+ const full = work(1024 * 1024);+ expect(full.chunks / half.chunks).toBeLessThan(2.1);+ expect(full.scanned / Math.max(1, half.scanned)).toBeLessThan(2.1);+ }, 60_000);+ }+});diff --git a/test/large-pages/rechunk-segmented.test.ts b/test/large-pages/rechunk-segmented.test.tsnew file mode 100644index 0000000000..0ed5618850--- /dev/null+++ b/test/large-pages/rechunk-segmented.test.ts@@ -0,0 +1,30 @@+/**+ * The re-chunk of segmented pages sealed at an older segmented chunker on PGLite (Wave B PR 4, lane recall).+ *+ * 1. Protects: `gbrain reindex --segmented` previews without writing, applies by re-staging only changed segments+ * under a body flip that keeps occurrences, knowledge revision and vectors of unchanged texts, and stamps the page+ * at SEGMENTED_CHUNKER_VERSION; a later write keeps an old page listed; migrations never re-chunk.+ * 2. Fails when: the preview writes, the apply loses a vector it could reuse or leaves the needle split, a seal after+ * an append stamps an old page as current, or a schema replay or the markdown reindex touches segmented chunks.+ * 3. Postgres arm: test/e2e/rechunk-segmented-postgres.test.ts; shared cases: test/helpers/rechunk-segmented-cases.ts.+ * 4. Embeddings come from a counting fake transport; nothing paid runs.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { defineRechunkSegmentedCases } from '../helpers/rechunk-segmented-cases.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('reindex --segmented [pglite]', () => {+ defineRechunkSegmentedCases({ getEngine: () => engine });+});diff --git a/test/large-pages/sealed-segmented-search.test.ts b/test/large-pages/sealed-segmented-search.test.tsindex d30884d8bc..ab0b2bac5e 100644--- a/test/large-pages/sealed-segmented-search.test.ts+++ b/test/large-pages/sealed-segmented-search.test.ts@@ -11,8 +11,9 @@* rebuilt (withdrawal.ts bumps the revision and deletes the chunk rows;* the rebuild rechunks from the overlaid text and reseals).* 2. Fails when: SEGMENTED_CHUNKER_VERSION drops below the safe-fence- * version (remote search and chunk windows withhold the page), or the- * seal indexes the raw lead (the withdrawn token is findable).+ * version (remote search and chunk windows withhold the page) or back to+ * the inline chunker's version (it names its own forced cuts since Wave B+ * PR 4), or the seal indexes the raw lead (the withdrawn token is findable).*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import type { BrainEngine } from '../../src/core/engine.ts';@@ -63,7 +64,7 @@ for (const kind of testBackends()) {expect(remote.map(h => h.slug)).toContain('notes/sealed');expect(remote.find(h => h.slug === 'notes/sealed')!.chunk_text).toContain('zzsealedneedle');expect(page).toEqual({ chunker_version: SEGMENTED_CHUNKER_VERSION, sealed: true });- expect(SEGMENTED_CHUNKER_VERSION).toBe(MARKDOWN_CHUNKER_VERSION);+ expect(SEGMENTED_CHUNKER_VERSION).toBeGreaterThan(MARKDOWN_CHUNKER_VERSION);expect(SEGMENTED_CHUNKER_VERSION).toBeGreaterThanOrEqual(SAFE_FENCE_CHUNKER_VERSION);}, 240_000);