Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(pages): oversized-page backfill, partial_embedding doctor check, title tier for large pages

garrytanbe2544ae7ff5
diff --git a/src/cli/commands/reindex.ts b/src/cli/commands/reindex.ts
index b6a5dff62d..5cdc42c4b9 100644
--- a/src/cli/commands/reindex.ts
+++ b/src/cli/commands/reindex.ts
@@ -48,6 +48,20 @@ export async function run(engine: BrainEngine, args: string[]): Promise<void> {
}
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; };
+ const limit = value('--limit');
+ const receipt = await runOversizedBackfill(engine, {
+ dryRun: args.includes('--dry-run'),
+ ...(value('--source') ? { sourceId: value('--source') } : {}),
+ ...(limit ? { limit: Number(limit) } : {}),
+ });
+ if (args.includes('--json')) console.log(JSON.stringify(receipt, null, 2));
+ else for (const line of formatOversizedBackfillReceipt(receipt)) console.log(line);
+ if (receipt.failed.length) setCliExitVerdict(1);
+ return;
+ }
if (args.includes('--vectors')) {
await (await import('../../commands/reindex-vectors.ts')).runReindexVectors(engine, args); // #4616
return;
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.ts
index bbb843ca31..f0f2a4c7b1 100644
--- a/src/commands/doctor/checks/content-quality.ts
+++ b/src/commands/doctor/checks/content-quality.ts
@@ -12,7 +12,7 @@ import { startHeartbeat } from '../../../core/progress.ts';
import { checkUnverifiedExtractions } from './extraction-sync.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
-import { agentFix, checkError } from '../check-fix.ts';
+import { agentFix, checkError, doctorVerify } from '../check-fix.ts';
async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
const { args, progress } = ctx;
@@ -57,7 +57,8 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
// loadConfig which caches in module-level config layer.)
const { loadConfig: _loadCfg } = await import('../../../core/config.ts');
const _cfg = _loadCfg();
- const bytesBlock = _cfg?.content_sanity?.bytes_block ?? 500_000;
+ const { DEFAULT_BYTES_BLOCK } = await import('../../../core/content-sanity.ts');
+ const bytesBlock = _cfg?.content_sanity?.bytes_block ?? DEFAULT_BYTES_BLOCK;
// #1871: engine.executeRaw, not the dead-on-PGLite postgres singleton.
const rows = await engine.executeRaw<{ slug: string; source_id: string; bytes: number }>(
`SELECT p.slug, p.source_id,
@@ -70,7 +71,21 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
LIMIT 100`,
[bytesBlock],
);
- if (rows.length === 0) {
+ // Pages an older gbrain stored chunkless for size that now fit under the block: the free backfill re-indexes them.
+ const [skipped] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM pages p
+ WHERE p.deleted_at IS NULL AND p.frontmatter->'embed_skip'->>'reason' = 'oversized'
+ AND (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, ''))) <= $1`, [bytesBlock]);
+ const backfillable = Number(skipped?.n ?? 0);
+ if (backfillable > 0) {
+ checks.push({
+ name: 'oversized_pages',
+ status: 'warn',
+ message: `${backfillable} page(s) were stored without chunks by an older gbrain because of their size, and now fit under the ${bytesBlock}-byte bytes_block. `
+ + 'They are invisible to search until re-indexed. Fix: gbrain reindex --oversized (free, CPU only; pages over 1 MiB then wait for embedding approval).',
+ fix: agentFix(['gbrain', 'reindex', '--oversized'], 'Re-chunks the size-skipped pages so keyword search finds them; it calls no paid provider and holds large pages for embedding approval.',
+ 'oversized_pages', { docs: 'docs/guides/memory-boundaries.md#large-pages-upgrade' }),
+ });
+ } else if (rows.length === 0) {
checks.push({
name: 'oversized_pages',
status: 'ok',
@@ -84,7 +99,8 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
checks.push({
name: 'oversized_pages',
status: 'warn',
- message: `${rows.length} page(s) exceed ${bytesBlock}-byte block threshold. Top: ${top}. New ingests with the same shape get frontmatter.embed_skip set automatically; existing oversized pages can be split or accepted as non-embeddable.`,
+ message: `${rows.length} page(s) exceed the ${bytesBlock}-byte content_sanity.bytes_block. Top: ${top}. A page over the block is stored without chunks on its next write. `
+ + 'Raise content_sanity.bytes_block (up to the 24 MiB page ceiling) to make them searchable, or exclude them from the source.',
});
}
} catch (err) {
@@ -96,6 +112,34 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
});
}
+ progress.heartbeat('partial_embedding');
+ try {
+ const { listBudgetLimitedPages } = await import('../../../core/page-embedding-budget.ts');
+ const limited = await listBudgetLimitedPages(engine, { limit: 100 });
+ if (limited.length === 0) {
+ checks.push({ name: 'partial_embedding', status: 'ok', message: 'No large page is held or capped by embed.max_usd_per_page.' });
+ } else {
+ const sources = [...new Set(limited.map(row => row.source_id))];
+ const sample = limited.slice(0, 3).map(row => `${row.slug} (${row.state}${row.reason ? `: ${row.reason}` : ''}, ${row.pending_chunks} chunk(s) without a vector)`).join('; ');
+ const approve = limited.length === 1
+ ? ['gbrain', 'embed', '--slugs', limited[0]!.slug, '--source', limited[0]!.source_id, '--max-usd', '<N>']
+ : ['gbrain', 'embed', '--held', ...(sources.length === 1 ? ['--source', sources[0]!] : []), '--max-usd', '<N>'];
+ checks.push({
+ name: 'partial_embedding',
+ status: 'warn',
+ message: `${limited.length} large page(s) are keyword-searchable but partially embedded: the per-page cap stopped them or they wait for approval. ${sample}. `
+ + `Preview the cost with gbrain embed --held --dry-run; with the user's approval: ${approve.join(' ')}`,
+ fix: { argv: approve, consent: ['paid', 'egress'], actor: 'agent', ask_user: true,
+ inputs: [{ name: 'N', how: 'The dollar amount the user approves per page, after seeing the cost from preview_argv.' }],
+ preview_argv: ['gbrain', 'embed', '--held', ...(sources.length === 1 ? ['--source', sources[0]!] : []), '--dry-run'],
+ why: 'Embedding the rest calls the paid embedding provider; the approved amount raises each page\'s cap (the lowest cap still wins).',
+ verify: doctorVerify('partial_embedding'), requires_exclusive: false, docs: 'docs/guides/memory-boundaries.md#large-pages' },
+ });
+ }
+ } catch (err) {
+ checks.push(checkError('partial_embedding', 'read the per-page embedding budget', err));
+ }
+
progress.heartbeat('scraper_junk_pages');
try {
const { assessContentSanity } = await import('../../../core/content-sanity.ts');
@@ -223,7 +267,7 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {
export const contentSanityEntry: DoctorEntry = {
name: 'oversized_pages',
- emits: ['oversized_pages', 'scraper_junk_pages', 'content_sanity_audit_recent'],
+ emits: ['oversized_pages', 'partial_embedding', 'scraper_junk_pages', 'content_sanity_audit_recent'],
run: runContentSanity,
};
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 36e1e81ef1..60c610e3f2 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -903,7 +903,8 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
const keylessConfig = loadConfig();
if (isKeylessStaleRefusal(args, keylessConfig?.embedding_disabled)) {
const enable = (await import('../core/readiness.ts')).embeddingEnablement(keylessConfig!).argv ?? ['gbrain', 'init', '--force', '--embedding-model', '<provider:model>'];
- process.stderr.write('[embed] Embeddings are disabled on this brain (keyless install). Nothing to backfill; keyword search keeps working. '
+ process.stderr.write('[embed] Embeddings are disabled on this brain (keyless install), so there are no vectors to compute. Keyword search covers every chunked page; '
+ + 'pages an older gbrain skipped for size become keyword-searchable with gbrain reindex --oversized (free). '
+ `Turn on semantic search (pages and facts are kept): ${(await import('../core/agent-output.ts')).shellQuote(enable)}\n`);
return {
embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0,
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index 0000b5a956..4305227391 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -89,6 +89,7 @@ USAGE
gbrain reindex --multimodal [--limit N] [--workers N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]
gbrain 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>]
TARGETS (exactly one required)
--markdown Re-chunk markdown pages whose chunker_version lags the
@@ -103,6 +104,13 @@ TARGETS (exactly one required)
pages whose frontmatter aliases predate the projection.
--vectors Rebuild every HNSW vector index from the stored vectors
(no re-embedding, no cost). Run after a PGLite WAL repair.
+ --oversized Re-chunk pages an older gbrain stored without chunks
+ because they were over 500 KB (embed_skip: oversized),
+ when they are under content_sanity.bytes_block (default:
+ the 24 MiB page ceiling). CPU only and free: it works
+ with embeddings off and makes them keyword-searchable
+ now. Pages over 1 MiB wait for approval before any paid
+ embedding (gbrain embed --held). Resumable.
OPTIONS
--type <t> --markdown only: restrict to one page type
@@ -119,7 +127,7 @@ 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 only: restrict to one source
+ --source <id> --aliases and --oversized: restrict to one source
--repo PATH --markdown only: brain repo override
--json Machine-readable output
--help, -h Show this help
@@ -163,6 +171,7 @@ export function validateReindexModeScope(args: string[]): string | null {
if (!args.includes('--type')) return 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';
return null;
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 8376b26501..fb0e9406c2 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -714,6 +714,8 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
await (await import('../core/feedback/upgrade-notice.ts')).printRetrievalFeedbackUpgradeNotice(engine);
// Entity mention index: [AGENT] catch-up line while pages are due (best-effort).
await (await import('../core/mentions/upgrade-notice.ts')).printMentionIndexUpgradeNotice(engine);
+ // Large pages: re-index pages an older gbrain stored chunkless for size (keyless-safe, time-boxed, resumable).
+ await (await import('../core/oversized-backfill.ts')).printOversizedBackfillUpgradeNotice(engine);
// Temporal typed edges: one-shot [AGENT] notice (live-by-default graph reads + relationship check), best-effort.
await (await import('../core/temporal-edges-upgrade-notice.ts')).printTemporalEdgesUpgradeNotice(engine);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d3a4d01996..f30331446a 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -51,7 +51,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--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'],
- 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--group', '--harness', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
+ 'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--max-cost', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--to', '--wait', '--yes'],
'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
'enrich': ['--accept-pending', '--access', '--add', '--allowed-operations', '--apply', '--asof', '--audit', '--background', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--full', '--fuzzy', '--group', '--help', '--http', '--id', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],
@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],
- 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--held', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],
'forget': ['--all-subjects', '--brain', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],
@@ -76,13 +76,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--conflicts', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
- 'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--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', '--kind', '--lanes', '--limit', '--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', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--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', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--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', '--kind', '--lanes', '--limit', '--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', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--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', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--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', '--full', '--get', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--is-inside-work-tree', '--json', '--local', '--local-env-vars', '--manifest', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--source', '--source-id', '--timeout', '--unset-all', '--wait', '--yes'],
'loops': ['--all', '--as-of', '--brain', '--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'],
'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--expect', '--expected-revision', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--group-by', '--hard-deadline', '--harness', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-pull', '--once', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--resume', '--retry-failed', '--reverse', '--safe', '--scope', '--scopes', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url-env', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
- 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
+ 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--full', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],
'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
@@ -91,7 +91,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', '--older-than', '--source', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--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', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--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-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--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', '--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', '--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-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
@@ -101,7 +101,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-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--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', '--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', '--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', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--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', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--quiet', '--repo', '--request', '--request-id', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--background', '--brain', '--class', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--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', '--skip', '--slug', '--source', '--stale', '--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', '--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'],
@@ -112,7 +112,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--adopt-slug-path', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--autostash', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--category', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--code', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--depth', '--detect', '--diff-filter', '--dir', '--disable', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--full', '--future-days', '--get', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--group-by', '--hard', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--local-env-vars', '--loops-exclude-labels', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-autostash', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-tags', '--no-verify', '--only', '--operations', '--origin', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--pull', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--require-clean', '--reset-checkpoint', '--reset-default', '--resolve', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--since', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--state', '--status', '--stdin', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--verify', '--wait', '--wait-drain', '--warn-only', '--window', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
- 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
+ 'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--pace', '--pace-max-concurrency', '--plan', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
@@ -128,12 +128,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--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', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--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', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--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-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--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', '--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', '--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-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--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', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.ts
index 523bc13599..94af88e971 100644
--- a/src/core/contextual-retrieval-service.ts
+++ b/src/core/contextual-retrieval-service.ts
@@ -64,6 +64,7 @@ import type { SourceRow } from './sources-ops.ts';
import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from './page-state/projections.ts';
import { reconcileContextualEmbeddingInputs } from './page-state/contextual-proof.ts';
import { digest } from './persistence/digest.ts';
+import { isLargePageBytes } from './page-size-policy.ts';
/**
* v3 = chunks embed with optional contextual retrieval wrapper. The
@@ -226,7 +227,7 @@ export type ReembedPageResult =
}
| {
kind: 'skipped';
- reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted';
+ reason: 'mode_none' | 'no_chunks' | 'page_missing' | 'soft_deleted' | 'budget_limited';
}
| {
kind: 'page_fallback';
@@ -391,7 +392,13 @@ export async function reembedPageWithContextualRetrieval(
// else undefined → page-summary's SYNOPSIS_MAX_TOKENS default (200).
const synopsisMaxTokens =
args.synopsisMaxTokens ?? (await resolveSynopsisMaxTokens(args.engine));
- let attemptMode: CRMode = resolution.mode;
+ // Large pages: the title tier until per-chunk synopses are metered per page
+ // (plan B8), and no re-embed while the per-page cap holds or capped the page.
+ const large = isLargePageBytes(Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8'));
+ if (large && (await args.engine.executeRaw(`SELECT 1 FROM page_embedding_budget WHERE page_id = $1 AND state <> 'open'`, [page.id])).length) {
+ return { kind: 'skipped', reason: 'budget_limited' };
+ }
+ let attemptMode: CRMode = large && resolution.mode === 'per_chunk_synopsis' ? 'title' : resolution.mode;
let fallbackReason: SynopsisFailureKind | null = null;
// eslint-disable-next-line no-constant-condition
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 9ea609ad42..816c106f13 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -149,6 +149,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'orphan_ratio',
'oversized_pages',
'parked_effects',
+ 'partial_embedding',
'pglite_scratch_probe',
'quarantined_pages',
'raw_provenance',
diff --git a/src/core/oversized-backfill.ts b/src/core/oversized-backfill.ts
new file mode 100644
index 0000000000..f45c5dd6f3
--- /dev/null
+++ b/src/core/oversized-backfill.ts
@@ -0,0 +1,226 @@
+/**
+ * The Wave A oversized-page backfill (`gbrain reindex --oversized`, and a
+ * time-boxed pass in `gbrain post-upgrade`).
+ *
+ * Before the 24 MiB page ceiling, the import gate stored any page over
+ * `content_sanity.bytes_block` (500 KB) with a gate-written
+ * `embed_skip: { reason: oversized }` marker and zero chunks, so it was
+ * invisible to keyword and vector search. Removing the marker alone does not
+ * help: import returns early on an unchanged content hash, so the page would
+ * stay chunkless. This backfill rewrites each such page through the normal
+ * write path (the canonical owner on a managed brain, exactly like
+ * `gbrain quarantine clear`) with the marker and its `content_flag: oversized`
+ * removed and a forced re-chunk. That is CPU-only and runs with embeddings
+ * disabled: chunks land with NULL vectors and become keyword-searchable at
+ * once; the embedding sweep fills vectors later.
+ *
+ * Limits are preserved: a page still above the effective `bytes_block`
+ * (env `GBRAIN_PAGE_BLOCK_BYTES`, file or DB `content_sanity.bytes_block`) is
+ * left as it is, and only the gate-written marker shape (`reason: oversized`)
+ * is touched. A large page (over `pages.inline_max_bytes`) is held in
+ * `page_embedding_budget` before its rewrite, so no paid embedding starts
+ * until the user approves the previewed cost (`gbrain embed --held --max-usd N`).
+ *
+ * Idempotent and resumable: the work list is recomputed from the markers on
+ * every run, so a page done is never redone and an interrupted run continues.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from './engine.ts';
+import { EMBED_SKIP_KEY } from './embed-skip.ts';
+import { CONTENT_FLAG_KEY } from './quarantine.ts';
+import { serializeMarkdown } from './markdown.ts';
+import { importFromContent } from './import-file.ts';
+import { loadConfig } from './config.ts';
+import type { OperationContext } from './ops/contract.ts';
+import { managedPersistenceEnabled } from './persistence/ownership.ts';
+import { submitPageMutation } from './persistence/page-mutations.ts';
+import { resolveCliWriteWaitMs } from './persistence/write-wait.ts';
+import { loadImportSanityConfig } from './import-screen.ts';
+import { DEFAULT_BYTES_BLOCK } from './content-sanity.ts';
+import { PAGE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';
+import { estimatePageEmbedUsd, holdPageEmbedding } from './page-embedding-budget.ts';
+import { currentEmbeddingSignature } from './embedding.ts';
+import type { PageType } from './types.ts';
+
+/** The `page_embedding_budget.reason` a backfilled large page waits under. */
+export const BACKFILL_HOLD_REASON = 'upgrade_backfill';
+
+const OVERSIZED_MARKER_SQL = `p.deleted_at IS NULL AND p.frontmatter->'${EMBED_SKIP_KEY}'->>'reason' = 'oversized'`;
+const PAGE_BYTES_SQL = `(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))`;
+
+export interface OversizedBackfillReceipt {
+ dry_run: boolean;
+ /** The bytes_block in effect: pages at or under it (and the ceiling) are re-indexed. */
+ block_bytes: number;
+ /** Size-skipped pages under the block when the run started. */
+ candidates: number;
+ reindexed: number;
+ /** Large pages whose embedding waits for approval. */
+ held_for_approval: number;
+ failed: Array<{ slug: string; source_id: string; error: string }>;
+ /** Candidates this run did not reach (limit or time budget); the same command continues. */
+ remaining: number;
+ /** Size-skipped pages still over the block; they stay as they are. */
+ over_block: number;
+ chunks_pending_embedding: number;
+ /** null when embeddings are off on this brain. */
+ estimated_usd: number | null;
+ embedding_enabled: boolean;
+ /** Exact commands: finish the backfill; approve held embedding. */
+ commands: { finish: string[]; approve: string[]; preview: string[] };
+}
+
+async function effectiveBlockBytes(engine: BrainEngine): Promise<number> {
+ const sanity = await loadImportSanityConfig(engine);
+ const block = sanity.disabled ? PAGE_MAX_BYTES : (sanity.cs.bytes_block ?? DEFAULT_BYTES_BLOCK);
+ return Math.min(block, PAGE_MAX_BYTES);
+}
+
+interface Candidate { id: number; slug: string; source_id: string; bytes: number }
+
+async function listCandidates(engine: BrainEngine, block: number, opts: { sourceId?: string; afterId: number; limit: number }): Promise<Candidate[]> {
+ const params: unknown[] = [block, opts.afterId, opts.limit];
+ const source = opts.sourceId ? ` AND p.source_id = $${params.push(opts.sourceId)}` : '';
+ const rows = await engine.executeRaw<Candidate>(`SELECT p.id, p.slug, p.source_id, ${PAGE_BYTES_SQL}::bigint AS bytes FROM pages p
+ WHERE ${OVERSIZED_MARKER_SQL} AND ${PAGE_BYTES_SQL} <= $1 AND p.id > $2${source} ORDER BY p.id LIMIT $3`, params);
+ return rows.map(row => ({ ...row, id: Number(row.id), bytes: Number(row.bytes) }));
+}
+
+async function countMarked(engine: BrainEngine, block: number, sourceId: string | undefined): Promise<{ under: number; over: number }> {
+ const params: unknown[] = [block];
+ const source = sourceId ? ` AND p.source_id = $${params.push(sourceId)}` : '';
+ const [row] = await engine.executeRaw<{ under: number; over: number }>(`SELECT
+ COUNT(*) FILTER (WHERE ${PAGE_BYTES_SQL} <= $1)::int AS under, COUNT(*) FILTER (WHERE ${PAGE_BYTES_SQL} > $1)::int AS over
+ FROM pages p WHERE ${OVERSIZED_MARKER_SQL}${source}`, params);
+ return { under: Number(row?.under ?? 0), over: Number(row?.over ?? 0) };
+}
+
+/** Rewrite one page without its size-gate markers, re-chunked, with no embedding. */
+async function reindexPage(engine: BrainEngine, page: Candidate, managed: boolean): Promise<void> {
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot || snapshot.page.id !== page.id) return;
+ const fm = { ...((snapshot.page.frontmatter ?? {}) as Record<string, unknown>) };
+ if ((fm[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason !== 'oversized') return;
+ delete fm[EMBED_SKIP_KEY];
+ if ((fm[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete fm[CONTENT_FLAG_KEY];
+ if (isLargePageBytes(page.bytes)) await holdPageEmbedding(engine, page.id, BACKFILL_HOLD_REASON);
+ const markdown = serializeMarkdown(fm, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {
+ type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,
+ });
+ if (!managed) {
+ await importFromContent(engine, page.slug, markdown, { sourceId: page.source_id, noEmbed: true, forceRechunk: true, preserveGateMarkers: true });
+ return;
+ }
+ const config = loadConfig() ?? { engine: engine.kind };
+ const ctx = { engine, config, remote: false, dryRun: false, sourceId: page.source_id, writeWaitMs: resolveCliWriteWaitMs({ config }),
+ logger: { info: () => {}, warn: (m: string) => console.error(m), error: (m: string) => console.error(m) } } as unknown as OperationContext;
+ await submitPageMutation(ctx, { operation: 'put_page', managedFileImport: true, params: { slug: page.slug, source_id: page.source_id, content: markdown,
+ kind: 'managed_quarantine_clear', expected_revision: snapshot.revision, request_id: randomUUID() } });
+}
+
+export async function runOversizedBackfill(engine: BrainEngine, opts: {
+ dryRun?: boolean; sourceId?: string; limit?: number; deadlineMs?: number; now?: () => number;
+ onPage?: (page: { slug: string; source_id: string; bytes: number }) => void;
+} = {}): Promise<OversizedBackfillReceipt> {
+ const now = opts.now ?? Date.now;
+ const started = now();
+ const block = await effectiveBlockBytes(engine);
+ const before = await countMarked(engine, block, opts.sourceId);
+ const embeddingEnabled = loadConfig()?.embedding_disabled !== true;
+ const scope = opts.sourceId ? ['--source', opts.sourceId] : [];
+ const receipt: OversizedBackfillReceipt = {
+ dry_run: opts.dryRun === true, block_bytes: block, candidates: before.under, reindexed: 0, held_for_approval: 0, failed: [],
+ remaining: before.under, over_block: before.over, chunks_pending_embedding: 0, estimated_usd: null, embedding_enabled: embeddingEnabled,
+ commands: { finish: ['gbrain', 'reindex', '--oversized', ...scope], approve: ['gbrain', 'embed', '--held', ...scope, '--max-usd', '<N>'],
+ preview: ['gbrain', 'embed', '--held', ...scope, '--dry-run'] },
+ };
+ const managed = !receipt.dry_run && await managedPersistenceEnabled(engine);
+ const touched: number[] = [];
+ let pendingChars = 0;
+ let afterId = 0;
+ let attempted = 0;
+ while (opts.limit === undefined || attempted < opts.limit) {
+ const batch = await listCandidates(engine, block, { sourceId: opts.sourceId, afterId, limit: Math.min(100, (opts.limit ?? Infinity) - attempted) });
+ if (batch.length === 0) break;
+ for (const page of batch) {
+ if (attempted > 0 && opts.deadlineMs !== undefined && now() - started >= opts.deadlineMs) break;
+ afterId = page.id;
+ attempted++;
+ opts.onPage?.(page);
+ if (receipt.dry_run) {
+ if (isLargePageBytes(page.bytes)) receipt.held_for_approval++;
+ pendingChars += page.bytes;
+ continue;
+ }
+ try {
+ await reindexPage(engine, page, managed);
+ touched.push(page.id);
+ receipt.reindexed++;
+ if (isLargePageBytes(page.bytes)) receipt.held_for_approval++;
+ } catch (error) {
+ receipt.failed.push({ slug: page.slug, source_id: page.source_id, error: (error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300) });
+ }
+ }
+ if (opts.deadlineMs !== undefined && now() - started >= opts.deadlineMs) break;
+ }
+ if (touched.length) {
+ const [pending] = await engine.executeRaw<{ chunks: number; chars: number }>(`SELECT COUNT(*)::int AS chunks, COALESCE(SUM(length(chunk_text)), 0)::bigint AS chars
+ FROM content_chunks WHERE page_id = ANY($1::int[]) AND embedded_at IS NULL`, [touched]);
+ receipt.chunks_pending_embedding = Number(pending?.chunks ?? 0);
+ pendingChars = Number(pending?.chars ?? 0);
+ }
+ receipt.remaining = receipt.dry_run ? before.under : (await countMarked(engine, block, opts.sourceId)).under;
+ if (embeddingEnabled) receipt.estimated_usd = estimatePageEmbedUsd(pendingChars, currentEmbeddingSignature());
+ return receipt;
+}
+
+/** Human lines for a receipt (stdout of `gbrain reindex --oversized` and post-upgrade). */
+export function formatOversizedBackfillReceipt(r: OversizedBackfillReceipt): string[] {
+ const lines = [`[reindex --oversized] ${r.dry_run ? 'Would re-index' : 'Re-indexed'} ${r.dry_run ? r.candidates : r.reindexed} size-skipped page(s) under the ${r.block_bytes}-byte bytes_block`
+ + `${r.dry_run ? '' : `; ${r.chunks_pending_embedding} chunk(s) are keyword-searchable now and wait for embedding`}.`];
+ if (r.failed.length) lines.push(` ${r.failed.length} page(s) failed (first: ${r.failed[0].source_id}/${r.failed[0].slug}: ${r.failed[0].error}); rerun: ${r.commands.finish.join(' ')}`);
+ if (!r.dry_run && r.remaining > r.failed.length) lines.push(` ${r.remaining} page(s) remain; continue with: ${r.commands.finish.join(' ')}`);
+ if (r.over_block) lines.push(` ${r.over_block} page(s) stay size-skipped: they are over content_sanity.bytes_block (${r.block_bytes} bytes).`);
+ if (!r.embedding_enabled) lines.push(' Embeddings are off on this brain, so keyword search is the whole result; nothing is spent.');
+ else if (r.held_for_approval) {
+ lines.push(` ${r.held_for_approval} large page(s) wait for approval before embedding (about $${(r.estimated_usd ?? 0).toFixed(2)} in total). `
+ + `Preview: ${r.commands.preview.join(' ')}; approve with: ${r.commands.approve.join(' ')}`);
+ } else if (r.estimated_usd !== null && r.chunks_pending_embedding) {
+ lines.push(` The embedding sweep embeds them under the existing caps (about $${r.estimated_usd.toFixed(2)}).`);
+ }
+ return lines;
+}
+
+/**
+ * `gbrain post-upgrade`: a two-minute backfill pass, then the receipt. When
+ * large pages wait for paid embedding, an [AGENT] block asks the user with the
+ * previewed cost before anything is spent. Best-effort: never blocks upgrade.
+ */
+export async function printOversizedBackfillUpgradeNotice(engine: BrainEngine): Promise<void> {
+ try {
+ const block = await effectiveBlockBytes(engine);
+ if ((await countMarked(engine, block, undefined)).under === 0) return;
+ const receipt = await runOversizedBackfill(engine, { deadlineMs: 120_000 });
+ const lines = ['', ...formatOversizedBackfillReceipt(receipt)];
+ if (receipt.embedding_enabled && receipt.held_for_approval > 0) {
+ const { agentBlock } = await import('./agent-markers.ts');
+ lines.push(...agentBlock({
+ ask: `Embed the ${receipt.held_for_approval} large page(s) that are searchable by keyword now?`,
+ why: 'Pages an older gbrain skipped for size are re-indexed and keyword-searchable. Embedding them adds semantic search and calls the paid embedding provider.',
+ risk: `About $${(receipt.estimated_usd ?? 0).toFixed(2)} in total; each page is capped by embed.max_usd_per_page and the run by --max-usd (the lowest cap wins).`,
+ consent: 'paid, egress',
+ actor: 'user',
+ next: 'ask_user',
+ if_yes: `Run ${receipt.commands.approve.join(' ')} with the amount the user approves. Preview: ${receipt.commands.preview.join(' ')}`,
+ if_no: 'Nothing to do: the pages stay keyword-searchable and doctor lists them under partial_embedding.',
+ verify: 'gbrain doctor --only partial_embedding --json',
+ }, {
+ showUser: `${receipt.held_for_approval} large page(s) that older gbrain skipped are searchable by keyword now. `
+ + `Embedding them for semantic search costs about $${(receipt.estimated_usd ?? 0).toFixed(2)}. Embed them?`,
+ }).trimEnd().split('\n'));
+ }
+ for (const line of lines) console.log(line);
+ } catch (error) {
+ console.error(`[gbrain] The oversized-page backfill did not finish (${error instanceof Error ? error.message.split('\n')[0] : String(error)}); run gbrain reindex --oversized.`);
+ }
+}
diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.ts
index f454f6fee6..8c07ea997a 100644
--- a/src/core/page-embedding-budget.ts
+++ b/src/core/page-embedding-budget.ts
@@ -135,16 +135,16 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,
reserved += reservedUsd;
const state: PageBudgetState = deferred > 0 ? 'capped' : 'open';
await tx.executeRaw(`UPDATE page_embedding_budget SET state = $2, reason = $3, embedding_signature = COALESCE($4, embedding_signature),
- spent_usd = $5, reserved_usd = $6, reserved_at = CASE WHEN $6 > 0 THEN now() ELSE NULL END,
- cap_usd = $7, updated_at = now() WHERE page_id = $1`,
+ spent_usd = $5::float8, reserved_usd = $6::float8, reserved_at = CASE WHEN $6::float8 > 0 THEN now() ELSE NULL END,
+ cap_usd = $7::float8, updated_at = now() WHERE page_id = $1`,
[page.id, state, deferred > 0 ? 'cap_reached' : null, opts.signature ?? null, spent, reserved,
approved && Number.isFinite(capUsd) ? capUsd : row.cap_usd]);
const grant: PageEmbedGrant = {
chunkIndexes, reservedUsd, deferred, capUsd,
settle: async ({ ok }) => {
if (reservedUsd === 0) return;
- await engine.executeRaw(`UPDATE page_embedding_budget SET reserved_usd = GREATEST(0, reserved_usd - $2),
- spent_usd = spent_usd + $3, unpriced_calls = unpriced_calls + $4, updated_at = now() WHERE page_id = $1`,
+ await engine.executeRaw(`UPDATE page_embedding_budget SET reserved_usd = GREATEST(0, reserved_usd - $2::float8),
+ spent_usd = spent_usd + $3::float8, unpriced_calls = unpriced_calls + $4::int, updated_at = now() WHERE page_id = $1`,
[page.id, reservedUsd, ok ? reservedUsd : 0, ok && !priced ? 1 : 0]);
},
};
diff --git a/test/oversized-backfill.serial.test.ts b/test/oversized-backfill.serial.test.ts
new file mode 100644
index 0000000000..e2f0e6f6b2
--- /dev/null
+++ b/test/oversized-backfill.serial.test.ts
@@ -0,0 +1,202 @@
+/**
+ * Large pages (Wave A, T15/T23/T34/T52/T16): the oversized-page backfill and
+ * the per-page embedding budget.
+ *
+ * The upgrade fixture is a page an older gbrain stored the old way: written
+ * under a 500 KB bytes_block, so it carries the gate's
+ * `embed_skip: { reason: oversized }` marker and has zero chunks. With no later
+ * content write and embeddings off, `gbrain reindex --oversized` must make a
+ * needle in its middle keyword-searchable with zero provider calls, hold a
+ * large page for embedding approval, and leave a page still over the block
+ * alone.
+ *
+ * Serial: installs the process-global embedding transport seam.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { isEmbedSkipped } from '../src/core/embed-skip.ts';
+import { assessContentSanity } from '../src/core/content-sanity.ts';
+import { runOversizedBackfill, BACKFILL_HOLD_REASON } from '../src/core/oversized-backfill.ts';
+import { listBudgetLimitedPages, planPageEmbedding } from '../src/core/page-embedding-budget.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+
+const DIMS = 1536;
+const MODEL = 'openai:text-embedding-3-large';
+const FRONTMATTER = '---\ntype: note\ntitle: Long conversation\n---\n\n';
+const NEEDLE = 'zebracornflowerneedle';
+
+let engine: PGLiteEngine;
+let providerCalls = 0;
+
+function body(bytes: number): string {
+ const line = 'alice-example and bob-example talked about acme-example plans today.\n';
+ const half = line.repeat(Math.floor(bytes / 2 / line.length));
+ return `${half}The secret word is ${NEEDLE}.\n${half}`;
+}
+
+async function withHome<T>(config: Record<string, unknown> | null, fn: () => Promise<T>): Promise<T> {
+ const home = mkdtempSync(join(tmpdir(), 'oversized-backfill-'));
+ if (config) {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...config }));
+ }
+ try {
+ return await withEnv({ GBRAIN_HOME: home, HOME: home, GBRAIN_AUDIT_DIR: home }, fn);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+/** Write a page the way gbrain did before the ceiling: under a 500 KB block. */
+async function seedSizeSkipped(slug: string, bytes: number): Promise<void> {
+ await engine.setConfig('content_sanity.bytes_block', '500000');
+ await importFromContent(engine, slug, FRONTMATTER + body(bytes), { noEmbed: true });
+ await engine.unsetConfig('content_sanity.bytes_block');
+ const page = await engine.getPage(slug);
+ expect(isEmbedSkipped(page!.frontmatter as Record<string, unknown>)).toBe(true);
+ expect((await engine.getChunks(slug)).length).toBe(0);
+}
+
+async function keywordHits(): Promise<string[]> {
+ return (await engine.searchKeyword(NEEDLE, { limit: 10 })).map(hit => hit.slug);
+}
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });
+ __setEmbedTransportForTests((async (input: { values: string[] }) => {
+ providerCalls++;
+ return { embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 } };
+ }) as never);
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: DIMS } as never);
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ providerCalls = 0;
+});
+
+describe('gbrain reindex --oversized (keyless upgrade path)', () => {
+ test('a zero-chunk size-skipped page becomes keyword-searchable with zero provider calls, and a rerun is a no-op', async () => {
+ await withHome({ embedding_disabled: true }, async () => {
+ await seedSizeSkipped('chats/small-large', 700_000);
+ expect(await keywordHits()).toEqual([]);
+
+ const receipt = await runOversizedBackfill(engine);
+ expect(receipt).toMatchObject({ candidates: 1, reindexed: 1, remaining: 0, held_for_approval: 0, embedding_enabled: false, estimated_usd: null });
+ expect(receipt.chunks_pending_embedding).toBeGreaterThan(100);
+ const page = await engine.getPage('chats/small-large');
+ expect(isEmbedSkipped(page!.frontmatter as Record<string, unknown>)).toBe(false);
+ expect((page!.frontmatter as Record<string, unknown>).content_flag).toBeUndefined();
+ expect(await keywordHits()).toEqual(['chats/small-large']);
+ expect(providerCalls).toBe(0);
+
+ expect(await runOversizedBackfill(engine)).toMatchObject({ candidates: 0, reindexed: 0 });
+ });
+ }, 120_000);
+
+ test('a page over 1 MiB is re-indexed and held for embedding approval: the stale sweep skips it until the user approves', async () => {
+ await withHome(null, async () => {
+ await seedSizeSkipped('chats/big', 1_500_000);
+ const receipt = await runOversizedBackfill(engine);
+ expect(receipt).toMatchObject({ reindexed: 1, held_for_approval: 1, embedding_enabled: true });
+ expect(receipt.estimated_usd).toBeGreaterThan(0);
+ expect(await keywordHits()).toEqual(['chats/big']);
+ expect(await listBudgetLimitedPages(engine)).toEqual([expect.objectContaining({ slug: 'chats/big', state: 'held', reason: BACKFILL_HOLD_REASON })]);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(providerCalls).toBe(0);
+
+ const approved = await runEmbedCore(engine, { slugs: ['chats/big'], quiet: true, approvedPageCapUsd: 5 });
+ expect(approved.embedded).toBe(receipt.chunks_pending_embedding);
+ expect(providerCalls).toBeGreaterThan(0);
+ expect(await listBudgetLimitedPages(engine)).toEqual([]);
+ });
+ }, 120_000);
+
+ test('a page still over the operator bytes_block keeps its marker', async () => {
+ await withHome({ embedding_disabled: true }, async () => {
+ await seedSizeSkipped('chats/operator-limit', 700_000);
+ await engine.setConfig('content_sanity.bytes_block', '500000');
+ const receipt = await runOversizedBackfill(engine);
+ expect(receipt).toMatchObject({ candidates: 0, reindexed: 0, over_block: 1, block_bytes: 500_000 });
+ expect(isEmbedSkipped((await engine.getPage('chats/operator-limit'))!.frontmatter as Record<string, unknown>)).toBe(true);
+ await engine.unsetConfig('content_sanity.bytes_block');
+ });
+ }, 120_000);
+});
+
+describe('per-page embedding budget (embed.max_usd_per_page)', () => {
+ const stale = (n: number) => Array.from({ length: n }, (_, i) => ({ chunk_index: i, chunk_text: 'x'.repeat(4000) }));
+ const page = (id: number) => ({ id, compiled_truth: 'y'.repeat(1_100_000), timeline: '' });
+
+ async function pageId(slug: string): Promise<number> {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'short' });
+ return (await engine.getPage(slug))!.id;
+ }
+
+ test('grants the newest chunks that fit the cap, marks the page capped, and never re-grants spent budget', async () => {
+ await withHome(null, async () => {
+ const id = await pageId('notes/capped');
+ await engine.setConfig('embed.max_usd_per_page', '0.0003');
+ const first = await planPageEmbedding(engine, page(id), stale(10), { signature: `${MODEL}:${DIMS}` });
+ if (first.kind !== 'grant') throw new Error(`expected a grant, got ${first.kind}`);
+ expect(first.grant.deferred).toBeGreaterThan(0);
+ expect([...first.grant.chunkIndexes].sort((a, b) => a - b)).toEqual(Array.from({ length: 10 - first.grant.deferred }, (_, i) => i + first.grant.deferred));
+ await first.grant.settle({ ok: true });
+ expect(await listBudgetLimitedPages(engine)).toEqual([expect.objectContaining({ slug: 'notes/capped', state: 'capped' })]);
+
+ const second = await planPageEmbedding(engine, page(id), stale(first.grant.deferred), { signature: `${MODEL}:${DIMS}` });
+ if (second.kind !== 'grant') throw new Error(`expected a grant, got ${second.kind}`);
+ expect(second.grant.chunkIndexes.size).toBe(0);
+ await engine.unsetConfig('embed.max_usd_per_page');
+ });
+ });
+
+ test('a page at or under the inline cap is unmetered', async () => {
+ await withHome(null, async () => {
+ const id = await pageId('notes/small');
+ expect((await planPageEmbedding(engine, { id, compiled_truth: 'small page' }, stale(3))).kind).toBe('unmetered');
+ });
+ });
+
+ const navRow = '| [x](http://a) | [y](http://b) | [z](http://c) | [w](http://d) |\n';
+
+ test('the 890K boilerplate case on current code: flagged markup_heavy, searchable, not skipped (under the inline cap it costs cents)', () => {
+ const r = assessContentSanity({ compiled_truth: navRow.repeat(Math.ceil(890_000 / navRow.length)), timeline: '', title: 'Scraped page' });
+ expect(r).toMatchObject({ shouldQuarantine: false, shouldSkipEmbed: false, shouldFlag: true, flag_reason: 'markup_heavy' });
+ });
+
+ test('a large page whose head, middle and tail windows are all boilerplate is held instead of embedded', async () => {
+ await withHome(null, async () => {
+ const id = await pageId('notes/boilerplate');
+ const decision = await planPageEmbedding(engine, { id, compiled_truth: navRow.repeat(Math.ceil(1_100_000 / navRow.length)) }, stale(3));
+ expect(decision).toEqual({ kind: 'held', reason: 'sampled_markup_heavy' });
+ expect(await listBudgetLimitedPages(engine)).toEqual([expect.objectContaining({ slug: 'notes/boilerplate', state: 'held' })]);
+ });
+ });
+
+ test('a large page of prose with a boilerplate head is granted (only the head is markup)', async () => {
+ await withHome(null, async () => {
+ const id = await pageId('notes/prose-with-nav');
+ const prose = 'alice-example wrote a long letter about the acme-example harvest. '.repeat(Math.ceil(1_100_000 / 66));
+ const decision = await planPageEmbedding(engine, { id, compiled_truth: navRow.repeat(2000) + prose }, stale(3));
+ expect(decision.kind).toBe('grant');
+ });
+ });
+});