Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Core Services (2/3, page windows and large writes)
Subsystem index · Previous entries. Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Bounded page windows under src/core/page-window/, the large-page write paths (append_page, segmented edits) and get_page's body modes.
src/core/page-window/bounded-lead.ts— leads, snippets and synopses read a bounded prefix, never the whole body: fan-out SQL selectsboundedBodyPrefixSql(alias)(left(coalesce(alias.compiled_truth, alias.truth_lead), 65536): a segmented page's NULL body falls back to its stored lead; the one COALESCE of body and lead the page body reader ratchet allows by name),boundedRawPrefixcuts a body at 64 KiB on a code point, andoverlaidBoundedRows/overlaidBoundedPrefixreplace a prefix holding agbrain:facts:beginmarker with the prefix of the withdrawal-overlaid body (one batchedreadPageSnapshotsBatchread; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its storedtruth_lead; when that lead holds a facts fence it is overlaid alone with the withdrawal ledger the snapshot read returns (overlayCanonicalBodies, then the same 64 KiB cut), never by reading segments.pageLeadSourcegives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page'struth_leadwithout touching its throwing body getters.projectedLeadis that prefix throughboundedProjectedPrefix(document.ts). Consumers: the exact-slug tier (exact-lookup.ts) and alias injection (alias-hop.ts) snippets, relational hydrate, the reflex pointer synopsis (retrieval-reflex.tssafeSynopsis: world-only reads take the projected prefix, the trusted entity-card widening the raw prefix through its own fence strip), the entity card's hit row andentity namesleads, and think's anchor and window-floor rows (think/gather.ts: the raw overlaid prefix for the trusted local CLI, the projected prefix otherwise). Small pages render as before. Pinned bytest/bounded-lead.test.tsandtest/large-pages/segmented-leads.test.ts.src/core/page-window/document.ts— the one read projection every remote window, outline and lead slices:projectPageText(fence overlay split,sanitizeRemoteBody+credentialSafeProjection, timeline afterTIMELINE_SEPARATOR),pageDocument/readPageDocument(UTF-8 bytes + timeline byte offset, with the page's fence overlay),chunkDocumentSpan+spanHoldsChunk(a chunk's storedprojected_byte_*span mapped into the document and verified),boundedProjectedPrefix,locateChunksByStoredSpans(byte spans to string offsets in one pass),DEFAULT_INLINE_BODY_BYTES(256 KB).src/core/page-window/window.ts— byte/line window arithmetic on a UTF-8 buffer: windows snap to code points and line starts (windowFrom,windowForLines,windowForBytes,windowAround; a lone line longer than the window is cut on a code point asforced_cut),pageOutline(single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged byfrom/limit), and the opaque revision-bound cursor (gpw1.).DocumentSlab/slabWindowrun the same arithmetic on a slice of a larger document and shift the result back to document coordinates.src/core/page-window/segmented.ts— Wave B PR 2 (spec 7.2, 7.4): get_page over a segmented page in projected bytes, the same coordinates as an inline page.SegmentedDocumentplaces units (segments fromprojectedUnitsplus fixed text) by stored sums and reads only the units a window, line lookup oraround_chunk_idtouches (slabaddsEDGEbytes so code-point and line snapping match the inline arithmetic).segmentedReadDocumentis the read projection;segmentedMarkdownDocumentthe markdown view (markdownHead, then the projection for a remote caller, the overlaid stored body andTIMELINE_SEPARATORfor a trusted one).page_view_digests(migration v253) caches per page revision, view and audience the read view's line count and the markdown view's size and sha256, checked against the current total.tailDigesthashes the lastTAIL_BYTESraw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region.segmentedOutlinepages headings from stored metadata, reading at mostOUTLINE_READ_BYTESof segments per page and carrying line counts forward between entries.segmentedReadWork(@internal) counts the units and segment bytes a read visits, for the read-cost bounds.cli/page-render.tsuses it for the localgbrain getstream (streamSegmentedGet); the thin client pages and verifies the markdown view (printPagedPage), and--jsonabovePAGE_MAX_BYTESis refused on both paths. Pinned bytest/large-pages/segmented-get-page-parity.test.ts,read-cost.test.ts,remote-get-page-privacy.test.ts,segmented-get-cli.test.tsandsegmented-get-over-ceiling.test.ts.
Large page writes
Writes that change part of a page in time proportional to the change (Wave B spec 6.1, 6.3): append_page, segmented edit_page and the splice engine both use. Tests: test/large-pages/append-cost.test.ts, test/large-pages/append-concurrency.test.ts and test/large-pages/edit-segmented.test.ts, PGLite and Postgres (helper test/helpers/append-brain.ts).
src/core/page-body/splice.ts+tail-digest.ts— byte-range splices of a segmented body.spliceSegmentedBodyreplaces stored byte ranges of the live generation (BodyReplacement) and stages the next one from the touched segments only: segmentation resumes at the last clean entry point before the first replaced byte and stops at the first old boundary whose entry state the new run reproduces, so later segments keep their bytes, text and chunks and only move (new manifest rows under the same occurrence; content_hash midstate recomputed). An append is an insertion at its region's end: it re-segments the old tail plus the text and moves nothing; an insertion at the truth/timeline boundary belongs to truth (replacementRegion), so exactly one row owns it. New segments equal to a replaced one keep its occurrence; the rest are chunked with vectors reused by chunk text. A change that flips a region's fence trust restages the whole body (rescanned).splicePagereads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind);spliceWorkcounts segments segmented, bytes read and manifest rows (the cost tests' work counters).tail-digest.tsis the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (inlineTailDigest; segmented pages usepage-window/segmented.tstailDigest); a tail holding facts or takes text is withheld from a remote caller, since a hash of hidden text is a guessing oracle. The cost test pins that a 10 KB append to a 4 MB and a 16 MB page segments only the tail plus the text, and a forced full-rewrite probe (appendProbe.fullRewrite) fails the bound.src/core/persistence/page-append.ts—append_page: text added to the end of a region (regionauto/truth/timeline,separatorauto/none), idempotent byrequest_id.admitPageAppend(also the upload lane'scommit_page_uploadappend entry, with a stagedbody_ref) journals the text or the reference, never the body; text is capped atAPPEND_TEXT_MAX_BYTES(4 MiB), a facts or takes fence marker in it refusesinvalid_paramsand a links fence markerappend_links_fence(write links withadd_link), and a missing or deleted page refusespage_not_found.prepareAppendMutationchecks the optional preconditions on the locked snapshot (expected_revisiongivesrevision_changed;expected_tail_sha256givestail_changed, whose fix carries the current tail digest). A segmented page splices onto its region's tail throughprepareSegmentedSpliceMutation, which segmented edit_page and append-mode upload commits share. It refuses a result overpages.max_bytesas a streamed import does (file_too_large, nothing written), and runs put_page's write gate over the new text only (title, frontmatter and the replacement bytes, O(text)): a flag verdict setscontent_flag(instruction_like), records the page gate receipt and returns put_page'sgatefield; an allowed append never clears an existing flag, since the stored text was not re-read; it declines (null, whole-body path) for an always-loaded core page, an external_untrusted write the write gate scans whole, a change that creates or empties a region, or a file a withdrawal ledger rewrites. An inline page composes the new body on put_page's path, which promotes it past the segmented threshold. Chunks and embeddings of the appended text follow commit as for any segmented write. A remote append to the compiled truth records the bytes it added (PreparedMutation.mentionRange: stored truth offsets and their SHA-256, from the splice or, inline, the parsed appended bytes placed at the end of the stored truth after publication, so a Tier 1 fence normalization before them cannot shift the range) and queues alinkseffect carrying them (data.range, #7122; seeeffect-links.ts); timeline rows and fence projections of appended text wait for PR 4's incremental derivation. A file-backed segmented page's canonical file gains the appended bytes, its frontmatter rendered in stored key order as inline edit_page and append write-through render it.src/core/ops/page-append.ts— theappend_pageoperation (write scope, client slug-fence allowlist,outputRedaction: 'no_stored_text'): params{slug, source_id?, text, request_id, expected_revision?, expected_tail_sha256?, region?, separator?}, returns{slug, revision, body_bytes, appended_bytes, chunks_new, size_state, receipt}. get_page'sbody: 'none'returnstail_sha256andtail_regionfor inline and segmented pages, and its window reads returnedit_target: {revision, byte_start, byte_end}in stored coordinates (ops/get-page-body.tseditTarget), withheld from a remote caller when hidden text precedes the window end (read-range.tshiddenBefore).
Segmented edit_page (persistence/page-edit.ts, entry in Core Persistence): optional within: {byte_start, byte_end} (stored coordinates, as edit_target returns them; parseEditWithin, edit_invalid) limits matching to one range, and a range the page no longer holds refuses revision_conflict. A remote caller's within refuses edit_invalid (one refusal for every range and edit, before any match or fence check) when hidden text starts before byte_end: on a segmented page the read projection's hidden units (read-range.ts hiddenBefore, the predicate editTarget withholds edit_target by), on an inline page a fence whose remote view differs from its stored text; such a range would measure the hidden text. A segmented page is never materialized: prepareSegmentedEditMutation (called first by page-prepare.ts preparePageMutation) finds each old_text by a streaming scan across segment boundaries (locateSegmentedEdits, with applyPageEdits' exactly-once, protected-span and remote-view rules; the scan keeps at most two matches per edit and refuses edit_ambiguous_match at the second, counted in spliceWork.matches) and splices the touched range; the receipt diff covers the touched range plus 2 KB of context, and only the first replacement past 256 KB (diff_truncated); its context never starts at or inside hidden facts or takes text, nor ends inside it, and its hunk lines count the caller's view (viewNewlinesBefore: row line counts plus, for a remote caller, each hidden run before the diff rendered as sanitizeRemoteBody renders it). With a withdrawal ledger that applies, the scan, the diff and those line counts read the page through its withdrawal overlay (storedPieces over trustedSegments, rows widened to whole fence blocks), on every path; a match into a block the overlay rewrote is never kept. A segmented page's remote edit view hides withdrawn rows as its remote windows do (SEGMENTED_REMOTE_VIEW, also on the whole-body path). A stored fence that does not compile refuses as applyPageEdits refuses it (typed target_fence_malformed, same location), at submission (assertSegmentedEditFences) and again at preparation: scanCanonicalFences runs over the stored fence text alone, each piece at its own line, so only segments holding fence text are read; with within, only the fences in the touched segments and those crossing into them. It declines to the whole-body path for an old_text naming the timeline sentinel or also found in the frontmatter head, or a miss without within on a page within the single-string ceiling.
src/core/ops/get-page-body.ts— get_page's body modes (auto|full|none|outline|window, selectorslines/bytes/around_chunk_id/cursor,view: read|markdown).parseBodyRequestfixes precedence (a selector → window, setting aside body full/include_content/content_only beside it; else explicit body; include_content/content_only → full; the thin client and the local CLI → full; else auto). Several selectors read one window,SELECTOR_ORDERcursor > around_chunk_id > lines > bytes (GBRA-280); an around_chunk_id not on the page falls back to the next one (fallbacks, tried in order: a cursor for another page or view, or issued before the page changed, falls back too, andview: markdowndrops around_chunk_id beside another selector), and the response'swindow_selector {applied, ignored, note}reports what was set aside.readPartialBodynever fills compiled_truth/timeline/content: it slices the read projection (readPageDocument) or, forview: markdown, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fitsresultByteCap.around_chunk_iduses the stored span (anchor: stored_span), a unique text match (located), or returns the chunk alone (chunk_only). Cursors are revision-bound; a stale one isrevision_changedwith a same-offset fix.readFetchWindow/fetchWindowResultserve fetch's windowed shape;LARGE_PAGES_CAPABILITYis advertised byget_brain_identity. A segmented page (Wave B PR 2, spec 7.2) is never read whole:fullispage_body_segmentedfor local and MCP callers alike withsegmentedReadFix(body: 'auto', argv and mcp; localgbrain getwith no--bodystreams it instead), andpage_too_large_for_inlineonly for gbrain's thin client, its paging signal (segmentedFullReadError);grammar_diagnosticson it isline_grammar: { state: 'skipped', reason: 'page_body_segmented' }(segmentedGrammarSkip, line-grammar-report.ts); window byte offsets are coordinates of the view'ssize.total_bytes, neverbody_bytes, and an offset past the end is an empty window on both storages;autois the outline plus the first window, andsegmentedWindowscuts every window, outline page andaround_chunk_idfrompage-window/segmented.ts. A segmentedaround_chunk_idresolves only from the chunk's live occurrence and segment-relative span (a retired occurrence isrevision_changed; no text match), andbody: 'none'reports stored sums plus the tail digest without chunk counts.section/grep:ops/get-page-slice.ts(continued).