Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane 2e: work counters, linearity test, reader baseline, ceilings and docs for streamed derived passes

garrytanfc1961b4d774
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 6b2e763af1..ef4c205054 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -30,7 +30,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
-- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). The job also carries the stable session `put_page:<slug>` (mirrors sync's `sync:<slug>`), so a re-extraction of the page feeds the #6333 `would_dedup_same_page` shadow counter and the facts it writes record that `source_session` (visible to `recall --session`). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Wave B: a write stored segmented (`stringWriteStorage`) skips with `page_body_segmented` and queues no effect, and `readFactsBackstopJobPage` returns that skip for a segmented page, so a facts-absorb job never reads its throwing body (`test/large-pages/segmented-derived-work.test.ts`). Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.
+- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). The job also carries the stable session `put_page:<slug>` (mirrors sync's `sync:<slug>`), so a re-extraction of the page feeds the #6333 `would_dedup_same_page` shadow counter and the facts it writes record that `source_session` (visible to `recall --session`). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Wave B PR 2: a segmented page queues the effect like an inline one (`bodyAlreadyOffered` is false for a segmented prior or an unread body); the facts-absorb job hands the backstop the page's bounded `truthLead` and its id, and `runPipeline` plans the extraction text with `planSegmentedExtraction` (`extraction-watermark.ts`: one streamed pass over the stored truth, head plus the newest tail window), so the job never reads the throwing body (`test/large-pages/segmented-derived-work.test.ts`). Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.
- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.md
index 4aef8f68bb..a6a634c557 100644
--- a/docs/architecture/key-files/core-services-2-continued.md
+++ b/docs/architecture/key-files/core-services-2-continued.md
@@ -19,6 +19,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share
- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.
- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).
- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.
+- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`.
- `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.`).
diff --git a/docs/guides/life-chronicle.md b/docs/guides/life-chronicle.md
index 14625128a1..15ead9d02a 100644
--- a/docs/guides/life-chronicle.md
+++ b/docs/guides/life-chronicle.md
@@ -254,7 +254,7 @@ brackets are filled in with real values on each surface.
| `not_yet_happened` | decision | The calendar event has not ended yet; it is picked up automatically after its end time, with no edit needed. | — | — | — |
| `too_short` | decision | The page body is under 80 characters, too short to hold events. | — | — | — |
| `dream_generated` | decision | Dream-generated pages are never mined for events. | — | — | — |
-| `page_body_segmented` | decision | The page body is over the 24 MiB single-string ceiling and is stored in segments; extraction reads the whole body as one string, so it skips this page. | — | — | — |
+| `page_body_segmented` | decision | An earlier release skipped this page: its body is over the 24 MiB single-string ceiling and is stored in segments. This release reads segmented pages, so the next revision or a backfill extracts it. | — | — | — |
| `no_write_decision` | discovery | This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it. | `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --yes` (preview: `gbrain chronicle-backfill --source <source> --since <YYYY-MM-DD> --limit 50 --dry-run`) | agent | paid |
| `not_chronicle_shaped` | decision | The page is no longer a meeting, conversation or calendar page, so the events extracted from it were retired. | — | — | — |
| `already_extracted` | decision | This exact content was already extracted; its events are current, so no new call is made. | — | — | — |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 023ce7c488..73799729a5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle re
src/commands/bootstrap.ts 2147 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags); +13 #4082: runAdoptHooks (the --adopt branch of the hooks subcommand, kept out of runHooks for the function-size ratchet) and its two help lines (adoption logic lives in core/bootstrap/adopt-connection.ts + adopted-connections.ts)
src/core/minions/worker.ts 1777 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler); +3 watchdog: gracefulShutdown records its reason and launchJob aborts a claim committed before it fired
src/commands/sources.ts 2059 ratchet +5 PR #5955 / fix wave 14 P2.7: sources set-strategy dispatch and help row, the strategy field of sources list --json (body in sources-strategy.ts); +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row
-src/core/link-extraction.ts 2379 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator
+src/core/link-extraction.ts 2420 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass); +21 fix wave 13 P4.10 #6266: resolveSameDirSlug + exported resolveMarkdownLinkSlug, shared with the link validator; +41 Wave B PR 2 lane 2e: extractPageLinks split into extractBodyLinks (window-scoped, offset-shifted, pass-tagged candidates) and frontmatterLinks, plus entityRefPasses, candidateKey, rolePriorPhrases and the roleText/regexBudget/window options, so a segmented page streams through the same extractor (window and merge logic in core/page-body/segment-links.ts)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index db15700756..bea1ef29c3 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -121,12 +121,7 @@ src/core/cycle/extract-atoms.ts runPhaseExtractAtoms call:serializeMarkdown SEGW
src/core/cycle/extract-facts.ts canonicalCacheState field STREAM segmented page: getter throws page_body_segmented
src/core/cycle/extract-facts.ts planFenceReconcile field STREAM managed preparer: segmented page: getter throws page_body_segmented before any write
src/core/cycle/extract-facts.ts runExtractFacts field STREAM segmented page skipped with warning FACTS_RECONCILE_SEGMENTED; its facts index is preserved (per-segment reconcile, PR 4)
-src/core/cycle/extract-takes.ts extractTakesFromDb field STREAM
-src/core/cycle/extract-takes.ts plannedTakes field STREAM
-src/core/cycle/extract-takes.ts prepareTakesReextract sql STREAM
-src/core/cycle/extract-takes.ts reconcilePageTakes field STREAM
-src/core/cycle/extract-takes.ts reextractCoordinated field STREAM
-src/core/cycle/extract-takes.ts reextractCoordinated sql STREAM
+src/core/cycle/extract-takes.ts readPageTakes field INLINE inline arm; a segmented page streams through parseTakesFenceBlocks (page-body/segment-takes.ts)
src/core/cycle/grade-takes.ts GradeTakesPhase.process field STREAM
src/core/cycle/link-manifest.ts buildLinkManifest field STREAM
src/core/cycle/pattern-claim-sources.ts dedupePatternClaimSources call:serializePageToMarkdown SEGW
@@ -274,8 +269,9 @@ src/core/import-identity.ts decideImportIdentity field META
src/core/import-screen.ts assessImportSanity field STREAM
src/core/import-screen.ts screenImportContent call:contentHash META
src/core/import-screen.ts screenImportContent field STREAM
-src/core/link-reconciliation.ts reconcileSourceLinks field STREAM segmented page skipped with failure code page_body_segmented; the cursor moves past it (per-segment links, PR 4)
+src/core/link-reconciliation.ts reconcileSourceLinks field INLINE inline arm; a segmented page streams through extractSegmentedPageLinks (page-body/segment-links.ts)
src/core/link-temporal-apply.ts applyTemporalEvidence field STREAM
+src/core/link-temporal-apply.ts temporalBodyOf field INLINE bodies held as strings; a segmented page collects its TemporalBody in extractSegmentedPageLinks
src/core/link-temporal-evidence.ts deriveTemporalEvidence field STREAM
src/core/markdown-chunks.ts overlaidChunks field STREAM
src/core/markdown-chunks.ts prepareFenceAwareMarkdownChunks call:prepareMarkdownChunks STREAM
@@ -284,9 +280,9 @@ src/core/markdown.ts parseMarkdown field STREAM
src/core/markdown.ts serializePageToMarkdown call:serializeMarkdown SEGW
src/core/markdown.ts serializePageToMarkdown field STREAM
src/core/mentions/aliases.ts deriveEntityAliases field STREAM
-src/core/mentions/pass.ts pagesMatchingNames sql STREAM segmented pages excluded in SQL
-src/core/mentions/pass.ts reconcileSource field STREAM inline rows only
-src/core/mentions/pass.ts reconcileSource sql STREAM segmented pages excluded in SQL (stay due and pending until the per-segment pass)
+src/core/mentions/pass.ts pageMentions field INLINE inline arm; a segmented page is scanned block by block
+src/core/mentions/pass.ts pagesMatchingNames sql STREAM segmented pages are selected by id without a body (each is a candidate; pageMentions streams it)
+src/core/mentions/pass.ts reconcileSource sql INLINE reads body_storage; a segmented row is scanned block by block (pageMentions)
src/core/mentions/pass.ts refreshAliases sql STREAM segmented pages excluded in SQL
src/core/minions/handlers/facts-absorb.ts makeFactsAbsorbHandler field STREAM
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot call:serializeMarkdown SEGW
@@ -354,10 +350,10 @@ src/core/page-window/document.ts readPageDocument field STREAM
src/core/persistence/atom-maintenance.ts prepareManagedAtomMutation field META
src/core/persistence/atom-maintenance.ts readAtomOrigin field META
src/core/persistence/atom-retry.ts retryManagedAtomBatch field STREAM
-src/core/persistence/canonical-projections.ts canonicalTakeRows field STREAM per-page projection: segmented page: getter throws page_body_segmented
src/core/persistence/canonical-projections.ts compileCanonicalProjections field STREAM per-page projection: segmented page: getter throws page_body_segmented
src/core/persistence/canonical-projections.ts materializeTimeline field STREAM per-page projection: segmented page: getter throws page_body_segmented
src/core/persistence/canonical-projections.ts prepareCanonicalProjections field STREAM per-page projection: segmented page: getter throws page_body_segmented
+src/core/persistence/canonical-projections.ts priorView field INLINE inline arm; an unread segmented prior streams through segmentedPriorView
src/core/persistence/canonical-projections.ts safeBody field STREAM per-page projection: segmented page: getter throws page_body_segmented
src/core/persistence/connector-google-receipts.ts prepareGoogleReceiptPatch call:contentHash META
src/core/persistence/connector-google-receipts.ts prepareGoogleReceiptPatch call:serializePageToMarkdown SEGW
@@ -366,7 +362,7 @@ src/core/persistence/connector-sync.ts prepareConnectorMutation call:serializePa
src/core/persistence/connector-sync.ts prepareConnectorMutation field SEGW
src/core/persistence/core-guard.ts prepareCoreGuard field INLINE
src/core/persistence/effect-facts.ts bodyAlreadyOffered field META
-src/core/persistence/effect-links.ts mentionTargets field STREAM per-page effect: segmented page: getter throws page_body_segmented
+src/core/persistence/effect-links.ts mentionTargets field INLINE inline arm; a segmented page streams its compiled truth through extractSegmentedPageLinks
src/core/persistence/effects.ts gitPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize
src/core/persistence/effects.ts mirrorPage call:serializePageToMarkdown SEGW segmented target skipped (skipped reason page_body_segmented) before the serialize; per-segment mirror in PR 2
src/core/persistence/embedding-settlement.ts listEmbeddingCandidates sql META
@@ -500,7 +496,7 @@ src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body
src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE
src/core/shared-skills/migration-export.ts exportInventory field INLINE
src/core/shared-skills/migration-projection.ts assertExportProjectionRoundtrip field INLINE
-src/core/sweep.ts runLinksTimelinePass field STREAM segmented page skipped (skip reason page_body_segmented:links_timeline)
+src/core/sweep.ts runLinksTimelinePass field INLINE inline arm; a segmented page streams its links (segment-links.ts) and timeline (bodyBlocks)
src/core/sweep.ts runMaintenanceSweep sql STREAM LIKE over NULL never matches a segmented page (skip)
src/core/think/gather.ts renderPagesBlockDetailed field LEAD segmented page: getter throws page_body_segmented
src/core/think/gather.ts runGather field LEAD visibleLeads reads Page.compiled_truth from listPages/search: segmented page: getter throws page_body_segmented (lead source in PR 2)
diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.ts
index 626b002803..12ad339dc8 100644
--- a/src/core/extraction-watermark.ts
+++ b/src/core/extraction-watermark.ts
@@ -23,7 +23,7 @@ import { createHash } from 'node:crypto';
import type { BrainEngine } from './engine.ts';
import { truncateUtf8 } from './text-safe.ts';
import { openSegmentedBody, readBodyRange } from './page-body/read-range.ts';
-import { readGarbageCollector } from './page-body/segment-blocks.ts';
+import { readGarbageCollector, segmentedPassWork } from './page-body/segment-blocks.ts';
export type ExtractionPipeline = 'facts_backstop' | 'extract_atoms' | 'conversation_facts';
@@ -120,6 +120,7 @@ export async function planSegmentedExtraction(engine: BrainEngine, pageId: numbe
for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region: 'truth', body })) {
const buf = piece.bytes;
collect(buf.length);
+ segmentedPassWork.bytes += buf.length;
whole.update(buf);
const text = decoder.decode(buf, { stream: true });
chars += text.length;
@@ -131,6 +132,7 @@ export async function planSegmentedExtraction(engine: BrainEngine, pageId: numbe
const after = tailDecoder.decode(buf.subarray(split), { stream: true });
tailChars += after.length;
tailText ||= after.trim().length > 0;
+ segmentedPassWork.carry += tail.length + after.length;
tail = (tail + after).slice(-2 * cap);
}
bytes += buf.length;
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index c01a4febba..8b36486709 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -392,7 +392,6 @@ async function runAutoLink(
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot) return;
const { prepareAutomaticLinks } = await import('../persistence/links-preparation.ts');
- // A segmented page keeps its body unread: link preparation streams it.
snapshot.page.frontmatter ??= {};
const prepared = await prepareAutomaticLinks(engine, slug, snapshot.page, sourceId);
return engine.transaction(async tx => {
diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.ts
index ac450aefeb..aecac45be1 100644
--- a/src/core/page-body/segment-blocks.ts
+++ b/src/core/page-body/segment-blocks.ts
@@ -38,6 +38,14 @@ export function readGarbageCollector(): (bytes: number) => void {
};
}
+/**
+ * @internal Work the derived passes do over a segmented body, for the linearity test: bytes read (`bytes`), UTF-16
+ * units of the blocks yielded (`blocks`) and of the link-extraction windows built around them (`windows`), and units a
+ * pass copies past its block (`carry`: a takes fence joined across blocks, the watermark planner's tail window).
+ * Counts, not time, so a busy machine cannot move them.
+ */
+export const segmentedPassWork = { bytes: 0, blocks: 0, windows: 0, carry: 0 };
+
/** The longest run of segments joined across forced cuts that a pass holds as one string. */
export const BLOCK_MAX_BYTES = 8 * SEGMENT_MAX_BYTES;
@@ -87,6 +95,8 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:
for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', region, body })) parts.push(piece.bytes);
const text = Buffer.concat(parts).toString('utf8');
collect(end - start);
+ segmentedPassWork.bytes += end - start;
+ segmentedPassWork.blocks += text.length;
yield { region, text, at };
at += text.length;
i = j + 1;
diff --git a/src/core/page-body/segment-links.ts b/src/core/page-body/segment-links.ts
index ba093ff2f7..5b4a6bbf82 100644
--- a/src/core/page-body/segment-links.ts
+++ b/src/core/page-body/segment-links.ts
@@ -26,7 +26,7 @@ import { rangedRelationLines } from '../link-effective.ts';
import type { TemporalBody } from '../link-temporal-apply.ts';
import { PageRegexBudget } from '../schema-pack/redos-guard.ts';
import type { PageType } from '../types.ts';
-import { bodyBlocks, detachedValue, type BodyBlock, type BodyBlockOptions } from './segment-blocks.ts';
+import { bodyBlocks, detachedValue, segmentedPassWork, type BodyBlock, type BodyBlockOptions } from './segment-blocks.ts';
/** Context a window carries after its block (an excerpt reaches 120 chars past a link) and, at least, before it. */
const CONTEXT_CHARS = 4096;
@@ -66,7 +66,12 @@ export async function* bodyWindows(engine: BrainEngine, page: { id: number; slug
const windowOf = (own: BodyBlock): BodyWindow => {
const lead = before[0]?.at ?? own.at;
const head = (lead === 0 ? '' : `\n${headings.filter(Boolean).map(h => `${h}\n`).join('')}`) + before.map(b => b.text).join('');
- const after = ahead.map(b => b.text).join('').slice(0, CONTEXT_CHARS);
+ let after = '';
+ for (const b of ahead) {
+ if (after.length >= CONTEXT_CHARS) break;
+ after += b.text.slice(0, CONTEXT_CHARS - after.length);
+ }
+ segmentedPassWork.windows += head.length + own.text.length + after.length;
return { text: head + own.text + after, start: head.length, end: head.length + own.text.length, offset: own.at - head.length, block: own };
};
const done = (own: BodyBlock) => {
diff --git a/src/core/page-body/segment-takes.ts b/src/core/page-body/segment-takes.ts
index 62d7d05d33..5605e53fc2 100644
--- a/src/core/page-body/segment-takes.ts
+++ b/src/core/page-body/segment-takes.ts
@@ -11,7 +11,7 @@
*/
import { indexOfOutsideCode } from '../fence-scan.ts';
import { parseTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END, type ParseResult } from '../takes-fence.ts';
-import { BLOCK_MAX_BYTES, blockTooLargeError, type BodyBlock } from './segment-blocks.ts';
+import { BLOCK_MAX_BYTES, blockTooLargeError, segmentedPassWork, type BodyBlock } from './segment-blocks.ts';
export interface StreamedTakes {
parsed: ParseResult;
@@ -49,6 +49,7 @@ export async function parseTakesFenceBlocks(blocks: AsyncIterable<BodyBlock>, pa
const end = indexOfOutsideCode(text, TAKES_FENCE_END, search);
const piece = text.slice(from, end === -1 ? text.length : end + TAKES_FENCE_END.length);
fenceChars += piece.length;
+ segmentedPassWork.carry += piece.length;
if (fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.source_id, fenceChars);
fence.push(piece);
if (end !== -1) return { parsed: parseTakesFence(fence.join('')), hasBegin, hasMarker };
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index aa3672123c..1153ae5857 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -143,11 +143,11 @@ function markedTimeline(safe: string, slug: string, marked = new Set<string>()):
}
/** What a body says about timeline rows: its canonical timeline, the tuples a marker still matches, the superseded citation readings. */
-interface TimelineView { timeline: Map<string, ExtractedTimelineEntry>; marked: Set<string>; superseded: Set<string> }
+interface TimelineView { entries: Map<string, ExtractedTimelineEntry>; marked: Set<string>; superseded: Set<string> }
function timelineView(body: CanonicalBody, slug: string): TimelineView {
const safe = safeBody(body);
- return { timeline: extractTimeline(safe, slug), marked: markedTimeline(safe, slug), superseded: new Set(supersededCitationTimeline(safe).map(t => timelineKey(t))) };
+ return { entries: extractTimeline(safe, slug), marked: markedTimeline(safe, slug), superseded: new Set(supersededCitationTimeline(safe).map(t => timelineKey(t))) };
}
/** The views a prior snapshot contributes, plus its takes rows per field and whether either field's takes fence warns. */
@@ -171,10 +171,10 @@ async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug:
markedTimeline(safe, slug, marked);
for (const t of supersededCitationTimeline(safe)) superseded.add(timelineKey(t));
}
- const timeline = new Map(extracted);
- for (const [key, entry] of parsed) timeline.set(key, entry);
+ const entries = new Map(extracted);
+ for (const [key, entry] of parsed) entries.set(key, entry);
const fields = await Promise.all((['truth', 'timeline'] as const).map(region => parseTakesFenceBlocks(bodyBlocks(engine, page, { regions: [region] }), page)));
- return { timeline, marked, superseded, takeRows: new Set(fields.flatMap(field => field.parsed.takes.map(t => t.rowNum))),
+ return { entries, marked, superseded, takeRows: new Set(fields.flatMap(field => field.parsed.takes.map(t => t.rowNum))),
takesWarn: fields.some(field => field.parsed.warnings.length > 0) };
}
@@ -191,7 +191,7 @@ async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug:
* before a transaction; unrecordedCanonicalTimeline filters it inside one.
*/
export async function storedCanonicalTimeline(engine: BrainEngine, page: PageSnapshot['page'], slug: string): Promise<Map<string, ExtractedTimelineEntry>> {
- return bodyUnread(page) ? (await segmentedPriorView(engine, page, slug)).timeline : canonicalTimeline(page, slug);
+ return bodyUnread(page) ? (await segmentedPriorView(engine, page, slug)).entries : canonicalTimeline(page, slug);
}
/**
@@ -241,9 +241,9 @@ export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: n
function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: TimelineView | null, slug: string, writer: ProjectionWriter,
policy?: TimelineWritePolicy) {
const incoming = timelineView(body, slug);
- const timeline = incoming.timeline;
+ const timeline = incoming.entries;
const exactIncoming = new Map([...timeline.values()].map(t => [exactTimelineKey(t), sanitizeForJsonb(t.detail ?? '')]));
- const priorTimeline = new Set(prior?.timeline.keys() ?? []);
+ const priorTimeline = new Set(prior?.entries.keys() ?? []);
const priorMarked = prior?.marked ?? new Set<string>();
const superseded = new Set([...incoming.superseded, ...(prior?.superseded ?? [])]);
const pinned = rows.map(row => {
diff --git a/test/helpers/work-counts.ts b/test/helpers/work-counts.ts
index 8de546d20e..5916d9cc37 100644
--- a/test/helpers/work-counts.ts
+++ b/test/helpers/work-counts.ts
@@ -29,6 +29,15 @@ export function countWork(counters: Counters, fn: () => unknown): Work {
return work;
}
+/** countWork for an async `fn`: nothing else that counts may run while it is awaited. */
+export async function countWorkAsync(counters: Counters, fn: () => Promise<unknown>): Promise<Work> {
+ countWork(counters, () => {});
+ await fn();
+ const work: Work = {};
+ for (const [name, group] of Object.entries(counters)) for (const [k, v] of Object.entries(group)) work[`${name}.${k}`] = v;
+ return work;
+}
+
export interface Sample { bytes: number; work: Work }
/**
diff --git a/test/large-pages/segmented-derived-linear.test.ts b/test/large-pages/segmented-derived-linear.test.ts
new file mode 100644
index 0000000000..6aa7feac56
--- /dev/null
+++ b/test/large-pages/segmented-derived-linear.test.ts
@@ -0,0 +1,132 @@
+/**
+ * Wave B PR 2 lane 2e (spec 8, full-pass mode): the derived passes over a
+ * segmented page do O(page) work.
+ *
+ * Protects: links (with temporal inputs), takes, timeline (entries and the
+ * stored canonical map), mentions and the watermark planner, run over a
+ * segmented page, count their work in `segmentedPassWork`: bytes read, units
+ * of the blocks yielded and of the link windows built around them, and units
+ * copied past a block (a takes fence join, the planner's tail window). Counts,
+ * not CPU time, so a co-tenant cannot move them.
+ * Fails when: at n and 2n bytes (n = 4 MiB) a counter exceeds its per-byte
+ * bound, or (with at least MIN_RATIO_COUNT counts at n) grows 2.1x or more: a
+ * window that keeps every earlier block as context, a planner tail that keeps
+ * the whole appended text, a pass that re-reads the body per block. The forced
+ * probe drives the same counted code to re-read the body's prefix before each
+ * block and asserts the counts catch it.
+ * Why existing coverage misses it: segmented-derived-parity checks results and
+ * reads per call; segmented-derived-memory bounds memory, not work.
+ * Seams: `segmentedPassWork` (@internal counters in segment-blocks.ts).
+ * Measured (deterministic; per byte at n, doubling ratio): bytes 6.86 x2.00
+ * (seven page reads: role phrases, link windows, takes, timeline, canonical
+ * timeline, mentions, the planner's truth), blocks 5.88 x2.00, windows 2.00
+ * x2.00 (a window holds the whole block before its own), carry 0.52 x1.99.
+ * Prefix-re-reading driver (n = 1 MiB): bytes and blocks x2.68.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { makeResolver } from '../../src/core/link-extraction.ts';
+import { extractSegmentedPageLinks } from '../../src/core/page-body/segment-links.ts';
+import { bodyBlocks, segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
+import { parseTakesFenceBlocks } from '../../src/core/page-body/segment-takes.ts';
+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';
+import { segmentedTimelineText } from '../../src/core/timeline-extract.ts';
+import { storedCanonicalTimeline } from '../../src/core/persistence/canonical-projections.ts';
+import { pageMentions } from '../../src/core/mentions/pass.ts';
+import { buildGazetteer } from '../../src/core/by-mention.ts';
+import { readMentionPolicy } from '../../src/core/mentions/policy.ts';
+import { EXTRACTION_PIPELINE_VERSION, planSegmentedExtraction } from '../../src/core/extraction-watermark.ts';
+import type { Page } from '../../src/core/types.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { countWorkAsync, describeWork, linearityViolations, MAX_DOUBLING_RATIO, type Sample } from '../helpers/work-counts.ts';
+
+const MB = 1024 * 1024;
+/** Per input byte, about 2x the measured value or more. */
+const PER_BYTE = { 'pass.bytes': 14, 'pass.blocks': 12, 'pass.windows': 4, 'pass.carry': 1.2 };
+
+let engine: PGLiteEngine;
+
+/** `bytes` of linked, dated, mentioning conversation with a takes fence mid-page and dated bullets in the timeline. */
+function page(bytes: number): string {
+ const parts: string[] = [];
+ const units = Math.round(bytes / (66 * 1024));
+ for (let i = 0; i < units; i++) {
+ parts.push(`## Section ${i}\n\n${conversationBody(64 * 1024, { seed: 100 + i })}\n\n`
+ + `- **2026-03-${String(10 + (i % 18)).padStart(2, '0')}** Met [[people/alice-example]] and [Acme Example](../companies/acme-example.md) about launch ${i}; `
+ + `Alice Example reviewed it.\n\n`);
+ if (i === Math.floor(units / 2)) parts.push(`${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n`
+ + `| 1 | Acme ships quarterly | fact | world | 1.0 | 2026-01 | notes |\n${TAKES_FENCE_END}\n\n`);
+ }
+ const timeline = Array.from({ length: units }, (_, i) => `- **2026-0${1 + (i % 9)}-${String(10 + (i % 18)).padStart(2, '0')}** | Met [[people/alice-example]] about item ${i}\n`).join('');
+ return `---\ntype: meeting\ntitle: Linear ${bytes}\n---\n\n${parts.join('')}\n<!-- timeline -->\n\n${timeline}`;
+}
+
+async function stored(slug: string): Promise<Page> {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ expect(snapshot.page.body_storage).toBe('segmented');
+ return snapshot.page;
+}
+
+/** Every derived pass this lane streams, once over the page. */
+async function passes(slug: string): Promise<void> {
+ const p = await stored(slug);
+ const resolver = makeResolver(engine, { mode: 'live', sourceId: 'default' });
+ const links = await extractSegmentedPageLinks(engine, { id: Number(p.id), slug, source_id: 'default', type: p.type, frontmatter: p.frontmatter },
+ resolver, { temporal: true, globalBasename: false });
+ expect(links.candidates.length).toBeGreaterThan(0);
+ expect((await parseTakesFenceBlocks(bodyBlocks(engine, p), { slug, source_id: 'default' })).parsed.takes).toHaveLength(1);
+ expect((await segmentedTimelineText(engine, p)).entries.length).toBeGreaterThan(0);
+ expect((await storedCanonicalTimeline(engine, p, slug)).size).toBeGreaterThan(0);
+ const gazetteer = await buildGazetteer(engine, { policy: await readMentionPolicy(engine), strict: true });
+ expect(await pageMentions(engine, { id: Number(p.id), slug, source_id: 'default', title: p.title, body_storage: 'segmented' }, gazetteer,
+ { fromSlug: slug, fromSourceId: 'default', allowCrossSource: false })).not.toHaveLength(0);
+ const half = Math.floor(Number((await engine.executeRaw<{ n: number }>(
+ "SELECT coalesce(sum(byte_len),0)::bigint AS n FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND region='truth'", [p.id]))[0]!.n) / 2);
+ const plan = await planSegmentedExtraction(engine, Number(p.id), { pipelineVersion: EXTRACTION_PIPELINE_VERSION.facts_backstop, bytes: half, sha256: '0'.repeat(64) },
+ { cap: 8000, pipeline: 'facts_backstop', emptyTail: 'skip' });
+ expect(plan.mode).toBe('head');
+}
+
+/** The deliberately quadratic driver: re-reads the body's prefix through bodyBlocks before each block. */
+async function prefixRereading(slug: string): Promise<void> {
+ const p = await stored(slug);
+ let seen = 0;
+ for await (const _ of bodyBlocks(engine, p)) {
+ let n = 0;
+ for await (const __ of bodyBlocks(engine, p)) if (++n > seen) break;
+ seen++;
+ }
+}
+
+const sample = async (bytes: number, slug: string, run: (slug: string) => Promise<void>): Promise<Sample> =>
+ ({ bytes, work: await countWorkAsync({ pass: segmentedPassWork }, () => run(slug)) });
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ await engine.putPage('companies/acme-example', { type: 'company', title: 'Acme Example', compiled_truth: 'Fixture.', timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ for (const [slug, bytes] of [['notes/linear-1', MB], ['notes/linear-2', 2 * MB], ['notes/linear-4', 4 * MB], ['notes/linear-8', 8 * MB]] as const) {
+ expect(await importFromContent(engine, slug, page(bytes), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ }
+}, 600_000);
+
+afterAll(async () => { await engine.disconnect(); });
+
+describe('derived pass work over a segmented page', () => {
+ test('work per byte is bounded and doubles with the page', async () => {
+ const a = await sample(4 * MB, 'notes/linear-4', passes);
+ const b = await sample(8 * MB, 'notes/linear-8', passes);
+ console.log(`[segmented-derived-linear] passes: ${describeWork(a, b)}`);
+ expect(linearityViolations(a, b, PER_BYTE)).toEqual([]);
+ }, 300_000);
+
+ test('forced probe: the same bounds fail a driver that re-reads the prefix before each block', async () => {
+ const a = await sample(MB, 'notes/linear-1', prefixRereading);
+ const b = await sample(2 * MB, 'notes/linear-2', prefixRereading);
+ console.log(`[segmented-derived-linear] prefix-re-reading driver (quadratic probe): ${describeWork(a, b)}`);
+ expect(b.work['pass.blocks']! / a.work['pass.blocks']!).toBeGreaterThan(MAX_DOUBLING_RATIO);
+ expect(b.work['pass.bytes']! / a.work['pass.bytes']!).toBeGreaterThan(MAX_DOUBLING_RATIO);
+ }, 300_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index f857224012..53a6e1f4db 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -78,6 +78,8 @@ test/large-pages/remote-window-privacy.test.ts
test/large-pages/sealed-segmented-search.test.ts
test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-body-unreachable.test.ts
+test/large-pages/segmented-derived-parity.test.ts
+test/large-pages/segmented-derived-passes.test.ts
test/large-pages/segmented-derived-work.test.ts
test/large-pages/segmented-embedding-paths.test.ts
test/large-pages/segmented-embedding.test.ts