Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(#6803 lane B): held embedding budgets surfaced, #6847 approval on free providers
garrytanec9aba9fb048
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.tsindex 5a50319e16..8a89b4f167 100644--- a/src/cli/commands/embed.ts+++ b/src/cli/commands/embed.ts@@ -5,7 +5,7 @@* src/cli/command-table.ts.*/import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';-import { lastBackgroundJob } from '../../core/cli-options.ts';+import { getCliOptions, lastBackgroundJob } from '../../core/cli-options.ts';import { BUDGET_STOP_EXIT_CODE } from '../../core/exit-codes.ts';import type { BrainEngine } from '../../core/engine.ts';import type { Authorization } from '../../core/consent.ts';@@ -27,6 +27,10 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC// and cron/CI/health gates read total silence as success. Surface// non-zero on failures > 0. (undefined = backgrounded via --background.)const embedResult = await runEmbed(engine, args, SELECTED_CONFIG_BY_ENGINE.get(engine) ?? null, consent);+ // #6803: large pages waiting for embedding approval left the stale queue; say so (informational, never a failure).+ if (embedResult && args.includes('--stale') && !args.some(a => a === '--images' || a === '--facts' || a === '--held')) {+ await (await import('../../core/held-embedding.ts')).noteBudgetLimited(engine, args, embedResult, getCliOptions().quiet);+ }// D2: under --json the result is the one document (a budget stop carries// remaining_stale + resume_command and exits 11; --background names its job).if (jsonRequested(args)) {@@ -82,8 +86,11 @@ async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<{ auconst EMBED_USAGE = ['Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --facts',' Embeds chunks without a vector (--stale; --catch-up keeps going until the backlog is empty) or re-embeds pages (--all, a slug, --slugs).',- ' A page over 1 MiB spends at most embed.max_usd_per_page (default $2) and embeds its newest chunks first; --held lists the pages a cap or a',- ' pending approval stopped, with the cost to finish, and --held --max-usd N (or --slugs <slug> --max-usd N) approves N more per page.',+ ' A page over 1 MiB spends at most embed.max_usd_per_page (default $2) and embeds its newest chunks first. --held --dry-run lists, for every',+ ' source, the pages a cap or a pending approval stopped, the cost to finish and one approve command per source. --held --source <id>',+ ' --max-usd N (or --slugs <slug> --source <id> --max-usd N) approves them, one source at a time: N is both the run\'s cap and the extra per-page allowance it',+ ' saves, so use the printed N (a ceiling, not the estimate). A run stopped early keeps what it embedded; the rest stays held. --yes never',+ ' approves a held page; --max-usd N does, on local providers too.',' It calls the configured embedding provider, which bills per token: without a terminal it stops with exit 3 and the consent payload',' unless --yes (cap: the estimate x1.5), --max-usd N, spend.posture=tokenmax or a per-run preapproval covers it. Pass those only after',' the user agrees. --dry-run previews with no provider calls. Local providers that bill nothing (ollama, llama-server, lmstudio) need no approval.',diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex 14c833edb8..767c0a528f 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, doctorVerify } from '../check-fix.ts';+import { agentFix, checkError } from '../check-fix.ts';async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const { args, progress } = ctx;@@ -106,34 +106,6 @@ 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');@@ -261,10 +233,35 @@ async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {export const contentSanityEntry: DoctorEntry = {name: 'oversized_pages',- emits: ['oversized_pages', 'partial_embedding', 'scraper_junk_pages', 'content_sanity_audit_recent'],+ emits: ['oversized_pages', 'scraper_junk_pages', 'content_sanity_audit_recent'],run: runContentSanity,};+/**+ * #6803 part 3: its own entry, so the full `pages` scans above never spend its+ * budget and `--only partial_embedding` runs only this indexed read. The+ * finding, its per-source approve Actions and their N live in core/held-embedding.ts.+ */+async function runPartialEmbedding(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ ctx.progress.heartbeat('partial_embedding');+ try {+ const { budgetLimitedFinding } = await import('../../../core/held-embedding.ts');+ const { currentEmbeddingSignature } = await import('../../../core/embedding.ts');+ const found = await budgetLimitedFinding(engine, currentEmbeddingSignature());+ if (!found) return [{ name: 'partial_embedding', status: 'ok', message: 'No large page has chunks waiting for embedding approval (held or capped by embed.max_usd_per_page).' }];+ return [{ name: 'partial_embedding', status: 'warn', message: found.message, fix: found.fix, details: found.details }];+ } catch (err) {+ return [checkError('partial_embedding', 'read the per-page embedding budget', err)];+ }+}++export const partialEmbeddingEntry: DoctorEntry = {+ name: 'partial_embedding',+ emits: ['partial_embedding'],+ run: runPartialEmbedding,+};+async function runQuarantine(ctx: DoctorContext): Promise<Check[]> {const { orphanRatioSourceId, progress } = ctx;const engine = connectedEngine(ctx);diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex e0aafeab7f..fb5861f6fd 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -73,7 +73,7 @@ import {crossModalEntry,markdownBodyEntry,} from './checks/data-integrity.ts';-import { contentSanityEntry, quarantineEntry, frontmatterEntry } from './checks/content-quality.ts';+import { contentSanityEntry, partialEmbeddingEntry, quarantineEntry, frontmatterEntry } from './checks/content-quality.ts';import {evalCaptureEntry,contradictionsEntry,@@ -196,6 +196,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [crossModalEntry,markdownBodyEntry,contentSanityEntry,+ partialEmbeddingEntry,quarantineEntry,frontmatterEntry,evalCaptureEntry,diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 00b79660f7..323c79652e 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -50,7 +50,8 @@ import { resolveEmbedConcurrency } from '../core/embed-concurrency.ts';export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } from '../core/embed-concurrency.ts';import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';-import { heldEmbedArgv, meterPageBatch, spendGrant } from '../core/page-embedding-budget.ts';+import { meterPageBatch, spendGrant } from '../core/page-embedding-budget.ts';+import { heldApprovalUsd, heldEmbedArgv } from '../core/held-embedding.ts';import { countSegmentedEmbedRows, embedSegmentedPage, readSealedSegmentedEmbedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../core/page-body/segmented-embedding.ts';import {restampIfDemotedToTitleTier,@@ -912,9 +913,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConfif (args.includes('--held')) {const held = await heldEmbedArgv(engine, args, currentEmbeddingSignature(), args.includes('--json') ? serr : slog);- if (held && 'error' in held) { serr(held.error); process.exit(1); }- if (held) return runEmbed(engine, held.argv, selectedConfig, consent);- return { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun: args.includes('--dry-run'), chunkless_pages_healed: 0 };+ return 'argv' in held ? runEmbed(engine, held.argv, selectedConfig, consent) : held;}const authorization = consent?.authorization ?? null;const costCap = args.includes('--dry-run') || args.includes('--background') ? null : embedCostCap(authorization?.cap_usd, authorization?.cap_source);@@ -982,7 +981,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConflet opts: EmbedOpts;if (slugsIdx >= 0) {- const approvedPageCapUsd = authorization?.via === 'max_usd' && authorization.cap_usd !== null ? authorization.cap_usd : undefined;+ const approvedPageCapUsd = await heldApprovalUsd(engine, args);opts = { slugs: slugsAfter(args, slugsIdx), dryRun, sourceId, batchSize, priority, catchUp, ...(approvedPageCapUsd !== undefined && { approvedPageCapUsd }) };} else if (all || stale) {// E-2: CLI-only single-flight for stale runs (the minion path locks itself).diff --git a/src/core/held-embedding-action.ts b/src/core/held-embedding-action.tsnew file mode 100644index 0000000000..78cfe7c08d--- /dev/null+++ b/src/core/held-embedding-action.ts@@ -0,0 +1,130 @@+/**+ * The one approval for large pages that wait for embedding (#6803 part 3,+ * #6847): the phrase every surface prints, the approval amount, and the+ * Action `gbrain embed --stale`, the embed-backfill job, doctor+ * `partial_embedding`, `gbrain embed --held --dry-run` and the per-page hold+ * line in `meterPageBatch` all render.+ *+ * The approval is `--max-usd N`, which is both the run's hard cap (paid+ * providers) and the extra per-page allowance the ledger saves, so N is a+ * ceiling, never the estimate: the pending text priced at the higher of the+ * run meter's rate (the budget tracker's chars-per-token basis) and the+ * per-page ledger's, through `derivedCapUsd` (x1.5, $0.25 floor, rounded up to+ * the cent). Dense text (CJK, minified code) bills more tokens than the+ * chars-per-token basis assumes; the floor and the headroom absorb that. A+ * provider whose recipe bills nothing gets the $0.01 floor and no paid/egress+ * consent.+ *+ * Leaf module: page-embedding-budget.ts imports it, so it never imports that.+ */+import { cliRenderContext, renderAction, type Action, type RenderContext } from './agent-output.ts';+import { derivedCapUsd } from './consent.ts';+import { reservationCostUsd } from './budget/reservation-cost.ts';+import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';+import { DEFAULT_CHARS_PER_TOKEN } from './ai/embed-batch-plan.ts';+import { getRecipe } from './ai/recipes/index.ts';++/** Price assumed for a model with no known rate (the conservative OpenAI large rate). */+export const UNPRICED_RATE_PER_MTOK = 0.13;+/** The approval a provider that bills nothing needs: never 0, which consent does not read as an approval. */+export const FREE_APPROVAL_USD = 0.01;+export const HELD_DOCS = 'docs/guides/memory-boundaries.md#large-pages';++/** True when the provider in `model` (`provider:model[:dims]`) is a local recipe billing $0 (ollama, llama-server, lmstudio). */+export function recipeIsFree(model: string | null | undefined): boolean {+ if (!model) return false;+ return getRecipe(model.split(':')[0] ?? '')?.touchpoints?.embedding?.cost_per_1m_tokens_usd === 0;+}++/** The per-page ledger's rate for the embedding signature: $0 for a free recipe, the known price, else the conservative fallback. */+export function ledgerPricePerMTok(signature: string | null | undefined): { rate: number; priced: boolean } {+ if (!signature) return { rate: UNPRICED_RATE_PER_MTOK, priced: false };+ if (recipeIsFree(signature)) return { rate: 0, priced: true };+ const hit = lookupEmbeddingPrice(signature.slice(0, signature.lastIndexOf(':')) || signature);+ return hit.kind === 'known' ? { rate: hit.pricePerMTok, priced: true } : { rate: UNPRICED_RATE_PER_MTOK, priced: false };+}++export interface ApprovalBasis { model: string | null; signature: string | null; free: boolean; charsPerToken: number }++/** The configured embedding model's pricing basis; an unreadable gateway reads as a paid, unknown model. */+export async function approvalBasis(): Promise<ApprovalBasis> {+ try {+ const { getEmbeddingModel } = await import('./ai/gateway.ts');+ const { currentEmbeddingSignature } = await import('./embedding.ts');+ const model = getEmbeddingModel();+ const charsPerToken = getRecipe(model.split(':')[0] ?? '')?.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;+ return { model, signature: currentEmbeddingSignature(), free: recipeIsFree(model), charsPerToken: Math.max(charsPerToken, 1) };+ } catch {+ return { model: null, signature: null, free: false, charsPerToken: DEFAULT_CHARS_PER_TOKEN };+ }+}++/** What approving `chars` of pending chunk text costs (`est_usd`) and the `--max-usd` to print (`max_usd`). */+export function approvalAmount(chars: number, basis: ApprovalBasis): { est_usd: number; max_usd: number } {+ if (basis.free) return { est_usd: 0, max_usd: FREE_APPROVAL_USD };+ const metered = basis.model ? reservationCostUsd(basis.model, 'embed', Math.ceil(chars / basis.charsPerToken), 0) : null;+ const est = Math.max(metered ?? 0, estimateCostFromChars(chars, ledgerPricePerMTok(basis.signature ?? basis.model).rate));+ return { est_usd: est, max_usd: derivedCapUsd(est) };+}++export interface HeldTarget { source_id: string; slug?: string; pending_chunks: number; est_usd: number; max_usd: number }++const previewArgv = (sourceId: string) => ['gbrain', 'embed', '--held', '--dry-run', '--source', sourceId, '--json'];++/**+ * The approve Action for one source (or one page of it, `slug`): run+ * `gbrain embed --held --source S --max-usd N`, preview and verify with the+ * same source-scoped dry run (held 0 for that source once it ran). Always+ * `ask_user`: the hold is the user's consent gate (no automatic release).+ */+export function heldApproveAction(target: HeldTarget, free: boolean): Action {+ const n = target.max_usd.toFixed(2);+ const scope = target.slug ? ['--slugs', target.slug, '--source', target.source_id] : ['--held', '--source', target.source_id];+ const what = `${target.pending_chunks} chunk(s) of ${target.slug ? `the large page ${target.slug}` : 'large pages'} in source ${target.source_id}`;+ const cost = free+ ? 'the embedding provider bills nothing, so the run costs nothing'+ : `estimated $${target.est_usd.toFixed(2)}, spends at most $${n}`;+ return {+ argv: ['gbrain', 'embed', ...scope, '--max-usd', n],+ preview_argv: previewArgv(target.source_id),+ consent: free ? [] : ['paid', 'egress'],+ actor: 'agent',+ ask_user: true,+ why: `${what} wait for embedding approval and stay keyword-only until approved (${cost}). --max-usd is both the run's cap and the per-page allowance it saves; a run stopped early keeps what it embedded, and the rest waits for the next approval.`,+ user_message: free+ ? `${what} are not indexed for meaning-based search yet. Embedding them runs on your local embedding model and costs nothing. OK to embed them?`+ : `${what} are not indexed for meaning-based search yet. Embedding them sends their text to your embedding provider: ${cost}. OK to spend it?`,+ verify: { argv: previewArgv(target.source_id) },+ requires_exclusive: false,+ docs: HELD_DOCS,+ };+}++/** The rendered shell command of an Action (routing pinned, as every printed fix is). */+export function renderedCommand(action: Action, ctx: RenderContext = cliRenderContext()): string {+ return renderAction(action, ctx).command ?? action.argv!.join(' ');+}++/**+ * `gbrain embed --held --dry-run [--source S]`, rendered. Without a source it+ * lists every source, so it opts out of routing's source pin (a pinned+ * `--source` would narrow the listing to the ambient source); the brain pin stays.+ */+export function heldPreviewCommand(sourceId?: string, ctx: RenderContext = cliRenderContext()): string {+ const argv = ['gbrain', 'embed', '--held', '--dry-run', ...(sourceId ? ['--source', sourceId] : [])];+ const routing = sourceId ? ctx.routing : ctx.routing?.brain ? { brain: ctx.routing.brain } : undefined;+ return renderedCommand({ argv, consent: [], actor: 'agent', why: 'Lists the held and capped large pages with the cost to finish; read-only.', requires_exclusive: false },+ { ...ctx, routing });+}++export interface BudgetLimitedCounts { held: number; capped: number; held_reasons: Record<string, number> }++/** The one sentence every surface prints about pages waiting for approval. */+export function budgetLimitedPhrase(b: BudgetLimitedCounts): string {+ const reasons = Object.entries(b.held_reasons);+ const parts = [+ ...(b.held ? [`${b.held} held: ${reasons.length === 1 ? reasons[0]![0] : reasons.map(([reason, n]) => `${reason} ${n}`).join(', ')}`] : []),+ ...(b.capped ? [`${b.capped} at their per-page cap`] : []),+ ];+ return `${b.held + b.capped} large page(s) have chunks waiting for embedding approval (${parts.join('; ')}); those chunks are keyword-only until approved.`;+}diff --git a/src/core/held-embedding.ts b/src/core/held-embedding.tsnew file mode 100644index 0000000000..5f32d62af1--- /dev/null+++ b/src/core/held-embedding.ts@@ -0,0 +1,219 @@+/**+ * Held embedding budgets, surfaced (#6803 part 3) and approvable on every+ * provider (#6847).+ *+ * Large pages the per-page ledger holds for approval (`upgrade_backfill`, a+ * sampled junk hit) or stopped at their cap leave the stale queue, so nothing+ * an operator runs routinely used to mention them. `readBudgetLimited` counts+ * them, with no row cap, against the active vector column and the embed+ * path's stale-input rules (a chunk without a vector or `embedded_at`, or a+ * page whose vectors came from another embedding signature): only pages with+ * such chunks count. `gbrain embed --stale` (`noteBudgetLimited`), the+ * embed-backfill job (`budgetLimitedField`) and doctor `partial_embedding`+ * (`budgetLimitedFinding`) report it through one phrase and one approve+ * Action per source (held-embedding-action.ts). It is never a failure and+ * never enters the embed-backfill stall fingerprint.+ *+ * `gbrain embed --held` (`heldEmbedArgv`): `--dry-run` lists every source+ * (exit 0) with per-page and per-source totals and one approve command per+ * source; an approval covers one source, so `--max-usd` with held pages in+ * several sources and no `--source` refuses with `invalid_params`.+ *+ * Approval (`heldApprovalUsd`): an explicit `--max-usd N` on `--slugs` /+ * `--held` is the hold approval whether or not the provider spends (a free+ * local provider has no consent Authorization to derive it from). It is refused+ * before any hold is released when embeddings are unavailable, or when a paid+ * model has no price (the run cap could not be enforced), so no per-page cap+ * is saved without a run. `--yes` never approves a hold.+ */+import type { BrainEngine } from './engine.ts';+import { cliRenderContext, renderAction, type Action, type RenderContext, type RenderedAction } from './agent-output.ts';+import { parseConsentFlags } from './consent.ts';+import { opError } from './ops/contract.ts';+import { chunkGenerationFilter } from './search/safe-chunks.ts';+import { quoteIdentifier } from './search/embedding-column.ts';+import { embeddingWriteTarget } from './page-state/projections.ts';+import { reservationCostUsd } from './budget/reservation-cost.ts';+import { estimatePageEmbedUsd, listBudgetLimitedPages } from './page-embedding-budget.ts';+import {+ approvalAmount, approvalBasis, budgetLimitedPhrase, heldApproveAction, heldPreviewCommand, renderedCommand,+ type ApprovalBasis, type BudgetLimitedCounts,+} from './held-embedding-action.ts';++export interface BudgetLimitedSource { source_id: string; held: number; capped: number; pending_chunks: number; pending_chars: number }+export interface BudgetLimited extends BudgetLimitedCounts { pending_chunks: number; by_source: BudgetLimitedSource[] }++/** Held and capped large pages that still have chunks waiting, by source (`sourceId` narrows it). */+export async function readBudgetLimited(engine: BrainEngine, opts: { sourceId?: string; signature?: string | null } = {}): Promise<BudgetLimited> {+ const column = `cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)}`;+ const params: unknown[] = [opts.signature ?? null];+ const bySource = opts.sourceId ? ` AND p.source_id = $${params.push(opts.sourceId)}` : '';+ const pending = `(${column} IS NULL OR (p.body_storage IS DISTINCT FROM 'segmented' AND cc.embedded_at IS NULL)+ OR ($1::text IS NOT NULL AND p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1::text))`;+ const rows = await engine.executeRaw<{ source_id: string; state: 'held' | 'capped'; reason: string; pages: number; chunks: number; chars: number }>(+ `SELECT p.source_id, b.state, COALESCE(b.reason, 'awaiting_approval') AS reason, count(*)::int AS pages,+ sum(w.chunks)::bigint AS chunks, sum(w.chars)::bigint AS chars+ FROM page_embedding_budget b JOIN pages p ON p.id = b.page_id+ CROSS JOIN LATERAL (SELECT count(*)::int AS chunks, COALESCE(sum(length(cc.chunk_text)), 0)::bigint AS chars+ FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')} AND ${pending}) w+ WHERE b.state <> 'open' AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND w.chunks > 0${bySource}+ GROUP BY 1, 2, 3 ORDER BY 1, 2, 3`, params);+ const out: BudgetLimited = { held: 0, capped: 0, held_reasons: {}, pending_chunks: 0, by_source: [] };+ const sources = new Map<string, BudgetLimitedSource>();+ for (const row of rows) {+ const pages = Number(row.pages);+ const source = sources.get(row.source_id) ?? { source_id: row.source_id, held: 0, capped: 0, pending_chunks: 0, pending_chars: 0 };+ if (row.state === 'held') out.held_reasons[row.reason] = (out.held_reasons[row.reason] ?? 0) + pages;+ out[row.state] += pages;+ source[row.state] += pages;+ out.pending_chunks += Number(row.chunks);+ source.pending_chunks += Number(row.chunks);+ source.pending_chars += Number(row.chars);+ sources.set(row.source_id, source);+ }+ out.by_source = [...sources.values()].sort((a, b) => b.pending_chunks - a.pending_chunks || a.source_id.localeCompare(b.source_id));+ return out;+}++export interface BudgetLimitedReportSource extends BudgetLimitedSource { est_usd: number; max_usd: number; fix: RenderedAction }+export interface BudgetLimitedReport extends BudgetLimitedCounts {+ pending_chunks: number;+ /** `gbrain embed --held --dry-run` for every source (the rendered listing command). */+ preview_command: string;+ by_source: BudgetLimitedReportSource[];+}++/** Every source's approve Action, the one for the source with the most pending chunks first. */+function sourceActions(b: BudgetLimited, basis: ApprovalBasis): Array<{ source: BudgetLimitedSource; amount: { est_usd: number; max_usd: number }; action: Action }> {+ return b.by_source.map(source => {+ const amount = approvalAmount(source.pending_chars, basis);+ return { source, amount, action: heldApproveAction({ source_id: source.source_id, pending_chunks: source.pending_chunks, ...amount }, basis.free) };+ });+}++/** The commands an operator runs: the listing preview, then one approve per source with its cost. */+function nextSteps(actions: ReturnType<typeof sourceActions>, ctx: RenderContext, free: boolean): string {+ const approves = actions.map(({ amount, action }) => `${renderedCommand(action, ctx)} (${free ? 'costs nothing' : `estimated $${amount.est_usd.toFixed(2)}, spends at most $${amount.max_usd.toFixed(2)}`})`);+ return `Preview: ${heldPreviewCommand(undefined, ctx)}; with the user's agreement, approve one source at a time: ${approves.join('; ')}.`;+}++/** The structured report (rendered fixes), or null when no large page waits. */+export async function budgetLimitedReport(engine: BrainEngine, opts: { sourceId?: string; signature?: string | null; ctx?: RenderContext } = {}): Promise<{ report: BudgetLimitedReport; line: string; fix: Action } | null> {+ const b = await readBudgetLimited(engine, opts);+ if (b.held + b.capped === 0) return null;+ const ctx = opts.ctx ?? cliRenderContext();+ const basis = await approvalBasis();+ const actions = sourceActions(b, basis);+ const report: BudgetLimitedReport = {+ held: b.held, capped: b.capped, held_reasons: b.held_reasons, pending_chunks: b.pending_chunks,+ preview_command: heldPreviewCommand(undefined, ctx),+ by_source: actions.map(({ source, amount, action }) => ({ ...source, ...amount, fix: renderAction(action, ctx) })),+ };+ return { report, line: `${budgetLimitedPhrase(b)} ${nextSteps(actions, ctx, basis.free)}`, fix: actions[0]!.action };+}++/** `gbrain embed --stale`: attach `budget_limited` to the result and print the line (stderr under --json, nothing when quiet). */+export async function noteBudgetLimited(engine: BrainEngine, args: readonly string[], result: object, quiet: boolean): Promise<void> {+ const at = args.indexOf('--source');+ const { currentEmbeddingSignature } = await import('./embedding.ts');+ const found = await budgetLimitedReport(engine, { ...(at >= 0 && args[at + 1] ? { sourceId: args[at + 1] } : {}), signature: currentEmbeddingSignature() });+ if (!found) return;+ Object.assign(result, { budget_limited: { ...found.report, fix: renderAction(found.fix, cliRenderContext()) } });+ if (quiet) return;+ if (args.includes('--json')) process.stderr.write(`[embed] ${found.line}\n`);+ else console.log(`[embed] ${found.line}`);+}++/** The embed-backfill job result field (one source); never throws: it is bookkeeping, not a failure. */+export async function budgetLimitedField(engine: BrainEngine, sourceId: string, signature: string | null): Promise<{ budget_limited?: BudgetLimitedReport }> {+ try {+ const found = await budgetLimitedReport(engine, { sourceId, signature });+ return found ? { budget_limited: found.report } : {};+ } catch {+ return {};+ }+}++/** Doctor `partial_embedding`: the warn's message, fix (the approve for the source with the most pending chunks) and details, or null. */+export async function budgetLimitedFinding(engine: BrainEngine, signature: string | null): Promise<{ message: string; fix: Action; details: Record<string, unknown> } | null> {+ const found = await budgetLimitedReport(engine, { signature });+ if (!found) return null;+ return { message: found.line, fix: found.fix, details: { ...found.report } };+}++type HeldListing = {+ embedded: 0; skipped: 0; would_embed: number; total_chunks: number; pages_processed: 0; failures: 0; failure_samples: []; dryRun: boolean; chunkless_pages_healed: 0;+ held?: number; capped?: number; pages?: Array<{ slug: string; source_id: string; state: string; reason: string | null; pending_chunks: number; spent_usd: number; est_usd: number }>;+ sources?: BudgetLimitedReportSource[];+};+const emptyListing = (dryRun: boolean): HeldListing => ({ embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun, chunkless_pages_healed: 0,+ ...(dryRun ? { held: 0, capped: 0, pages: [], sources: [] } : {}) });++/**+ * `gbrain embed --held`: list the held and capped large pages with what each+ * would cost to finish. A dry run returns the listing (every source unless+ * `--source`); otherwise the `--source S --slugs ...` argv that embeds them+ * under the user's `--max-usd`, one source per approval.+ */+export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[], signature: string | null, say: (line: string) => void): Promise<{ argv: string[] } | HeldListing> {+ if (args.includes('--background')) {+ throw opError('invalid_params', '[embed] --held runs in the foreground: the per-page approval is not carried into background jobs.', 'Run it again without --background.');+ }+ const at = args.indexOf('--source');+ const sourceId = at >= 0 ? args[at + 1] : undefined;+ const dryRun = args.includes('--dry-run');+ const limited = await listBudgetLimitedPages(engine, { ...(sourceId ? { sourceId } : {}), limit: null });+ if (limited.length === 0) {+ say('[embed] No large pages are held or capped by embed.max_usd_per_page.');+ return emptyListing(dryRun);+ }+ const pages = limited.map(row => ({ slug: row.slug, source_id: row.source_id, state: row.state, reason: row.reason, pending_chunks: row.pending_chunks,+ spent_usd: row.spent_usd, est_usd: estimatePageEmbedUsd(row.pending_chars, signature) }));+ for (const row of pages) {+ say(`[embed] ${row.slug} (${row.source_id}): ${row.state}${row.reason ? ` (${row.reason})` : ''}, ${row.pending_chunks} chunk(s) without a vector, `+ + `spent $${row.spent_usd.toFixed(2)}, about $${row.est_usd.toFixed(2)} to finish`);+ }+ const sources = [...new Set(limited.map(row => row.source_id))];+ if (dryRun) {+ const found = await budgetLimitedReport(engine, { ...(sourceId ? { sourceId } : {}), signature });+ if (found) say(`[embed] ${found.line}`);+ return { ...emptyListing(true), would_embed: found?.report.pending_chunks ?? 0, total_chunks: found?.report.pending_chunks ?? 0,+ held: found?.report.held ?? 0, capped: found?.report.capped ?? 0, pages, sources: found?.report.by_source ?? [] };+ }+ if (sources.length > 1) {+ const found = await budgetLimitedReport(engine, { signature });+ const each = found ? found.report.by_source.map(s => s.fix.command).join('; ') : sources.map(id => heldPreviewCommand(id)).join('; ');+ throw opError('invalid_params',+ `[embed] Held pages span ${sources.length} sources and one approval covers one source, so --held needs --source. Run per source, each with the user's agreement: ${each}`,+ `Preview every source with ${heldPreviewCommand()}, then approve one source at a time.`);+ }+ const rest = args.filter((a, i) => a !== '--held' && a !== '--source' && args[i - 1] !== '--source');+ return { argv: [...rest, '--source', sources[0]!, '--slugs', ...limited.map(row => row.slug)] };+}++/**+ * #6847: the per-page approval an explicit `--max-usd N` carries on `--slugs` /+ * `--held` (undefined without it, and on a dry run, which releases nothing).+ * Refused before any hold is released when embeddings are unavailable, or a+ * paid model has no price.+ */+export async function heldApprovalUsd(engine: BrainEngine, args: readonly string[]): Promise<number | undefined> {+ const { maxUsd } = parseConsentFlags(args);+ if (maxUsd === null || args.includes('--dry-run')) return undefined;+ const { embedWouldSpend, embeddingProviderIsFree } = await import('./embed-consent.ts');+ const { embeddingsDisabled } = await import('./embedding-disabled.ts');+ const { getEmbeddingModel, isAvailable } = await import('./ai/gateway.ts');+ const unchanged = 'nothing ran: every hold and per-page cap is unchanged';+ if (await embedWouldSpend(engine)) {+ const model = getEmbeddingModel();+ if (reservationCostUsd(model, 'embed', 1, 0) !== null) return maxUsd;+ const { noPricingFix, noPricingGuidance, noPricingMessage } = await import('./budget/no-pricing.ts');+ const guidance = noPricingGuidance(model, 'embed');+ throw opError('no_pricing', `[embed] ${noPricingMessage(guidance, { capUsd: maxUsd })} (${unchanged}.)`, 'Register the model\'s price, then re-run the approval.',+ { why: 'A paid run under a user cap refuses an unpriced model at its first provider call, after the hold would already be released.', fix: noPricingFix(guidance) });+ }+ if (!(await embeddingsDisabled(engine)) && isAvailable('embedding') && await embeddingProviderIsFree()) return maxUsd;+ throw opError('embedding_unavailable', `[embed] Embeddings are unavailable on this brain (disabled, or the provider has no credentials), so --max-usd ${maxUsd} approves nothing; ${unchanged}.`,+ 'Check the provider with gbrain doctor --only embedding_provider --json, fix it, then re-run the approval.',+ { why: 'Releasing a hold without a run that can embed would save the approval with nothing embedded.' });+}diff --git a/src/core/minions/handlers/embed-backfill.ts b/src/core/minions/handlers/embed-backfill.tsindex 9895e079b0..7d8d1156f0 100644--- a/src/core/minions/handlers/embed-backfill.ts+++ b/src/core/minions/handlers/embed-backfill.ts@@ -48,6 +48,7 @@ import { embedStaleForSource } from '../../embed-stale.ts';import { createEmbedStallWatchdog, resolveEmbedStallAbortSeconds } from '../../embed-stall.ts';import { currentEmbeddingSignature } from '../../embedding.ts';import { readEmbedBackfillBlockers } from '../../embed-backfill-stall.ts';+import { budgetLimitedField, type BudgetLimitedReport } from '../../held-embedding.ts';import { UnrecoverableError } from '../errors.ts';import { type DbPacer, createDbPacer, createNoopPacer } from '../../db-pacer.ts';import { resolvePaceMode, loadPaceModeConfig, readPaceEnv } from '../../pace-mode.ts';@@ -85,6 +86,8 @@ export interface EmbedBackfillResult {spentUsd: number;/** Set when status === 'budget_exhausted'. */budgetCapUsd?: number;+ /** #6803: large pages of this source waiting for embedding approval (informational; never a failure or a stall). */+ budget_limited?: BudgetLimitedReport;}/**@@ -389,6 +392,7 @@ export function makeEmbedBackfillHandler(invalidated: result.invalidated,...(result.invalidationSkipped && { invalidationSkipped: result.invalidationSkipped }),spentUsd: tracker.totalSpent,+ ...(await budgetLimitedField(engine, sourceId, currentEmbeddingSignature())),};} catch (err) {if (err instanceof BudgetExhausted) {diff --git a/src/core/oversized-backfill.ts b/src/core/oversized-backfill.tsindex 3c92ffdfd9..de61d76ffb 100644--- a/src/core/oversized-backfill.ts+++ b/src/core/oversized-backfill.ts@@ -20,7 +20,7 @@* (`reason: oversized`) is touched. A chunkless one is still re-chunked with* the marker kept (#6722), so every page up to the ceiling is keyword-searchable. 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`).+ * until the user approves the previewed cost (`gbrain embed --held --source S --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.@@ -40,6 +40,7 @@ import { effectiveBytesBlock } from './import-screen.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 { budgetLimitedReport } from './held-embedding.ts';import type { PageType } from './types.ts';/** The `page_embedding_budget.reason` a backfilled large page waits under. */@@ -70,8 +71,10 @@ export interface OversizedBackfillReceipt {/** 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[] };+ /** Exact commands: finish the backfill; preview held embedding; approve it for the source with the most waiting chunks (null until a run holds pages). */+ commands: { finish: string[]; approve: string[] | null; preview: string[] };+ /** Every source's approve command (a concrete --max-usd ceiling), one approval per source (#6803). */+ approvals: string[];}interface Candidate { id: number; slug: string; source_id: string; bytes: number }@@ -131,8 +134,8 @@ export async function runOversizedBackfill(engine: BrainEngine, opts: {const receipt: OversizedBackfillReceipt = {dry_run: opts.dryRun === true, block_bytes: block, candidates: before.candidates, reindexed: 0, held_for_approval: 0, failed: [],remaining: before.candidates, over_block: before.over, rechunked_over_block: 0, 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'] },+ commands: { finish: ['gbrain', 'reindex', '--oversized', ...scope], approve: null,+ preview: ['gbrain', 'embed', '--held', ...scope, '--dry-run'] }, approvals: [],};const managed = !receipt.dry_run && await managedPersistenceEnabled(engine);const touched: number[] = [];@@ -174,6 +177,12 @@ export async function runOversizedBackfill(engine: BrainEngine, opts: {}receipt.remaining = receipt.dry_run ? before.candidates : (await countMarked(engine, block, opts.sourceId)).candidates;if (embeddingEnabled) receipt.estimated_usd = estimatePageEmbedUsd(pendingChars, currentEmbeddingSignature());+ const found = embeddingEnabled && receipt.held_for_approval && !receipt.dry_run+ ? await budgetLimitedReport(engine, { ...(opts.sourceId ? { sourceId: opts.sourceId } : {}), signature: currentEmbeddingSignature() }) : null;+ if (found) {+ receipt.commands.approve = found.report.by_source[0]!.fix.argv!;+ receipt.approvals = found.report.by_source.map(s => s.fix.command!);+ }return receipt;}@@ -188,7 +197,7 @@ export function formatOversizedBackfillReceipt(r: OversizedBackfillReceipt): strif (!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(' ')}`);+ + `Preview: ${r.commands.preview.join(' ')}${r.approvals.length ? `; with the user's agreement, approve one source at a time: ${r.approvals.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)}).`);}@@ -215,7 +224,7 @@ export async function printOversizedBackfillUpgradeNotice(engine: BrainEngine):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_yes: `Preview: ${receipt.commands.preview.join(' ')}. Then, one source at a time, run ${receipt.approvals.join('; ') || 'the approve command the preview prints'}.`,if_no: 'Nothing to do: the pages stay keyword-searchable and doctor lists them under partial_embedding.',verify: 'gbrain doctor --only partial_embedding --json',}, {diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex f556a88b3c..b08fa7cdd6 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -24,8 +24,9 @@* page waits for the user's approval (the oversized-page upgrade backfill, or* a sampled junk hit). Held and capped pages leave the stale-chunk queue* (engine-sql/chunks.ts staleChunkWhere) so the sweep never retries them; an explicit- * approval (`gbrain embed --slugs <slug> --max-usd N`, `gbrain embed --held- * --max-usd N`) passes `approvedCapUsd`, lifts the hold and raises the cap.+ * approval (`gbrain embed --held --source S --max-usd N`, or `--slugs <slug>+ * --source S --max-usd N`) passes `approvedCapUsd`, lifts the hold and raises the+ * cap. Every printed approve and its N come from held-embedding-action.ts.** Crash safety: a reservation older than an hour (the provider call never* settled) is counted as spent, never released, so a crash cannot reopen@@ -35,18 +36,17 @@ import type { BrainEngine } from './engine.ts';import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './content-sanity.ts';import type { BodyStorage, ManifestRow } from './page-body/types.ts';import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';-import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';+import { estimateCostFromChars } from './embedding-pricing.ts';import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';import { isEmbedSkipped } from './embed-skip.ts';import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';import { chunkGenerationFilter } from './search/safe-chunks.ts';import { quoteIdentifier } from './search/embedding-column.ts';import { embeddingWriteTarget } from './page-state/projections.ts';+import { approvalAmount, approvalBasis, heldApproveAction, heldPreviewCommand, ledgerPricePerMTok, renderedCommand } from './held-embedding-action.ts';export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';export const DEFAULT_PAGE_EMBED_CAP_USD = 2;-/** Price assumed for a model with no known rate (the conservative OpenAI large rate). */-const UNPRICED_RATE_PER_MTOK = 0.13;export type PageBudgetState = 'open' | 'held' | 'capped';@@ -106,12 +106,6 @@ async function segmentedSampleWindows(engine: BrainEngine, pageId: number): Promreturn [await forward(0), await forward(Math.max(0, middle)), tail.slice(-JUNK_SAMPLE_CHARS)];}-function currentPricePerMTok(signature: string | null | undefined): { rate: number; priced: boolean } {- if (!signature) return { rate: UNPRICED_RATE_PER_MTOK, priced: false };- const hit = lookupEmbeddingPrice(signature.slice(0, signature.lastIndexOf(':')) || signature);- return hit.kind === 'known' ? { rate: hit.pricePerMTok, priced: true } : { rate: UNPRICED_RATE_PER_MTOK, priced: false };-}-/** Hold a large page's embedding until the user approves it (`reason` names why). Idempotent; never touches open spend. */export async function holdPageEmbedding(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, reason: string): Promise<void> {await engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'held', $2)@@ -130,7 +124,7 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,if (!isLargePageBytes(pageBodyBytes(page)) || stale.length === 0) return { kind: 'unmetered' };const approved = opts.approvedCapUsd !== undefined;const configured = await resolvePageEmbedCapUsd(engine);- const { rate, priced } = currentPricePerMTok(opts.signature);+ const { rate, priced } = ledgerPricePerMTok(opts.signature);return engine.transaction(async tx => {await tx.executeRaw('INSERT INTO page_embedding_budget (page_id) VALUES ($1) ON CONFLICT (page_id) DO NOTHING', [page.id]);const [row] = await tx.executeRaw<BudgetRow>(`SELECT state, reason, embedding_signature, spent_usd, reserved_usd, cap_usd,@@ -186,14 +180,14 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,export interface PageBudgetReport { slug: string; source_id: string; state: Exclude<PageBudgetState, 'open'>; reason: string | null;spent_usd: number; cap_usd: number | null; pending_chunks: number; pending_chars: number }-/** Estimated provider cost of embedding `chars` of chunk text with the model in `signature` (unknown models use the conservative rate). */+/** Estimated provider cost of embedding `chars` of chunk text with the model in `signature` (unknown models use the conservative rate, free recipes $0). */export function estimatePageEmbedUsd(chars: number, signature: string | null | undefined): number {- return estimateCostFromChars(chars, currentPricePerMTok(signature).rate);+ return estimateCostFromChars(chars, ledgerPricePerMTok(signature).rate);}-/** Held and capped pages with their stale chunk counts (doctor `partial_embedding`, `gbrain embed --held`). */-export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: { state?: 'held' | 'capped'; sourceId?: string; limit?: number } = {}): Promise<PageBudgetReport[]> {- const params: unknown[] = [opts.limit ?? 1000];+/** Held and capped pages with their stale chunk counts (`gbrain embed --held`); `limit: null` lists every one. */+export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: { state?: 'held' | 'capped'; sourceId?: string; limit?: number | null } = {}): Promise<PageBudgetReport[]> {+ const params: unknown[] = [opts.limit === undefined ? 1000 : opts.limit];const filters = [`b.state <> 'open'`, 'p.deleted_at IS NULL'];if (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);@@ -202,7 +196,7 @@ export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeR(SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${pending} AND ${chunkGenerationFilter('p', 'cc')}) AS pending_chunks,(SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND ${pending} AND ${chunkGenerationFilter('p', 'cc')}) AS pending_charsFROM page_embedding_budget b JOIN pages p ON p.id = b.page_id- WHERE ${filters.join(' AND ')} ORDER BY b.updated_at DESC, p.id LIMIT $1`, params);+ WHERE ${filters.join(' AND ')} ORDER BY b.updated_at DESC, p.id LIMIT $1::int`, params);return rows.map(row => ({ ...row, spent_usd: Number(row.spent_usd), cap_usd: row.cap_usd === null ? null : Number(row.cap_usd), pending_chunks: Number(row.pending_chunks), pending_chars: Number(row.pending_chars) }));}@@ -219,54 +213,38 @@ export async function spendGrant<T>(grant: PageEmbedGrant | undefined, call: ()}}+/** The approve command for one page's waiting chunks, with a concrete --max-usd ceiling (held-embedding-action.ts). */+async function pageApproveCommand(page: { slug: string; source_id?: string }, waiting: ReadonlyArray<{ chunk_text: string }>): Promise<string> {+ const basis = await approvalBasis();+ const amount = approvalAmount(waiting.reduce((n, c) => n + c.chunk_text.length, 0), basis);+ return renderedCommand(heldApproveAction({ source_id: page.source_id ?? 'default', slug: page.slug, pending_chunks: waiting.length, ...amount }, basis.free));+}+/*** One embedding run's per-page step: meter `candidates` (the page's chunks* without a vector) and narrow them to the grant, saying on stderr why chunks* wait. Null means embed nothing now (held, or the cap left no chunk);* otherwise `chunks` is the batch to embed, every candidate on an unmetered page.*/-export async function meterPageBatch<C extends { chunk_index: number; chunk_text: string }>(engine: BrainEngine, page: BudgetPage & { slug: string },+export async function meterPageBatch<C extends { chunk_index: number; chunk_text: string }>(engine: BrainEngine, page: BudgetPage & { slug: string; source_id?: string },candidates: readonly C[], opts: { signature?: string | null; approvedCapUsd?: number; announceHeld?: boolean }): Promise<{ grant?: PageEmbedGrant; chunks: C[] } | null> {const decision = await planPageEmbedding(engine, page, candidates, opts);if (decision.kind === 'unmetered') return { chunks: [...candidates] };- const approve = `gbrain embed --slugs ${page.slug} --max-usd <N>`;if (decision.kind === 'held') {- if (opts.announceHeld) process.stderr.write(`[embed] ${page.slug}: embedding held (${decision.reason}); the page stays keyword-searchable. Approve with: ${approve}\n`);+ if (opts.announceHeld) process.stderr.write(`[embed] ${page.slug}: embedding held (${decision.reason}); the page stays keyword-searchable. With the user's approval: ${await pageApproveCommand(page, candidates)}\n`);return null;}const { grant } = decision;const chunks = candidates.filter(c => grant.chunkIndexes.has(c.chunk_index));- if (grant.deferred) process.stderr.write(`[embed] ${page.slug}: per-page cap $${grant.capUsd.toFixed(2)} reached; ${grant.deferred} older chunk(s) stay keyword-only until it rises (${approve})\n`);+ if (grant.deferred) {+ const waiting = candidates.filter(c => !grant.chunkIndexes.has(c.chunk_index));+ process.stderr.write(`[embed] ${page.slug}: per-page cap $${grant.capUsd.toFixed(2)} reached; ${grant.deferred} older chunk(s) stay keyword-only until it rises (${await pageApproveCommand(page, waiting)})\n`);+ }if (chunks.length) return { grant, chunks };await grant.settle({ ok: true });return null;}-/**- * `gbrain embed --held`: list the held and capped large pages with what each- * would cost to finish, then return the `--source S --slugs ...` argv that- * embeds them under the user's `--max-usd` (one source per approval).- */-export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[], signature: string | null, say: (line: string) => void): Promise<{ argv: string[] } | { error: string } | null> {- if (args.includes('--background')) return { error: '[embed] --held runs in the foreground: the per-page approval is not carried into background jobs.' };- const sourceIdx = args.indexOf('--source');- const limited = await listBudgetLimitedPages(engine, sourceIdx >= 0 ? { sourceId: args[sourceIdx + 1] } : {});- if (limited.length === 0) {- say('[embed] No large pages are held or capped by embed.max_usd_per_page.');- return null;- }- for (const row of limited) {- say(`[embed] ${row.slug} (${row.source_id}): ${row.state}${row.reason ? ` (${row.reason})` : ''}, ${row.pending_chunks} chunk(s) without a vector, `- + `spent $${row.spent_usd.toFixed(2)}, about $${estimatePageEmbedUsd(row.pending_chars, signature).toFixed(2)} to finish`);- }- const sources = [...new Set(limited.map(row => row.source_id))];- if (sources.length > 1) {- return { error: `[embed] Held pages span ${sources.length} sources; one approval covers one source. Run per source: ${sources.map(id => `gbrain embed --held --source ${id} --max-usd <N>`).join('; ')}` };- }- const rest = args.filter((a, i) => a !== '--held' && a !== '--source' && args[i - 1] !== '--source');- return { argv: [...rest, '--source', sources[0], '--slugs', ...limited.map(row => row.slug)] };-}-/*** #6722: what a write left a page's embedding in, for write, sync and* remember receipts. Null for an ordinary page (embedded with the write, or by@@ -292,7 +270,7 @@ export function pageSizeState(bytes: number, frontmatter: Record<string, unknown* pageSizeState for stored pages of one source with a non-null state: the given slugs, or (null) every* such page in the source, as a full sync walked them all.*/-export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slugs: readonly string[] | null): Promise<Array<{ slug: string } & PageSizeState>> {+export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slugs: readonly string[] | null): Promise<Array<{ slug: string; source_id: string } & PageSizeState>> {if (slugs?.length === 0) return [];const bytes = `(CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END)`;const rows = await engine.executeRaw<{ slug: string; bytes: number; segmented: boolean; frontmatter: Record<string, unknown> | null; state: PageBudgetState | null; reason: string | null }>(@@ -303,7 +281,7 @@ export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>slugs ? [sourceId, PAGE_INLINE_MAX_BYTES, [...slugs]] : [sourceId, PAGE_INLINE_MAX_BYTES]);return rows.flatMap(row => {const state = pageSizeState(Number(row.bytes), row.frontmatter, row.state ? { state: row.state, reason: row.reason } : null, row.segmented === true);- return state ? [{ slug: row.slug, ...state }] : [];+ return state ? [{ slug: row.slug, source_id: sourceId, ...state }] : [];});}@@ -318,10 +296,10 @@ export async function sizeStateField(engine: Pick<BrainEngine, 'executeRaw'>, so}/** #6722: the sync receipt's tally of pages a run left large or embed_skip: the total and the first SIZE_STATE_SAMPLE. */-export interface SyncSizeStates { total: number; pages: Array<{ slug: string; path?: string } & PageSizeState> }+export interface SyncSizeStates { total: number; pages: Array<{ slug: string; path?: string; source_id?: string } & PageSizeState> }export const SIZE_STATE_SAMPLE = 50;-export function addSizeState(tally: SyncSizeStates | undefined, entry: { slug: string; path?: string } & PageSizeState): SyncSizeStates {+export function addSizeState(tally: SyncSizeStates | undefined, entry: { slug: string; path?: string; source_id?: string } & PageSizeState): SyncSizeStates {const pages = tally?.pages ?? [];return { total: (tally?.total ?? 0) + 1, pages: pages.length < SIZE_STATE_SAMPLE ? [...pages, entry] : pages };}@@ -329,9 +307,9 @@ export function addSizeState(tally: SyncSizeStates | undefined, entry: { slug: s/** One line per sampled page for the sync output, and the rest as a count. */export function sizeStateLines(tally: SyncSizeStates | undefined): string[] {if (!tally?.total) return [];- const what = (s: PageSizeState) => s.embedding === 'skipped'+ const what = (s: PageSizeState & { source_id?: string }) => s.embedding === 'skipped'? `no vectors (${s.reason === 'oversized' ? 'over the content_sanity.bytes_block limit' : 'embed_skip marker'}); chunks keep it in keyword search`- : s.embedding === 'held' ? `embedding held (${s.reason}); \`gbrain reindex --held\` previews the cost`+ : s.embedding === 'held' ? `embedding held (${s.reason}); \`${heldPreviewCommand(s.source_id)}\` previews the cost`: s.embedding === 'partial' ? 'partly embedded under embed.max_usd_per_page; the rest stays keyword-only': 'large page; embedding runs after the commit under embed.max_usd_per_page';const lines = tally.pages.slice(0, 20).map(p => ` Size ${p.path ?? p.slug} (${p.bytes} bytes): ${what(p)}.`);diff --git a/test/e2e/held-embedding-budgets-postgres.test.ts b/test/e2e/held-embedding-budgets-postgres.test.tsnew file mode 100644index 0000000000..c2d24626a6--- /dev/null+++ b/test/e2e/held-embedding-budgets-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../held-embedding-budgets.test.ts'));diff --git a/test/held-embedding-budgets.test.ts b/test/held-embedding-budgets.test.tsnew file mode 100644index 0000000000..27e0149443--- /dev/null+++ b/test/held-embedding-budgets.test.ts@@ -0,0 +1,207 @@+/**+ * #6803 part 3: held embedding budgets, surfaced (PGLite, and Postgres via+ * test/e2e/held-embedding-budgets-postgres.test.ts).+ *+ * Protects: one count of the large pages that wait for embedding approval+ * (held or at their per-page cap) against the active vector column, with no+ * row cap, and one phrase for it; `sizeStateLines` names a command that exists+ * (`gbrain embed --held --dry-run --source <id>`, never `gbrain reindex+ * --held`); doctor `partial_embedding` is its own registry entry, so a slow+ * full `pages` scan in the content-sanity entry no longer turns it unknown;+ * its fix is a per-source approve with a concrete N; the embed-backfill job+ * reports `budget_limited` without counting it as a failure; a local model's+ * per-page ledger charges $0 (#6847); the printed N is a ceiling with the+ * `derivedCapUsd` floor.+ * Fails when: any surface goes silent again, truncates at 1,000 rows, or+ * prints a placeholder or a command that does not exist.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { ChunkInput } from '../src/core/types.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { PAGE_INLINE_MAX_BYTES } from '../src/core/page-size-policy.ts';+import { PAGE_EMBED_CAP_KEY, holdPageEmbedding, listBudgetLimitedPages, planPageEmbedding, readPageSizeStates, addSizeState, sizeStateLines } from '../src/core/page-embedding-budget.ts';+import { budgetLimitedField, budgetLimitedFinding, heldEmbedArgv, readBudgetLimited } from '../src/core/held-embedding.ts';+import { FREE_APPROVAL_USD, approvalAmount, budgetLimitedPhrase, ledgerPricePerMTok } from '../src/core/held-embedding-action.ts';+import { derivedCapUsd } from '../src/core/consent.ts';+import { makeEmbedBackfillHandler } from '../src/core/minions/handlers/embed-backfill.ts';+import { buildChecks } from '../src/commands/doctor.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';++const BODY = 'Weekly notes from acme-example with alice-example. '.repeat(Math.ceil((PAGE_INLINE_MAX_BYTES + 4096) / 51));+const vector = () => new Float32Array(1536).fill(0.1);++for (const backend of testBackends()) {+ describe(`held embedding budgets (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ }, 120_000);+ afterAll(async () => { resetGateway(); await close(); });+ beforeEach(async () => {+ if (backend === 'pglite') await resetPgliteState(engine as PGLiteEngine);+ else {+ await engine.executeRaw('DELETE FROM page_embedding_budget');+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw(`DELETE FROM sources WHERE id <> 'default'`);+ }+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alpha', 'alpha') ON CONFLICT (id) DO NOTHING`);+ });++ /** A large page with `chunks` chunks; the indexes in `embedded` carry a vector. */+ async function largePage(slug: string, sourceId: string, chunks: number, embedded: number[] = []): Promise<number> {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: BODY }, { sourceId });+ const inputs: ChunkInput[] = Array.from({ length: chunks }, (_, i) => ({ chunk_index: i, chunk_text: `chunk ${i} `.padEnd(2000, 'acme-example '),+ chunk_source: 'compiled_truth', token_count: 500, ...(embedded.includes(i) ? { embedding: vector() } : {}) }));+ await installFixtureChunks(engine, slug, inputs, { sourceId });+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, sourceId]);+ return Number(row!.id);+ }+ const cap = (pageId: number) => engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, state, reason, spent_usd, cap_usd) VALUES ($1, 'capped', 'cap_reached', 2, 2)+ ON CONFLICT (page_id) DO UPDATE SET state = 'capped', reason = 'cap_reached'`, [pageId]);++ test('the phrase: a held page with one retained vector and a capped page with an embedded chunk', async () => {+ await holdPageEmbedding(engine, await largePage('chats/held', 'default', 3, [2]), 'upgrade_backfill');+ await cap(await largePage('chats/capped', 'alpha', 4, [3]));+ await holdPageEmbedding(engine, await largePage('chats/done', 'default', 2, [0, 1]), 'upgrade_backfill');+ const b = await readBudgetLimited(engine);+ expect(b).toEqual({ held: 1, capped: 1, held_reasons: { upgrade_backfill: 1 }, pending_chunks: 5, by_source: [+ { source_id: 'alpha', held: 0, capped: 1, pending_chunks: 3, pending_chars: 6000 },+ { source_id: 'default', held: 1, capped: 0, pending_chunks: 2, pending_chars: 4000 },+ ] });+ expect(budgetLimitedPhrase(b)).toBe('2 large page(s) have chunks waiting for embedding approval (1 held: upgrade_backfill; 1 at their per-page cap); those chunks are keyword-only until approved.');+ expect((await readBudgetLimited(engine, { sourceId: 'default' })).by_source.map(s => s.source_id)).toEqual(['default']);+ }, 60_000);++ test('a page whose vectors came from another embedding signature still waits', async () => {+ const id = await largePage('chats/old-model', 'default', 2, [0, 1]);+ await holdPageEmbedding(engine, id, 'upgrade_backfill');+ await engine.executeRaw(`UPDATE pages SET embedding_signature = 'openai:text-embedding-3-small:1536' WHERE id = $1`, [id]);+ expect((await readBudgetLimited(engine, { signature: 'openai:text-embedding-3-large:1536' })).pending_chunks).toBe(2);+ expect((await readBudgetLimited(engine, { signature: 'openai:text-embedding-3-small:1536' })).held).toBe(0);+ }, 60_000);++ test('more than 1000 held pages are counted and listed, none truncated', async () => {+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, content_hash, created_at, updated_at)+ SELECT 'archive/day-' || g, 'default', 'note', 'Day ' || g, 'x', '{}', 'h' || g, now(), now() FROM generate_series(1, 1001) AS g`);+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text) SELECT id, 0, 'acme-example notes' FROM pages WHERE slug LIKE 'archive/day-%'`);+ await engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, state, reason) SELECT id, 'held', 'upgrade_backfill' FROM pages WHERE slug LIKE 'archive/day-%'`);+ expect((await readBudgetLimited(engine)).held).toBe(1001);+ expect(await listBudgetLimitedPages(engine, { limit: null })).toHaveLength(1001);+ const listing = await heldEmbedArgv(engine, ['--held', '--dry-run'], null, () => {});+ expect('pages' in listing && listing.pages).toHaveLength(1001);+ const run = await heldEmbedArgv(engine, ['--held', '--max-usd', '1'], null, () => {});+ expect('argv' in run && run.argv.filter(a => a.startsWith('archive/day-'))).toHaveLength(1001);+ }, 60_000);++ test('sizeStateLines names the source-scoped preview that exists, not gbrain reindex --held', async () => {+ await holdPageEmbedding(engine, await largePage('chats/receipt', 'alpha', 2), 'upgrade_backfill');+ const states = await readPageSizeStates(engine, 'alpha', ['chats/receipt']);+ expect(states).toEqual([expect.objectContaining({ slug: 'chats/receipt', embedding: 'held', reason: 'upgrade_backfill', source_id: 'alpha' })]);+ const text = sizeStateLines(states.reduce<ReturnType<typeof addSizeState> | undefined>((t, s) => addSizeState(t, s), undefined)).join('\n');+ expect(text).not.toContain('reindex --held');+ expect(text).toContain('`gbrain embed --held --dry-run --source alpha` previews the cost');+ }, 60_000);++ test('#6847: the per-page ledger prices a free local recipe at $0, so a local model never hits its cap', async () => {+ expect(ledgerPricePerMTok('ollama:nomic-embed-text:768')).toEqual({ rate: 0, priced: true });+ await engine.setConfig(PAGE_EMBED_CAP_KEY, '0');+ const id = await largePage('chats/local', 'default', 3);+ const page = { id, compiled_truth: BODY, timeline: '' };+ const stale = [0, 1, 2].map(chunk_index => ({ chunk_index, chunk_text: 'acme-example '.repeat(200) }));+ const decision = await planPageEmbedding(engine, page, stale, { signature: 'ollama:nomic-embed-text:768' });+ expect(decision.kind).toBe('grant');+ if (decision.kind !== 'grant') return;+ expect(decision.grant.chunkIndexes.size).toBe(3);+ expect(decision.grant.reservedUsd).toBe(0);+ await decision.grant.settle({ ok: true });+ const [row] = await engine.executeRaw<{ spent_usd: number; state: string }>('SELECT spent_usd, state FROM page_embedding_budget WHERE page_id = $1', [id]);+ expect({ spent: Number(row!.spent_usd), state: row!.state }).toEqual({ spent: 0, state: 'open' });+ await engine.unsetConfig(PAGE_EMBED_CAP_KEY);+ }, 60_000);++ test('the printed N is a ceiling: derivedCapUsd of the higher of the run-meter and ledger estimates, $0.01 on a free provider', () => {+ const paid = { model: 'openai:text-embedding-3-small', signature: 'openai:text-embedding-3-small:1536', free: false, charsPerToken: 4 };+ const small = approvalAmount(4000, paid);+ expect(small.max_usd).toBe(0.25);+ const big = approvalAmount(400_000_000, paid);+ expect(big.max_usd).toBe(derivedCapUsd(big.est_usd));+ expect(big.max_usd).toBeGreaterThanOrEqual(big.est_usd * 1.5);+ expect(approvalAmount(400_000_000, { ...paid, model: 'ollama:nomic-embed-text', signature: 'ollama:nomic-embed-text:768', free: true })).toEqual({ est_usd: 0, max_usd: FREE_APPROVAL_USD });+ });++ test('doctor partial_embedding is its own entry and still warns while the content scans are over budget', async () => {+ expect(DOCTOR_CHECK_REGISTRY.filter(e => e.emits.includes('partial_embedding')).map(e => e.emits)).toEqual([['partial_embedding']]);+ await holdPageEmbedding(engine, await largePage('chats/doctor-a', 'default', 3), 'upgrade_backfill');+ await cap(await largePage('chats/doctor-b', 'alpha', 2));+ await engine.setConfig('doctor.entry_budget_ms', '300');+ const slow = new Proxy(engine, {+ get(target, key) {+ if (key === 'executeRaw') {+ return async (sql: string, params?: unknown[], opts?: unknown) => {+ if (/octet_length\(p\.compiled_truth\)/.test(sql)) await new Promise(r => setTimeout(r, 1500));+ return target.executeRaw(sql, params, opts as never);+ };+ }+ const value = Reflect.get(target, key, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ }) as BrainEngine;+ try {+ const checks = await buildChecks(slow, ['--json', '--scope=brain', '--only', 'partial_embedding']);+ const check = checks.find(c => c.name === 'partial_embedding')!;+ expect(check.status).toBe('warn');+ expect(check.details?.health).toBeUndefined();+ expect(check.message).toContain('2 large page(s) have chunks waiting for embedding approval (1 held: upgrade_backfill; 1 at their per-page cap)');+ const fix = check.fix as { argv: string[]; preview_argv: string[]; verify: { argv: string[] }; consent: string[]; next?: string };+ expect(fix.argv.slice(0, 6)).toEqual(['gbrain', 'embed', '--held', '--source', 'default', '--max-usd']);+ expect(Number(fix.argv[6])).toBeGreaterThan(0);+ expect(fix.argv.join(' ')).not.toContain('<N>');+ expect(fix.preview_argv.slice(0, 7)).toEqual(['gbrain', 'embed', '--held', '--dry-run', '--source', 'default', '--json']);+ expect(fix.verify.argv.slice(0, 7)).toEqual(fix.preview_argv.slice(0, 7));+ expect(fix.consent).toEqual(['paid', 'egress']);+ const bySource = check.details!.by_source as Array<{ source_id: string; fix: { command: string; next: string } }>;+ expect(bySource.map(s => s.source_id)).toEqual(['default', 'alpha']);+ expect(bySource[1]!.fix.command).toMatch(/^gbrain embed --held --source alpha --max-usd \d+\.\d\d/);+ expect(bySource[1]!.fix.next).toBe('ask_user');+ } finally {+ await engine.unsetConfig('doctor.entry_budget_ms');+ }+ }, 60_000);++ test('doctor partial_embedding is ok when every held page is fully embedded', async () => {+ await holdPageEmbedding(engine, await largePage('chats/complete', 'default', 2, [0, 1]), 'upgrade_backfill');+ expect(await budgetLimitedFinding(engine, null)).toBeNull();+ }, 60_000);++ test('the embed-backfill job reports budget_limited for its source and still succeeds', async () => {+ await holdPageEmbedding(engine, await largePage('chats/job', 'default', 3), 'upgrade_backfill');+ await holdPageEmbedding(engine, await largePage('chats/other', 'alpha', 2), 'upgrade_backfill');+ const controller = new AbortController();+ const job = { id: 1, name: 'embed-backfill', data: { sourceId: 'default' }, attempts_made: 0, signal: controller.signal, deadlineAtMs: null,+ shutdownSignal: controller.signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {}, isActive: async () => true, readInbox: async () => [] } as unknown as MinionJobContext;+ const handler = makeEmbedBackfillHandler(engine, { runStale: async () => ({ embedded: 0, chunksProcessed: 0, pagesProcessed: 0, invalidated: 0, lastCursor: null, done: true, aborted: false }) });+ const result = await handler(job);+ expect(result.status).toBe('success');+ expect(result.budget_limited).toMatchObject({ held: 1, capped: 0, held_reasons: { upgrade_backfill: 1 }, pending_chunks: 3 });+ expect(result.budget_limited!.by_source.map(s => s.source_id)).toEqual(['default']);+ expect(result.budget_limited!.by_source[0]!.fix.command).toMatch(/^gbrain embed --held --source default --max-usd \d+\.\d\d/);+ expect(await budgetLimitedField(engine, 'alpha', null)).toMatchObject({ budget_limited: { held: 1 } });+ }, 60_000);+ });+}diff --git a/test/held-embedding-printed-commands.serial.test.ts b/test/held-embedding-printed-commands.serial.test.tsnew file mode 100644index 0000000000..3ada0fdf55--- /dev/null+++ b/test/held-embedding-printed-commands.serial.test.ts@@ -0,0 +1,142 @@+/**+ * #6803 plan B7: the printed-command guard for held embedding budgets.+ *+ * Protects: every command `sizeStateLines`, `budget_limited` (`gbrain embed+ * --stale`), doctor `partial_embedding` (message, fix, preview, verify and+ * `details.by_source`), the `meterPageBatch` hold line, `gbrain embed --held`+ * and the edited docs print is rendered through `renderAction` with routing set+ * (brain `host`, source `alpha`) and runs in dry form through the real CLI on+ * a two-source brain with exit 0; no literal `<N>`; every approve names+ * `--source`; the every-source listing is not narrowed by the source pin.+ * Fails when: a surface prints `gbrain reindex --held` (which does not exist),+ * an approve without `--source` (refused on a multi-source brain), or a+ * placeholder.+ * Extension point: test/helpers/printed-command-guard.ts+ * (`PRINTED_COMMAND_PRODUCERS`); lane A's projection texts register there.+ * Serial: it installs the process-wide CLI fix routing (installCliRouting), which+ * every renderAction in the process reads.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { __resetCliRoutingForTests, installCliRouting } from '../src/core/fix-routing.ts';+import { addSizeState, readPageSizeStates, sizeStateLines, type SyncSizeStates } from '../src/core/page-embedding-budget.ts';+import { budgetLimitedReport } from '../src/core/held-embedding.ts';+import { heldPreviewCommand } from '../src/core/held-embedding-action.ts';+import { argvOf, gbrain, makeHeldBrain, seedHeldPage, startFakeEmbeddings, withBrain, type FakeEmbeddings, type HeldBrain } from './helpers/held-embedding-fixture.ts';+import { PRINTED_COMMAND_PRODUCERS, docSection, dryForm, extractCommands, registerPrintedCommandProducer, type GuardFixture } from './helpers/printed-command-guard.ts';++const ROUTING = { brain: 'host', source: 'alpha' };+/** The held-embedding commands of a doc section (the embed approvals and previews, doctor's check); the rest of the section is other lanes' surface. */+const heldCommand = (argv: string[]) => (argv[0] === 'embed' && (argv.includes('--held') || argv.includes('--slugs'))) || (argv[0] === 'doctor' && argv.includes('partial_embedding'));++registerPrintedCommandProducer({+ name: 'sizeStateLines (sync, put_page and remember receipts)',+ text: async ({ brain }) => withBrain(brain, async engine => {+ let tally: SyncSizeStates | undefined;+ for (const source of ['default', 'alpha']) for (const state of await readPageSizeStates(engine, source, null)) tally = addSizeState(tally, state);+ return sizeStateLines(tally).join('\n');+ }),+});+registerPrintedCommandProducer({+ name: 'budget_limited, rendered in-process',+ text: async ({ brain }) => withBrain(brain, async engine => {+ const found = (await budgetLimitedReport(engine, { signature: null }))!;+ return [found.line, found.report.preview_command, ...found.report.by_source.map(s => s.fix.command!)].join('\n');+ }),+});+registerPrintedCommandProducer({+ name: 'gbrain embed --stale (budget_limited line and JSON)',+ text: async ({ run }) => {+ const out = await run(['embed', '--stale', '--json']);+ const doc = JSON.parse(out.stdout);+ return [out.stderr, doc.budget_limited.preview_command, doc.budget_limited.fix.command, ...doc.budget_limited.by_source.map((s: { fix: { command: string } }) => s.fix.command)].join('\n');+ },+});+registerPrintedCommandProducer({+ name: 'doctor partial_embedding',+ text: async ({ run }) => {+ const out = await run(['doctor', '--only', 'partial_embedding', '--json'], { GBRAIN_SOURCE: 'alpha' });+ const check = JSON.parse(out.stdout).checks.find((c: { name: string }) => c.name === 'partial_embedding');+ expect(check.status).toBe('warn');+ const fix = check.fix as { command: string; preview_argv: string[]; verify: { argv: string[] } };+ return [check.message, fix.command, fix.preview_argv.join(' '), fix.verify.argv.join(' '), check.details.preview_command,+ ...check.details.by_source.map((s: { fix: { command: string } }) => s.fix.command)].join('\n');+ },+});+registerPrintedCommandProducer({+ name: 'meterPageBatch hold line',+ text: async ({ run }) => (await run(['embed', '--slugs', 'archive/day-b', '--source', 'alpha'])).stderr,+});+registerPrintedCommandProducer({+ name: 'gbrain embed --held (listing and multi-source refusal)',+ text: async ({ run }) => {+ const listing = await run(['embed', '--held', '--dry-run']);+ expect(listing.exitCode, listing.stderr).toBe(0);+ const refused = await run(['embed', '--held', '--max-usd', '1']);+ expect(refused.exitCode).toBe(2);+ return `${listing.stdout}\n${listing.stderr}\n${refused.stderr}`;+ },+});+registerPrintedCommandProducer({+ name: 'docs/guides/memory-boundaries.md (large pages)',+ text: async () => [docSection('docs/guides/memory-boundaries.md', '## Large pages', '| Page body |'),+ docSection('docs/guides/memory-boundaries.md', 'id="large-pages-upgrade"', '## Where text goes')].join('\n'),+ fill: { '<id>': 'alpha', '<N>': '1', '<slug>': 'archive/day-b' },+ owns: heldCommand,+});+registerPrintedCommandProducer({+ name: 'docs/guides/troubleshooting.md (held embedding row)',+ text: async () => docSection('docs/guides/troubleshooting.md', 'chunks waiting for embedding approval'),+ fill: { '<id>': 'alpha', '<N>': '1' },+ owns: heldCommand,+});++let fake: FakeEmbeddings;+let brain: HeldBrain;+let fixture: GuardFixture;++beforeAll(async () => {+ fake = startFakeEmbeddings();+ brain = await makeHeldBrain('ollama:nomic-embed-text', { OLLAMA_BASE_URL: fake.url });+ await withBrain(brain, async engine => {+ await seedHeldPage(engine, 'archive/day-a', 'default', 3);+ await seedHeldPage(engine, 'archive/day-b', 'alpha', 2);+ await seedHeldPage(engine, 'archive/day-c', 'alpha', 2);+ await engine.executeRaw(`UPDATE page_embedding_budget SET state = 'capped', reason = 'cap_reached', cap_usd = 2, spent_usd = 2+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'archive/day-c')`);+ });+ installCliRouting(() => ROUTING);+ fixture = { brain, run: (args, env) => gbrain(brain, args, env), routing: ROUTING };+}, 120_000);++afterAll(() => {+ __resetCliRoutingForTests();+ fake.stop();+ brain.cleanup();+});++test('the every-source listing opts out of the source pin; a source-scoped preview keeps it', () => {+ expect(heldPreviewCommand()).toBe('gbrain embed --held --dry-run --brain host');+ expect(heldPreviewCommand('default')).toBe('gbrain embed --held --dry-run --source default --brain host');+});++test('every printed command runs in dry form through the real CLI with exit 0', async () => {+ const failures: string[] = [];+ let guarded = 0;+ for (const producer of PRINTED_COMMAND_PRODUCERS) {+ const text = await producer.text(fixture);+ const commands = extractCommands(text).map(c => Object.entries(producer.fill ?? {}).reduce((s, [k, v]) => s.split(k).join(v), c))+ .filter(c => !producer.owns || producer.owns(argvOf(c)));+ if (commands.length === 0) failures.push(`${producer.name}: printed no gbrain command`);+ for (const command of commands) {+ guarded++;+ const argv = argvOf(command);+ if (command.includes('<') || command.includes('>')) { failures.push(`${producer.name}: placeholder left in ${command}`); continue; }+ if (argv[0] === 'reindex' && argv.includes('--held')) { failures.push(`${producer.name}: ${command} does not exist`); continue; }+ if (argv[0] === 'embed' && argv.includes('--max-usd') && !argv.includes('--source')) { failures.push(`${producer.name}: approve without --source: ${command}`); continue; }+ const out = await fixture.run(dryForm(argv));+ if (out.exitCode !== 0) failures.push(`${producer.name}: gbrain ${dryForm(argv).join(' ')} exited ${out.exitCode}: ${(out.stderr || out.stdout).slice(0, 400)}`);+ }+ }+ expect(failures).toEqual([]);+ expect(guarded).toBeGreaterThan(10);+}, 280_000);diff --git a/test/helpers/held-embedding-fixture.ts b/test/helpers/held-embedding-fixture.tsnew file mode 100644index 0000000000..c3f5a70de8--- /dev/null+++ b/test/helpers/held-embedding-fixture.ts@@ -0,0 +1,106 @@+/**+ * Fixture for the held-embedding CLI tests (#6803 part 3, #6847): an on-disk+ * PGLite brain made by the real `gbrain init`, large pages held for approval+ * the way the post-upgrade backfill holds them (`upgrade_backfill`), and a+ * local OpenAI-compatible `/v1/embeddings` server standing in for the+ * provider. `dense` bills one token per character (CJK, minified code): four+ * times the chars-per-token basis the run meter assumes.+ */+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { ChunkInput } from '../../src/core/types.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PAGE_INLINE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { holdPageEmbedding } from '../../src/core/page-embedding-budget.ts';+import { installFixtureChunks } from './page-projection.ts';+import { runCli, type CliResult } from './cli-spawn.ts';++export interface FakeEmbeddings { url: string; calls: number; tokens: number; stop(): void }++export function startFakeEmbeddings(opts: { dense?: boolean; dims?: number } = {}): FakeEmbeddings {+ const fake = { url: '', calls: 0, tokens: 0, stop: () => server.stop(true) };+ const server = Bun.serve({+ hostname: '127.0.0.1', port: 0,+ async fetch(req) {+ if (!new URL(req.url).pathname.endsWith('/embeddings')) return Response.json({ object: 'list', data: [{ id: 'fixture-embedder', object: 'model' }] });+ const body = await req.json() as { input: string | string[]; dimensions?: number };+ const inputs = Array.isArray(body.input) ? body.input : [body.input];+ const chars = inputs.reduce((n, s) => n + s.length, 0);+ const tokens = opts.dense ? chars : Math.ceil(chars / 4);+ fake.calls++;+ fake.tokens += tokens;+ const dims = body.dimensions ?? opts.dims ?? 1536;+ return Response.json({ object: 'list', model: 'fixture-embedder', usage: { prompt_tokens: tokens, total_tokens: tokens },+ data: inputs.map((_, index) => ({ object: 'embedding', index, embedding: new Array(dims).fill(0.01) })) });+ },+ });+ fake.url = `http://127.0.0.1:${server.port}/v1`;+ return fake;+}++export interface HeldBrain { home: string; env: Record<string, string | undefined>; cleanup(): void }++const SCRUB = ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'VOYAGE_API_KEY', 'GEMINI_API_KEY', 'GOOGLE_GENERATIVE_AI_API_KEY', 'ANTHROPIC_API_KEY',+ 'OLLAMA_BASE_URL', 'GBRAIN_EMBEDDING_MODEL', 'GBRAIN_SOURCE', 'GBRAIN_DATABASE_URL', 'DATABASE_URL'];++/** The real CLI against the fixture brain (argv without `gbrain`); `env` overlays the brain's env. */+export function gbrain(brain: HeldBrain, args: string[], env: Record<string, string | undefined> = {}): Promise<CliResult> {+ return runCli(args, { home: brain.home, env: { ...brain.env, ...env }, timeoutMs: 120_000 });+}++/** A PGLite brain made by `gbrain init` (keyless), then pointed at `model` with 1536 dimensions. */+export async function makeHeldBrain(model: string, env: Record<string, string | undefined>): Promise<HeldBrain> {+ const home = mkdtempSync(join(tmpdir(), 'gb-held-'));+ const brain: HeldBrain = { home, env: { ...Object.fromEntries(SCRUB.map(k => [k, undefined])), ...env }, cleanup: () => rmSync(home, { recursive: true, force: true }) };+ const init = await gbrain(brain, ['init', '--pglite', '--no-embedding', '--non-interactive']);+ if (init.exitCode !== 0) throw new Error(`gbrain init failed: ${init.stderr}`);+ const path = join(home, '.gbrain', 'config.json');+ const cfg = JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;+ delete cfg.embedding_disabled;+ writeFileSync(path, JSON.stringify({ ...cfg, embedding_model: model, embedding_dimensions: 1536 }));+ return brain;+}++/** The brain's PGLite opened in-process (never while a CLI child holds it). */+export async function withBrain<T>(brain: HeldBrain, fn: (engine: BrainEngine) => Promise<T>): Promise<T> {+ const cfg = JSON.parse(readFileSync(join(brain.home, '.gbrain', 'config.json'), 'utf8')) as { database_path: string };+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: cfg.database_path } as never);+ try {+ return await fn(engine);+ } finally {+ await engine.disconnect();+ }+}++const BODY = 'Weekly notes from acme-example with alice-example. '.repeat(Math.ceil((PAGE_INLINE_MAX_BYTES + 4096) / 51));++/** A large page with `chunks` 2,000-character chunks and no vectors, held `upgrade_backfill` as the post-upgrade backfill leaves it. */+export async function seedHeldPage(engine: BrainEngine, slug: string, sourceId: string, chunks: number): Promise<void> {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [sourceId]);+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: BODY }, { sourceId });+ const inputs: ChunkInput[] = Array.from({ length: chunks }, (_, i) => ({ chunk_index: i, chunk_text: `${slug} chunk ${i} `.padEnd(2000, 'acme-example '),+ chunk_source: 'compiled_truth', token_count: 500 }));+ await installFixtureChunks(engine, slug, inputs, { sourceId });+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, sourceId]);+ await holdPageEmbedding(engine, Number(row!.id), 'upgrade_backfill');+}++export interface BudgetRow { slug: string; source_id: string; state: string | null; reason: string | null; spent_usd: number; cap_usd: number | null; chunks: number; embedded: number }++/** Every seeded page's ledger row and how many of its chunks carry a vector. */+export function budgetRows(brain: HeldBrain): Promise<BudgetRow[]> {+ return withBrain(brain, async engine => (await engine.executeRaw<BudgetRow>(`SELECT p.slug, p.source_id, b.state, b.reason, b.spent_usd, b.cap_usd,+ (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id) AS chunks,+ (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedding IS NOT NULL) AS embedded+ FROM pages p LEFT JOIN page_embedding_budget b ON b.page_id = p.id WHERE p.deleted_at IS NULL ORDER BY p.slug`))+ .map(r => ({ ...r, spent_usd: Number(r.spent_usd ?? 0), cap_usd: r.cap_usd === null ? null : Number(r.cap_usd), chunks: Number(r.chunks), embedded: Number(r.embedded) })));+}++/** A printed command's argv, without the leading `gbrain`. */+export function argvOf(command: string): string[] {+ const argv = command.trim().split(/\s+/);+ return argv[0] === 'gbrain' ? argv.slice(1) : argv;+}diff --git a/test/helpers/printed-command-guard.ts b/test/helpers/printed-command-guard.tsnew file mode 100644index 0000000000..37d98fa623--- /dev/null+++ b/test/helpers/printed-command-guard.ts@@ -0,0 +1,69 @@+/**+ * The printed-command guard (#6803 plan B7): every command a surface prints+ * for an operator or agent to run is rendered through `renderAction` with+ * routing set, then executed in dry form through the real dispatcher on a+ * two-source fixture, and must exit 0. A command that does not exist, a+ * literal `<N>` placeholder, an approve that a multi-source brain refuses, or+ * a listing narrowed by the routing pin fails here.+ *+ * Extension point: `PRINTED_COMMAND_PRODUCERS` is the list the guard runs.+ * Each producer seeds what its surface needs on the fixture brain and returns+ * the text (or rendered commands) the surface printed; the guard extracts+ * every `gbrain ...` command from it. Lane B (#6803 part 3) registers+ * `sizeStateLines`, `budget_limited` (`embed --stale`), doctor+ * `partial_embedding`, the `meterPageBatch` hold line, `embed --held` and+ * the edited docs. Lane A's projection texts (A9) join by pushing producers+ * here (`registerPrintedCommandProducer`).+ */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import type { CliResult } from './cli-spawn.ts';+import type { HeldBrain } from './held-embedding-fixture.ts';++/** What a producer gets: the fixture brain (two sources, `default` and `alpha`) and the real CLI against it. */+export interface GuardFixture {+ brain: HeldBrain;+ /** The real CLI (argv without `gbrain`); `env` overlays the fixture env. */+ run(args: string[], env?: Record<string, string | undefined>): Promise<CliResult>;+ /** The routing every in-process render uses (`installCliRouting`): the fixture's brain and source `alpha`. */+ routing: { brain: string; source: string };+}++export interface PrintedCommandProducer {+ /** The surface, for the failure message. */+ name: string;+ /** The printed text; every `gbrain ...` command in it is guarded. */+ text(fixture: GuardFixture): Promise<string>;+ /** Placeholders a doc command carries, filled before the run (`<id>` -> a fixture source). */+ fill?: Record<string, string>;+ /** Which extracted commands this producer owns (a doc section also names unrelated, mutating commands such as `gbrain upgrade`); default all. */+ owns?: (argv: string[]) => boolean;+}++export const PRINTED_COMMAND_PRODUCERS: PrintedCommandProducer[] = [];++export function registerPrintedCommandProducer(producer: PrintedCommandProducer): void {+ PRINTED_COMMAND_PRODUCERS.push(producer);+}++const TOKEN = String.raw`[^\s;()\x60,"]+`;+const COMMAND = new RegExp(`gbrain(?: ${TOKEN})+`, 'g');++/** Every `gbrain ...` command in `text` (single-space separated tokens), sentence punctuation trimmed. */+export function extractCommands(text: string): string[] {+ return [...new Set((text.match(COMMAND) ?? []).map(c => c.replace(/[.:]+$/, '')))];+}++/** The dry form: an approval (`--max-usd`) runs as its `--dry-run`; read-only commands run as printed. */+export function dryForm(argv: string[]): string[] {+ return argv.includes('--max-usd') && !argv.includes('--dry-run') ? [...argv, '--dry-run'] : argv;+}++/** A doc section: from the line containing `from` up to the line containing `to` (just that line without `to`). */+export function docSection(rel: string, from: string, to?: string): string {+ const lines = readFileSync(join(import.meta.dir, '..', '..', rel), 'utf8').split('\n');+ const start = lines.findIndex(l => l.includes(from));+ const end = to === undefined ? start + 1 : lines.findIndex((l, i) => i > start && l.includes(to));+ if (start < 0 || end < 0) throw new Error(`docSection: ${rel} has no section ${from} .. ${to}`);+ return lines.slice(start, end).join('\n');+}diff --git a/test/oversized-backfill.serial.test.ts b/test/oversized-backfill.serial.test.tsindex 835b06b830..451d93e36f 100644--- a/test/oversized-backfill.serial.test.ts+++ b/test/oversized-backfill.serial.test.ts@@ -22,7 +22,7 @@ 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 { runOversizedBackfill, formatOversizedBackfillReceipt, 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';@@ -131,6 +131,10 @@ describe('gbrain reindex --oversized (keyless upgrade path)', () => {const receipt = await runOversizedBackfill(engine);expect(receipt).toMatchObject({ reindexed: 1, held_for_approval: 1, embedding_enabled: true });expect(receipt.estimated_usd).toBeGreaterThan(0);+ expect(receipt.commands.approve).toEqual(['gbrain', 'embed', '--held', '--source', 'default', '--max-usd', expect.stringMatching(/^\d+\.\d{2}$/)]);+ expect(Number(receipt.commands.approve![6])).toBeGreaterThanOrEqual(receipt.estimated_usd!);+ expect(formatOversizedBackfillReceipt(receipt).join('\n')).toContain(`approve one source at a time: ${receipt.commands.approve!.join(' ')}`);+ expect(formatOversizedBackfillReceipt(receipt).join('\n')).not.toContain('<N>');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);