Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): bullet-aligned timeline passages in the segmented chunker (v5)

garrytan95bf7db52ea7
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 812f222c59..e72051e425 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -40,6 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/chunkers/def-types.ts` — `DEF_TYPES`: the ONE list of definition-shaped normalized (post-`normalizeSymbolType`) symbol types, shared by `gbrain code-def`'s lookup allowlist (`src/commands/code-def.ts` re-exports it) and the code chunker's small-sibling merge guard so the two can't drift — a symbol type code-def can resolve never has its `symbol_name` erased by merging a small definition into a neighbor. Includes the fallthrough forms `normalizeSymbolType` emits verbatim for tree-sitter node types it doesn't canonicalize (`'method declaration'`, `'struct specifier'`, `'record declaration'`, …) — most of an OO codebase's symbols arrive in those forms. Pinned by `test/chunkers/code-merge-defs.test.ts`.
+- `src/core/chunkers/bullet-chunks.ts` — `chunkTimelineBullets(text, {maxTokens})`: the segmented chunker's passages for a timeline segment with bullet lines (`prepareSegmentChunks`, SEGMENTED_CHUNKER_VERSION 5). A passage breaks only at a bullet start chosen by a hash of that bullet and its word count, so an entry added at the top changes at most two passages; a run over the size bound re-splits and merges back from its end; a single over-limit bullet falls back to `chunkProjectedText` with `boundaryCuts`. No overlap. Returns null for text with no bullet line (the caller chunks it as before). `bulletChunkWork` counts units and runs for the linearity test.
- `src/core/chunkers/recursive.ts` — base chunker: 300-word chunks, 50-word sentence-aware overlap, 5-level delimiter hierarchy. Applies `sanitizeRemoteBody` and then `credentialSafeProjection` (`src/core/credential-projection.ts`) before splitting, so only world Facts and ordinary prose enter retrieval text and private keys enter only as `<REDACTED:private_key_pem>`; all Takes and malformed protected sections are omitted. Non-overlapping portions reassemble to that sanitized input. The overlap extractor counts chars (not whitespace tokens) for CJK-dominant chunks — same unit as `countWords` — and aligns to `。!?` or a whitespace-followed ASCII `.!?`; the L4 char-slice fallback advances through `safeSplitIndex` so astral pairs (emoji, non-BMP CJK) are never halved. Both are gated on `isCJKDominant`, so English output is byte-identical (pinned by `test/chunkers/recursive-cjk-overlap.test.ts`). The hard cap skips the token count for a chunk whose UTF-8 byte length already fits the token budget (`fitsEmbedTokens` in `token-estimate.ts`: bytes bound both the cl100k count and the weighted CJK estimate), so typical CJK chunks never reach the tiktoken WASM; boundaries are unchanged (`test/chunkers/fits-embed-tokens.test.ts`). The markdown chunker version records the current index format. With `spans: true` each chunk carries `byte_start`/`byte_end`, its exact UTF-8 span in the sanitized, credential-projected text; markdown prose chunks store them as `content_chunks.projected_byte_start/end`.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d399593f50..dcb0a48ede 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1026,7 +1026,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// PR 4 E (one provider call per chunk content version, gbrain-evals#180). `since` is stamped at the merge slot.
{ since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },
// PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
- { since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },
+ { since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search; and their timeline passages break only between bullet entries, at entries chosen by their own text, so an entry added at the top of the timeline re-embeds at most two passages instead of every passage after it. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },
// PR 4 4e (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
{ since: 'TBD', text: 'New transcript sessions import as one page; existing split sessions stop rewriting every part when a session grows. `gbrain transcripts ingest` writes a session with no part pages as one page up to the page ceiling (`pages.max_bytes` or the content-sanity block line, whichever is lower), at its base slug with the same `<id>-p1` identity; only a message or session over that ceiling continues into `-pN` pages. A session already split into parts keeps them and their grouping. The part count left hashed content (titles read `(part X)`, `transcript_import.of` is gone and `part_bytes` records the part size), so each part is rewritten once on its next import; after that a grown session changes only its last part or adds one. Nothing merges a split session into one page.' },
// PR 4 (Wave B incremental derivation, transcripts)
diff --git a/src/core/chunkers/bullet-chunks.ts b/src/core/chunkers/bullet-chunks.ts
new file mode 100644
index 0000000000..6339fd25d1
--- /dev/null
+++ b/src/core/chunkers/bullet-chunks.ts
@@ -0,0 +1,132 @@
+/**
+ * Bullet-aligned passages for the timeline region of a segmented page (Wave B PR 4, lane recall; #7172 follow-up).
+ *
+ * The recursive chunker packs about 300 words greedily with a 50-word overlap, so in a descending timeline of uniform
+ * bullets an entry added at the top moves every passage boundary below it, and each moved passage is new text the
+ * embedder is paid for again. Here a timeline passage breaks only at a bullet start, and where it breaks depends only on
+ * the bullet that starts there: a passage starts at bullet b when hash(b) < 2^32 * min(1, words(b) / target), so
+ * passages average `target` words whatever the bullet length, and a new bullet can change only the passage it joins
+ * (or start one of its own). A run over the size bound is split again at a quarter of the target, and so on, and its
+ * pieces merge back from the run's end while they fit, so an entry at the top of a long run changes only its top piece
+ * and at most one piece more; a run of one bullet over the bound falls back to the hard-capped chunker (`chunkProjectedText` with `boundaryCuts`).
+ * Passages carry no overlap, so a change in one never rewrites the next. A region with no bullet line is not handled
+ * here (null): the caller chunks it as before.
+ */
+import { countCJKAwareWords } from '../cjk.ts';
+import { chunkProjectedText, utf16ToUtf8Offsets, type TextChunk } from './recursive.ts';
+import { DEFAULT_MAX_CHUNK_TOKENS, fitsEmbedTokens } from './token-estimate.ts';
+
+/** Words a timeline passage averages; the size bound is the recursive chunker's merge limit (1.5x), chars and tokens. */
+const TARGET_WORDS = 300;
+const LIMIT_WORDS = Math.ceil(TARGET_WORDS * 1.5);
+const MAX_CHARS = 6000;
+/** Past this many re-splits every bullet starts a passage (a run of zero-word bullets would never meet the hash rule). */
+const MAX_LEVEL = 6;
+/** A top-level list item: `- `, `* ` or `+ ` at a line start followed by text; indented lines continue the item above. */
+const BULLET = /^[-*+][ \t]+\S/;
+
+/** @internal Units hashed and runs measured, for the linearity test (counts, not time). */
+export const bulletChunkWork = { units: 0, runs: 0 };
+
+/** One bullet with its continuation lines; the first also holds the text before it. `key` hashes the bullet alone. */
+interface Unit { start: number; end: number; key: number; words: number }
+
+function fnv1a(text: string, from: number, to: number): number {
+ let h = 0x811c9dc5;
+ for (let i = from; i < to; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h >>> 0;
+}
+
+function units(text: string): Unit[] | null {
+ const starts: number[] = [];
+ for (let at = 0; at < text.length;) {
+ const nl = text.indexOf('\n', at);
+ const end = nl < 0 ? text.length : nl;
+ if (BULLET.test(text.slice(at, Math.min(end, at + 4)))) starts.push(at);
+ at = end + 1;
+ }
+ if (!starts.length) return null;
+ return starts.map((bullet, i) => {
+ const end = i + 1 < starts.length ? starts[i + 1]! : text.length;
+ let last = end;
+ while (last > bullet && /\s/.test(text[last - 1]!)) last--;
+ bulletChunkWork.units++;
+ return { start: i === 0 ? 0 : bullet, end, key: fnv1a(text, bullet, last), words: countCJKAwareWords(text.slice(bullet, end)) };
+ });
+}
+
+/**
+ * Passages of a timeline region's projected text, with UTF-8 spans as chunkProjectedText returns them; null when the
+ * text has no bullet line.
+ */
+export function chunkTimelineBullets(text: string, opts: { maxTokens?: number } = {}): TextChunk[] | null {
+ if (!text.trim()) return [];
+ const list = units(text);
+ if (!list) return null;
+ const maxTokens = opts.maxTokens && opts.maxTokens > 0 ? Math.min(opts.maxTokens, DEFAULT_MAX_CHUNK_TOKENS) : DEFAULT_MAX_CHUNK_TOKENS;
+ const words = [0];
+ for (const unit of list) words.push(words[words.length - 1]! + unit.words);
+ const runs: Array<[number, number]> = [];
+ const fits = (from: number, to: number) => {
+ bulletChunkWork.runs++;
+ const start = list[from]!.start, end = list[to - 1]!.end;
+ return words[to]! - words[from]! <= LIMIT_WORDS && end - start <= MAX_CHARS && fitsEmbedTokens(text.slice(start, end).trim(), maxTokens);
+ };
+ const starts = (from: number, to: number, level: number) => {
+ const target = TARGET_WORDS / 4 ** level;
+ const out = [from];
+ for (let k = from + 1; k < to; k++) {
+ const unit = list[k]!;
+ if (level >= MAX_LEVEL || unit.key < 2 ** 32 * Math.min(1, unit.words / target)) out.push(k);
+ }
+ out.push(to);
+ return out;
+ };
+ // A run over the bound splits at the next level's bullets, and its pieces merge again from the run's end while they
+ // fit: an entry added at the top of the run then changes its top piece, and the pieces below keep their text.
+ const refine = (from: number, to: number, level: number): Array<[number, number]> => {
+ if (to - from === 1 || fits(from, to)) return [[from, to]];
+ const cuts = starts(from, to, level);
+ const pieces = cuts.slice(0, -1).flatMap((at, i) => refine(at, cuts[i + 1]!, level + 1));
+ const merged: Array<[number, number]> = [];
+ for (let i = pieces.length - 1; i >= 0; i--) {
+ const last = merged[merged.length - 1];
+ if (last && fits(pieces[i]![0], last[1])) last[0] = pieces[i]![0];
+ else merged.push([pieces[i]![0], pieces[i]![1]]);
+ }
+ return merged.reverse();
+ };
+ // Level-0 starts are never merged across: they depend on their bullet alone.
+ const top = starts(0, list.length, 0);
+ for (let i = 0; i + 1 < top.length; i++) runs.push(...refine(top[i]!, top[i + 1]!, 1));
+
+ const pieces: Array<{ text: string; start: number; end: number } | { inner: TextChunk[]; base: number }> = [];
+ const offsets: number[] = [];
+ for (const [from, to] of runs) {
+ const start = list[from]!.start, end = list[to - 1]!.end;
+ const raw = text.slice(start, end);
+ const body = raw.trim();
+ if (!body) continue;
+ if (to - from === 1 && !fits(from, to)) {
+ pieces.push({ inner: chunkProjectedText(raw, { maxTokens, spans: true, boundaryCuts: true }), base: start });
+ offsets.push(start);
+ continue;
+ }
+ const lead = raw.length - raw.trimStart().length;
+ pieces.push({ text: body, start: start + lead, end: start + lead + body.length });
+ offsets.push(start + lead, start + lead + body.length);
+ }
+ const bytes = utf16ToUtf8Offsets(text, offsets);
+ const out: TextChunk[] = [];
+ for (const piece of pieces) {
+ if ('inner' in piece) {
+ const base = bytes.get(piece.base)!;
+ for (const c of piece.inner) out.push({ text: c.text, index: out.length,
+ ...(c.byte_start !== undefined && c.byte_end !== undefined ? { byte_start: base + c.byte_start, byte_end: base + c.byte_end } : {}) });
+ } else out.push({ text: piece.text, index: out.length, byte_start: bytes.get(piece.start), byte_end: bytes.get(piece.end) });
+ }
+ return out;
+}
diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.ts
index 8793ea1cc6..c3efdbd72f 100644
--- a/src/core/page-body/segment-chunks.ts
+++ b/src/core/page-body/segment-chunks.ts
@@ -21,6 +21,7 @@
* Inline pages keep prepareMarkdownChunks; this is a separate chunker identity.
*/
import { chunkProjectedText, chunkText } from '../chunkers/recursive.ts';
+import { chunkTimelineBullets } from '../chunkers/bullet-chunks.ts';
import { estimateEmbedTokens } from '../chunkers/token-estimate.ts';
import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';
import { fencedCodeChunks, newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';
@@ -37,7 +38,9 @@ import { projectSegment } from './segment-projection.ts';
* stays at or above SAFE_FENCE_CHUNKER_VERSION, but it is its own identity: inline pages keep MARKDOWN_CHUNKER_VERSION.
*
* 5: the hard cap's forced cuts land on a sentence or line end (chunkProjectedText `boundaryCuts`), so a sentence the
- * cap used to split now sits whole in one chunk. Pages sealed at 4 keep serving their chunks until
+ * cap used to split now sits whole in one chunk; and a timeline segment with bullet lines breaks only at bullet starts
+ * chosen by the bullet itself (chunkers/bullet-chunks.ts), so an entry added at the top changes only the passage it joins.
+ * Pages sealed at 4 keep serving their chunks until
* `gbrain reindex --segmented --apply` re-chunks them (page-body/rechunk.ts). A change to the cuts or the stored
* per-segment metadata bumps SEGMENTER_VERSION instead.
*/
@@ -90,7 +93,9 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segm
const wholeSegment = { raw_byte_start: 0, raw_byte_end: segment.bytes.length };
if (projection.trim()) {
- for (const c of chunkProjectedText(projection, { maxTokens, spans: true, headingsLead: true, boundaryCuts: true })) {
+ const prose = (segment.region === 'timeline' ? chunkTimelineBullets(projection, { maxTokens }) : null)
+ ?? chunkProjectedText(projection, { maxTokens, spans: true, headingsLead: true, boundaryCuts: true });
+ for (const c of prose) {
if (c.byte_start === undefined || c.byte_end === undefined) {
push({ chunk_text: c.text, chunk_source: source, ...wholeSegment });
continue;
diff --git a/test/helpers/timeline-bullets.ts b/test/helpers/timeline-bullets.ts
new file mode 100644
index 0000000000..4e8318ad41
--- /dev/null
+++ b/test/helpers/timeline-bullets.ts
@@ -0,0 +1,22 @@
+/**
+ * A descending timeline of uniform bullets (placeholder sources and names), the shape where the recursive chunker's
+ * greedy 300-word packing moves every passage boundary when an entry is added at the top (#7172 follow-up).
+ * Used by test/large-pages/timeline-bullet-chunks.test.ts and test/large-pages/timeline-top-insert-reembed.test.ts.
+ */
+import { mulberry32 } from './seeded-random.ts';
+
+const WORDS = ('launch pricing roadmap hiring metrics retention design latency budget customer review shipped meeting '
+ + 'acme-example alice-example partner deck notes').split(' ');
+
+/** One bullet dated by `day` (days after 2020-01-01), 18 to 23 filler words after the date and source. */
+export function timelineBullet(r: () => number, day: number): string {
+ const date = new Date(Date.UTC(2020, 0, 1 + day)).toISOString().slice(0, 10);
+ return `- **${date}** | source-a — ${Array.from({ length: 18 + Math.floor(r() * 6) }, () => WORDS[Math.floor(r() * WORDS.length)]).join(' ')}`;
+}
+
+/** `n` bullets newest first, and the entry a later write adds above them. */
+export function descendingTimeline(seed: number, n = 55): { bullets: string[]; top: string } {
+ const r = mulberry32(seed);
+ const bullets = Array.from({ length: n }, (_, i) => timelineBullet(r, 1000 - i));
+ return { bullets, top: timelineBullet(r, 1001) };
+}
diff --git a/test/large-pages/timeline-bullet-chunks.test.ts b/test/large-pages/timeline-bullet-chunks.test.ts
new file mode 100644
index 0000000000..1279beea75
--- /dev/null
+++ b/test/large-pages/timeline-bullet-chunks.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Bullet-aligned timeline passages in the segmented chunker (chunkers/bullet-chunks.ts; Wave B PR 4 lane recall, #7172
+ * follow-up).
+ *
+ * 1. Protects: a timeline segment with bullet lines breaks only at bullet starts the bullet itself chooses, so an entry
+ * added at the top of a 55-bullet descending timeline leaves every passage but at most two (the one it joins and one
+ * neighbour) byte for byte the same; passages fit maxChunkTokens and their spans tile the segment; a timeline
+ * without bullet lines and every truth segment chunk exactly as before; the work is linear in the bullets.
+ * 2. Fails when: timeline passages pack greedily (a top entry shifts every boundary: the recursive chunker rewrites all
+ * 4 passages for 184 of these 200 seeds), carry overlap, or a run re-split for size rewrites more than its top
+ * piece; or bullet alignment leaks into truth segments or bullet-free timelines.
+ * 3. Engines: test/large-pages/timeline-top-insert-reembed.test.ts counts embedder inputs on PGLite and Postgres.
+ * 4. No production seam: pure functions.
+ */
+import { describe, expect, test } from 'bun:test';
+import { bulletChunkWork, chunkTimelineBullets } from '../../src/core/chunkers/bullet-chunks.ts';
+import { chunkProjectedText } from '../../src/core/chunkers/recursive.ts';
+import { estimateEmbedTokens } from '../../src/core/chunkers/token-estimate.ts';
+import { initialEntryState, timelineEntryState } from '../../src/core/page-body/entry-state.ts';
+import { segmentString } from '../../src/core/page-body/segmenter.ts';
+import { prepareSegmentChunks } from '../../src/core/page-body/segment-chunks.ts';
+import { descendingTimeline } from '../helpers/timeline-bullets.ts';
+import { segmentOptions } from '../helpers/segment-bodies.ts';
+
+const SEGMENTED = { maxTokens: 2000, spans: true, headingsLead: true, boundaryCuts: true } as const;
+const fresh = (before: readonly string[], after: readonly string[]) => { const old = new Set(before); return after.filter(t => !old.has(t)).length; };
+
+async function segmentChunks(text: string, region: 'truth' | 'timeline') {
+ const entry = region === 'truth' ? initialEntryState({ region }) : timelineEntryState(initialEntryState({ region: 'truth' }));
+ const segments = segmentString(text, entry, segmentOptions('trusted'));
+ expect(segments.length).toBe(1);
+ return { segment: segments[0]!, chunks: await prepareSegmentChunks(segments[0]!, { fenceTrust: 'trusted' }) };
+}
+
+describe('timeline passages break at bullet starts', () => {
+ test('a top entry in a 55-bullet descending timeline changes at most 2 passages, for each of 200 seeds', () => {
+ let oldRewritesAll = 0;
+ for (let seed = 1; seed <= 200; seed++) {
+ const { bullets, top } = descendingTimeline(seed);
+ const before = bullets.join('\n') + '\n', after = [top, ...bullets].join('\n') + '\n';
+ const passages = chunkTimelineBullets(after)!.map(c => c.text);
+ expect(fresh(chunkTimelineBullets(before)!.map(c => c.text), passages)).toBeLessThanOrEqual(2);
+ for (const p of passages) expect(p.startsWith('- **')).toBe(true);
+ const old = chunkProjectedText(after, SEGMENTED).map(c => c.text);
+ if (fresh(chunkProjectedText(before, SEGMENTED).map(c => c.text), old) === old.length) oldRewritesAll++;
+ }
+ expect(oldRewritesAll).toBe(184);
+ });
+
+ test('a timeline segment chunks into bullet-aligned passages that fit the token cap and tile the segment', async () => {
+ const { bullets } = descendingTimeline(7);
+ const text = '## Timeline\n\n' + bullets.join('\n') + '\n';
+ for (const max of [2000, 256]) {
+ const segments = segmentString(text, timelineEntryState(initialEntryState({ region: 'truth' })), segmentOptions('trusted'));
+ const chunks = await prepareSegmentChunks(segments[0]!, { fenceTrust: 'trusted', maxChunkTokens: max });
+ const bytes = Buffer.from(text);
+ expect(chunks[0]!.projected_byte_start).toBe(0);
+ for (let i = 0; i < chunks.length; i++) {
+ const c = chunks[i]!;
+ expect(estimateEmbedTokens(c.chunk_text)).toBeLessThanOrEqual(max);
+ expect(c.chunk_source).toBe('timeline');
+ expect(bytes.subarray(c.projected_byte_start!, c.projected_byte_end!).toString()).toBe(c.chunk_text);
+ if (i > 0) {
+ expect(c.chunk_text.startsWith('- **')).toBe(true);
+ expect(bytes.subarray(chunks[i - 1]!.projected_byte_end!, c.projected_byte_start!).toString().trim()).toBe('');
+ }
+ }
+ expect(chunks[chunks.length - 1]!.projected_byte_end).toBe(Buffer.byteLength(text.trimEnd()));
+ }
+ });
+
+ test('truth segments and timelines without bullet lines chunk exactly as before', async () => {
+ const { bullets } = descendingTimeline(11);
+ const withBullets = bullets.join('\n') + '\n';
+ const prose = bullets.map(b => b.slice(2)).join('\n\n') + '\n';
+ for (const [text, region] of [[withBullets, 'truth'], [prose, 'timeline'], [prose, 'truth']] as const) {
+ const { chunks } = await segmentChunks(text, region);
+ expect(chunks.map(c => [c.chunk_text, c.projected_byte_start, c.projected_byte_end]))
+ .toEqual(chunkProjectedText(text, SEGMENTED).map(c => [c.text, c.byte_start, c.byte_end]));
+ }
+ expect(chunkTimelineBullets(prose)).toBeNull();
+ });
+
+ test('a bullet over the size bound falls back to the hard-capped chunker inside its own span', () => {
+ const { bullets } = descendingTimeline(13, 6);
+ const giant = '- **2020-01-01** | source-a — ' + 'the acme-example review covered latency and budget at length. '.repeat(400);
+ const text = [bullets[0], giant, ...bullets.slice(1)].join('\n') + '\n';
+ const chunks = chunkTimelineBullets(text, { maxTokens: 512 })!;
+ for (const c of chunks) expect(estimateEmbedTokens(c.text)).toBeLessThanOrEqual(512);
+ expect(chunks.filter(c => c.text.includes('acme-example review')).length).toBeGreaterThan(2);
+ const bytes = Buffer.from(text);
+ for (const c of chunks) expect(bytes.subarray(c.byte_start!, c.byte_end!).toString()).toBe(c.text);
+ });
+
+ test('work is linear in the bullets: each is hashed once and runs measured stay a small multiple of them', () => {
+ const measure = (n: number) => {
+ const r = descendingTimeline(17, n).bullets.join('\n') + '\n';
+ bulletChunkWork.units = 0;
+ bulletChunkWork.runs = 0;
+ chunkTimelineBullets(r);
+ return { ...bulletChunkWork };
+ };
+ const small = measure(4000), large = measure(8000);
+ expect(small.units).toBe(4000);
+ expect(large.units).toBe(8000);
+ expect(large.runs / large.units).toBeLessThan(2);
+ expect(large.runs / small.runs).toBeLessThan(2.1);
+ });
+});
diff --git a/test/large-pages/timeline-top-insert-reembed.test.ts b/test/large-pages/timeline-top-insert-reembed.test.ts
new file mode 100644
index 0000000000..d6100726fd
--- /dev/null
+++ b/test/large-pages/timeline-top-insert-reembed.test.ts
@@ -0,0 +1,73 @@
+/**
+ * An entry added at the top of a segmented page's timeline re-embeds at most two passages (Wave B PR 4 lane recall,
+ * #7172 follow-up; pure coverage in timeline-bullet-chunks.test.ts).
+ *
+ * 1. Protects: timeline passages break at bullet starts chosen by the bullet alone (chunkers/bullet-chunks.ts), so when
+ * a write adds an entry above a 55-bullet descending timeline the rewritten timeline segment keeps every other
+ * passage's text, segment vector reuse copies their vectors, and the embedder is sent at most 2 inputs. The truth
+ * region (1.3 MB) is untouched and embeds nothing.
+ * 2. Fails when: the timeline packs greedily with overlap (chunkProjectedText): every boundary moves under a top entry
+ * and all 4 timeline passages are embedded again.
+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The embedder is a counting fake; nothing is paid.
+ */
+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 { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { runEmbedCore } from '../../src/commands/embed.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { TIMELINE_SEPARATOR } from '../../src/core/page-window/document.ts';
+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { descendingTimeline } from '../helpers/timeline-bullets.ts';
+
+const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer'];
+const paragraph = (k: number) => [`para${k}`, ...Array.from({ length: 98 }, (_, i) => WORDS[(k * 7 + i) % WORDS.length])].join(' ') + '.';
+
+for (const kind of testBackends()) {
+ describe(`timeline top entry re-embeds at most two passages (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const embedded: string[] = [];
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ const dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;
+ await engine.setConfig('pages.segmented_storage', 'on');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };
+ }) as never);
+ }, 120_000);
+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); });
+
+ test('a 55-bullet timeline gains a top entry: at most 2 embedder inputs, all timeline passages', async () => {
+ let truth = '';
+ for (let k = 0; Buffer.byteLength(truth) < 1_300_000; k++) truth += paragraph(k) + '\n\n';
+ const { bullets, top } = descendingTimeline(3);
+ const page = (entries: string[]) => `---\ntitle: Acme example\ntype: company\n---\n\n${truth.trimEnd()}${TIMELINE_SEPARATOR}${entries.join('\n')}\n`;
+ const slug = 'companies/acme-example-timeline';
+ await importFromContent(engine, slug, page(bullets), { noEmbed: true });
+ const [row] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug = $1', [slug]);
+ expect(row!.body_storage).toBe('segmented');
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(embedded.filter(t => t.includes('| source-a —')).length).toBeGreaterThanOrEqual(4);
+
+ embedded.length = 0;
+ await importFromContent(engine, slug, page([top, ...bullets]), { noEmbed: true });
+ await runEmbedCore(engine, { stale: true, quiet: true });
+ expect(embedded.length).toBeGreaterThanOrEqual(1);
+ expect(embedded.length).toBeLessThanOrEqual(2);
+ expect(embedded.some(t => t.includes(top.slice(2, 40)))).toBe(true);
+ for (const t of embedded) expect(t).toContain('| source-a —');
+ }, 300_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index e6d54fed85..0f31328401 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -186,6 +186,7 @@ test/large-pages/segmented-withdrawn-fence-delete.test.ts
test/large-pages/streamed-import-drift.test.ts
test/large-pages/streamed-sync-origin-b14.test.ts
test/large-pages/stuck-recovery-large.slow.test.ts
+test/large-pages/timeline-top-insert-reembed.test.ts
test/large-pages/upload-binding.test.ts
test/large-pages/upload-over-ceiling.test.ts
test/large-pages/upload-review.test.ts