Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane 1b-ii: release segments after a truncated tail, prune region ends, streaming linear test, orphan entries
garrytan742651a67519
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjsindex 4fd946fb5b..7b6be53074 100644--- a/scripts/check-orphan-modules.mjs+++ b/scripts/check-orphan-modules.mjs@@ -53,6 +53,10 @@ const ALLOWLIST = new Map([// string in a reviewer-visible edit. Modules reached from `scripts/**` carry// reason 'script-reachable', which the guard verifies.const PERMITTED_TEST_ONLY = [+ { path: 'src/core/page-body/entry-state.ts', reason: 'held: Wave B PR 1 segmenter state; the segmented ingest path (spec 13 PR 1 integration) imports it' },+ { path: 'src/core/page-body/region-scan.ts', reason: 'held: Wave B PR 1 streaming region scan; the segmented ingest path (spec 13 PR 1 integration) imports it' },+ { path: 'src/core/page-body/segmenter.ts', reason: 'held: Wave B PR 1 segmenter; the segmented ingest path (spec 13 PR 1 integration) imports it' },+ { path: 'src/core/page-body/segment-chunks.ts', reason: 'held: Wave B PR 1 per-segment chunker; the segmented projection (spec 13 PR 1 integration) imports it' },{ path: 'src/core/bootstrap/template-repo.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/diagnostics.ts', reason: 'script-reachable' },{ path: 'src/eval/longmemeval/evidence-brief.ts', reason: 'held: eval-only wave 1 brief builder (10x memory advantage plan A3), loaded by path from gbrain-evals eval/runner/pilot; product wiring is plan item A8, conditional on the A5 pilot' },diff --git a/src/core/page-body/region-scan.ts b/src/core/page-body/region-scan.tsindex 6fac5e8902..33c8cc6df9 100644--- a/src/core/page-body/region-scan.ts+++ b/src/core/page-body/region-scan.ts@@ -181,7 +181,7 @@ export function findTokens(carry: string, text: string, tokens: readonly string[// ---------------------------------------------------------------------------/** The open fenced code block: its fence character and run length, plus the mispairing flag. */-export interface FenceWalk { fence: '`' | '~' | null; len: number; mispaired: boolean }+export interface FenceRun { fence: '`' | '~' | null; len: number; mispaired: boolean }/** A fence-line judgement in progress: up to 3 spaces, a run of ` or ~, then the rest of the line. */export interface FenceProbe {@@ -195,13 +195,13 @@ export interface FenceProbe {ws: boolean;}-export function newFenceWalk(): FenceWalk { return { fence: null, len: 0, mispaired: false }; }+function newFenceRun(): FenceRun { return { fence: null, len: 0, mispaired: false }; }-export function newFenceProbe(): FenceProbe {+function newFenceProbe(): FenceProbe {return { phase: 'indent', indent: 0, ch: null, run: 0, tick: false, sep: false, ws: true };}-export function feedFenceProbe(p: FenceProbe, s: string): void {+function feedFenceProbe(p: FenceProbe, s: string): void {for (let i = 0; i < s.length && p.phase !== 'none'; i++) {const c = s.charCodeAt(i);if (p.phase === 'indent') {@@ -225,12 +225,12 @@ function probeOpens(p: FenceProbe): boolean {return (p.phase === 'run' || p.phase === 'rest') && p.run >= 3 && !p.sep && !(p.ch === '`' && p.tick);}-function probeCloses(p: FenceProbe, walk: FenceWalk): boolean {+function probeCloses(p: FenceProbe, walk: FenceRun): boolean {return (p.phase === 'run' || p.phase === 'rest') && p.ch === walk.fence && p.run >= walk.len && p.ws;}/** Advance the walk past a judged line. */-export function advanceFenceWalk(walk: FenceWalk, p: FenceProbe): void {+function advanceFenceRun(walk: FenceRun, p: FenceProbe): void {if (!walk.fence) {if (probeOpens(p)) { walk.fence = p.ch; walk.len = p.run; }} else if (probeCloses(p, walk)) {@@ -242,7 +242,7 @@ export function advanceFenceWalk(walk: FenceWalk, p: FenceProbe): void {}/** The trust scanMarkdownCode would give the body scanned so far, were it to end here. */-export function walkTrusted(walk: FenceWalk): boolean {+export function walkTrusted(walk: FenceRun): boolean {return !walk.fence && !walk.mispaired;}@@ -258,7 +258,7 @@ const MARKER_LEAD = MARKER_TEXTS.reduce((a, b) => { let k = 0; while (k < a.leng/** The region scanner's parser state at a line start (or inside a long line). JSON-safe. */export interface RegionTrack {- walk: FenceWalk;+ walk: FenceRun;/** The open protected region: its pair index, stored-stream byte start and `read`. */open: { pair: number; start: number; read: boolean } | null;/** Byte where an ambiguous tail starts; everything from there to the end of the region is protected. */@@ -285,7 +285,7 @@ export interface ScanOut {}export function newRegionTrack(): RegionTrack {- return { walk: newFenceWalk(), open: null, truncatedAt: null, long: null };+ return { walk: newFenceRun(), open: null, truncatedAt: null, long: null };}/** Scan one whole line (no terminator in `text`) starting at stored byte `byteStart`. */@@ -310,7 +310,7 @@ export function scanRegionLine(track: RegionTrack, trusted: boolean, text: strin}if (coverFrom !== -1) out.covers.push({ from: coverFrom, to: text.length, pair: track.open?.pair ?? -1, start: track.open?.start ?? track.truncatedAt! });out.coverTerm = coverFrom !== -1 && term !== '';- advanceFenceWalk(track.walk, probe);+ advanceFenceRun(track.walk, probe);}/**@@ -343,7 +343,7 @@ export function scanRegionPiece(track: RegionTrack, trusted: boolean, text: striif (coverFrom !== -1) out.covers.push({ from: coverFrom, to: text.length, pair: track.open?.pair ?? -1, start: track.open?.start ?? track.truncatedAt! });out.coverTerm = coverFrom !== -1 && !!term;if (term !== null) {- advanceFenceWalk(track.walk, long.probe);+ advanceFenceRun(track.walk, long.probe);track.long = null;}}@@ -482,7 +482,7 @@ export function pemResolvedTo(st: PemScanState): number {/** Ask whether a cut at projection offset `at` is a clean resume point; answered once `at` is resolved. */export function markPemCut(st: PemScanState, at: number): void {- st.cuts.push({ at });+ st.cuts.push(st.final ? { at, done: pemCutCheck(st, at) } : { at });}/** The answer for a marked cut (removing it), or null while unresolved. */diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.tsindex db943b83e5..1dd039ba49 100644--- a/src/core/page-body/segmenter.ts+++ b/src/core/page-body/segmenter.ts@@ -361,7 +361,8 @@ export class Segmenter {char = b;}this.pemPending += projected;- if (this.pemPending.length >= PEM_FEED_CHARS) this.feedPem(false);+ if (track.truncatedAt !== null) this.feedPem(true);+ else if (this.pemPending.length >= PEM_FEED_CHARS) this.feedPem(false);}}@@ -379,6 +380,7 @@ export class Segmenter {}private feedPem(final: boolean): void {+ if (this.pem.final) return;const text = this.pemPending;this.pemPending = '';feedPemScan(this.pem, text, final, (s, e) => this.pemSpans.push({ start: this.rawAt(s, false), end: this.rawAt(e, true) }));@@ -447,6 +449,7 @@ export class Segmenter {regions.push(region);}this.pemSpans = this.pemSpans.filter(s => s.end > segEnd);+ for (const [start, end] of this.regionEnds) if (end <= segEnd) this.regionEnds.delete(start);regions.sort((a, b) => a.start - b.start || b.end - a.end);const parts = segmentProjectionParts(raw, regions, seg.byteStart);let projected = '';diff --git a/test/large-pages/segmenter-linear.test.ts b/test/large-pages/segmenter-linear.test.tsindex ec0740eb89..e429be834c 100644--- a/test/large-pages/segmenter-linear.test.ts+++ b/test/large-pages/segmenter-linear.test.ts@@ -11,11 +11,12 @@* 3. Forced probe: the same ratio check run on an append path that* resegments the whole prefix on each append (the quadratic variant)* exceeds the bound, so the check can tell the two apart.- * 4. Each size takes its best of three runs in thread CPU time (cpuMs).+ * 4. After one warm-up run, each size takes its best of five runs in thread+ * CPU time (cpuMs).*/import { describe, expect, test } from 'bun:test';import { initialEntryState } from '../../src/core/page-body/entry-state.ts';-import { segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';+import { Segmenter, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';import { cpuMs } from '../helpers/cpu-time.ts';import { mulberry32 } from '../helpers/seeded-random.ts';import { bigPage, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';@@ -26,13 +27,17 @@ const entry = () => initialEntryState({ region: 'truth' });function bestMs(fn: () => unknown): number {let best = Infinity;- for (let k = 0; k < 3; k++) best = Math.min(best, cpuMs(fn));+ for (let k = 0; k < 5; k++) {+ best = Math.min(best, cpuMs(fn));+ }return best;}function ratio(make: (bytes: number) => string, small: number, run: (body: string) => unknown): number {const a = make(small);const b = make(2 * small);+ run(a);+ run(b);return bestMs(() => run(b)) / bestMs(() => run(a));}@@ -40,7 +45,15 @@ const page = bigPage(mulberry32(7), 4.5 * MB);const prefix = (bytes: number) => page.slice(0, page.indexOf('\n', bytes) + 1);const segmentAll = (body: string) => segmentString(body, entry(), segmentOptions('trusted'));-describe('segmentString scales linearly', () => {+/** Segment `body` in 256 KiB pushes, keeping only a count (ingest streams segments out; holding them all would time the GC). */+function segmentStreaming(body: string): number {+ const seg = new Segmenter(entry(), segmentOptions('trusted'));+ let n = 0;+ for (let i = 0; i < body.length; i += 256 * 1024) n += seg.push(body.slice(i, i + 256 * 1024)).length;+ return n + seg.finish().length;+}++describe('the segmenter scales linearly', () => {const shapes: Array<[string, (bytes: number) => string, number]> = [['mixed page', prefix, 2 * MB],['short lines', bytes => 'a\n'.repeat(bytes / 2), MB / 2],@@ -51,7 +64,7 @@ describe('segmentString scales linearly', () => {];for (const [name, make, small] of shapes) {test(`${name}: twice the input takes under ${BOUND}x the time`, () => {- const r = ratio(make, small, segmentAll);+ const r = ratio(make, small, segmentStreaming);console.log(`[segmenter-linear] ${name}: ${r.toFixed(2)}x`);expect(r).toBeLessThan(BOUND);}, 120_000);@@ -62,17 +75,13 @@ const STEP = 64 * 1024;/** Append `body` in STEP-char writes, each resegmenting only the last segment from its stored entry state. */function appendResuming(body: string): SegmentOut[] {- let segs: SegmentOut[] = [];- let stored = Buffer.alloc(0);+ const segs: SegmentOut[] = [];for (let at = 0; at < body.length; at += STEP) {- const added = Buffer.from(body.slice(at, at + STEP), 'utf8');const last = segs.pop();- const start = last ? last.byteStart : 0;- const tail = Buffer.concat([stored.subarray(start), added]).toString('utf8');- segs = segs.concat(segmentString(tail, last ? last.entryState : entry(), segmentOptions('trusted', {- byteStart: start, lineStart: last ? last.lineStart : 0,+ const tail = (last ? Buffer.from(last.bytes).toString('utf8') : '') + body.slice(at, at + STEP);+ segs.push(...segmentString(tail, last ? last.entryState : entry(), segmentOptions('trusted', {+ byteStart: last ? last.byteStart : 0, lineStart: last ? last.lineStart : 0,})));- stored = Buffer.concat([stored, added]);}return segs;}diff --git a/test/large-pages/segmenter.test.ts b/test/large-pages/segmenter.test.tsindex d647fc9f03..99f85f9135 100644--- a/test/large-pages/segmenter.test.ts+++ b/test/large-pages/segmenter.test.ts@@ -25,7 +25,7 @@ import { pickHeadPattern } from '../../src/core/conversation-parser/parse.ts';import { initialEntryState, isCleanResumePoint, readEntryState, timelineEntryState } from '../../src/core/page-body/entry-state.ts';import { PEM_CONTEXT_CHARS } from '../../src/core/page-body/region-scan.ts';import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES } from '../../src/core/page-body/limits.ts';-import { regionFlags, segmentStream, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';+import { regionFlags, Segmenter, segmentStream, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';import { mulberry32 } from '../helpers/seeded-random.ts';import {bigPage, FACTS_BLOCK, joinedProjection, KEY_BODY, MARKER_BULLET, PEM_BLOCK, segmentOptions, segmentPieces, segmentShapeErrors, soup,@@ -242,6 +242,18 @@ describe('forced cuts with open state', () => {expect(joinedProjection(Buffer.from(body), segs)).toBe(credentialSafeProjection(sanitizeRemoteBody(body)));});+ test('after a truncated tail, closed segments are released without waiting for EOF', () => {+ const lead = filler(200_000);+ const body = lead + '<!--- gbrain:takes:begin -->\nsecret\n<!--- gbrain:facts:begin -->\n' + filler(4 * MAX);+ const seg = new Segmenter(truthEntry(), segmentOptions('trusted'));+ const early: SegmentOut[] = [];+ for (let i = 0; i < body.length; i += 256 * 1024) early.push(...seg.push(body.slice(i, i + 256 * 1024)));+ const all = [...early, ...seg.finish()];+ expect(early.length).toBeGreaterThanOrEqual(3);+ expect(all.map(fingerprint)).toEqual(segmentString(body, truthEntry(), segmentOptions('trusted')).map(fingerprint));+ expect(regionFlags(all[all.length - 1]!.exitState, 'trusted').protectedTailFrom).toBe(Buffer.byteLength(lead));+ });+test('a protected region crossing a forced cut keeps its full extent on both sides', () => {const lead = filler(900_000);const region = '<!--- gbrain:takes:begin -->\n' + filler(400_000) + '<!--- gbrain:takes:end -->\n';