Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(get_versions): add limit and include_body response bounds (#5375)

time-attack745117a3394b
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index c900852ca2..010cb47240 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -115,6 +115,7 @@ jobs:
test/persistence-tombstone-noop.test.ts \
test/persistence-version-deletion.test.ts \
test/version-history-privacy.test.ts \
+ test/get-versions-response-bounds.test.ts \
test/persistence-take-receipt-authority.test.ts \
test/import-revision-revival.test.ts \
test/persistence-source-lifecycle.test.ts \
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index c9e4a6ea9c..1a7a32de86 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -167,7 +167,7 @@ Every non-localOnly operation on the MCP surface: 139 tools across 23 areas. **S
| `get_chunks` | Return a page's indexed content chunks (the units search ranks). | read | | |
| `get_page` | Read a page by slug (fuzzy optional; renamed slugs redirect). | read | yes | |
| `get_raw_data` | Retrieve raw data for a page. | read | | |
-| `get_versions` | Page version history. | read | | |
+| `get_versions` | Page version history, newest snapshot first. | read | | |
| `get_write_request` | Read your write's receipt by request_id (after write_pending or a lost reply). | write | yes | |
| `list_pages` | List pages with filters. | read | yes | |
| `list_write_requests` | List your write receipts in one source, newest first. | write | yes | |
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e628be0fa1..d5348cc045 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 512 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3254 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts)
src/core/cycle/synthesize.ts 3195 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition
src/core/cycle/extract-atoms.ts 1814 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts)
-src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso
+src/core/engine.ts 2708 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
src/core/import-file.ts 2179 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 339 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)
-src/core/pglite-engine.ts 2995 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)
-src/core/postgres-engine.ts 2932 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)
+src/core/pglite-engine.ts 2996 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
+src/core/postgres-engine.ts 2933 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows)
src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2212 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +2 #5951: Chunk.source_id (get_chunks names each row's source)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index b6306b104a..f498962efb 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -14,7 +14,8 @@
*/
import type { BrainEngine } from '../engine.ts';
import type { DomainBankSampleOpts, CorpusSampleOpts, DomainBankRow } from '../types.ts';
-import type { Page, PageInput, PageFilters, PageVersion, StalePageRow } from '../types.ts';
+import type { Page, PageInput, PageFilters, StalePageRow } from '../types.ts';
+import type { GetVersionsOpts, PageVersionRows } from '../page-state/version-types.ts';
import { PAGE_SORT_SQL } from '../types.ts';
import type { PageWriteOptions } from '../page-state/types.ts';
import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.ts';
@@ -802,42 +803,35 @@ export async function getPageTimestamps(exec: LegacyUnscopedRead, slugs: string[
*/
const PAGE_VERSION_COLUMNS = trustedSql('pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, '
+ 'pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path');
+const PAGE_VERSION_METADATA_COLUMNS = trustedSql('pv.id, pv.page_id, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, '
+ + 'pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path');
-export async function getVersions(
+/**
+ * Newest first (`pv.id` breaks snapshot_at ties). Scope and privacy
+ * predicates sit in WHERE, so `limit` bounds only rows the caller may read;
+ * `includeBody: false` never selects the body columns.
+ */
+export async function getVersions<B extends boolean = true>(
exec: LegacyUnscopedRead,
slug: string,
- opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
-): Promise<PageVersion[]> {
+ opts?: GetVersionsOpts<B>,
+): Promise<PageVersionRows<B>> {
const privacy = opts?.excludePrivate
? trustedSql(`AND ${privatePagesFilterFragment('p')} AND ${privateSnapshotFilterFragment('pv')}`) : sqlFragment``;
- if (opts?.sourceIds && opts.sourceIds.length > 0) {
- const { rows } = await exec.run<PageVersion>(sqlFragment`
- SELECT ${PAGE_VERSION_COLUMNS} FROM page_versions pv
- JOIN pages p ON p.id = pv.page_id
- WHERE p.slug = ${slug} AND p.source_id = ANY(${opts.sourceIds}::text[])
- ${privacy}
- ORDER BY pv.snapshot_at DESC
- `);
- return rows;
- }
- if (opts?.sourceId) {
- const { rows } = await exec.run<PageVersion>(sqlFragment`
- SELECT ${PAGE_VERSION_COLUMNS} FROM page_versions pv
- JOIN pages p ON p.id = pv.page_id
- WHERE p.slug = ${slug} AND p.source_id = ${opts.sourceId}
- ${privacy}
- ORDER BY pv.snapshot_at DESC
- `);
- return rows;
- }
- const { rows } = await exec.run<PageVersion>(sqlFragment`
- SELECT ${PAGE_VERSION_COLUMNS} FROM page_versions pv
+ const scope = opts?.sourceIds && opts.sourceIds.length > 0
+ ? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`
+ : opts?.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;
+ const columns = opts?.includeBody === false ? PAGE_VERSION_METADATA_COLUMNS : PAGE_VERSION_COLUMNS;
+ const limit = opts?.limit !== undefined ? sqlFragment`LIMIT ${opts.limit}` : sqlFragment``;
+ const { rows } = await exec.run(sqlFragment`
+ SELECT ${columns} FROM page_versions pv
JOIN pages p ON p.id = pv.page_id
- WHERE p.slug = ${slug}
+ WHERE p.slug = ${slug} ${scope}
${privacy}
- ORDER BY pv.snapshot_at DESC
+ ORDER BY pv.snapshot_at DESC, pv.id DESC
+ ${limit}
`);
- return rows;
+ return rows as PageVersionRows<B>;
}
export async function revertToVersion(
diff --git a/src/core/engine.ts b/src/core/engine.ts
index cef81dc187..8cf79d480e 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1,4 +1,5 @@
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
+import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';
import type { LinkReadScope } from './link-validity.ts';
import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './search/chunk-windows.ts';
import type { DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';
@@ -2307,7 +2308,7 @@ export interface BrainEngine {
* When omitted, returns versions for every same-slug page across sources
* (pre-v0.31.8 behavior; preserved via two-branch query).
*/
- getVersions(slug: string, opts?: PageReadScope): Promise<PageVersion[]>;
+ getVersions<B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>): Promise<PageVersionRows<B>>;
/**
* v0.31.8 (D12): `opts.sourceId` source-scopes both the version lookup
* and the page revert. Without it, multi-source brains can revert the
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 1f0da8f1b5..43791346bc 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -2,6 +2,7 @@ import { pageMutationSource, submitPageMutation } from '../persistence/page-muta
import { PAGE_MUTATION_PARAMS } from '../persistence/params.ts';
import { readPolicyOpts } from './context.ts';
import { attributeVersions, canReadWriteAttribution } from './attribution.ts';
+import { invalidParam } from './op-fix.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
/**
* Admin operation cluster — pure move from operations.ts (v0.46.x tranche 2).
@@ -191,12 +192,26 @@ const get_versions: Operation = {
mutating: false,
idempotent: true,
outputRedaction: { exempt: 'full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)' },
- description: 'Page version history. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it).',
+ description: 'Page version history, newest snapshot first. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). `limit` returns only the newest N; `include_body: false` returns metadata only.',
params: {
slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },
+ limit: { type: 'number', description: 'Return only the newest N versions (a positive integer). Omit for the full history.' },
+ include_body: { type: 'boolean', description: 'false omits compiled_truth and timeline from every version (metadata only). Default true.' },
},
handler: async (ctx, p) => {
- const plain = await ctx.engine.getVersions(p.slug as string, await readPolicyOpts(ctx));
+ // #5234: the bound and the body projection run in SQL, after the scope and
+ // privacy predicates, so a bounded or metadata-only read never loads more
+ // than it returns and never widens what the caller may see.
+ const limit = p.limit === undefined || p.limit === null ? undefined : p.limit;
+ if (limit !== undefined && !(typeof limit === 'number' && Number.isSafeInteger(limit) && limit >= 1)) {
+ throw invalidParam(ctx, 'get_versions', 'limit', 'get_versions: limit must be a positive integer.', { example: 5 });
+ }
+ const opts = { ...(await readPolicyOpts(ctx)), ...(limit !== undefined ? { limit } : {}) };
+ if (p.include_body === false) {
+ const metadata = await ctx.engine.getVersions(p.slug as string, { ...opts, includeBody: false });
+ return canReadWriteAttribution(ctx) ? attributeVersions(ctx.engine, metadata) : metadata;
+ }
+ const plain = await ctx.engine.getVersions(p.slug as string, opts);
const versions = canReadWriteAttribution(ctx) ? await attributeVersions(ctx.engine, plain) : plain;
if (ctx.remote === false) return versions;
return versions.map(v => ({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),
diff --git a/src/core/ops/attribution.ts b/src/core/ops/attribution.ts
index c2ab1e6db7..3e1160bf3d 100644
--- a/src/core/ops/attribution.ts
+++ b/src/core/ops/attribution.ts
@@ -10,7 +10,8 @@
* Never import from '../operations.ts' here (cycle).
*/
import type { BrainEngine } from '../engine.ts';
-import type { AttributedPageVersion, PageVersion, WriteAttributionView } from '../types.ts';
+import type { WriteAttributionView } from '../types.ts';
+import type { PageVersionMetadata } from '../page-state/version-types.ts';
import { hasScope } from '../scope.ts';
import { opError, type Operation, type OperationContext } from './contract.ts';
import type { McpCall } from '../agent-output.ts';
@@ -71,7 +72,9 @@ export async function resolveWriteAttributions(engine: BrainEngine, stored: Stor
}
/** `get_versions` for trusted and admin callers: each snapshot with its origin and archiving writer. */
-export async function attributeVersions(engine: BrainEngine, versions: PageVersion[]): Promise<AttributedPageVersion[]> {
+export async function attributeVersions<V extends PageVersionMetadata>(
+ engine: BrainEngine, versions: V[],
+): Promise<Array<V & { written_by: WriteAttributionView; archived_by: WriteAttributionView }>> {
if (!versions.length) return [];
const rows = await engine.executeRaw<{ id: number; w_req: string | null; w_kind: string | null; w_id: string | null;
a_req: string | null; a_kind: string | null; a_id: string | null }>(
diff --git a/src/core/page-state/version-types.ts b/src/core/page-state/version-types.ts
index 63dcb2a5e7..ac6dcdcf0c 100644
--- a/src/core/page-state/version-types.ts
+++ b/src/core/page-state/version-types.ts
@@ -1,3 +1,5 @@
+import type { PageReadScope } from '../types.ts';
+
/** Complete canonical version fields are optional only for legacy partial snapshots. */
export interface PageVersion {
/** NULL/absent on legacy versions: reverting preserves current deletion state. */
@@ -15,3 +17,17 @@ export interface PageVersion {
frontmatter: Record<string, unknown>;
snapshot_at: Date;
}
+
+/** A version without its snapshot bodies (`get_versions` with `include_body: false`). */
+export type PageVersionMetadata = Omit<PageVersion, 'compiled_truth' | 'timeline'>;
+
+/** `getVersions` options: the read scope plus a newest-first row bound and the body projection. */
+export interface GetVersionsOpts<B extends boolean = true> extends PageReadScope {
+ /** Newest-first prefix length, applied in SQL after every scope and privacy predicate. */
+ limit?: number;
+ /** false selects no compiled_truth/timeline columns. */
+ includeBody?: B;
+}
+
+/** `getVersions` rows: bodies unless `includeBody` is false. */
+export type PageVersionRows<B extends boolean> = B extends false ? PageVersionMetadata[] : PageVersion[];
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index c6c0d1b75e..c4b419cbf7 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -3,6 +3,7 @@ import { replaceDerivedLinks, type DerivedLinkOrigin, type DerivedLinkReplacemen
import { trackPgliteDatabase, PgliteClosingError, notifyPgliteOpened } from './pglite-lifecycle.ts';
import { mutatePageTag } from './page-state/tags.ts';
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
+import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';
import { assertPageRevision } from './page-state/types.ts';
import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
@@ -2607,7 +2608,7 @@ export class PGLiteEngine implements BrainEngine {
return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);
}
- async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {
+ async getVersions<B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>): Promise<PageVersionRows<B>> {
return pagesImpl.getVersions(unscopedExecutor(this.engineSql, 'pages: unscoped on master (EO4 inventory)'), slug, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 55039f1eac..19c9ed15c9 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2,6 +2,7 @@ import { tryAcquirePoolLongHold, PoolCapacityError } from './pool-budget.ts';
import { replaceDerivedLinks, type DerivedLinkOrigin, type DerivedLinkReplacementOptions } from './derived-links.ts';
import { mutatePageTag } from './page-state/tags.ts';
import type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions } from './page-state/types.ts';
+import type { GetVersionsOpts, PageVersionRows } from './page-state/version-types.ts';
import { assertPageRevision } from './page-state/types.ts';
import { lockUnheldPageKeys, withHeldPageKeys, type HeldPageKeys } from './page-state/guards.ts';
import { readPageSnapshot as readCanonicalPageSnapshot } from './page-state/snapshot.ts';
@@ -2333,7 +2334,7 @@ export class PostgresEngine implements BrainEngine {
return createPageVersion(this, slug, opts?.sourceId ?? 'default', opts?.preimage);
}
- async getVersions(slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean }): Promise<PageVersion[]> {
+ async getVersions<B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>): Promise<PageVersionRows<B>> {
return pagesImpl.getVersions(unscopedExecutor(this.engineSql, 'pages: unscoped on master (EO4 inventory)'), slug, opts);
}
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 3d005df5d1..889c11ee3d 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 204774,
- "stdoutSha256": "604bc3babd6d521ed848e4dc37dac37064a7e058c7cded48e6f4c1706d39a8bc",
+ "stdoutBytes": 205288,
+ "stdoutSha256": "395ac331e90598fe83ef06b0144a6910c70381162fad370f67e410af45661a04",
"toolNames": [
"remember",
"entity",
@@ -2041,17 +2041,27 @@
"scope": "admin"
},
{
- "description": "Page version history. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it).",
+ "description": "Page version history, newest snapshot first. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). `limit` returns only the newest N; `include_body: false` returns metadata only.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_versions",
"parameters": {
+ "include_body": "boolean?",
+ "limit": "number?",
"slug": "string"
},
"required_scopes": [],
"schema": {
"properties": {
+ "include_body": {
+ "description": "false omits compiled_truth and timeline from every version (metadata only). Default true.",
+ "type": "boolean"
+ },
+ "limit": {
+ "description": "Return only the newest N versions (a positive integer). Omit for the full history.",
+ "type": "number"
+ },
"slug": {
"description": "Slug of the page whose version history to list.",
"type": "string"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index dbb88546a2..f972051407 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -126,7 +126,7 @@
"getTimeline: (slug: string, opts?: TimelineOpts) => Promise<TimelineEntry[]>",
"getTimelineForDate: (date: string, opts?: ChronicleTimelineOpts) => Promise<ChronicleTimelineRow[]>",
"getUnverifiedExtractionPageIds: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, { unverified: boolean; status: string; }>>",
- "getVersions: (slug: string, opts?: PageReadScope) => Promise<PageVersion[]>",
+ "getVersions: <B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>) => Promise<PageVersionRows<B>>",
"initSchema: () => Promise<void>",
"insertFact: (input: NewFact, ctx: { source_id: string; supersedeId?: number; }) => Promise<{ id: number; status: FactInsertStatus; }>",
"insertFacts: (rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number; }>, ctx: { source_id: string; }, opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean; }; }) => Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number; }>",
@@ -1075,7 +1075,7 @@
"getTimeline: (slug: string, opts?: TimelineOpts) => Promise<TimelineEntry[]>",
"getTimelineForDate: (date: string, opts?: ChronicleTimelineOpts) => Promise<ChronicleTimelineRow[]>",
"getUnverifiedExtractionPageIds: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, { unverified: boolean; status: string; }>>",
- "getVersions: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<PageVersion[]>",
+ "getVersions: <B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>) => Promise<PageVersionRows<B>>",
"initSchema: (opts?: { embedding?: { dimensions: number; model: string; }; }) => Promise<void>",
"insertFact: (input: NewFact, ctx: { source_id: string; supersedeId?: number; }) => Promise<{ id: number; status: FactInsertStatus; }>",
"insertFacts: (rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number; }>, ctx: { source_id: string; }, opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean; }; }) => Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number; }>",
@@ -3186,7 +3186,7 @@
"getTimeline: (slug: string, opts?: TimelineOpts) => Promise<TimelineEntry[]>",
"getTimelineForDate: (date: string, opts?: ChronicleTimelineOpts) => Promise<ChronicleTimelineRow[]>",
"getUnverifiedExtractionPageIds: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, { unverified: boolean; status: string; }>>",
- "getVersions: (slug: string, opts?: PageReadScope) => Promise<PageVersion[]>",
+ "getVersions: <B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>) => Promise<PageVersionRows<B>>",
"initSchema: () => Promise<void>",
"insertFact: (input: NewFact, ctx: { source_id: string; supersedeId?: number; }) => Promise<{ id: number; status: FactInsertStatus; }>",
"insertFacts: (rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number; }>, ctx: { source_id: string; }, opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean; }; }) => Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number; }>",
@@ -5997,7 +5997,7 @@
"getTimeline: (slug: string, opts?: TimelineOpts) => Promise<TimelineEntry[]>",
"getTimelineForDate: (date: string, opts?: ChronicleTimelineOpts) => Promise<ChronicleTimelineRow[]>",
"getUnverifiedExtractionPageIds: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, { unverified: boolean; status: string; }>>",
- "getVersions: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<PageVersion[]>",
+ "getVersions: <B extends boolean = true>(slug: string, opts?: GetVersionsOpts<B>) => Promise<PageVersionRows<B>>",
"initSchema: () => Promise<void>",
"insertFact: (input: NewFact, ctx: { source_id: string; supersedeId?: number; }) => Promise<{ id: number; status: FactInsertStatus; }>",
"insertFacts: (rows: Array<NewFact & { row_num: number; source_markdown_slug: string; superseded_by_row?: number; }>, ctx: { source_id: string; }, opts?: { deleteForPageFirst?: { slug: string; excludeSourcePrefixes?: string[]; preserveExpiredLegacy?: boolean; }; }) => Promise<{ inserted: number; ids: number[]; warnings: string[]; deleted: number; }>",
diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
index e156efd3db..27893a88d3 100644
--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json
@@ -154,6 +154,8 @@
"getTimelineForDate#week+sourceId": {},
"getVersions#default": {},
"getVersions#excludePrivate": {},
+ "getVersions#limit": {},
+ "getVersions#metadataOnly": {},
"getVersions#sourceId": {},
"getVersions#sourceIds": {},
"insertFact#default": {},
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index b57da1e965..6b40c98d03 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -1466,6 +1466,28 @@
],
"flagOnScopes": []
},
+ "getVersions#limit": {
+ "flagOffLanes": [
+ "pool"
+ ],
+ "flagOffOpensTransaction": false,
+ "flagOn": "unscoped",
+ "flagOnLanes": [
+ "pool"
+ ],
+ "flagOnScopes": []
+ },
+ "getVersions#metadataOnly": {
+ "flagOffLanes": [
+ "pool"
+ ],
+ "flagOffOpensTransaction": false,
+ "flagOn": "unscoped",
+ "flagOnLanes": [
+ "pool"
+ ],
+ "flagOnScopes": []
+ },
"getVersions#sourceId": {
"flagOffLanes": [
"pool"
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 2a412ae254..6f7b91d00f 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2568,6 +2568,28 @@
"via": "unsafe"
}
],
+ "limit": [
+ {
+ "paramCount": 3,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "metadataOnly": [
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
"sourceId": [
{
"paramCount": 2,
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 4c978d77ec..7bab5bc9f4 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -298,8 +298,8 @@
"params": [
"string"
],
- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 ORDER BY pv.snapshot_at DESC",
- "textSha256": "2968a1918d83184a9281aac18f262f12558b9676fc0fa85413b764eb0d5d910c"
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 ORDER BY pv.snapshot_at DESC, pv.id DESC",
+ "textSha256": "32879564166486f18b4931ad6f8c763b6869c5d116a8286665d44cb37271049c"
}
],
"excludePrivate": [
@@ -308,8 +308,31 @@
"params": [
"string"
],
- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type = 'atom' OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' ORDER BY pv.snapshot_at DESC",
- "textSha256": "c2ec5cf6dbd26923230987037168c8e5f0dd67035a401b5bb512788256a069f2"
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type = 'atom' OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' ORDER BY pv.snapshot_at DESC, pv.id DESC",
+ "textSha256": "61ec852c6f4e094a4c57383807bd27a368f129ff38931e2d318d1ce177b5164f"
+ }
+ ],
+ "limit": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "string",
+ "number"
+ ],
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC LIMIT $3",
+ "textSha256": "9839ece55c3a9571965051d0380fd26c9ac4b11e70b44b9a5c44731f4d9e7087"
+ }
+ ],
+ "metadataOnly": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "array<string>"
+ ],
+ "sql": "SELECT pv.id, pv.page_id, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",
+ "textSha256": "58fb695b83a4ff6bf64add66f0caf4d76515e10bc88e43e9148c070ec41d9ce0"
}
],
"sourceId": [
@@ -319,8 +342,8 @@
"string",
"string"
],
- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC",
- "textSha256": "96b8bd58257e4f3bfd04fc5e6987e996bbc9fed3546454cfffd62612071d7b16"
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC",
+ "textSha256": "b42549daaa1a104ab1da4c06e09b4f47a80d14f75a3ea85a198d76b4e47f3847"
}
],
"sourceIds": [
@@ -330,8 +353,8 @@
"string",
"array<string>"
],
- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC",
- "textSha256": "46dfc6cd0b414fd9fd8447c464925076c5237bfe80b14a2dd19354776bb5f9bf"
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",
+ "textSha256": "45b816d8e527a6e0e92fee18a95d7c02fa86fcb30e5295d2d9e47aa56d2bedfb"
}
]
},
diff --git a/test/get-versions-response-bounds.test.ts b/test/get-versions-response-bounds.test.ts
new file mode 100644
index 0000000000..86230a4b9b
--- /dev/null
+++ b/test/get-versions-response-bounds.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #5234: get_versions `limit` and `include_body`.
+ *
+ * 1. Protects: a caller can ask for the newest N versions, or metadata only,
+ * and the bound and projection run in SQL after the scope and privacy
+ * predicates, so a bounded read never loads every body and hidden versions
+ * never shift the prefix.
+ * 2. Fails when: the params are dropped, the bound is applied after loading
+ * (bodies still selected), the LIMIT runs before the privacy or source
+ * predicate, same-time snapshots order nondeterministically, or an invalid
+ * explicit limit silently returns the full history.
+ * 3. Existing get_versions tests cover privacy and attribution of the full
+ * history only.
+ * 4. No new seam: the real handler over PGLite (and Postgres when
+ * DATABASE_URL is set).
+ */
+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 { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { toAgentError } from '../src/core/agent-output.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const SOURCE = 'acme-example';
+const OTHER = 'widget-co';
+let engine: PGLiteEngine;
+const databases: Array<{ name: string; engine: BrainEngine; close?: () => Promise<void> }> = [];
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ databases.push({ name: 'pglite', engine });
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ databases.push({ name: 'postgres', engine: pg.engine, close: pg.close });
+ }
+ for (const { engine: e } of databases) {
+ await e.executeRaw('INSERT INTO sources(id, name) VALUES ($1, $1), ($2, $2)', [SOURCE, OTHER]);
+ await seed(e);
+ }
+}, 120_000);
+
+afterAll(async () => {
+ for (const { close } of databases) if (close) await close();
+ await engine.disconnect();
+});
+
+/**
+ * notes/history in SOURCE: versions v1..v4 (v3 and v4 share one snapshot_at,
+ * so pv.id breaks the tie), then v5, a private snapshot, newest of all.
+ * The same slug in OTHER has a version newer than everything in SOURCE.
+ */
+async function seed(e: BrainEngine): Promise<void> {
+ const page = await e.putPage('notes/history', { type: 'note', title: 'History', compiled_truth: 'current body' }, { sourceId: SOURCE });
+ const other = await e.putPage('notes/history', { type: 'note', title: 'Other', compiled_truth: 'other body' }, { sourceId: OTHER });
+ const rows: Array<[number, string, string, string]> = [
+ [page.id, 'body v1', '2026-01-01T00:00:00Z', '{"visibility":"world"}'],
+ [page.id, 'body v2', '2026-01-02T00:00:00Z', '{"visibility":"world"}'],
+ [page.id, 'body v3', '2026-01-03T00:00:00Z', '{"visibility":"world"}'],
+ [page.id, 'body v4', '2026-01-03T00:00:00Z', '{"visibility":"world"}'],
+ [page.id, 'body v5 private', '2026-01-05T00:00:00Z', '{"visibility":"private"}'],
+ [other.id, 'other source body', '2026-02-01T00:00:00Z', '{"visibility":"world"}'],
+ ];
+ for (const [pageId, body, at, fm] of rows) {
+ await e.executeRaw(
+ `INSERT INTO page_versions (page_id, compiled_truth, timeline, frontmatter, snapshot_at, title)
+ VALUES ($1, $2, $3, $4::text::jsonb, $5::timestamptz, $2)`,
+ [pageId, body, `${body} timeline`, fm, at]);
+ }
+}
+
+function ctx(e: BrainEngine, remote: boolean): OperationContext {
+ return { engine: e, config: { engine: e.kind }, sourceId: SOURCE, remote, dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+}
+
+const getVersions = (e: BrainEngine, remote: boolean, params: Record<string, unknown> = {}) =>
+ operationsByName.get_versions.handler(ctx(e, remote), { slug: 'notes/history', ...params }) as Promise<Array<Record<string, unknown>>>;
+
+const bodies = (rows: Array<Record<string, unknown>>) => rows.map(r => r.compiled_truth);
+
+describe('get_versions limit and include_body (#5234)', () => {
+ test('without params the full history comes back, newest first, pv.id breaking a snapshot tie', async () => {
+ for (const { engine: e } of databases) {
+ expect(bodies(await getVersions(e, false))).toEqual(['body v5 private', 'body v4', 'body v3', 'body v2', 'body v1']);
+ }
+ });
+
+ test('limit is the newest-first prefix of what the caller may read, local and remote', async () => {
+ for (const { engine: e } of databases) {
+ expect(bodies(await getVersions(e, false, { limit: 2 }))).toEqual(['body v5 private', 'body v4']);
+ // The private newest snapshot and the other source's newer version are
+ // filtered in WHERE, so the remote prefix is still two visible versions.
+ expect(bodies(await getVersions(e, true, { limit: 2 }))).toEqual(['body v4', 'body v3']);
+ expect(bodies(await getVersions(e, true, { limit: 50 }))).toEqual(['body v4', 'body v3', 'body v2', 'body v1']);
+ }
+ });
+
+ test('include_body false never selects the body columns and keeps metadata and attribution', async () => {
+ for (const { engine: e } of databases) {
+ const rows = await e.getVersions('notes/history', { sourceId: SOURCE, includeBody: false, limit: 1 });
+ expect(rows).toHaveLength(1);
+ expect(Object.hasOwn(rows[0], 'compiled_truth')).toBe(false);
+ expect(Object.hasOwn(rows[0], 'timeline')).toBe(false);
+ expect(rows[0].title).toBe('body v5 private');
+
+ for (const remote of [false, true]) {
+ const meta = await getVersions(e, remote, { include_body: false });
+ expect(meta.map(r => r.title)).toEqual(remote
+ ? ['body v4', 'body v3', 'body v2', 'body v1']
+ : ['body v5 private', 'body v4', 'body v3', 'body v2', 'body v1']);
+ for (const row of meta) {
+ expect(Object.hasOwn(row, 'compiled_truth')).toBe(false);
+ expect(Object.hasOwn(row, 'timeline')).toBe(false);
+ for (const key of ['id', 'page_id', 'frontmatter', 'snapshot_at']) expect(Object.hasOwn(row, key)).toBe(true);
+ expect(Object.hasOwn(row, 'written_by')).toBe(!remote);
+ }
+ }
+ }
+ });
+
+ test('limit and include_body combine; include_body must be exactly false to drop bodies', async () => {
+ for (const { engine: e } of databases) {
+ const [only] = await getVersions(e, true, { limit: 1, include_body: false });
+ expect(only.title).toBe('body v4');
+ expect(Object.hasOwn(only, 'compiled_truth')).toBe(false);
+ for (const include_body of [true, undefined]) {
+ expect(bodies(await getVersions(e, true, { limit: 1, include_body }))).toEqual(['body v4']);
+ }
+ }
+ });
+
+ test('an invalid explicit limit is refused with invalid_params, never answered with the full history', async () => {
+ const render = { transport: 'stdio' as const, isCallable: () => true, preapproved: () => false };
+ for (const limit of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, 'two', '2', true, 2 ** 60]) {
+ const err = await getVersions(engine, true, { limit }).then(() => undefined, (e: unknown) => e);
+ const env = toAgentError(err, { transport: 'stdio', op: 'get_versions', render });
+ expect(env.code).toBe('invalid_params');
+ expect(env.message).toBe('get_versions: limit must be a positive integer.');
+ expect(env.suggestion).toContain('"limit": 5');
+ expect(JSON.stringify(env)).not.toContain('two');
+ }
+ expect(bodies(await getVersions(engine, true, { limit: null }))).toHaveLength(4);
+ });
+});
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index 87dc89959c..c26ae02cce 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -353,6 +353,8 @@ export const SQL_CASES: SqlCase[] = [
['sourceId', (e) => e.getVersions(SLUG, { sourceId: SRC })],
['sourceIds', (e) => e.getVersions(SLUG, { sourceIds: SRCS })],
['excludePrivate', (e) => e.getVersions(SLUG, { excludePrivate: true })],
+ ['limit', (e) => e.getVersions(SLUG, { sourceId: SRC, limit: 3 })],
+ ['metadataOnly', (e) => e.getVersions(SLUG, { sourceIds: SRCS, includeBody: false })],
]),
...variants('revertToVersion', [
['default', (e) => e.revertToVersion(SLUG, 3)],
diff --git a/test/version-history-privacy.test.ts b/test/version-history-privacy.test.ts
index 31789c379f..b77a1deb38 100644
--- a/test/version-history-privacy.test.ts
+++ b/test/version-history-privacy.test.ts
@@ -75,8 +75,8 @@ test('legacy NULL and absent timeline fields stay unchanged while their body sti
// of fabricating an empty timeline that a caller could mistake for data.
const original = engine.getVersions;
engine.getVersions = async function (this: BrainEngine, ...args: Parameters<BrainEngine['getVersions']>) {
- return (await original.apply(this, args)).map(({ timeline: _timeline, ...version }) => version);
- };
+ return ((await original.apply(this, args)) as PageVersion[]).map(({ timeline: _timeline, ...version }) => version);
+ } as BrainEngine['getVersions'];
try {
const [absent] = await history(engine, slug, true);
expect(absent.timeline).toBeUndefined(); expect(Object.hasOwn(absent, 'timeline')).toBe(false);