Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Lane 1b-ii: bounded hold, fail-closed pem_guard release, close-time region metadata; segmenter-linear to the slow lane
garrytan4bbba2c5a5bc
diff --git a/src/core/page-body/region-scan.ts b/src/core/page-body/region-scan.tsindex 33c8cc6df9..b71387b75d 100644--- a/src/core/page-body/region-scan.ts+++ b/src/core/page-body/region-scan.ts@@ -492,6 +492,43 @@ export function takePemCut(st: PemScanState, at: number): { clean: boolean; starreturn st.cuts.splice(i, 1)[0]!.done!;}+/** The answer for a marked cut taken before it resolved: never clean; where a resumed scan restarts. */+export function forcePemCut(st: PemScanState, at: number): { clean: boolean; start: PemStart } {+ const i = st.cuts.findIndex(c => c.at === at);+ const done = i === -1 ? undefined : st.cuts.splice(i, 1)[0]!.done;+ if (done) return done;+ const rel = at - st.base;+ return { clean: false, start: rel <= 0 && st.base >= 0 ? 'region_start' : st.buf.charCodeAt(rel - 1) === 10 ? 'line_start' : 'mid_line' };+}++const PEM_LINE_DONE = /^[ \t]*[A-Za-z0-9+/=]+[ \t]*(?:\r|\\r)?$/;+const PEM_LINE_OPEN = /^[ \t]*[A-Za-z0-9+/=]*[ \t]*(?:\r|\\r?|\\)?$/;++/**+ * The earliest projection offset a span reported after this point could+ * start at, whatever text follows: a fence not yet decided or a BEGIN still+ * waiting for its lookahead, or the run of lines at the end of the text that+ * a later END fence's backward claim could cover (each line one base64 run+ * between indents, as pemBackwardStart reads them; a superset). Spans+ * starting before it have all been reported.+ */+export function pemExposedFrom(st: PemScanState): number {+ const buf = st.buf;+ const end = st.base + buf.length;+ const lo = Math.max(st.base, Math.min(end, pemResolvedTo(st))) - st.base;+ let exposed = Math.min(end, st.find.begin.safe, st.find.end.safe, headFence(st)?.start ?? end);+ let start = buf.length;+ for (let i = buf.length, open = true; i > lo; open = false) {+ let j = i;+ while (j > lo && buf.charCodeAt(j - 1) !== 10 && !(buf.charCodeAt(j - 1) === 110 && buf.charCodeAt(j - 2) === 92)) j--;+ if (!(open ? PEM_LINE_OPEN : PEM_LINE_DONE).test(buf.slice(j, i))) break;+ start = j;+ i = buf.charCodeAt(j - 1) === 10 ? j - 1 : j - 2;+ }+ exposed = Math.min(exposed, start + st.base);+ return Math.max(lo + st.base, exposed);+}+function discoverPem(st: PemScanState, kind: 'begin' | 'end'): void {const re = kind === 'begin' ? BEGIN_RE : END_RE;const prefix = kind === 'begin' ? '-----BEGIN ' : '-----END ';diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.tsindex 1dd039ba49..64dd93b6fb 100644--- a/src/core/page-body/segmenter.ts+++ b/src/core/page-body/segmenter.ts@@ -45,7 +45,7 @@ import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES, SEGMENT_RANK4_BYTES, SEGMENT_TARGimport type { BodyRegion, SegmentCutKind } from './types.ts';import { cloneEntryState, type EntryState } from './entry-state.ts';import {- feedPemScan, findTokens, initialPemScan, markPemCut, newLineSplit, pemBodyLike, pemResolvedTo, PEM_CONTEXT_CHARS,+ feedPemScan, findTokens, forcePemCut, initialPemScan, markPemCut, pemExposedFrom, newLineSplit, pemBodyLike, pemResolvedTo, PEM_CONTEXT_CHARS,PROTECTED_MARKERS, scanRegionLine, scanRegionPiece, splitLines, takePemCut, utf8Len,type Cover, type LineSplit, type PemScanState, type RegionTrack, type ScanOut, type SplitEvent,} from './region-scan.ts';@@ -58,6 +58,8 @@ const GEAR_TOP_BITS = 10;const OUTLINE_MAX_HEADINGS = 64;/** Projection text is handed to the PEM scan in batches of this many chars (its buffer is re-read per feed). */const PEM_FEED_CHARS = 64 * 1024;+/** Closed segments waiting on the PEM lookahead are held up to this many bytes, then released fail closed. */+const HOLD_MAX_BYTES = 2 * SEGMENT_MAX_BYTES;const PEM_FENCE_TAIL = 'PRIVATE KEY-----';const ATX_TOP = /^#{1,2}\s/;const ATX_DEEP = /^#{3,6}\s/;@@ -98,9 +100,20 @@ export interface SegmentOptions {end: 'region_end' | 'eof';}-export type StoredRegionKind = 'facts' | 'takes' | 'tail' | 'marker' | 'pem';+/**+ * `pem_guard`: the end of a segment released before a private-key claim could+ * be ruled out over it (a protected region longer than the hold bound stalled+ * the projection), projected as nothing: never more visible than whole-body+ * sanitization, possibly less.+ */+export type StoredRegionKind = 'facts' | 'takes' | 'tail' | 'marker' | 'pem' | 'pem_guard';-/** A protected run of a segment: segment-relative raw bytes; `open_*` give the full extent in stored-stream bytes when it crosses the segment's bounds (`open_end` absent while unknown). */+/**+ * A protected run of a segment: segment-relative raw bytes; `open_*` give the+ * full extent in stored-stream bytes when it crosses the segment's bounds.+ * `open_end` is set only when the run ends by the segment's end; a run still+ * open there has none, and the segment holding its end carries both.+ */export interface StoredRegion { kind: StoredRegionKind; start: number; end: number; open_start?: number; open_end?: number }/** A facts region of a segment, rendered at read time where its zero-length slot sits in the static projection. */@@ -160,11 +173,22 @@ interface OpenSegment {projStart: number;}-interface ClosedSegment extends OpenSegment { cutKind: SegmentCutKind; exit: EntryState; projEnd: number }+interface ClosedSegment extends OpenSegment {+ cutKind: SegmentCutKind;+ exit: EntryState;+ projEnd: number;+ /** The truncated tail as known at the cut, so stored kinds never depend on when a segment is released. */+ tailFrom: number | null;+}/*** Incremental segmenter for one region: push text, take the segments that are- * final. Memory is O(segment + PEM_CONTEXT_CHARS + one line).+ * final. A closed segment waits until no private-key claim can still start+ * before its end; at a cut, segments held past HOLD_MAX_BYTES are released+ * with a `pem_guard` over what a later claim could still cover. Memory is+ * O(HOLD_MAX_BYTES + segment + PEM_CONTEXT_CHARS). Release decisions are made+ * at cuts, where the PEM scan has read exactly the projection before the cut,+ * so the output does not depend on how the input is pushed.*/export class Segmenter {private readonly st: EntryState;@@ -177,6 +201,7 @@ export class Segmenter {private regionEnds = new Map<number, number>();private cur: OpenSegment;private closed: ClosedSegment[] = [];+ private ready: SegmentOut[] = [];private outline: { fence: boolean; midLine: boolean };private done = false;@@ -215,9 +240,21 @@ export class Segmenter {private close(cutKind: SegmentCutKind): void {const exit = cloneEntryState(this.st);- this.closed.push({ ...this.cur, cutKind, exit, projEnd: this.proj });- if (!this.done) markPemCut(this.pem, this.proj);+ this.closed.push({ ...this.cur, cutKind, exit, projEnd: this.proj, tailFrom: this.actual().truncatedAt });this.cur = this.openSegment(exit, this.cur.byteStart + this.cur.bytes, this.cur.lineStart + this.cur.lines);+ if (this.done) return;+ markPemCut(this.pem, this.proj);+ this.feedPem(false);+ this.release();+ let held = this.closed.reduce((n, seg) => n + seg.bytes, 0);+ while (held > HOLD_MAX_BYTES) {+ const seg = this.closed.shift()!;+ held -= seg.bytes;+ seg.exit.pem = forcePemCut(this.pem, seg.projEnd);+ const exposed = pemExposedFrom(this.pem);+ const guardFrom = exposed >= seg.projEnd ? null : exposed <= seg.projStart || this.projPieces.length === 0 ? seg.byteStart : this.rawAt(exposed, false);+ this.ready.push(this.emit(seg, guardFrom));+ }}private onEvent(e: SplitEvent): void {@@ -410,7 +447,12 @@ export class Segmenter {}private drain(): SegmentOut[] {- const out: SegmentOut[] = [];+ this.release();+ return this.ready.splice(0);+ }++ /** Emit the held segments no private-key claim can still reach, in order. */+ private release(): void {while (this.closed.length) {const seg = this.closed[0]!;let pem = takePemCut(this.pem, seg.projEnd);@@ -418,23 +460,23 @@ export class Segmenter {if (!pem || (!this.done && pemResolvedTo(this.pem) < seg.projEnd)) break;this.closed.shift();seg.exit.pem = pem;- out.push(this.emit(seg));+ this.ready.push(this.emit(seg, null));}- return out;}- private emit(seg: ClosedSegment): SegmentOut {+ private emit(seg: ClosedSegment, guardFrom: number | null): SegmentOut {const raw = seg.parts.join('');const bytes = Buffer.from(raw, 'utf8');const segEnd = seg.byteStart + seg.bytes;- const tailFrom = this.actual().truncatedAt;+ const tailFrom = seg.tailFrom;const regions: StoredRegion[] = [];for (const r of seg.removals) {const kind = tailFrom !== null && r.kind !== 'marker' && r.regionStart >= tailFrom ? 'tail' : r.kind;const region: StoredRegion = { kind, start: r.start - seg.byteStart, end: r.end - seg.byteStart };if (kind !== 'marker') {- const regionEnd = kind === 'tail' ? undefined : this.regionEnds.get(r.regionStart);- if (r.regionStart < seg.byteStart || regionEnd === undefined || regionEnd > segEnd) {+ const known = kind === 'tail' ? undefined : this.regionEnds.get(r.regionStart);+ const regionEnd = known !== undefined && known <= segEnd ? known : undefined;+ if (r.regionStart < seg.byteStart || regionEnd === undefined) {region.open_start = r.regionStart;if (regionEnd !== undefined) region.open_end = regionEnd;else if (kind === 'tail' && seg.cutKind === this.opts.end && this.done) region.open_end = segEnd;@@ -448,6 +490,7 @@ export class Segmenter {if (s.start < seg.byteStart || s.end > segEnd) { region.open_start = s.start; region.open_end = s.end; }regions.push(region);}+ if (guardFrom !== null && guardFrom < segEnd) regions.push({ kind: 'pem_guard', start: guardFrom - seg.byteStart, end: seg.bytes });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);@@ -578,7 +621,8 @@ export interface ProjectionPart {/*** A segment's static projection in parts, from its raw text and stored- * regions: text kept, takes / tail / marker runs removed, facts runs as+ * regions: text kept, takes / tail / marker / pem_guard runs removed (a+ * removal that overlaps an earlier part removes its remainder), facts runs as* slots (`text` holds the raw fence for read-time rendering), and each* private-key span as the projection token (in the segment where the span* starts) plus the newlines of its projected text. `byteStart` is the@@ -595,7 +639,13 @@ export function segmentProjectionParts(raw: string, regions: readonly StoredRegicharAt.set(0, 0);for (let i = 0; i < sorted.length; i++) {const r = sorted[i]!;- if (r.start < cursor) continue;+ if (r.end <= cursor) continue;+ if (r.start < cursor) {+ if (r.kind === 'facts' || r.kind === 'pem') continue;+ parts.push({ kind: 'removed', start: cursor, end: r.end, text: '', region: r });+ cursor = r.end;+ continue;+ }text(r.start);const from = charAt.get(r.start)!;const to = charAt.get(r.end)!;diff --git a/test/large-pages/segmenter-linear.test.ts b/test/large-pages/segmenter-linear.slow.test.tssimilarity index 100%rename from test/large-pages/segmenter-linear.test.tsrename to test/large-pages/segmenter-linear.slow.test.tsdiff --git a/test/large-pages/segmenter.test.ts b/test/large-pages/segmenter.test.tsindex 99f85f9135..862ce796f6 100644--- a/test/large-pages/segmenter.test.ts+++ b/test/large-pages/segmenter.test.ts@@ -28,7 +28,7 @@ import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES } from '../../src/core/page-body/limport { 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,+ bigPage, FACTS_BLOCK, joinedProjection, KEY_BODY, MARKER_BULLET, PEM_BLOCK, pick, segmentOptions, segmentPieces, segmentShapeErrors, soup,} from '../helpers/segment-bodies.ts';const MAX = SEGMENT_MAX_BYTES;@@ -42,6 +42,17 @@ const fingerprint = (s: SegmentOut) => JSON.stringify({});const KEY_COUNT = (s: string) => s.split(KEY_BODY).length - 1;+/** Whether `a` is `b` with some characters deleted (shows nothing `b` does not). */+function isSubsequence(a: string, b: string): boolean {+ let j = 0;+ for (let i = 0; i < a.length; i++) {+ j = b.indexOf(a[i]!, j);+ if (j === -1) return false;+ j++;+ }+ return true;+}+function filler(bytes: number): string {const line = 'plain words without structure '.repeat(3) + '\n';return line.repeat(Math.ceil(bytes / line.length));@@ -228,16 +239,18 @@ describe('forced cuts with open state', () => {expect(segs.slice(0, -1).every(s => s.cutKind === 'forced')).toBe(true);});- test('an unterminated protected region becomes the truncated tail; later segments project nothing', () => {+ test('an unterminated protected region: open takes runs, the truncated tail at EOF, later segments project nothing', () => {const lead = filler(200_000);const body = lead + '<!--- gbrain:takes:begin -->\n' + ('## secret heading\n\n' + filler(1_000)).repeat(3_000);const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));const flags = regionFlags(segs[segs.length - 1]!.exitState, 'trusted');expect(flags.protectedTailFrom).toBe(Buffer.byteLength(lead));expect(segs.length).toBeGreaterThan(2);- for (const s of segs.slice(1)) {+ for (const [i, s] of segs.entries()) {+ if (i === 0) continue;expect(s.staticProjBytes).toBe(0);- expect(s.protectedRegions).toEqual([expect.objectContaining({ kind: 'tail', start: 0, end: s.bytes.length, open_start: Buffer.byteLength(lead) })]);+ const kind = i === segs.length - 1 ? 'tail' : 'takes';+ expect(s.protectedRegions).toEqual([expect.objectContaining({ kind, start: 0, end: s.bytes.length, open_start: Buffer.byteLength(lead) })]);}expect(joinedProjection(Buffer.from(body), segs)).toBe(credentialSafeProjection(sanitizeRemoteBody(body)));});@@ -254,7 +267,57 @@ describe('forced cuts with open state', () => {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', () => {+ for (const [name, open, close] of [+ ['an unterminated takes block', '<!--- gbrain:takes:begin -->\n', ''],+ ['a closed takes block', '<!--- gbrain:takes:begin -->\n', '<!--- gbrain:takes:end -->\n'],+ ['a giant facts fence', '<!--- gbrain:facts:begin -->\n', '<!--- gbrain:facts:end -->\n'],+ ] as const) {+ test(`${name} longer than the hold bound: segments leave as they close, the same for any feed chunking`, () => {+ const body = filler(200_000) + KEY_BODY + '\n' + open + filler(12 * MAX) + close + '## after\n' + filler(300_000);+ const seg = new Segmenter(truthEntry(), segmentOptions('trusted'));+ const early: SegmentOut[] = [];+ let maxHeld = 0;+ for (let i = 0; i < body.length; i += 256 * 1024) {+ early.push(...seg.push(body.slice(i, i + 256 * 1024)));+ const closed = Buffer.byteLength(body.slice(0, Math.min(body.length, i + 256 * 1024))) - early.reduce((n, x) => n + x.bytes.length, 0);+ maxHeld = Math.max(maxHeld, closed);+ }+ const all = [...early, ...seg.finish()];+ expect(maxHeld).toBeLessThanOrEqual(4 * MAX);+ expect(all.map(fingerprint)).toEqual(segmentString(body, truthEntry(), segmentOptions('trusted')).map(fingerprint));+ const r = mulberry32(name.length);+ expect(all.map(fingerprint)).toEqual(segmentPieces(body, segmentOptions('trusted'), () => 1 + Math.floor(r() * 400_000)).map(fingerprint));+ const bytes = Buffer.from(body, 'utf8');+ expect(segmentShapeErrors(bytes, all, MAX)).toEqual([]);+ expect(isSubsequence(joinedProjection(bytes, all), credentialSafeProjection(sanitizeRemoteBody(body)))).toBe(true);+ }, 60_000);+ }++ test('released early, a segment never shows what whole-body sanitization hides (key lines around giant regions)', () => {+ const r = mulberry32(91);+ const keyish = [`${KEY_BODY}\n`, ` ${KEY_BODY.slice(0, 40)}\n`, 'prose line here\n', '\n', '-----BEGIN RSA PRIVATE KEY-----\n',+ '-----END RSA PRIVATE KEY-----\n', `"k": "${KEY_BODY}\\n${KEY_BODY}\\n`, 'é😀\n', '## heading\n'];+ const regions = [['<!--- gbrain:takes:begin -->\n', '<!--- gbrain:takes:end -->\n'], ['<!--- gbrain:takes:begin -->\n', ''],+ ['<!--- gbrain:facts:begin -->\n', '<!--- gbrain:facts:end -->\n']];+ let guarded = 0;+ for (let t = 0; t < 12; t++) {+ const around = (n: number) => Array.from({ length: n }, () => pick(r, keyish)).join('');+ const [open, close] = pick(r, regions);+ const body = filler(Math.floor(r() * 300_000)) + around(1 + Math.floor(r() * 12)) + open + filler(Math.floor((2.5 + r() * 2) * MAX))+ + (close ? close + around(1 + Math.floor(r() * 12)) + filler(Math.floor(r() * 300_000)) : '');+ const bytes = Buffer.from(body, 'utf8');+ const segs = segmentPieces(body, segmentOptions(trustOf(body)), () => 1 + Math.floor(r() * 500_000));+ const want = credentialSafeProjection(sanitizeRemoteBody(body));+ const got = joinedProjection(bytes, segs);+ expect(isSubsequence(got, want)).toBe(true);+ expect(KEY_COUNT(got)).toBeLessThanOrEqual(KEY_COUNT(want));+ if (segs.some(s => s.protectedRegions.some(x => x.kind === 'pem_guard'))) guarded++;+ else if (!open.includes('facts')) expect(got).toBe(want);+ }+ expect(guarded).toBeGreaterThan(0);+ });++ test('a protected region crossing a forced cut: its start on both sides, its end where it ends', () => {const lead = filler(900_000);const region = '<!--- gbrain:takes:begin -->\n' + filler(400_000) + '<!--- gbrain:takes:end -->\n';const body = lead + region + filler(10_000);@@ -262,8 +325,7 @@ describe('forced cuts with open state', () => {const start = Buffer.byteLength(lead);const end = start + Buffer.byteLength(region) - 1;const parts = segs.flatMap(s => s.protectedRegions.filter(r => r.kind === 'takes').map(r => ({ ...r, segStart: s.byteStart })));- expect(parts.length).toBe(2);- for (const p of parts) expect([p.open_start, p.open_end]).toEqual([start, end]);+ expect(parts.map(p => [p.open_start, p.open_end])).toEqual([[start, undefined], [start, end]]);});});