Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(pages): meter every paid embedding path, stdio carries ceiling pages, bounded large-page history

garrytan00330d7d7add
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 9552c60b8c..5260cca453 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -33,6 +33,9 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy
- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.
+- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.
+- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v244; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation). `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`.
+- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`, body under the effective `bytes_block`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with the marker and `content_flag: oversized` removed, `forceRechunk` and no embedding: CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.
- `src/core/extraction-watermark.ts` — large pages A7: no silent head-only page extraction. `planExtraction(body, stored, { cap, pipeline, emptyTail })` decides what one extraction reads: the whole body when it fits `cap` (`full`); the text past a stored watermark when the body still starts with exactly the watermarked prefix (`tail`; UTF-8 byte offset + sha256 of the prefix + `EXTRACTION_PIPELINE_VERSION`), its newest `cap` characters when the tail is longer (receipt `tail_window`, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (`truncateUtf8`) with receipt `head` and reason `no_watermark` / `prefix_changed` / `version_changed` / `no_new_text`. An empty tail is a skip (`facts_backstop`) or a head re-read (`extract_atoms`, after a cap rise). `readPageWatermark` (by source + slug, fail-soft), `commitExtractionPlan` (after a successful extraction: the watermark moves to the end of the planned body; a full read clears `input_truncated`, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and `setExtractionReceipt` (the conversation-facts size skip, no watermark) write `page_extraction_state` (migration v245; hashes, offsets and counts only, rows cascade with the page). Doctor `extraction_input_truncated` reads the receipts. Tests: `test/extraction-watermark.test.ts`, `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`.
- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 8d57a7e72d..95b9b98822 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -124,7 +124,7 @@ wrong with the page.
| --- | --- | --- |
| Markdown import and sync (`gbrain import`, `gbrain sync`, the managed sync blob read) | 24 MiB | — |
| CLI stdin (`gbrain put`, `gbrain capture --stdin`) | 24 MiB (was 5 MB) | — |
-| MCP stdio (local agents) | the MCP SDK reads at most 10 MiB per JSON-RPC message, and the page travels JSON-escaped | write the file into the brain repository and run `gbrain sync`, or run `gbrain import <file>` or `gbrain put <slug> < file` on the brain host |
+| MCP stdio (local agents, `gbrain serve`) | 64 MiB per JSON-RPC message (the MCP SDK default of 10 MiB is raised), so a JSON-escaped page at the ceiling fits | — |
| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default) | the same: sync or the CLI on the brain host (chunked uploads arrive in a later release) |
| Legacy HTTP transport | 1 MiB (`GBRAIN_HTTP_MAX_BODY_BYTES`) | the same |
| `put_pages` batch | 8 MiB per batch | send large pages one per `put_page`, or by file |
@@ -145,8 +145,11 @@ describes how to read the next window.
**Cost.** Chunking and keyword indexing run locally and cost nothing.
Embedding a large page costs about $0.15 per 10 MB at the default embedding
model, so a page at the 24 MiB ceiling costs about $0.40. Each page has a paid
-spend cap, `embed.max_usd_per_page` (default $2), covering its embedding,
-per-chunk contextual synopsis and conversation facts. When several caps apply,
+spend cap, `embed.max_usd_per_page` (default $2), covering its embedding at
+every paid entry point (the stale sweep, `gbrain embed`, the post-write
+embedding job). A large page uses the free title context tier, never paid
+per-chunk synopses; conversation facts keep their own 25 MiB input bound and
+are not yet metered by this cap. When several caps apply,
the lowest wins: the per-page cap, the run's consent cap (`--max-usd`),
`embed.backfill_max_usd` and `embed.backfill_max_usd_per_source_24h`. A page
over its cap is still keyword-searchable, and its newest chunks are embedded
@@ -156,14 +159,17 @@ is the user's call.
<a id="large-pages-upgrade"></a>
**After upgrading.** Older releases stored a page over 500 KB with an
-`embed_skip` marker (reason `oversized`) and no chunks. `gbrain upgrade` and
-`gbrain apply-migrations --yes` re-chunk and keyword-index those pages
-themselves, on the CPU, on keyless brains too. The backfill is idempotent and
+`embed_skip` marker (reason `oversized`) and no chunks. `gbrain upgrade` (its
+`gbrain post-upgrade` step) re-chunks and keyword-indexes those pages itself
+for up to two minutes, on the CPU, on keyless brains too, and prints a receipt;
+`gbrain reindex --oversized` does the rest. The backfill is idempotent and
resumes where it stopped. It removes only gate-written markers whose reason is
`oversized`, and the matching `content_flag: oversized`; a page above the
-operator's effective `bytes_block` keeps both. The backfill never embeds:
-backfilled pages are held for consent. The post-upgrade notice and doctor show
-how many pages are held and what embedding them would cost.
+operator's effective `bytes_block` keeps both. The backfill never embeds.
+Backfilled pages over 1 MiB are held for consent; the post-upgrade notice and
+doctor's `partial_embedding` check show how many are held and what embedding
+them would cost. Pages between 500 KB and 1 MiB cost a cent or two each and
+embed through the normal sweep under the existing caps.
```bash
gbrain reindex --oversized --dry-run --json # preview the backfill: free, no provider calls
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 60c610e3f2..40bb06da60 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -1380,7 +1380,7 @@ async function embedAll(
}
page = prepared.snapshot.page;
const chunks = prepared.chunks;
- const toEmbed = chunks; // staleOnly path handled above via embedAllStale
+ let toEmbed = chunks; // staleOnly path handled above via embedAllStale
result.total_chunks += chunks.length;
result.skipped += chunks.length - toEmbed.length;
@@ -1400,6 +1400,19 @@ async function embedAll(
return;
}
+ // A large page is metered as a whole under embed.max_usd_per_page (page-embedding-budget.ts).
+ const decision = await planPageEmbedding(engine, page, toEmbed, { signature });
+ const grant = decision.kind === 'grant' ? decision.grant : undefined;
+ if (grant) toEmbed = toEmbed.filter(c => grant.chunkIndexes.has(c.chunk_index));
+ if (decision.kind === 'held' || toEmbed.length === 0) {
+ await grant?.settle({ ok: true });
+ serr(`\n ${page.slug}: embedding ${decision.kind === 'held' ? `held (${decision.reason})` : 'stopped by the per-page cap'}; approve with: gbrain embed --slugs ${page.slug} --max-usd <N>`);
+ processed++;
+ result.pages_processed++;
+ onProgress?.(processed, pages.length, result.embedded);
+ return;
+ }
+
try {
// #3507: reproduce the page's stored wrapping convention (see embedPage).
// #3037: per-chunk failure isolation — one bad chunk costs one chunk,
@@ -1408,7 +1421,7 @@ async function embedAll(
const { embeddings, failed, firstError } = await embedPageTexts(
wrapChunkTextsForStoredMode(page, toEmbed),
signal ? { abortSignal: signal } : {},
- );
+ ).finally(() => grant?.settle({ ok: true }));
// Build a map of new embeddings by chunk_index
const embeddingMap = new Map<number, Float32Array>();
for (let j = 0; j < toEmbed.length; j++) {
@@ -1428,8 +1441,9 @@ async function embedAll(
// Partial failures retain their old context; a full completion stamps
// its vectors and title-tier convention in the same guarded transaction.
if (!await observed(pacer, () => engine.transaction(async tx => {
- if (!await installPageEmbeddings(tx, prepared, updated, failed === 0 ? signature : undefined)) return false;
- if (failed === 0) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, page.slug, pageSourceId);
+ const complete = failed === 0 && toEmbed.length === chunks.length;
+ if (!await installPageEmbeddings(tx, prepared, updated, complete ? signature : undefined)) return false;
+ if (complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, page.slug, pageSourceId);
return true;
}))) {
recordFailure(result, toEmbed.length, page.slug, EMBED_UNAVAILABLE_MESSAGE);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 02e4931d06..9b39c052b4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -566,6 +566,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: 'TBD', text: '`extract_atoms` on a page over `cycle.extract_atoms.max_input_chars` now reads the text appended since its last extraction instead of the page head again. Such a read is still partial input: no completion stamp is written and no atom is retired. A complete appended-text read prints no stderr line; a cut read still does.' },
{ since: 'TBD', text: '`gbrain extract-conversation-facts` now checks a `raw_transcript` sidecar\'s size before reading it: a sidecar over the 25 MiB cap is skipped without being read (before, it was read whole and bypassed the cap), and the cap now applies to the text the parser reads, so a sidecar page whose own body is over the cap but whose sidecar is under it is no longer skipped. The cap is derived from the page ceiling and never sits below it. A size skip now leaves a durable receipt as well as the stderr line.' },
{ since: 'TBD', text: 'Doctor has a new `extraction_input_truncated` check listing pages whose last extraction read only part of their input (facts from the head or the newest window of a long append, atoms cut at the input cap, conversation pages skipped for size), with sample slugs and the remedy. It warns when atoms or conversation-facts receipts exist (naming `gbrain config set cycle.extract_atoms.max_input_chars <n>`, a paid change for the user to decide); facts-only receipts are reported as info.' },
+ // Large pages A6/A9/T33/T3/F10 (Lane 3). `since` is set at the merge-slot stamp.
+ { since: 'TBD', text: 'Pages up to 24 MiB are now stored, chunked and keyword-searchable: `content_sanity.bytes_block` defaults to the 24 MiB page ceiling (was 500 KB), so a page between 500 KB and 24 MiB is no longer stored with `embed_skip` and zero chunks. Import, sync, the managed sync read, CLI stdin (`gbrain put`, was 5 MB) and the MCP stdio message limit (was the SDK\'s 10 MiB) all admit a page at the ceiling; one byte more is refused with the limit named. Code files keep their 5 MB limit. Size refusals no longer tell agents to split pages under the ceiling. An operator who set a lower `bytes_block` keeps the old behavior above it.' },
+ { since: 'TBD', text: 'A page over 1 MiB now commits with its chunks keyword-searchable and no vectors, and is embedded after the write by the stale sweep, `gbrain embed` or the post-write embedding job, instead of embedding every chunk inline before the write commits. Each such page spends at most `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset; `off` disables it) over its lifetime per embedding model, newest chunks first; the run caps still apply and the lowest cap wins. A page the cap stopped, or one held for approval, leaves the stale queue, and doctor\'s new `partial_embedding` check names it with the approval command (`gbrain embed --held --max-usd N`, or `gbrain embed --slugs <slug> --max-usd N`). Before embedding, a large page whose head, middle and tail samples are all markup, or two of them match junk patterns, is held instead. Large pages use the free title context tier, never paid per-chunk synopses.' },
+ { since: 'TBD', text: '`gbrain upgrade` now re-indexes pages an older gbrain stored without chunks because they were over 500 KB (`embed_skip: oversized`) when they fit under the effective `bytes_block`: for up to two minutes in its post-upgrade step, then `gbrain reindex --oversized` (new; `--dry-run`, `--source`, `--limit`, `--json`) finishes. It is CPU-only, works with embeddings off, makes those pages keyword-searchable at once and prints a receipt. It removes only the gate-written marker and its `content_flag: oversized`. Pages over 1 MiB are held for embedding approval; the post-upgrade notice shows their count and estimated cost and asks before anything is spent.' },
+ { since: 'TBD', text: 'A page over 1 MiB keeps only its newest 5 large version snapshots in `page_versions` (each snapshot is a full copy of the body); its snapshots at or under 1 MiB, and every snapshot of a smaller page, are kept as before. The persistence journal now admits 64 MiB of outstanding write intent per principal (was 32 MiB), so a second ceiling-size write can wait behind the first. Write-through never writes a canonical file over the 25 MiB pre-push secret-scan limit: it skips with `over_push_scan_cap`, and a managed write that would produce one is refused with `request_too_large`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/interaction.ts b/src/core/interaction.ts
index 73c8f10fe7..a78aa1a00c 100644
--- a/src/core/interaction.ts
+++ b/src/core/interaction.ts
@@ -11,6 +11,7 @@
import { fstatSync, readFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
+import { PAGE_MAX_BYTES } from './page-size-policy.ts';
export interface InteractiveProbe {
env?: NodeJS.ProcessEnv;
@@ -182,7 +183,7 @@ export interface StdinReadOptions {
firstByteMs?: number;
/** Silence allowed between chunks once data flows; reset on every chunk. Default 60 s. */
inactivityMs?: number;
- /** Byte cap; more input is an error, never a truncated success. Default 5 MB. */
+ /** Byte cap; more input is an error, never a truncated success. Default: the 24 MiB page ceiling. */
maxBytes?: number;
signal?: AbortSignal;
/** Also return the undecoded bytes as `raw` on a `data` result. */
@@ -194,7 +195,7 @@ export interface StdinReadOptions {
const DEFAULT_FIRST_BYTE_MS = 30_000;
const FIRST_BYTE_NOTICE_MS = 5_000;
const DEFAULT_INACTIVITY_MS = 60_000;
-export const DEFAULT_STDIN_MAX_BYTES = 5_000_000;
+export const DEFAULT_STDIN_MAX_BYTES = PAGE_MAX_BYTES;
function firstByteDeadlineMs(explicit: number | undefined): number {
if (explicit !== undefined) return explicit;
diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.ts
index 65d5b64d60..dd9abc5715 100644
--- a/src/core/page-state/versions.ts
+++ b/src/core/page-state/versions.ts
@@ -1,6 +1,15 @@
import type { BrainEngine } from '../engine.ts';
import type { PageVersion } from '../types.ts';
import type { PageSnapshot } from './types.ts';
+import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from '../page-size-policy.ts';
+
+/**
+ * Snapshots of a large page (over the inline cap) kept per page. Each one is a
+ * full copy of the body, so an append-heavy 24 MiB page would otherwise grow
+ * history by 24 MiB per write. Snapshots at or under the inline cap, and every
+ * snapshot of a small page, are never pruned.
+ */
+export const LARGE_PAGE_VERSIONS_KEPT = 5;
/**
* Version the same canonical view an API reader receives, including withdrawals.
@@ -14,6 +23,11 @@ export async function createPageVersion(engine: BrainEngine, slug: string, sourc
(page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path)
VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,
[page.id, page.compiled_truth, JSON.stringify(page.frontmatter), revision, page.timeline, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);
+ if (isLargePageBytes(Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8'))) {
+ await tx.executeRaw(`DELETE FROM page_versions WHERE page_id = $1 AND id IN (SELECT id FROM page_versions WHERE page_id = $1
+ AND octet_length(compiled_truth) + octet_length(COALESCE(timeline, '')) > $2 ORDER BY id DESC OFFSET $3)`,
+ [page.id, PAGE_INLINE_MAX_BYTES, LARGE_PAGE_VERSIONS_KEPT]);
+ }
return { ...rows[0], snapshot_at: new Date(rows[0].snapshot_at) };
};
if (preimage) return insert(engine, preimage);
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index f5bc0c6dc9..b61aa4212a 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -43,6 +43,7 @@ import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { isLockOpenFailure } from './native-lock.ts';
+import { planPageEmbedding } from '../page-embedding-budget.ts';
const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(
`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,
@@ -306,7 +307,15 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
if (!signature) throw opError('embedding_unconfigured', 'Configure an embedding provider before explicitly retrying.',
`Page ${snapshot.page.slug} in source ${effect.source_id} was saved but cannot be embedded: this brain has no embedding provider. Pages and keyword search keep working; check embedding readiness and ask the user before configuring a paid provider.`,
{ fix: embeddingsFix() });
- const { prepared, pending } = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);
+ const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);
+ const { prepared } = projection;
+ let pending = projection.pending;
+ // A large page is metered as a whole under embed.max_usd_per_page (page-embedding-budget.ts).
+ const decision = pending.length ? await planPageEmbedding(engine, prepared.snapshot.page, pending, { signature }) : { kind: 'unmetered' as const };
+ if (decision.kind === 'held') { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'budget_held' }); return; }
+ const grant = decision.kind === 'grant' ? decision.grant : undefined;
+ if (grant) pending = pending.filter(chunk => grant.chunkIndexes.has(chunk.chunk_index));
+ if (grant && !pending.length) { await grant.settle({ ok: true }); await completeEffect(engine, effect, { embedding: 'skipped', reason: 'budget_capped' }); return; }
if (pending.length) {
await assertEmbeddingEffectEnabled(engine, config);
if (effect.attempts - (effect.data.embedding_retry_base ?? effect.data.embedding_attempt_base ?? 0) > MAX_RATE_LIMIT_RETRIES) {
@@ -338,7 +347,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
signal.throwIfAborted();
await assertEmbeddingEffectEnabled(engine, config);
}, () => (opts.embedding?.embed ?? embedBatch)(wrapChunkTextsForStoredMode(prepared.snapshot.page, pending), { abortSignal: signal, maxRetries: 0 }));
+ await grant?.settle({ ok: true });
} catch (error) {
+ await grant?.settle({ ok: isEmbeddingZeroNormError(error) }).catch(() => {});
if (!isEmbeddingZeroNormError(error) || error.vectors.length !== pending.length) throw error;
refused = error;
vectors = error.vectors;
@@ -364,7 +375,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
// A partially refused page keeps its signature unstamped so `gbrain embed --stale` finds the refused chunks.
const installed = await installPageEmbeddings(tx, prepared, pending.map((chunk, i) => ({ chunk_index: chunk.chunk_index,
chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source, embedding: vectors[i] ?? undefined, model: opts.embedding?.model })),
- refused ? undefined : signature);
+ refused || grant?.deferred ? undefined : signature);
if (installed && refused) {
// A refused chunk keeps no vector from an earlier convention, and the page reads as not fully embedded.
const ids = refused.failures.map(f => pending[f.index]?.id).filter((id): id is number => id !== undefined);
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index d954bcc592..b5d5aaa9d4 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -1,6 +1,7 @@
import { noteForwardProgress } from '../core/forward-progress.ts';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+import type { Readable, Writable } from 'node:stream';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import type { BrainEngine } from '../core/engine.ts';
import { opError, type OperationMeta } from '../core/ops/contract.ts';
@@ -26,6 +27,20 @@ import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback
import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';
import { assertStdioSourceBindable } from './source-preflight.ts';
+/**
+ * Largest JSON-RPC message the stdio server reads (the SDK default is 10 MiB,
+ * and an oversized message closes the session). A page at the 24 MiB ceiling
+ * travels JSON-escaped, and newlines and quotes double, so 64 MiB carries it
+ * with room; the persistence journal caps a principal's outstanding intents at
+ * the same 64 MiB.
+ */
+export const MCP_STDIO_MAX_MESSAGE_BYTES = 64 * 1024 * 1024;
+
+/** The stdio transport `gbrain serve` connects, sized for ceiling-size page writes. */
+export function mcpStdioTransport(stdin: Readable = process.stdin, stdout: Writable = process.stdout): StdioServerTransport {
+ return new StdioServerTransport(stdin, stdout, { maxBufferSize: MCP_STDIO_MAX_MESSAGE_BYTES });
+}
+
// initialize and tools/list read OPERATION_MANIFEST; the handler graph behind
// dispatch.ts (src/core/operations.ts, ~760 modules) loads with the deferred
// boot in startMcpServer, or on the first tools/call.
@@ -491,7 +506,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
}), dispatchRenderContext);
}));
- const transport = new StdioServerTransport();
+ const transport = mcpStdioTransport();
bootPhase('mcp_connect');
await server.connect(transport);
diff --git a/test/large-pages-ingress-matrix.slow.test.ts b/test/large-pages-ingress-matrix.slow.test.ts
new file mode 100644
index 0000000000..ed235349c5
--- /dev/null
+++ b/test/large-pages-ingress-matrix.slow.test.ts
@@ -0,0 +1,149 @@
+/**
+ * Large pages (Wave A, T14/T35/A8): the ingress x size matrix.
+ *
+ * Every raisable ingress bound derives from PAGE_MAX_BYTES (24 MiB), so a page
+ * at the ceiling is admitted end to end and one byte over is refused with a
+ * named limit, never truncated. Arms: CLI import (importFromContent, the local
+ * put_page path), import and sync file reads, stdin, a managed put_page
+ * through the journal and the local persistence IPC (with a second outstanding
+ * write from the same principal), and export of a ceiling-size page.
+ *
+ * Slow tier: each ceiling-size import chunks 24 MiB.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, readdirSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PassThrough, Readable } from 'node:stream';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { readImportBytes } from '../src/core/persistence/import-prepare.ts';
+import { readSyncFile } from '../src/core/persistence/sync-discovery.ts';
+import { readStdinBounded, DEFAULT_STDIN_MAX_BYTES } from '../src/core/interaction.ts';
+import { PAGE_MAX_BYTES, PUSH_SCAN_MAX_FILE_BYTES } from '../src/core/page-size-policy.ts';
+import { SYNC_READ_BOUND } from '../src/core/persistence/sync-blobs.ts';
+import { PERSISTENCE_IPC_MAX_BYTES } from '../src/core/persistence/ipc.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { mcpStdioTransport } from '../src/mcp/server.ts';
+
+const MB = 1_000_000;
+const SIZES = [4.9 * MB, 12 * MB, PAGE_MAX_BYTES] as const;
+const NEEDLE = 'quokkalanternneedle';
+const LINE = 'alice-example: did acme-example ship the harvest report yet?\n';
+
+/** A Markdown page of exactly `bytes` UTF-8 bytes with a needle in the middle. */
+function page(bytes: number, title = 'Long chat'): string {
+ const head = `---\ntype: note\ntitle: ${title}\n---\n\n`;
+ const marker = `The code word is ${NEEDLE}.\n`;
+ const room = bytes - head.length - marker.length;
+ const half = LINE.repeat(Math.floor(room / 2 / LINE.length));
+ const body = half + marker + half;
+ return head + body + 'z'.repeat(bytes - head.length - body.length);
+}
+
+let engine: PGLiteEngine;
+let dir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ dir = mkdtempSync(join(tmpdir(), 'large-pages-matrix-'));
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+describe('ingress bounds derive from the 24 MiB page ceiling', () => {
+ test('every raisable bound is at least the ceiling, and the push-scan cap leaves room for frontmatter', () => {
+ expect(SYNC_READ_BOUND).toBe(PAGE_MAX_BYTES);
+ expect(DEFAULT_STDIN_MAX_BYTES).toBe(PAGE_MAX_BYTES);
+ expect(PUSH_SCAN_MAX_FILE_BYTES - PAGE_MAX_BYTES).toBeGreaterThanOrEqual(1024 * 1024);
+ // A ceiling page of chat text escapes to well under the 32 MiB IPC frame as JSON.
+ expect(JSON.stringify({ content: page(PAGE_MAX_BYTES) }).length).toBeLessThan(PERSISTENCE_IPC_MAX_BYTES);
+ });
+
+ for (const bytes of SIZES) {
+ test(`CLI import (importFromContent): ${bytes} bytes is admitted, chunked and keyword-searchable`, async () => {
+ const slug = `chats/import-${bytes}`;
+ const result = await importFromContent(engine, slug, page(bytes), { noEmbed: true });
+ expect(result.status).toBe('imported');
+ expect((await engine.getChunks(slug)).length).toBeGreaterThan(100);
+ expect((await engine.searchKeyword(NEEDLE, { limit: 20 })).map(hit => hit.slug)).toContain(slug);
+ }, 180_000);
+ }
+
+ test('CLI import: one byte over the ceiling is refused before parsing, with the limit named', async () => {
+ const result = await importFromContent(engine, 'chats/over', page(PAGE_MAX_BYTES + 1), { noEmbed: true });
+ expect(result.status).toBe('skipped');
+ expect(result.error).toContain('too large');
+ expect(await engine.getPage('chats/over')).toBeNull();
+ }, 60_000);
+
+ test('import and sync file reads admit the ceiling and refuse one byte more', () => {
+ const at = join(dir, 'at.md');
+ const over = join(dir, 'over.md');
+ writeFileSync(at, page(PAGE_MAX_BYTES));
+ writeFileSync(over, page(PAGE_MAX_BYTES + 1));
+ expect(readImportBytes(at).length).toBe(PAGE_MAX_BYTES);
+ expect(() => readImportBytes(over)).toThrow(/too large/i);
+ expect(readSyncFile(dir, 'at.md')?.length).toBe(PAGE_MAX_BYTES);
+ expect(() => readSyncFile(dir, 'over.md')).toThrow(/exceeds|too large/i);
+ });
+
+ test('stdin admits the ceiling and refuses one byte more, never truncating', async () => {
+ const at = await readStdinBounded({ stream: Readable.from([Buffer.from(page(PAGE_MAX_BYTES))]) });
+ expect(at.kind).toBe('data');
+ const over = await readStdinBounded({ stream: Readable.from([Buffer.from(page(PAGE_MAX_BYTES + 1))]) });
+ expect(over.kind).toBe('error');
+ }, 60_000);
+
+ test('MCP stdio: a put_page JSON-RPC message carrying a ceiling-size page is read whole, not dropped with the session', async () => {
+ const stdin = new PassThrough();
+ const transport = mcpStdioTransport(stdin, new PassThrough());
+ const errors: unknown[] = [];
+ transport.onerror = error => { errors.push(error); };
+ const received = new Promise<{ params?: { arguments?: { content?: string } } }>(resolve => { transport.onmessage = message => resolve(message as never); });
+ await transport.start();
+ const content = page(PAGE_MAX_BYTES).replaceAll('?', '"');
+ stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'put_page', arguments: { slug: 'chats/stdio', content } } })}\n`);
+ const message = await received;
+ expect(errors).toEqual([]);
+ expect(message.params?.arguments?.content?.length).toBe(content.length);
+ await transport.close();
+ }, 60_000);
+
+ test('managed put_page: a ceiling-size write commits while the same principal has another write outstanding', async () => {
+ await managedBrain(async brain => {
+ const ctx = { ...brain.ctx, writeWaitMs: 240_000 };
+ await Promise.all([
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'chats/managed-ceiling', request_id: randomUUID(), content: page(PAGE_MAX_BYTES, 'Ceiling') } }),
+ submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'chats/managed-second', request_id: randomUUID(), content: page(4.9 * MB, 'Second') } }),
+ ]);
+ await disposePersistenceConsumer(brain.engine);
+ const hits = (await brain.engine.searchKeyword(NEEDLE, { limit: 20 })).map(hit => hit.slug);
+ expect(hits).toEqual(expect.arrayContaining(['chats/managed-ceiling', 'chats/managed-second']));
+ const file = readFileSync(join(brain.root, 'chats', 'managed-ceiling.md'));
+ expect(file.length).toBeGreaterThanOrEqual(PAGE_MAX_BYTES - 64);
+ expect(file.length).toBeLessThan(PUSH_SCAN_MAX_FILE_BYTES);
+ });
+ }, 300_000);
+
+ test('export writes a ceiling-size page whole', async () => {
+ const { runExport } = await import('../src/commands/export.ts');
+ const out = join(dir, 'export');
+ await runExport(engine, ['--dir', out]);
+ const files: string[] = [];
+ const walk = (d: string) => { for (const name of readdirSync(d)) { const p = join(d, name); if (statSync(p).isDirectory()) walk(p); else files.push(p); } };
+ walk(out);
+ const exported = files.find(f => f.endsWith(`import-${PAGE_MAX_BYTES}.md`));
+ expect(exported).toBeDefined();
+ expect(readFileSync(exported!, 'utf-8')).toContain(NEEDLE);
+ expect(statSync(exported!).size).toBeGreaterThanOrEqual(PAGE_MAX_BYTES - 64);
+ }, 120_000);
+});
diff --git a/test/page-versions-large-retention.test.ts b/test/page-versions-large-retention.test.ts
new file mode 100644
index 0000000000..d7d6f35bf0
--- /dev/null
+++ b/test/page-versions-large-retention.test.ts
@@ -0,0 +1,52 @@
+/**
+ * Large pages (Wave A, eng F10): each version snapshot copies the whole body,
+ * so a page over the inline cap keeps only its newest LARGE_PAGE_VERSIONS_KEPT
+ * large snapshots. Small pages, and the small snapshots of a page that grew,
+ * keep their full history.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { LARGE_PAGE_VERSIONS_KEPT } from '../src/core/page-state/versions.ts';
+import { PAGE_INLINE_MAX_BYTES } from '../src/core/page-size-policy.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+async function versionSizes(slug: string): Promise<number[]> {
+ const rows = await engine.executeRaw<{ bytes: number }>(`SELECT octet_length(v.compiled_truth)::int AS bytes FROM page_versions v
+ JOIN pages p ON p.id = v.page_id WHERE p.slug = $1 ORDER BY v.id`, [slug]);
+ return rows.map(row => Number(row.bytes));
+}
+
+describe('page_versions retention for large pages', () => {
+ test('a large page keeps its newest large snapshots and every small one', async () => {
+ const small = 'early notes about acme-example. ';
+ await engine.putPage('chats/growing', { type: 'note', title: 'growing', compiled_truth: small });
+ await engine.createVersion('chats/growing');
+ await engine.createVersion('chats/growing');
+ const large = 'x'.repeat(PAGE_INLINE_MAX_BYTES + 10);
+ for (let i = 0; i < LARGE_PAGE_VERSIONS_KEPT + 3; i++) {
+ await engine.putPage('chats/growing', { type: 'note', title: 'growing', compiled_truth: `${large}${i}` });
+ await engine.createVersion('chats/growing');
+ }
+ const sizes = await versionSizes('chats/growing');
+ expect(sizes.filter(bytes => bytes <= PAGE_INLINE_MAX_BYTES)).toHaveLength(2);
+ expect(sizes.filter(bytes => bytes > PAGE_INLINE_MAX_BYTES)).toHaveLength(LARGE_PAGE_VERSIONS_KEPT);
+ });
+
+ test('a small page keeps every snapshot', async () => {
+ for (let i = 0; i < LARGE_PAGE_VERSIONS_KEPT + 3; i++) {
+ await engine.putPage('notes/small', { type: 'note', title: 'small', compiled_truth: `revision ${i}` });
+ await engine.createVersion('notes/small');
+ }
+ expect(await versionSizes('notes/small')).toHaveLength(LARGE_PAGE_VERSIONS_KEPT + 3);
+ });
+});
diff --git a/test/persistence-embedding-effects.test.ts b/test/persistence-embedding-effects.test.ts
index 21b2c2d905..f70a1d33cd 100644
--- a/test/persistence-embedding-effects.test.ts
+++ b/test/persistence-embedding-effects.test.ts
@@ -56,7 +56,7 @@ for (const kind of testBackends()) {
if (scratch) rmSync(scratch, { recursive: true, force: true });
});
const check = (name: string, fn: () => Promise<void>) => test(name, () => withEnv({ GBRAIN_HOME: scratch }, fn), 120_000);
- async function fixture() {
+ async function fixture(body = 'Current') {
await registerLocalWriter(engine, 'cli');
const sourceId = `embedding-${randomUUID()}`;
const [source] = await engine.executeRaw<{ incarnation: string }>('INSERT INTO sources(id,name) VALUES($1,$1) RETURNING incarnation', [sourceId]);
@@ -68,7 +68,7 @@ for (const kind of testBackends()) {
const row = (await claimNextWrite(engine, localHostId()))!;
expect(row.id).toBe(admitted.id);
await publishMutation(engine, row, { observedRevision: null, apply: async tx => {
- await tx.putPage('page', page('Current'), { sourceId }); return {};
+ await tx.putPage('page', page(body), { sourceId }); return {};
} }, localHostId());
const prepared = (await readProjectionSnapshot(engine, 'page', sourceId, { allowUnsealed: true }))!;
await installPageProjection(engine, prepared, [{ chunk_index: 0, chunk_source: 'compiled_truth', chunk_text: 'Current' }], { seal: true });
@@ -100,6 +100,16 @@ for (const kind of testBackends()) {
'SELECT state,attempts,error_code,EXTRACT(EPOCH FROM next_attempt_at-now())*1000 AS wait_ms FROM persistence_effects WHERE id=$1', [effectId]))[0];
}
+ check('large pages: a page held by embed.max_usd_per_page completes its effect without calling the provider', async () => {
+ const f = await fixture('x'.repeat(1024 * 1024 + 10));
+ await engine.executeRaw("INSERT INTO page_embedding_budget (page_id, state, reason) VALUES ($1, 'held', 'upgrade_backfill')", [f.snapshot.page.id]);
+ let calls = 0;
+ await run(async () => { calls++; return vectors(); });
+ expect(calls).toBe(0);
+ expect((await state(f.effectId)).state).toBe('committed');
+ expect((await readProjectionSnapshot(engine, 'page', f.sourceId))!.chunks[0].embedding).toBeNull();
+ });
+
check('already-complete projection uses provenance without reading vectors or calling the provider', async () => {
const f = await fixture();
const prepared = (await readProjectionSnapshot(engine, 'page', f.sourceId))!;