Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
15.2 KB
Raw Blame

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 selects boundedBodyPrefixSql(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), boundedRawPrefix cuts a body at 64 KiB on a code point, and overlaidBoundedRows / overlaidBoundedPrefix replace a prefix holding a gbrain:facts:begin marker with the prefix of the withdrawal-overlaid body (one batched readPageSnapshotsBatch read; a page it no longer returns, or a failed read, gets an empty lead). A segmented page's row carries its stored truth_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. pageLeadSource gives getPage callers (exact-slug and alias snippets) a page's compiled truth, or a segmented page's truth_lead without touching its throwing body getters. projectedLead is that prefix through boundedProjectedPrefix (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.ts safeSynopsis: 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 and entity names leads, 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 by test/bounded-lead.test.ts and test/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 after TIMELINE_SEPARATOR), pageDocument / readPageDocument (UTF-8 bytes + timeline byte offset, with the page's fence overlay), chunkDocumentSpan + spanHoldsChunk (a chunk's stored projected_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 as forced_cut), pageOutline (single pass: ATX headings outside code fences, or 64 KiB blocks for pages with fewer than two headings, with date ranges, paged by from/limit), and the opaque revision-bound cursor (gpw1.). DocumentSlab / slabWindow run 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. SegmentedDocument places units (segments from projectedUnits plus fixed text) by stored sums and reads only the units a window, line lookup or around_chunk_id touches (slab adds EDGE bytes so code-point and line snapping match the inline arithmetic). segmentedReadDocument is the read projection; segmentedMarkdownDocument the markdown view (markdownHead, then the projection for a remote caller, the overlaid stored body and TIMELINE_SEPARATOR for 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. tailDigest hashes the last TAIL_BYTES raw bytes of the last region, withheld from a remote caller when those rows hold a protected or facts region. segmentedOutline pages headings from stored metadata, reading at most OUTLINE_READ_BYTES of 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.ts uses it for the local gbrain get stream (streamSegmentedGet); the thin client pages and verifies the markdown view (printPagedPage), and --json above PAGE_MAX_BYTES is refused on both paths. Pinned by test/large-pages/segmented-get-page-parity.test.ts, read-cost.test.ts, remote-get-page-privacy.test.ts, segmented-get-cli.test.ts and segmented-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. spliceSegmentedBody replaces 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). splicePage reads the page row a splice needs (generation, region sizes, cr tier, corpus generation, kind); spliceWork counts segments segmented, bytes read and manifest rows (the cost tests' work counters). tail-digest.ts is the append precondition's digest for inline pages, sha256 of a region's last min(4096, region bytes) raw stored bytes (inlineTailDigest; segmented pages use page-window/segmented.ts tailDigest); 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 (region auto/truth/timeline, separator auto/none), idempotent by request_id. admitPageAppend (also the upload lane's commit_page_upload append entry, with a staged body_ref) journals the text or the reference, never the body; text is capped at APPEND_TEXT_MAX_BYTES (4 MiB), a facts or takes fence marker in it refuses invalid_params and a links fence marker append_links_fence (write links with add_link), and a missing or deleted page refuses page_not_found. prepareAppendMutation checks the optional preconditions on the locked snapshot (expected_revision gives revision_changed; expected_tail_sha256 gives tail_changed, whose fix carries the current tail digest). A segmented page splices onto its region's tail through prepareSegmentedSpliceMutation, which segmented edit_page and append-mode upload commits share. It refuses a result over pages.max_bytes as 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 sets content_flag (instruction_like), records the page gate receipt and returns put_page's gate field; 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 a links effect carrying them (data.range, #7122; see effect-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 — the append_page operation (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's body: 'none' returns tail_sha256 and tail_region for inline and segmented pages, and its window reads return edit_target: {revision, byte_start, byte_end} in stored coordinates (ops/get-page-body.ts editTarget), withheld from a remote caller when hidden text precedes the window end (read-range.ts hiddenBefore).

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, selectors lines/bytes/around_chunk_id/cursor, view: read|markdown). parseBodyRequest fixes 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_ORDER cursor > 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, and view: markdown drops around_chunk_id beside another selector), and the response's window_selector {applied, ignored, note} reports what was set aside. readPartialBody never fills compiled_truth/timeline/content: it slices the read projection (readPageDocument) or, for view: markdown, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits resultByteCap. around_chunk_id uses 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 is revision_changed with a same-offset fix. readFetchWindow / fetchWindowResult serve fetch's windowed shape; LARGE_PAGES_CAPABILITY is advertised by get_brain_identity. A segmented page (Wave B PR 2, spec 7.2) is never read whole: full is page_body_segmented for local and MCP callers alike with segmentedReadFix (body: 'auto', argv and mcp; local gbrain get with no --body streams it instead), and page_too_large_for_inline only for gbrain's thin client, its paging signal (segmentedFullReadError); grammar_diagnostics on it is line_grammar: { state: 'skipped', reason: 'page_body_segmented' } (segmentedGrammarSkip, line-grammar-report.ts); window byte offsets are coordinates of the view's size.total_bytes, never body_bytes, and an offset past the end is an empty window on both storages; auto is the outline plus the first window, and segmentedWindows cuts every window, outline page and around_chunk_id from page-window/segmented.ts. A segmented around_chunk_id resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is revision_changed; no text match), and body: 'none' reports stored sums plus the tail digest without chunk counts. section/grep: ops/get-page-slice.ts (continued).