Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane 2r WIP: segmented refusal paths for remember, get_page, entity and import
garrytan642897af32d6
diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 6907d1bc6a..bcffe2d4ab 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -349,7 +349,7 @@ export const CODES = {page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },page_projection_stale: { class: 'server', summary: "A segment of this large page has projection metadata gbrain cannot use, so the read returned nothing for it rather than unsanitized text.", why: "Windows of a segmented page are cut from each segment's stored protected regions; when they are stale (another segmenter version, a text that does not match its hash) gbrain recomputes them from the segment's carried parser state, and refuses when that state is missing or of another version, or when a facts fence block crosses a forced cut while the source has withdrawals.", docs: 'docs/guides/windowed-reads.md#page_projection_stale', suggestion: 'Rewrite the page body (import or sync its file again), which segments it with this gbrain version, then read it again; other windows and the outline still work.' },- page_body_segmented: { class: 'caller', summary: "This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything.", why: "With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths.", docs: 'docs/guides/windowed-reads.md#page_body_segmented', suggestion: "Read the page's revision and stored size with get_page body: 'none' (size.body_bytes); windowed reads of a segmented body arrive with the segment reader.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'none', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body.", requires_exclusive: false } },+ page_body_segmented: { class: 'caller', summary: "This page's body is stored in segments, and the path that hit it reads or writes the whole body as one string, so it stopped before reading or changing anything.", why: "With pages.segmented_storage on, a page over 1 MiB keeps its body in segments instead of the page row; a whole-body path would otherwise see an empty body and could overwrite the page or drop the unread rest. Windowed reads and segment-aware writers replace these paths.", docs: 'docs/guides/windowed-reads.md#page_body_segmented', suggestion: "Retrying refuses the same way. Read the page in pieces: get_page body: 'auto' returns its outline and first window, and body: 'window' reads any lines or bytes.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--body', 'auto', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'auto' } }, consent: [], actor: 'agent', why: "Returns the page's outline and its first window, with next_cursor to read on.", requires_exclusive: false } },page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },parse_error: { class: 'caller', summary: "The request body is not valid JSON." },diff --git a/src/core/line-grammar-report.ts b/src/core/line-grammar-report.tsindex 684f722058..b7ad6a5b94 100644--- a/src/core/line-grammar-report.ts+++ b/src/core/line-grammar-report.ts@@ -69,6 +69,17 @@ function canonicalLine(d: GrammarDiagnostic): string | undefined {return m ? `${m[1]}${m[2]}${m[3]}` : undefined;}+/** get_page grammar_diagnostics on a page stored in segments: the grammar parses one whole body string, so the report is skipped, never thrown. */+export interface LineGrammarSkip { state: 'skipped'; reason: 'page_body_segmented'; message: string; fix: Action }+export function segmentedGrammarSkip(slug: string, sourceId: string): LineGrammarSkip {+ return {+ state: 'skipped', reason: 'page_body_segmented',+ message: `Line-grammar diagnostics parse the whole body as one string, and page ${slug} stores its body in segments, so they were skipped; nothing about this page's typed lines is known. The rest of this response is complete.`,+ fix: readFix("Returns the page's outline and its first window, to read its typed lines directly.",+ { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'auto', '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'auto' } } }),+ };+}+export async function lineGrammarReport(engine: BrainEngine, opts: {slug: string; sourceId: string; body: string; limit?: number;}): Promise<LineGrammarReport> {diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex c52548b370..7c732af4c1 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -66,7 +66,7 @@ export const LARGE_PAGES_CAPABILITY = 'large_pages_v1';export const GET_PAGE_BODY_PARAMS: Record<string, ParamDef> = {body: { type: 'string', enum: [...BODY_MODES], description: 'auto: whole up to 256 KB, else outline + window. none: revision + size.', fullSurfaceOnly: true },lines: { type: 'object', description: 'Window: 1-based lines.', properties: { from: { type: 'number', required: true }, count: { type: 'number', required: true } }, fullSurfaceOnly: true },- bytes: { type: 'object', description: 'Window: UTF-8 bytes (snapped to a line start).', properties: { offset: { type: 'number', required: true }, length: { type: 'number', required: true } }, fullSurfaceOnly: true },+ bytes: { type: 'object', description: 'Window: UTF-8 bytes of size.total_bytes, not body_bytes (snapped to a line start).', properties: { offset: { type: 'number', required: true }, length: { type: 'number', required: true } }, fullSurfaceOnly: true },around_chunk_id: { type: 'number', description: 'Window around a search hit chunk_id.', fullSurfaceOnly: true },context_lines: { type: 'number', description: 'Lines around around_chunk_id (20).', fullSurfaceOnly: true },cursor: { type: 'string', description: 'next_cursor: read on.', fullSurfaceOnly: true },@@ -213,28 +213,39 @@ export async function assertFullReadFits(ctx: OperationContext, page: Pick<Page,}/**- * A segmented page is never built whole (spec 7.2). Over a transport the refusal comes from body_bytes before any- * body is read: page_too_large_for_inline, which the thin client answers by paging view: 'markdown'. A trusted local- * read refuses with page_body_segmented, which `gbrain get` answers by streaming the page.+ * A segmented page is never built whole (spec 7.2). Every caller gets page_body_segmented with a fix that reads it in+ * pieces (body: 'auto' gives the outline and the first window), and a trusted local `gbrain get` answers it by+ * streaming the page. The thin client's whole-page read keeps page_too_large_for_inline: that is its paging signal+ * (it pages view: 'markdown' to the end), refused from body_bytes before any body is read.*/export function segmentedFullReadError(ctx: OperationContext, page: Page, req: BodyRequest): OperationError {const total = pageBodyBytes(page);- const windows = "Read it in windows: get_page body: 'outline' lists the sections, then body: 'window' with lines, bytes, around_chunk_id or next_cursor.";+ const windows = "Read it in pieces: get_page body: 'auto' returns the outline and the first window, then body: 'window' with lines, bytes, around_chunk_id or next_cursor reads on.";+ const fix = segmentedReadFix(page.slug, page.source_id);if (ctx.remote === false) {return opError('page_body_segmented', `get_page: page ${page.slug} (source ${page.source_id}) stores its ${total}-byte body in segments; it is not returned as one string.`,- `${windows} gbrain get prints it whole, streamed.`,- { fix: readFix('Prints the page whole, streamed segment by segment.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],- mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'outline' } } }) });+ `${windows} gbrain get (no --body) prints it whole, streamed.`, { fix });}const transport = egressTransport(ctx)!;+ const detail = JSON.stringify({ total_bytes: total, body_storage: 'segmented', transport });+ if (ctx.thinClient !== true) {+ return opError('page_body_segmented', `get_page: page ${page.slug} (source ${page.source_id}) stores its ${total}-byte body in segments; it is never returned as one string.`,+ `${windows} Edit with edit_page (revision from body: 'none').`, { detail, fix });+ }return opError('page_too_large_for_inline', `Page ${page.slug} is stored in segments (${total} bytes) and is never returned whole on this connection.`,req.legacyThin? 'This gbrain CLI is older than the host and reads pages whole. Upgrade it (gbrain upgrade) to page through large pages, or read windows over MCP with get_page body: \'window\'.': `${windows} Edit with edit_page (revision from body: 'none').`,- { legacy_error: 'invalid_params', detail: JSON.stringify({ total_bytes: total, body_storage: 'segmented', transport }),+ { legacy_error: 'invalid_params', detail,fix: sizeFix(page.slug, page.source_id, "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.") });}+/** The read a segmented page's whole-body refusal names: body 'auto' (outline plus the first window, with a cursor to read on). */+export function segmentedReadFix(slug: string, sourceId: string) {+ return readFix("Returns the page's outline and its first window, with next_cursor to read on; body: 'window' reads any lines or bytes.",+ { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'auto', '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'auto' } } });+}+/** The largest window this caller may receive: the request, the per-window ceiling and the egress cap minus metadata room. */async function windowBudget(ctx: OperationContext, requested: number | undefined, fallback: number): Promise<number> {const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex db9c50787b..6b03dc85e1 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -218,7 +218,9 @@ const get_page: Operation = {const timelineEntries = includeTimelineEntries? await stampRowTrust(ctx.engine, 'timeline_entries', await ctx.engine.getTimeline(page.slug, { ...await readPolicyOpts(ctx, { sourceId: page.source_id }), eligibility: readable.eligibility }), e => e.id) : undefined;// Read-only, over the same visibility-filtered body the reader gets.- const lineGrammar = p.grammar_diagnostics === true ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth }) : undefined;+ const grammar = p.grammar_diagnostics === true ? await import('../line-grammar-report.ts') : undefined;+ const lineGrammar = !grammar ? undefined : isSegmentedPage(page) ? grammar.segmentedGrammarSkip(page.slug, page.source_id)+ : await grammar.lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth });const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259const fileHeld = held ? { file_held: fileHeldField(held, isUntrustedReader) } : {};const segmented = isSegmentedPage(page);diff --git a/src/core/page-body/page-shape.ts b/src/core/page-body/page-shape.tsindex 1ee79132ca..ffacf0dca2 100644--- a/src/core/page-body/page-shape.ts+++ b/src/core/page-body/page-shape.ts@@ -57,10 +57,10 @@ export function pageBodySegmentedError(page: { slug?: string; source_id?: stringconst sourceId = page.source_id ?? 'default';return opError('page_body_segmented',`${site}: page ${slug} (source ${sourceId}) stores its body in segments, and this path reads or writes the whole body as one string. Nothing was read or changed.`,- "Read the page's revision and stored size with get_page body: 'none' (size.body_bytes). Windowed reads of a segmented body arrive with the segment reader; until then this path cannot process the page.",- { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'none', '--', slug],- mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } },- consent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's revision and size without its body." } });+ "This path cannot process a page stored in segments yet; retrying refuses the same way. Read the page in pieces: get_page body: 'auto' returns its outline and first window, and body: 'window' reads any lines or bytes.",+ { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--body', 'auto', '--', slug],+ mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'auto' } },+ consent: [], actor: 'agent', requires_exclusive: false, why: "Returns the page's outline and its first window, with next_cursor to read on." } });}/** Throws `page_body_segmented` for a segmented page; `site` names the caller. Inline pages pass. */diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex b3f3a5bad3..09ff123186 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -126,7 +126,7 @@ export async function importManagedFiles(engine: BrainEngine, files: readonly Maconst path = canonicalInput ? canonicalRelative : sourcePath;const target = resolve(root, path);await assertImportPaths(reads, sourceId, root, inputPath, target);- const streamed = await managedStreamedIdentity(sourcePath, inputPath, target, bodyPolicy);+ const streamed = await managedStreamedIdentity(sourcePath, inputPath, target, bodyPolicy, sourceId);const bytes = streamed ? null : readImportBytes(inputPath);const { slug, content } = streamed ? { slug: streamed.slug, content: undefined } : managedImportContent(sourcePath, bytes!, opts.activePack);if (slugs.has(slug)) { rest = i; break; }diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 0917faddc4..f766cf6282 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -51,6 +51,17 @@ const reimportFix = (inputPath: string, sourceId: string): Action => ({argv: ['gbrain', 'import', inputPath, '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,why: `Re-reads the file as it is now and imports it into source ${sourceId} under a new request through its canonical owner.`,});+/** A Markdown file over the single-string ceiling imports only from its place in the source root: the user moves it there, then imports it. */+const moveIntoSourceFix = (inputPath: string, target: string, sourceId: string): Action => ({+ argv: ['gbrain', 'import', target, '--source', sourceId], consent: [], actor: 'user', requires_exclusive: false,+ user_message: `Move ${inputPath} to ${target}, inside source ${sourceId}'s root, then run this command.`,+ why: `A file over the single-string import limit imports only from its place inside the source root, since its canonical file is never rewritten; this imports it from ${target}.`,+});+/** The refusal of a Markdown file over the single-string ceiling imported from outside its source root: the message itself names the move. */+function outsideRootTooLarge(inputPath: string, target: string, sourceId: string, bytes: number, suggestion: string, fix: Action = moveIntoSourceFix(inputPath, target, sourceId)): OperationError {+ return opError('invalid_params', `File too large (${bytes} bytes, max ${PAGE_MAX_BYTES}): a file over the single-string import limit imports only from its place inside the source root. Move it to ${target} and import it there.`,+ suggestion, { fix });+}const receiptFix = (row: WriteRequest): Action => readFix('Reads the import request\'s durable receipt: its state and recorded error, read-only.',{ argv: ['gbrain', 'write-request', '--', row.request_id] });const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner and its state, read-only.`,@@ -120,14 +131,14 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa* place in the canonical root (`input === target`), since its canonical file is* never rewritten.*/-export async function managedStreamedIdentity(sourcePath: string, input: string, target: string, policy: PageBodyPolicy):+export async function managedStreamedIdentity(sourcePath: string, input: string, target: string, policy: PageBodyPolicy, sourceId: string):Promise<{ slug: string; bodyRef: ManagedImportBodyRef } | null> {if (!policy.segmented || !/\.mdx?$/i.test(sourcePath)) return null;if (realpathSync(input) !== resolve(input) || !lstatSync(input).isFile()) return null;const bytes = lstatSync(input).size;if (bytes <= importSizeLimit(input) || bytes > policy.maxBytes) return null;managedImportPathChecks(sourcePath);- if (target !== input) throw opError('invalid_params', `File too large (max ${PAGE_MAX_BYTES} bytes).`,+ if (target !== input) throw outsideRootTooLarge(input, target, sourceId, bytes,`${basename(input)} is over the single-string import limit, so it imports only from its place inside the source root (its canonical file is never rewritten). Move it into the source and import it there.`);const hash = createHash('sha256');for await (const part of createReadStream(input)) hash.update(part);@@ -312,7 +323,8 @@ async function prepareStreamedManagedImport(engine: BrainEngine, row: WriteRequeconst tooLarge = (why: string) => opError('invalid_params', `File too large (max ${PAGE_MAX_BYTES} bytes).`,`${p.sourcePath} is ${ref.bytes} bytes, over the single-string import limit, and ${why}, so import request ${row.request_id} published nothing.`,{ fix: receiptFix(row) });- if (resolve(p.inputPath) !== path) throw tooLarge(`a file this size is imported only from its place inside source ${row.source_id}'s root (its canonical file is never rewritten); move it into the source and import it there`);+ if (resolve(p.inputPath) !== path) throw outsideRootTooLarge(p.inputPath, path, row.source_id, ref.bytes,+ `${p.sourcePath} is over the single-string import limit, and a file this size is imported only from its place inside source ${row.source_id}'s root (its canonical file is never rewritten), so import request ${row.request_id} published nothing. Move it into the source and import it there.`);const policy = await readPageBodyPolicy(engine);if (!policy.segmented || ref.bytes > policy.maxBytes) throw tooLarge(`segmented page storage (pages.segmented_storage) is off or the file is over pages.max_bytes`);await checkPlacement(engine);diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 0e97637b07..99b52d8796 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -11,6 +11,8 @@ import { isFactWithdrawn, recordFactWithdrawal, type WithdrawalCommit } from '..import { rebuildPendingPageProjections } from '../page-state/projections.ts';import { inferFactSubject, isEntityInferenceEnabled, type InferredVia } from '../facts/subject-infer.ts';import { parseFactsFence } from '../facts-fence.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { segmentedRememberRefusal } from './verb-errors.ts';import { excludesPrivateWrites } from './page-visibility.ts';import { emitFenceNotice, initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';import { authorizeStoredRequest, submissionAuthority } from './authority.ts';@@ -86,6 +88,8 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc`Entity page ${slug} in source ${sourceId} is deleted or not visible to this caller, so nothing was saved. Remember the fact against a visible entity, or without an entity (it is then filed under memory/unattributed).`);}if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');+ // Wave B: a segmented entity page cannot take a fence row yet; named or inferred, the save refuses before admission instead of misfiling it.+ if (entitySlug !== null && snapshot && isSegmentedPage(snapshot.page)) throw segmentedRememberRefusal(slug, sourceId, inferred !== null);if (inferred && (await isFactWithdrawn(ctx.engine, sourceId, inferred.visibility, inferred.fact, slug)|| parseFactsFence(snapshot!.page.compiled_truth).warnings.length)) throw new InferredTargetRejected('ENTITY_LINK_FAILED');// Preserve the stub guard: a fallback name remains DB-only until a real@@ -142,6 +146,7 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sourreturn { target, via: inferred.via };} catch (error) {if (error instanceof InferredTargetRejected) return { warning: error.warning };+ if (error instanceof OperationError && error.canonicalCode === 'page_body_segmented') throw error;if (error instanceof OperationError) return null;throw error;}diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 2524c8f336..cb7de292a5 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -19,7 +19,7 @@ export const WRITE_ERROR_CODES = ['invalid_connector_text', 'connector_holds_exhausted', 'connector_fence_below_timeline','core_budget_exceeded', 'core_mark_owner_only', 'core_remote_edit_refused', 'core_delete_owner_only','timeline_rows_would_be_removed', 'purged_content', 'preparation_stalled',- 'fence_unrenderable',+ 'fence_unrenderable', 'page_body_segmented','write_outcome_unknown',] as const;diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 4e7c34da10..5ae8826211 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -1,4 +1,5 @@-import { verbError, OperationError } from '../ops/contract.ts';+import { verbError, opError, OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';import { pendingWriteHint } from './health.ts';import { UNBOUND_COLLISION_MESSAGE, UNBOUND_PUBLICATION_MESSAGE } from './unbound-source.ts';@@ -116,6 +117,8 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {// #6188 (UC3): a company-brain source names the fence correction it will not write; the repository commit is the fix.if (code === 'source_writeback_required' && message?.startsWith('Canonical preparation would normalize a facts or takes fence (')) return { reason: code, message,suggestion: 'A company-brain source never rewrites repository files: fix the named fence in the repository, commit it, and resume the sync.' };+ // Wave B: a page whose body is stored in segments refuses a whole-body write; a deliberate per-page verdict, never a server fault.+ if (code === 'page_body_segmented') return { reason: code, message: message ?? SEGMENTED_WRITE_MESSAGE, suggestion: SEGMENTED_WRITE_SUGGESTION };// #5575: a purged claim or page content is refused for good; the owner alone can clear its tombstone.if (code === 'purged_content') return { reason: code, message: 'This content was purged from this source and cannot be saved again.',suggestion: PURGED_SUGGESTION };@@ -126,6 +129,27 @@ export function writeFailureDiagnostic(code: string, message?: string | null): {suggestion: 'Resolve the reported write failure before starting a corrected attempt.' };}+const SEGMENTED_WRITE_MESSAGE = 'The target page stores its body in segments, and this write needs the whole body as one string; nothing was changed.';+const SEGMENTED_WRITE_SUGGESTION = 'The target page is over 1 MiB and stores its body in segments, which this write cannot change yet, so retrying refuses the same way. '+ + 'For remember: save the claim without an entity (omit entity, infer_entity: false); it is filed under memory/unattributed, and remembering it with entity once that page accepts fact rows replaces that copy. '+ + "Read the page with get_page body: 'auto' or a window.";++/** The next step of a `remember` refused because its entity page stores its body in segments: save the claim unattributed. */+export function segmentedRememberFix(): Action {+ return { argv: ['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false'],+ mcp: { tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false } },+ inputs: [{ name: 'FACT', how: 'The claim you tried to remember, unchanged.' }, { name: 'PROVENANCE', how: 'The same provenance you passed.' }],+ consent: [], actor: 'agent', requires_exclusive: false,+ why: "Saves the claim without an entity: the entity page's facts fence cannot take a row while its body is stored in segments. Remembering it with entity later replaces this copy." };+}++/** A `remember` whose entity (named or inferred) stores its body in segments: refused before admission with the unattributed-save fix. */+export function segmentedRememberRefusal(slug: string, sourceId: string, inferred: boolean): OperationError {+ return opError('page_body_segmented',+ `remember: the entity page ${slug} (source ${sourceId})${inferred ? ', inferred from a mention in the fact,' : ''} stores its body in segments, and remember cannot add a row to its facts fence yet. Nothing was saved.`,+ SEGMENTED_WRITE_SUGGESTION, { fix: segmentedRememberFix() });+}+const PURGED_SUGGESTION = 'Do not retry the same content. If it is still true, write it in new words; only the owner can clear a purge tombstone on the brain host.';/** `remember` refusals decided at preparation (withdrawal, `replaces` under the target row lock) keep their code and next step. */@@ -158,6 +182,12 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {purged.canonical = 'purged_content'; purged.writeError = 'purged_content';throw purged;}+ // Wave B: a segmented target is a caller-class refusal; the frozen wire code is invalid_params and the canonical code says why.+ if (error.canonicalCode === 'page_body_segmented') {+ const segmented = verbError('invalid_params', error.message, error.suggestion ?? SEGMENTED_WRITE_SUGGESTION);+ Object.assign(segmented, { canonical: 'page_body_segmented', writeError: 'page_body_segmented', fix: error.fix ?? segmentedRememberFix() });+ throw segmented;+ }const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)? 'invalid_params' : 'unavailable';@@ -179,7 +209,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorC: receipt.state === 'conflict' ? 'revision_conflict': receipt.state === 'cancelled' ? 'cancelled' : 'storage_error');const code = ['source_changed','permission_denied','scope_denied','writer_registration_required'].includes(writeError) ? 'scope_denied'- : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed','purged_content'].includes(writeError) || writeError.startsWith('core_')+ : ['revision_required', 'revision_conflict', 'idempotency_conflict','invalid_params','page_identity_changed','purged_content','page_body_segmented'].includes(writeError) || writeError.startsWith('core_')? 'invalid_params' : 'unavailable';const diagnostic = writeFailureDiagnostic(writeError, message);const suggestion = pending@@ -192,6 +222,7 @@ export function frozenVerbWriteError(receipt: WriteReceipt, reason?: WriteErrorCsuggestion);if (!pending) error.detail = diagnostic.reason;if (writeError === 'purged_content') error.canonical = 'purged_content';+ if (writeError === 'page_body_segmented') Object.assign(error, { canonical: 'page_body_segmented', fix: segmentedRememberFix() });error.writeError = writeError;error.writeRequest = receipt;return error;diff --git a/src/core/verbs/entity-card-identity.ts b/src/core/verbs/entity-card-identity.tsindex 05b6850cf8..891b66564c 100644--- a/src/core/verbs/entity-card-identity.ts+++ b/src/core/verbs/entity-card-identity.ts@@ -14,6 +14,9 @@* malformed fences removed) for every caller, at most EXCERPT_PAGE_CHARS per* page and EXCERPT_CARD_CHARS per card; a page that did not fit is listed in* `identity_excerpt_omitted`. The excerpt adds nothing to the mention index.+ * A segmented page (body stored in segments) is excerpted from its trusted,+ * withdrawal-overlaid lead, the first EXCERPT_LEAD_BYTES of its compiled truth+ * ending on a whole line, so lines past that window are not considered.*/import type { BrainEngine } from '../engine.ts';@@ -25,9 +28,16 @@ import { readIdentitySiblings, SIBLING_GROUP_CAP } from '../mentions/siblings.tsimport type { MentionPolicy, PackTypes } from '../mentions/policy.ts';import type { Notice } from '../agent-output.ts';import type { RecordGroupView } from './entity-references.ts';+import type { Page } from '../types.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { truthLead } from '../page-body/segment-blocks.ts';+import { boundedRawPrefix } from '../page-window/bounded-lead.ts';+import { BOUNDED_PREFIX_BYTES } from '../page-window/document.ts';export const EXCERPT_PAGE_CHARS = 600;export const EXCERPT_CARD_CHARS = 1200;+/** How much of a segmented page's compiled truth the excerpt reads: the bounded lead every other lead reader uses. */+export const EXCERPT_LEAD_BYTES = BOUNDED_PREFIX_BYTES;const EXCERPT_LINE_CHARS = 300;const NOT_NAMES = new Set(['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'ARR', 'MRR', 'TBD', 'N/A', 'NA', 'CEO', 'CFO', 'CTO', 'COO', 'VP', 'UTC', 'PST', 'PDT', 'EST', 'ID']);const NAME_RUN_RE = /\b[A-Z][\p{L}\p{N}&'’-]*(?:\s+[A-Z][\p{L}\p{N}&'’-]*)+/gu;@@ -140,6 +150,15 @@ export async function readSiblingIdentity(engine: BrainEngine, sourceId: string,};}+/** The body an excerpt is cut from: the compiled truth, or a segmented page's lead (EXCERPT_LEAD_BYTES, cut back to a whole line when the truth goes on). */+async function excerptSource(engine: BrainEngine, page: Page): Promise<string> {+ if (!isSegmentedPage(page)) return page.compiled_truth ?? '';+ const lead = await truthLead(engine, page.id, EXCERPT_LEAD_BYTES);+ const bounded = boundedRawPrefix(lead, EXCERPT_LEAD_BYTES);+ if (bounded.length === lead.length && lead.length < EXCERPT_LEAD_BYTES) return lead;+ return bounded.slice(0, Math.max(0, bounded.lastIndexOf('\n')));+}+/** The card's identity fields for `row`. Fail-soft: a failed read leaves the field out. */export async function readCardIdentity(engine: BrainEngine, sourceId: string,row: { slug: string; title: string | null; compiled_truth: string | null },@@ -159,7 +178,7 @@ export async function readCardIdentity(engine: BrainEngine, sourceId: string,const bodies = new Map<string, { title: string; body: string }>();for (const slug of slugs) {const snapshot = snapshots.get(pageSnapshotKey(sourceId, slug));- if (snapshot) bodies.set(slug, { title: snapshot.page.title ?? slug, body: snapshot.page.compiled_truth ?? '' });+ if (snapshot) bodies.set(slug, { title: snapshot.page.title ?? slug, body: await excerptSource(engine, snapshot.page).catch(() => '') });}const excerpt: IdentityExcerptLine[] = [];const omitted: string[] = [];diff --git a/test/large-pages/segmented-read-refusals.test.ts b/test/large-pages/segmented-read-refusals.test.tsnew file mode 100644index 0000000000..2d7b283a44--- /dev/null+++ b/test/large-pages/segmented-read-refusals.test.ts@@ -0,0 +1,147 @@+/**+ * Wave B PR 2 lane 2r: the read refusals and partial reads of a page stored in+ * segments, next to the same content stored inline.+ *+ * 1. Protects:+ * - get_page body 'full' refuses with page_body_segmented for a trusted local+ * caller and for a remote MCP caller alike, with a fix that reads it in+ * pieces (body 'auto', argv and mcp); gbrain's thin client keeps its+ * paging signal, page_too_large_for_inline. The fix runs and answers.+ * - grammar_diagnostics on a segmented page answers the read with a+ * structured `line_grammar: { state: 'skipped', reason }` instead of+ * throwing; an inline page still gets its report.+ * - entity builds the same card (identity excerpt included) for the+ * segmented page as for the inline one when the excerpt's lines sit in+ * the lead it reads (EXCERPT_LEAD_BYTES).+ * - window byte offsets are coordinates of size.total_bytes on both+ * storages: a tail window computed from total_bytes returns the last+ * bytes, and an offset at or past total_bytes returns the same empty+ * window for the inline and the segmented page.+ * 2. Fails when: the local and remote refusals carry different codes, a fix+ * points at body 'none', grammar_diagnostics or entity read the body+ * getters of a segmented page, or the two storages answer a window+ * differently.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { OperationError, type OperationContext } from '../../src/core/ops/contract.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { GBrainConfig } from '../../src/core/config.ts';+import { EXCERPT_LEAD_BYTES } from '../../src/core/verbs/entity-card-identity.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'people/zara-example';+const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };++/** A person page over 1 MiB whose identity lines and a typed relation line sit in its first few KB. */+function content(): string {+ const lead = ['# Zara Example', '', 'Zara Example, also known as Z. Example, founded Acme Example.', '', '- Role: founder at Widget Co',+ '- Board: Northwind Example', '- advises [[companies/acme-example]]', '', 'Met Bob Example and Carol Example at the launch.', ''].join('\n');+ return `---\ntype: person\ntitle: Zara Example\n---\n\n${lead}\n${conversationBody(1_300_000, { seed: 9 })}\n`;+}++async function refusal(run: Promise<unknown>): Promise<OperationError> {+ try { await run; } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++for (const kind of testBackends()) {+ describe(`segmented read refusals and partial reads (${kind})`, () => {+ const engines = {} as Record<'inline' | 'segmented', BrainEngine>;+ const closers: Array<() => Promise<void>> = [];++ beforeAll(async () => {+ for (const storage of ['inline', 'segmented'] as const) {+ let engine: BrainEngine;+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; closers.push(pg.close);+ } else {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ closers.push(() => engine.disconnect());+ }+ await engine.setConfig('pages.segmented_storage', storage === 'segmented' ? 'on' : 'off');+ await importFromContent(engine, SLUG, content(), { sourceId: 'default', noEmbed: true });+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [SLUG]);+ expect(row?.body_storage).toBe(storage);+ engines[storage] = engine;+ }+ }, 300_000);++ afterAll(async () => { for (const close of closers) await close(); });++ const ctx = (engine: BrainEngine, remote: boolean, thinClient = false): OperationContext => ({ engine, config: {} as GBrainConfig, logger: noopLogger,+ dryRun: false, remote, sourceId: 'default', ...(remote ? { transport: 'stdio', thinClient, auth: { token: 'fixture', clientId: 'refusal-client',+ principal: { kind: 'oauth_client', id: 'refusal-client' }, scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+ const call = async (storage: 'inline' | 'segmented', op: string, params: Record<string, unknown>, remote = false, thin = false) =>+ await operationsByName[op]!.handler(ctx(engines[storage], remote, thin), params) as Record<string, any>;++ test('body full refuses page_body_segmented locally and remotely, with a fix that reads it in pieces', async () => {+ const local = await refusal(call('segmented', 'get_page', { slug: SLUG, body: 'full' }));+ const remote = await refusal(call('segmented', 'get_page', { slug: SLUG, body: 'full' }, true));+ const implicit = await refusal(call('segmented', 'get_page', { slug: SLUG }));+ for (const e of [local, remote, implicit]) {+ expect(e.code).toBe('page_body_segmented');+ expect(e.canonicalCode).toBe('page_body_segmented');+ expect(e.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug: SLUG, source_id: 'default', body: 'auto' } });+ expect(e.fix?.argv).toEqual(['gbrain', 'get', '--source', 'default', '--body', 'auto', '--', SLUG]);+ expect(e.suggestion).toContain("body: 'auto'");+ }+ const thin = await refusal(call('segmented', 'get_page', { slug: SLUG }, true, true));+ expect(thin.canonicalCode).toBe('page_too_large_for_inline');+ for (const remoteCall of [false, true]) {+ const auto = await call('segmented', 'get_page', local.fix!.mcp!.arguments as Record<string, unknown>, remoteCall);+ expect(auto).toMatchObject({ body: 'outline', body_storage: 'segmented', truncated: true, auto_reason: 'over_inline_bytes' });+ expect(auto.window.text).toContain('Zara Example, also known as');+ }+ }, 120_000);++ test('grammar_diagnostics is skipped with a reason on a segmented page, never thrown', async () => {+ for (const remote of [false, true]) {+ const segmented = await call('segmented', 'get_page', { slug: SLUG, body: 'none', grammar_diagnostics: true }, remote);+ expect(segmented.body).toBe('none');+ expect(segmented.line_grammar).toMatchObject({ state: 'skipped', reason: 'page_body_segmented' });+ expect(segmented.line_grammar.fix.mcp).toEqual({ tool: 'get_page', arguments: { slug: SLUG, source_id: 'default', body: 'auto' } });+ const inline = await call('inline', 'get_page', { slug: SLUG, body: 'none', grammar_diagnostics: true }, remote);+ expect(inline.line_grammar.state).toBe('ok');+ }+ }, 120_000);++ test('entity builds the same card from the segmented lead as from the inline body', async () => {+ expect(content().indexOf('Met Bob Example')).toBeLessThan(EXCERPT_LEAD_BYTES);+ for (const remote of [false, true]) {+ const [inline, segmented] = await Promise.all((['inline', 'segmented'] as const).map(s => call(s, 'entity', { name: 'Zara Example' }, remote)));+ expect(segmented.found).toBe(true);+ expect(segmented.card.identity_excerpt?.length).toBeGreaterThan(0);+ const comparable = (r: Record<string, any>) => {+ const card = JSON.parse(JSON.stringify(r.card));+ delete card.last_touched;+ delete card.coverage;+ return card;+ };+ expect(comparable(segmented)).toEqual(comparable(inline));+ }+ }, 120_000);++ test('window offsets are size.total_bytes coordinates; past the end both storages return the same empty window', async () => {+ for (const remote of [false, true]) {+ const [inlineNone, segmentedNone] = await Promise.all((['inline', 'segmented'] as const).map(s => call(s, 'get_page', { slug: SLUG, body: 'none' }, remote)));+ const total = inlineNone.size.total_bytes;+ expect(segmentedNone.size.total_bytes).toBe(total);+ for (const bytes of [{ offset: total - 64, length: 64 }, { offset: total, length: 64 }, { offset: total + 10_000, length: 64 }]) {+ const [inline, segmented] = await Promise.all((['inline', 'segmented'] as const).map(s => call(s, 'get_page', { slug: SLUG, body: 'window', bytes }, remote)));+ expect(segmented.window).toEqual(inline.window);+ expect(segmented.truncated).toBe(inline.truncated);+ expect(segmented.next_cursor).toBe(inline.next_cursor);+ if (bytes.offset >= total) expect(segmented.window).toMatchObject({ text: '', byte_start: total, byte_end: total });+ else expect(segmented.window.byte_end).toBe(total);+ }+ }+ }, 120_000);+ });+}diff --git a/test/large-pages/segmented-remember-refusal.test.ts b/test/large-pages/segmented-remember-refusal.test.tsnew file mode 100644index 0000000000..a92e4fab63--- /dev/null+++ b/test/large-pages/segmented-remember-refusal.test.ts@@ -0,0 +1,137 @@+/**+ * Wave B PR 2 lane 2r: `remember` against an entity page stored in segments.+ *+ * 1. Protects: a remember whose entity page (named, or inferred from one+ * exact mention) stores its body in segments refuses before admission with+ * the frozen wire code `invalid_params`, the canonical code and write_error+ * `page_body_segmented`, not retryable, and a fix that saves the claim+ * unattributed (infer_entity: false); no fact row is written. A receipt+ * that failed with `page_body_segmented` in preparation (a page that became+ * segmented after admission) maps the same way, and its write diagnostic+ * names the code. Inline entity pages keep linking as before.+ * 2. Fails when: the refusal surfaces as `unavailable` / storage_error (a+ * server fault an agent retries), or an inferred subject on a segmented+ * page is silently saved with NO_ENTITY.+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { OperationError } from '../../src/core/ops/contract.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { disposePersistenceConsumer, writeResponse } from '../../src/core/persistence/service.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { runMemoryWrite, writeFailureDiagnostic } from '../../src/core/persistence/verb-errors.ts';+import type { WriteRequest } from '../../src/core/persistence/model.ts';+import { toAgentError, type RenderContext } from '../../src/core/agent-output.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../helpers/legacy-embedding-config.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SEGMENTED = 'people/zara-example';+const INLINE = 'people/yuri-example';+const sourceId = 'default';++async function refusal(run: Promise<unknown>): Promise<OperationError> {+ try { await run; } catch (error) { if (error instanceof OperationError) return error; throw error; }+ throw new Error('expected a refusal');+}++const factCount = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: unknown }>('SELECT count(*) AS n FROM facts'))[0]!.n);++for (const kind of testBackends()) {+ describe(`remember on a segmented entity page (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const ctx = (): OperationContext => ({ engine, remote: false, sourceId, config: { engine: kind }, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext);+ const remember = (params: Record<string, unknown>) => operationsByName.remember!.handler(ctx(), { provenance: 'chat 2026-10-15', ...params }) as Promise<Record<string, any>>;++ beforeAll(async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; close = pg.close;+ } else {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema();+ engine = lite; close = () => lite.disconnect();+ }+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await registerLocalWriter(engine, 'cli');+ await engine.setConfig('pages.segmented_storage', 'on');+ await importFromContent(engine, SEGMENTED, `---\ntype: person\ntitle: Zara Example\n---\n\n# Zara Example\n\n${conversationBody(1_300_000, { seed: 3 })}\n`, { sourceId, noEmbed: true });+ await importFromContent(engine, INLINE, '---\ntype: person\ntitle: Yuri Example\n---\n\n# Yuri Example\n\nA small inline person page.\n', { sourceId, noEmbed: true });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', [SEGMENTED]);+ expect(row?.body_storage).toBe('segmented');+ }, 300_000);++ afterAll(async () => {+ await disposePersistenceConsumer(engine);+ await close();+ resetGateway();+ });++ const expectSegmentedRefusal = (e: OperationError, slug: string) => {+ expect(e.code).toBe('invalid_params');+ expect(e.canonicalCode).toBe('page_body_segmented');+ expect(e.writeError).toBe('page_body_segmented');+ expect(e.message).toContain(slug);+ expect(e.fix?.mcp).toEqual({ tool: 'remember', arguments: { fact: '<FACT>', provenance: '<PROVENANCE>', infer_entity: false } });+ expect(e.fix?.argv).toEqual(['gbrain', 'remember', '<FACT>', '--provenance', '<PROVENANCE>', '--infer-entity', 'false']);+ const render: RenderContext = { transport: 'stdio', surface: 'full', isCallable: () => true, preapproved: () => false, routing: { brain: 'host', source: sourceId } };+ const envelope = toAgentError(e, { transport: 'stdio', op: 'remember', mutating: true, idempotent: true, render }) as unknown as Record<string, any>;+ expect(envelope.code).toBe('page_body_segmented');+ expect(envelope.retryable).toBe(false);+ };++ test('a named segmented entity refuses page_body_segmented with the unattributed-save fix, not unavailable/storage_error', async () => {+ const before = await factCount(engine);+ const e = await refusal(remember({ fact: 'Zara Example prefers tea', entity: SEGMENTED }));+ expectSegmentedRefusal(e, SEGMENTED);+ expect(await factCount(engine)).toBe(before);+ }, 60_000);++ test('an inferred segmented subject refuses the same way instead of saving with NO_ENTITY', async () => {+ const before = await factCount(engine);+ const e = await refusal(remember({ fact: 'Zara Example moved the offsite to May' }));+ expectSegmentedRefusal(e, SEGMENTED);+ expect(e.message).toContain('inferred from a mention');+ expect(await factCount(engine)).toBe(before);+ }, 60_000);++ test('the fix saves the claim unattributed; inline entities still link, named and inferred', async () => {+ const unattributed = await remember({ fact: 'Zara Example moved the offsite to May', infer_entity: false });+ expect(unattributed).toMatchObject({ status: 'inserted', entity_slug: null, warnings: ['NO_ENTITY'] });+ expect(await remember({ fact: 'Yuri Example likes chess', entity: INLINE })).toMatchObject({ status: 'inserted', entity_slug: INLINE });+ expect(await remember({ fact: 'Yuri Example joined the board' })).toMatchObject({ status: 'inserted', entity_slug: INLINE, entity_inferred: 'mention' });+ }, 60_000);+ });+}++describe('a receipt that failed page_body_segmented in preparation', () => {+ const row = {+ id: '00000000-0000-4000-8000-000000000001', request_id: '00000000-0000-4000-8000-000000000002', state: 'failed', operation: 'remember',+ source_id: 'default', slug: SEGMENTED, principal_kind: 'local', principal_id: 'cli', outcome: null, authority: { remote: false },+ error_code: 'page_body_segmented', error_detail: null,+ error_message: `remember facts fence write: page ${SEGMENTED} (source default) stores its body in segments, and this path reads or writes the whole body as one string. Nothing was read or changed.`,+ created_at: '2026-10-15T00:00:00.000Z', updated_at: '2026-10-15T00:00:01.000Z',+ } as unknown as WriteRequest;++ test('keeps its code through the verb boundary and the write diagnostic', async () => {+ const e = await refusal(runMemoryWrite(async () => writeResponse(row)));+ expect(e.code).toBe('invalid_params');+ expect(e.canonicalCode).toBe('page_body_segmented');+ expect(e.writeError).toBe('page_body_segmented');+ expect(e.detail).toBe('page_body_segmented');+ expect(e.message).toContain('stores its body in segments');+ expect(e.fix?.mcp?.arguments).toMatchObject({ infer_entity: false });+ const diagnostic = writeFailureDiagnostic('page_body_segmented', row.error_message);+ expect(diagnostic).toMatchObject({ reason: 'page_body_segmented', message: row.error_message });+ expect(diagnostic.suggestion).toContain('infer_entity: false');+ });+});