Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(delta): per-arm cursor with a legacy-safe contract (P0, migration v208)

garrytan9010001c9e2c
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index deaa60e26a..0b2a679701 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -245,6 +245,7 @@ jobs:
test/company-brain-policy.test.ts
test/company-brain-runtime.test.ts
test/delta-cursor-integrity.test.ts
+ test/engine-sql-facts-keyset.test.ts
test/derived-link-reconciliation.test.ts
test/doctor-frontmatter-holds.test.ts
test/embedding-completion-atomic.serial.test.ts
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 2aafb128a8..c9e4a6ea9c 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -139,7 +139,7 @@ Every non-localOnly operation on the MCP surface: 139 tools across 23 areas. **S
| Tool | Description | Scope | Starter | Gate |
|---|---|---|---|---|
| `context_pack` | MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
-| `delta` | MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. | read | yes | |
+| `delta` | MEMORY VERB (v1): pages, facts, thread events changed since a cursor, zero LLM. | read | yes | |
| `entity` | MEMORY VERB (v1): person/company/account card, zero LLM. | read | yes | |
| `forget` | MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). | write | yes | |
| `recall` | MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. | read | yes | |
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 73c8936dce..e9345bc76a 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -599,6 +599,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The brain database could not be reached or refused the operation. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |
+### delta_cursor_upgrade_required
+
+<a id="delta_cursor_upgrade_required"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A since/since_slug delta call reached more undelivered facts at one timestamp than that cursor can page; repeat the call with the opaque cursor. | The legacy cursor is a single timestamp, so facts that share one can only be paged by fact id, which next_cursor.cursor carries. Nothing was skipped and no cursor moved. | Repeat the delta call with the cursor from fix (next_cursor.cursor) instead of since/since_slug, and keep passing next_cursor.cursor afterwards. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/guides/ambient-recall.md#replay-after-a-degraded-wake)
+
### demo_graph_failed
<a id="demo_graph_failed"></a>
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8402fe67bb..27c100c740 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3253 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
src/core/cycle/synthesize.ts 3312 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)
src/core/cycle/extract-atoms.ts 1809 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)
-src/core/engine.ts 2693 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)
+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/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 2987 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
-src/core/postgres-engine.ts 2924 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
+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/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 2210 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)
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/context/delta-cursor.ts b/src/core/context/delta-cursor.ts
new file mode 100644
index 0000000000..bdd86c2f45
--- /dev/null
+++ b/src/core/context/delta-cursor.ts
@@ -0,0 +1,261 @@
+/**
+ * delta's per-arm cursor (contributor audit wave P0). Pages page by the
+ * keyset `(updated_at, slug)`, facts by `(created_at, id)`, both at column
+ * (microsecond) precision. Each arm advances through the prefix it actually
+ * delivered and no further; an arm whose result is unknown does not move.
+ *
+ * The opaque `cursor` request param carries both keysets; the legacy
+ * `since`/`slug` pair stays conservative so an older client re-sees pages but
+ * never skips facts. Pure: no engine access.
+ */
+
+/** Pages arm position. `slug` undefined = strictly after `since` (a legacy stateless call). */
+export interface PagesPos { since: string; slug?: string }
+/** Facts arm position. `id` null = strictly after `at` (a legacy `since`). */
+export interface FactsPos { at: string; id: number | null }
+export interface DeltaPosition { pages: PagesPos; facts: FactsPos }
+
+/** Rows committed in a transaction that started before this lag can still be missed (documented bound). */
+export const DELTA_COMMIT_LAG_MS = 2_000;
+export const DELTA_TIMESTAMP_RANGE = '0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999Z';
+
+const MICRO_ISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/;
+
+/** Normalize an ISO UTC timestamp to the 6-digit `…ss.ffffffZ` shape so lexicographic order is time order. */
+export function toMicroIso(iso: string): string {
+ const m = MICRO_ISO.exec(iso);
+ if (m) return `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}.${(m[7] ?? '').padEnd(6, '0')}Z`;
+ return toMicroIso(new Date(Date.parse(iso)).toISOString());
+}
+
+/** Microseconds since the epoch, exact (BigInt) for a micro-ISO string. */
+function toMicros(iso: string): bigint {
+ const m = toMicroIso(iso);
+ return BigInt(Date.parse(`${m.slice(0, 19)}Z`)) * 1000n + BigInt(m.slice(20, 26));
+}
+
+function fromMicros(us: bigint): string {
+ const ms = us / 1000n - (us % 1000n < 0n ? 1n : 0n);
+ const rem = us - ms * 1000n;
+ const base = new Date(Number(ms)).toISOString();
+ return `${base.slice(0, 23)}${String(rem).padStart(3, '0')}Z`;
+}
+
+/** One microsecond earlier: the strictly-earlier clamp at column precision. */
+export function microBefore(iso: string): string {
+ return fromMicros(toMicros(iso) - 1n);
+}
+
+export function horizonIso(now: number = Date.now()): string {
+ return toMicroIso(new Date(now - DELTA_COMMIT_LAG_MS).toISOString());
+}
+
+/**
+ * Validate a timestamp the way delta's `since` is validated: parseable,
+ * a real calendar date, and inside 0001-9999 on the PARSED (UTC) value,
+ * so an offset cannot smuggle year 0 or an extended year past the check.
+ * Returns the canonical form or an error message.
+ */
+export function checkDeltaTimestamp(raw: string): { ok: true; value: string } | { ok: false; why: 'unparseable' | 'calendar' | 'range' } {
+ const ms = Date.parse(raw);
+ if (!Number.isFinite(ms)) return { ok: false, why: 'unparseable' };
+ if (/^[+-]/.test(raw.trim())) return { ok: false, why: 'range' };
+ const iso = raw.match(/^(\d{4})-(\d{2})-(\d{2})T/);
+ if (iso) {
+ const [year, month, day] = iso.slice(1).map(Number);
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
+ const dim = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+ if (month < 1 || month > 12 || day < 1 || day > dim[month - 1]) return { ok: false, why: 'calendar' };
+ }
+ const year = new Date(ms).getUTCFullYear();
+ if (year < 1 || year > 9999) return { ok: false, why: 'range' };
+ return {
+ ok: true,
+ value: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(raw) ? raw : new Date(ms).toISOString(),
+ };
+}
+
+/** Total order on pages positions; an undefined slug sorts after every slug at that timestamp. */
+export function comparePages(a: PagesPos, b: PagesPos): number {
+ const t = toMicroIso(a.since).localeCompare(toMicroIso(b.since));
+ if (t !== 0) return t;
+ if (a.slug === b.slug) return 0;
+ if (a.slug === undefined) return 1;
+ if (b.slug === undefined) return -1;
+ return a.slug < b.slug ? -1 : 1;
+}
+
+/** Total order on facts positions; a null id sorts after every id at that timestamp. */
+export function compareFacts(a: FactsPos, b: FactsPos): number {
+ const t = toMicroIso(a.at).localeCompare(toMicroIso(b.at));
+ if (t !== 0) return t;
+ if (a.id === b.id) return 0;
+ if (a.id === null) return 1;
+ if (b.id === null) return -1;
+ return a.id < b.id ? -1 : 1;
+}
+
+const maxPages = (a: PagesPos, b: PagesPos) => (comparePages(a, b) >= 0 ? a : b);
+const maxFacts = (a: FactsPos, b: FactsPos) => (compareFacts(a, b) >= 0 ? a : b);
+
+/** Opaque wire form: base64url JSON `{v:1, p:[since, slug], f:[at, id]}`. */
+export function encodeDeltaCursor(pos: DeltaPosition): string {
+ const body = { v: 1, p: [pos.pages.since, pos.pages.slug ?? null], f: [pos.facts.at, pos.facts.id] };
+ return Buffer.from(JSON.stringify(body), 'utf8').toString('base64url');
+}
+
+const MAX_CURSOR_LEN = 2_048;
+const MAX_SLUG_LEN = 512;
+
+/** Decode + validate a `cursor` param. Returns the position or the reason it was refused. */
+export function decodeDeltaCursor(raw: string): { ok: true; pos: DeltaPosition } | { ok: false; why: string } {
+ if (raw.length > MAX_CURSOR_LEN || !/^[A-Za-z0-9_-]+$/.test(raw)) return { ok: false, why: 'not a cursor returned by delta (expected base64url)' };
+ let body: unknown;
+ try {
+ body = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
+ } catch {
+ return { ok: false, why: 'not a cursor returned by delta (undecodable)' };
+ }
+ const b = body as { v?: unknown; p?: unknown; f?: unknown };
+ if (!b || typeof b !== 'object' || b.v !== 1 || !Array.isArray(b.p) || !Array.isArray(b.f) || b.p.length !== 2 || b.f.length !== 2) {
+ return { ok: false, why: 'not a version-1 delta cursor' };
+ }
+ const [ps, pslug] = b.p as unknown[];
+ const [fa, fid] = b.f as unknown[];
+ if (typeof ps !== 'string' || typeof fa !== 'string') return { ok: false, why: 'cursor timestamps must be strings' };
+ for (const ts of [ps, fa]) {
+ const c = checkDeltaTimestamp(ts);
+ if (!c.ok) return { ok: false, why: c.why === 'range' ? `cursor timestamp outside ${DELTA_TIMESTAMP_RANGE}` : 'cursor timestamp is not a valid ISO 8601 calendar timestamp' };
+ }
+ if (pslug !== null && (typeof pslug !== 'string' || pslug.length > MAX_SLUG_LEN)) return { ok: false, why: 'cursor page slug is invalid' };
+ if (fid !== null && (typeof fid !== 'number' || !Number.isSafeInteger(fid) || fid < 0)) return { ok: false, why: 'cursor fact id must be a non-negative integer' };
+ const canonical = (ts: string) => (checkDeltaTimestamp(ts) as { value: string }).value;
+ return {
+ ok: true,
+ pos: {
+ pages: { since: canonical(ps), ...(pslug !== null ? { slug: pslug as string } : {}) },
+ facts: { at: canonical(fa), id: fid as number | null },
+ },
+ };
+}
+
+/** Whether an arm's read completed (`ok`), threw (`failed`) or never finished before the deadline (`unknown`). */
+export type ArmStatus = 'ok' | 'failed' | 'unknown';
+
+/**
+ * Next pages position: through the last DELIVERED page at or before the
+ * horizon. An empty, complete, undropped session arm advances to the horizon (rows
+ * from a transaction that commits later than the lag can still be missed —
+ * the documented bound). Anything else holds.
+ */
+export function nextPagesPos(input: {
+ start: PagesPos;
+ complete: boolean;
+ delivered: Array<{ updated_at: string; slug: string }>;
+ undelivered: boolean;
+ horizon: string;
+ /** Session callers move an empty, complete arm up to the horizon; a stateless cursor stays put (its caller owns it). */
+ advanceOnEmpty: boolean;
+}): PagesPos {
+ const { start, complete, delivered, undelivered, horizon, advanceOnEmpty } = input;
+ if (!complete) return start;
+ let next = start;
+ for (const p of delivered) {
+ if (toMicroIso(p.updated_at) > horizon) return next;
+ next = { since: p.updated_at, slug: p.slug };
+ }
+ if (delivered.length === 0 && !undelivered && advanceOnEmpty) return maxPages(start, { since: horizon, slug: '' });
+ return next;
+}
+
+export interface RawFactRef { id: number; at: string; repId: number }
+
+/**
+ * Next facts position, computed from the RAW rows (duplicate collapse emits a
+ * cluster's newest row at its first-seen position): the largest raw row such
+ * that every raw row at or below it belongs to a delivered cluster and is at
+ * or before the horizon. Also returns the oldest raw row NOT covered, which
+ * the conservative legacy cursor must stay strictly before.
+ */
+export function nextFactsPos(input: {
+ start: FactsPos;
+ complete: boolean;
+ raw: RawFactRef[];
+ overflowRow: { id: number; at: string } | null;
+ deliveredRepIds: ReadonlySet<number>;
+ horizon: string;
+ advanceOnEmpty: boolean;
+}): { next: FactsPos; oldestUndelivered: string | null } {
+ const { start, complete, raw, overflowRow, deliveredRepIds, horizon, advanceOnEmpty } = input;
+ if (!complete) return { next: start, oldestUndelivered: null };
+ const oldestUndelivered = raw.find((r) => !deliveredRepIds.has(r.repId))?.at ?? overflowRow?.at ?? null;
+ if (raw.length === 0 && !overflowRow) return { next: advanceOnEmpty ? maxFacts(start, { at: horizon, id: 0 }) : start, oldestUndelivered };
+ let next = start;
+ for (const r of raw) {
+ if (!deliveredRepIds.has(r.repId) || toMicroIso(r.at) > horizon) break;
+ next = { at: r.at, id: r.id };
+ }
+ return { next, oldestUndelivered };
+}
+
+/** Session row fields delta resumes from (see session-state.ts DeltaSessionState). */
+interface SessionCursor {
+ last_wake_at: string | null;
+ cursor_slug: string | undefined;
+ facts_cursor_at: string | null;
+ facts_cursor_id: number | null;
+}
+
+/**
+ * Where a delta call starts. Precedence: explicit `cursor` > explicit `since`
+ * (both arms strictly after it, slug only when supplied) > the session row
+ * (`since_slug` may override its slug) > none (a first wake).
+ */
+export function resolveDeltaStart(input: {
+ cursorPos: DeltaPosition | null;
+ explicitSince: string | null;
+ explicitSlug: string | undefined;
+ session: SessionCursor | null;
+}): DeltaPosition | null {
+ const { cursorPos, explicitSince, explicitSlug, session } = input;
+ if (cursorPos) return cursorPos;
+ if (explicitSince) {
+ return { pages: { since: explicitSince, ...(explicitSlug !== undefined ? { slug: explicitSlug } : {}) }, facts: { at: explicitSince, id: null } };
+ }
+ if (!session?.last_wake_at) return null;
+ const slug = explicitSlug ?? session.cursor_slug;
+ return {
+ pages: { since: session.last_wake_at, ...(slug !== undefined ? { slug } : {}) },
+ facts: session.facts_cursor_at ? { at: session.facts_cursor_at, id: session.facts_cursor_id } : { at: session.last_wake_at, id: null },
+ };
+}
+
+/**
+ * The conservative single cursor for clients that do not send `cursor`.
+ * No advance at all while any arm is failed or unknown; otherwise the last
+ * delivered page, or on a page-less wake the newest delivered fact (an old
+ * client reads facts strictly after `since`, so a budget that fits only part
+ * of the facts still drains them). Never at or past the oldest undelivered
+ * fact: it clamps one microsecond before it and resets the slug.
+ */
+export function legacyDeltaCursor(input: {
+ start: DeltaPosition;
+ pagesNext: PagesPos;
+ factsNext: FactsPos;
+ oldestUndelivered: string | null;
+ incomplete: boolean;
+ pagesDelivered: number;
+ factsDelivered: number;
+ pagesQuiet: boolean;
+}): { legacy: PagesPos; clamped: boolean } {
+ const { start, pagesNext, factsNext, oldestUndelivered, incomplete, pagesDelivered, factsDelivered, pagesQuiet } = input;
+ if (incomplete) return { legacy: start.pages, clamped: false };
+ const legacy: PagesPos =
+ pagesDelivered > 0 ? pagesNext
+ : pagesQuiet && factsDelivered > 0 && compareFacts(factsNext, start.facts) > 0 ? { since: factsNext.at, slug: '' }
+ : start.pages;
+ if (oldestUndelivered !== null && toMicroIso(legacy.since) >= toMicroIso(oldestUndelivered)) {
+ return { legacy: { since: microBefore(oldestUndelivered), slug: '' }, clamped: true };
+ }
+ return { legacy, clamped: false };
+}
diff --git a/src/core/context/session-state.ts b/src/core/context/session-state.ts
index e059ea70b8..b476166079 100644
--- a/src/core/context/session-state.ts
+++ b/src/core/context/session-state.ts
@@ -53,8 +53,31 @@ export interface SessionContextPatch {
* bucket). Stored in the surfaced_slugs jsonb column (single-element).
*/
cursorSlug?: string;
+ /** delta's facts keyset `(created_at, id)` at column precision (omit to leave unchanged). */
+ factsCursor?: { at: string; id: number | null };
+ /** `increment` adds one atomically (returned); `reset` sets 0 (omit to leave unchanged). */
+ degradedWakes?: 'increment' | 'reset';
}
+/** delta's view of a session row: both arm cursors plus the incomplete-wake counter. */
+export interface DeltaSessionState {
+ last_wake_at: string | null;
+ cursor_slug: string | undefined;
+ facts_cursor_at: string | null;
+ facts_cursor_id: number | null;
+ degraded_wakes: number;
+}
+
+/**
+ * delta reads distinguish ABSENT (no row: a first wake) from UNAVAILABLE (the
+ * read failed). Treating a failed read as absence would re-initialize the
+ * session at now and silently drop everything since its checkpoint.
+ */
+export type DeltaSessionRead =
+ | { status: 'absent' }
+ | { status: 'loaded'; state: DeltaSessionState }
+ | { status: 'unavailable'; error: string };
+
/** 'local' sentinel for the trusted CLI/hook path; the auth client id otherwise. */
export function resolveClientId(clientId?: string | null): string {
return typeof clientId === 'string' && clientId.trim()
@@ -113,6 +136,45 @@ export async function getSessionContextState(
}
}
+const ISO_US = (col: string) => `to_char(${col} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+export async function readDeltaSessionState(
+ engine: BrainEngine,
+ sourceId: string,
+ clientId: string | null | undefined,
+ sessionId: string,
+): Promise<DeltaSessionRead> {
+ try {
+ const rows = await engine.executeRaw<{
+ surfaced_slugs: unknown;
+ last_wake_at: string | null;
+ facts_cursor_at: string | null;
+ facts_cursor_id: string | number | null;
+ degraded_wakes: string | number | null;
+ }>(
+ `SELECT surfaced_slugs, ${ISO_US('last_wake_at')} AS last_wake_at,
+ ${ISO_US('facts_cursor_at')} AS facts_cursor_at, facts_cursor_id, degraded_wakes
+ FROM session_context_state
+ WHERE source_id = $1 AND client_id = $2 AND session_id = $3`,
+ [sourceId, resolveClientId(clientId), normSession(sessionId)],
+ );
+ if (!rows.length) return { status: 'absent' };
+ const r = rows[0];
+ return {
+ status: 'loaded',
+ state: {
+ last_wake_at: r.last_wake_at ?? null,
+ cursor_slug: toStringArray(r.surfaced_slugs)[0],
+ facts_cursor_at: r.facts_cursor_at ?? null,
+ facts_cursor_id: r.facts_cursor_id == null ? null : Number(r.facts_cursor_id),
+ degraded_wakes: Number(r.degraded_wakes ?? 0),
+ },
+ };
+ } catch (e) {
+ return { status: 'unavailable', error: e instanceof Error ? e.message : String(e) };
+ }
+}
+
/**
* Upsert the session cursor. SINGLE-STATEMENT atomic (adversarial review):
* keep-if-absent and monotonic-cursor semantics run inside the UPDATE itself,
@@ -132,21 +194,30 @@ export async function upsertSessionContextState(
clientId: string | null | undefined,
sessionId: string,
patch: SessionContextPatch,
-): Promise<void> {
+): Promise<{ ok: true; degradedWakes: number } | { ok: false; error: string }> {
try {
const replaceStanding = Array.isArray(patch.standingEntities);
const replaceCursorSlug = typeof patch.cursorSlug === 'string';
- await engine.executeRaw(
+ const rows = await engine.executeRaw<{ degraded_wakes: string | number }>(
`INSERT INTO session_context_state
- (source_id, client_id, session_id, standing_entities, surfaced_slugs, last_wake_at, updated_at)
- VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6, now())
+ (source_id, client_id, session_id, standing_entities, surfaced_slugs, last_wake_at,
+ facts_cursor_at, facts_cursor_id, degraded_wakes, updated_at)
+ VALUES ($1, $2, $3, $4::text::jsonb, $5::text::jsonb, $6::text::timestamptz, $9::text::timestamptz, $10::bigint,
+ CASE WHEN $11::text = 'increment' THEN 1 ELSE 0 END, now())
ON CONFLICT (source_id, client_id, session_id) DO UPDATE SET
standing_entities = CASE WHEN $7::boolean THEN EXCLUDED.standing_entities
ELSE session_context_state.standing_entities END,
surfaced_slugs = CASE WHEN $8::boolean THEN EXCLUDED.surfaced_slugs
ELSE session_context_state.surfaced_slugs END,
last_wake_at = COALESCE(EXCLUDED.last_wake_at, session_context_state.last_wake_at),
- updated_at = now()`,
+ facts_cursor_at = COALESCE(EXCLUDED.facts_cursor_at, session_context_state.facts_cursor_at),
+ facts_cursor_id = CASE WHEN EXCLUDED.facts_cursor_at IS NULL THEN session_context_state.facts_cursor_id
+ ELSE EXCLUDED.facts_cursor_id END,
+ degraded_wakes = CASE $11::text WHEN 'increment' THEN session_context_state.degraded_wakes + 1
+ WHEN 'reset' THEN 0
+ ELSE session_context_state.degraded_wakes END,
+ updated_at = now()
+ RETURNING degraded_wakes`,
[
sourceId,
resolveClientId(clientId),
@@ -156,10 +227,15 @@ export async function upsertSessionContextState(
patch.lastWakeAt ?? null,
replaceStanding,
replaceCursorSlug,
+ patch.factsCursor?.at ?? null,
+ patch.factsCursor ? patch.factsCursor.id : null,
+ patch.degradedWakes ?? 'keep',
],
);
- } catch {
- /* fail-open: a state-write failure must never block the recall read path */
+ return { ok: true, degradedWakes: Number(rows[0]?.degraded_wakes ?? 0) };
+ } catch (e) {
+ /* fail-open: a state-write failure never blocks the read path; delta surfaces it as `session_state` */
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
}
}
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 37cfad3e70..44ee6e5371 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -37,6 +37,7 @@ import {
import { volunteerContext, type VolunteeredPage } from './volunteer.ts';
import { getBrainHotMemoryMeta } from '../facts/meta-hook.ts';
import { collapseHotFacts } from '../facts/capture-dedup.ts';
+import type { ArmStatus, RawFactRef } from './delta-cursor.ts';
import { buildEntityCard, type EntityCard, type EntityOpenThread } from '../verbs/entity-card.ts';
import { estimateTokens } from '../search/token-budget.ts';
import type { DecideSlotMeta } from '../search/decide-stage.ts';
@@ -124,6 +125,16 @@ export interface TurnContextResult {
deltaOverflow?: boolean;
/** pack/delta mode — the hot facts included (structured, for the verb JSON). */
facts?: TurnContextFact[];
+ /**
+ * delta mode — per-arm completion captured in the SAME snapshot as the
+ * arrays: `ok` (read completed), `failed` (read threw), `unknown` (the
+ * deadline fired first). The verb advances only `ok` arms.
+ */
+ deltaArms?: { pages: ArmStatus; facts: ArmStatus; threads: ArmStatus };
+ /** delta mode — every raw fact row the facts arm read (oldest first) with its collapsed representative. */
+ deltaFactsRaw?: RawFactRef[];
+ /** delta mode — the facts arm's limit+1 probe row when more facts are waiting. */
+ deltaFactsOverflowRow?: { id: number; at: string } | null;
/** The mode this result was assembled in. */
mode?: ContextMode;
/**
@@ -173,6 +184,12 @@ export interface AssembleTurnContextOpts {
* timestamp pages deterministically. Facts/threads still use `since` (time).
*/
sinceSlug?: string;
+ /**
+ * delta — the facts arm's own keyset (contributor audit wave P0): facts
+ * strictly after `(at, id)` (`id: null` = strictly after `at`). Defaults to
+ * `{ at: since, id: null }`, the legacy shared time cursor.
+ */
+ factsAfter?: { at: string; id: number | null };
/**
* Widen ALL arms to include private facts. Default false = world-only
* (the safe injected-context posture). Fail-closed: only an explicit `true`
@@ -547,6 +564,8 @@ async function assemblePack(
*/
/** Max changed pages fetched per delta call (+1 probe row detects overflow). */
export const DELTA_PAGE_FETCH_LIMIT = 50;
+/** Max facts fetched per delta call (+1 probe row detects overflow). */
+export const DELTA_FACT_FETCH_LIMIT = 50;
async function assembleDelta(
engine: BrainEngine,
@@ -554,15 +573,19 @@ async function assembleDelta(
): Promise<TurnContextResult> {
const remote = opts.includePrivate !== true;
const since = typeof opts.since === 'string' && opts.since.trim() ? opts.since : undefined;
+ // Each arm publishes its result in ONE assignment when it completes, so the
+ // snapshot taken after the deadline race sees an arm either whole or absent
+ // (`unknown`), never half-filled.
const acc: {
- pages: DeltaPage[];
- overflow: boolean;
- facts: TurnContextFact[];
- threads: EntityOpenThread[];
- failedArms: ('pages' | 'facts')[];
- } = { pages: [], overflow: false, facts: [], threads: [], failedArms: [] };
+ pages?: { status: 'ok'; rows: DeltaPage[]; overflow: boolean } | { status: 'failed' };
+ facts?:
+ | { status: 'ok'; facts: TurnContextFact[]; raw: RawFactRef[]; overflowRow: { id: number; at: string } | null }
+ | { status: 'failed' };
+ threads?: { status: ArmStatus; items: EntityOpenThread[] };
+ } = {};
const deadlineAt =
typeof opts.deadlineMs === 'number' && opts.deadlineMs > 0 ? Date.now() + opts.deadlineMs : null;
+ const pastDeadline = () => deadlineAt !== null && Date.now() >= deadlineAt;
const build = (async () => {
if (since) {
@@ -585,40 +608,49 @@ async function assembleDelta(
limit: DELTA_PAGE_FETCH_LIMIT + 1,
sort: 'updated_asc',
});
- acc.overflow = pages.length > DELTA_PAGE_FETCH_LIMIT;
- acc.pages = pages.slice(0, DELTA_PAGE_FETCH_LIMIT).map((p) => ({
- slug: p.slug,
- source_id: opts.sourceId,
- title: p.title,
- // Column-precision cursor: `next_cursor.since` minted from a JS Date
- // re-selects every same-millisecond row on the next wake.
- updated_at:
- p.updated_at_iso ?? (p.updated_at instanceof Date ? p.updated_at.toISOString() : String(p.updated_at)),
- }));
+ acc.pages = {
+ status: 'ok',
+ overflow: pages.length > DELTA_PAGE_FETCH_LIMIT,
+ rows: pages.slice(0, DELTA_PAGE_FETCH_LIMIT).map((p) => ({
+ slug: p.slug,
+ source_id: opts.sourceId,
+ title: p.title,
+ // Column-precision cursor: `next_cursor.since` minted from a JS Date
+ // re-selects every same-millisecond row on the next wake.
+ updated_at:
+ p.updated_at_iso ?? (p.updated_at instanceof Date ? p.updated_at.toISOString() : String(p.updated_at)),
+ })),
+ };
} catch {
- acc.pages = [];
- acc.failedArms.push('pages');
+ acc.pages = { status: 'failed' };
}
}
// Facts arm: query the store DIRECTLY by recording time (pre-landing
// review): the hot-memory meta hook's fallback window is 24h/topK-25, so a
// cursor older than a day would silently miss facts recorded between the
- // cursor and yesterday — the exact O(changes) contract violation delta
- // exists to prevent. "New since" means created_at (recording time).
- if (deadlineAt === null || Date.now() < deadlineAt) {
+ // cursor and yesterday. Contributor audit wave P0: OLDEST first after the
+ // arm's own (created_at, id) keyset with a limit+1 probe, so the facts
+ // dropped by the limit are the NEWEST ones, past the advanced keyset.
+ if (!pastDeadline()) {
try {
- const sinceDate = since ? new Date(since) : new Date(0);
+ const after = opts.factsAfter ?? (since ? { at: since, id: null } : null);
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
- const rows = await engine.listFactsSince(opts.sourceId, sinceDate, {
- activeOnly: true,
- limit: 50,
- visibility,
- fingerprint: true,
- });
+ const rows = await engine.listFactsKeyset(
+ opts.sourceId,
+ after ? { createdAt: after.at, id: after.id } : null,
+ { activeOnly: true, limit: DELTA_FACT_FETCH_LIMIT + 1, visibility, fingerprint: true },
+ );
+ const kept = rows.slice(0, DELTA_FACT_FETCH_LIMIT);
+ const probe = rows.length > DELTA_FACT_FETCH_LIMIT ? rows[DELTA_FACT_FETCH_LIMIT] : null;
+ const iso = (r: (typeof rows)[number]) => r.created_at_iso ?? r.created_at.toISOString();
+ const members = new Map<number, number>();
// #5888: duplicates collapse to their newest representative, as in hot memory.
- acc.facts = (await collapseHotFacts(engine, opts.sourceId, rows))
- .filter((r) => !since || isAfter(r.created_at.toISOString(), since))
- .map((r) => ({
+ const collapsed = await collapseHotFacts(engine, opts.sourceId, kept, members);
+ acc.facts = {
+ status: 'ok',
+ raw: kept.map((r) => ({ id: r.id, at: iso(r), repId: members.get(r.id) ?? r.id })),
+ overflowRow: probe ? { id: probe.id, at: iso(probe) } : null,
+ facts: collapsed.map((r) => ({
id: r.id,
fact: r.fact,
kind: r.kind,
@@ -630,47 +662,67 @@ async function assembleDelta(
// #4206: provenance context rides delta like the other projections.
context: r.context ?? null,
confidence: r.confidence,
- }));
+ })),
+ };
} catch {
- acc.facts = [];
- acc.failedArms.push('facts');
+ acc.facts = { status: 'failed' };
}
}
+ // Threads are best-effort: buildEntityCard caps and swallows internally,
+ // and thread events key on event date, not a keyset. A throw still marks
+ // the arm `failed` (degraded_reason `threads`) and holds the time cursor
+ // the events follow.
const entities = (opts.entities ?? [])
.filter((e) => typeof e === 'string' && e.trim())
.slice(0, clampPositive(opts.maxEntities, PACK_DEFAULT_MAX_ENTITIES));
+ const items: EntityOpenThread[] = [];
+ let failed = false;
for (const name of entities) {
- if (deadlineAt !== null && Date.now() >= deadlineAt) return;
+ if (pastDeadline()) return;
try {
const res = await buildEntityCard(engine, opts.sourceId, name, { remote });
if (res.found && res.card) {
for (const t of res.card.open_threads ?? []) {
- if (!since || (t.date && isAfter(t.date, since))) acc.threads.push(t);
+ if (!since || (t.date && isAfter(t.date, since))) items.push(t);
}
}
} catch {
- /* fail-soft */
+ failed = true;
}
}
+ acc.threads = { status: failed ? 'failed' : 'ok', items };
})();
const deadlineReason = await raceDeadline(build, opts.deadlineMs);
- const degradedReason = [deadlineReason, ...acc.failedArms].filter(Boolean).join(',') || undefined;
- // Snapshot copies — same post-deadline mutation hazard as assemblePack.
- const pages = [...acc.pages];
- const facts = [...acc.facts];
- const threads = [...acc.threads];
+ // ONE snapshot: arm flags and arrays come from the same read of `acc`.
+ const snap = { ...acc };
+ const pagesArm = snap.pages;
+ const factsArm = snap.facts;
+ const threadsArm = snap.threads;
+ const arms = {
+ pages: (since ? pagesArm?.status ?? 'unknown' : 'ok') as ArmStatus,
+ facts: (factsArm?.status ?? 'unknown') as ArmStatus,
+ threads: (threadsArm?.status ?? 'unknown') as ArmStatus,
+ };
+ const failedArms = (['pages', 'facts', 'threads'] as const).filter((a) => arms[a] === 'failed');
+ const degradedReason = [deadlineReason, ...failedArms].filter(Boolean).join(',') || undefined;
+ const pages = pagesArm?.status === 'ok' ? [...pagesArm.rows] : [];
+ const facts = factsArm?.status === 'ok' ? [...factsArm.facts] : [];
+ const threads = [...(threadsArm?.items ?? [])];
const text = renderDelta(pages, facts, threads, since);
return {
text,
pointers: [],
factsCount: facts.length,
deltaPages: pages,
- deltaOverflow: acc.overflow,
+ deltaOverflow: pagesArm?.status === 'ok' && pagesArm.overflow,
openThreads: threads,
facts,
mode: 'delta',
+ deltaArms: arms,
+ deltaFactsRaw: factsArm?.status === 'ok' ? factsArm.raw : [],
+ deltaFactsOverflowRow: factsArm?.status === 'ok' ? factsArm.overflowRow : null,
...(degradedReason ? { degradedReason } : {}),
};
}
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 21d7426ed6..3140f33377 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -400,6 +400,45 @@ export async function listFactsSince(
return rows.map(rowToFact);
}
+/**
+ * delta's facts arm (contributor audit wave P0): facts strictly after a
+ * `(created_at, id)` keyset, OLDEST first, so a caller that delivers a prefix
+ * can advance its keyset through exactly what it delivered. `after.id = null`
+ * means "strictly after the timestamp" (a legacy `since`). `created_at_iso`
+ * projects the column's microseconds: a keyset minted from a JS Date would
+ * re-select or skip same-millisecond rows, and the bound goes through
+ * `::text::timestamptz` so the postgres.js driver cannot truncate it to
+ * milliseconds on the way in. recall's newest-first
+ * `listFactsSince` is unchanged.
+ */
+export async function listFactsKeyset(
+ exec: LegacyUnscopedRead,
+ source_id: string,
+ after: { createdAt: string; id: number | null } | null,
+ opts?: FactListOpts,
+): Promise<FactRow[]> {
+ const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);
+ const activeOnly = opts?.activeOnly !== false;
+ const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;
+ const afterCondition = after === null
+ ? sqlFragment``
+ : after.id === null
+ ? sqlFragment`AND created_at > ${after.createdAt}::text::timestamptz`
+ : sqlFragment`AND (created_at > ${after.createdAt}::text::timestamptz OR (created_at = ${after.createdAt}::text::timestamptz AND id > ${after.id}))`;
+ const rows = (await exec.run<FactRowSqlShape>(sqlFragment`
+ SELECT *${opts?.fingerprint ? sqlFragment`, gbrain_fact_fingerprint(fact) AS fact_fingerprint` : sqlFragment``},
+ to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS created_at_iso
+ FROM facts
+ WHERE source_id = ${source_id}
+ ${afterCondition}
+ ${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}
+ ORDER BY created_at ASC, id ASC
+ LIMIT ${limit}
+ `)).rows;
+ return rows.map(rowToFact);
+}
+
export async function listFactsBySession(
exec: LegacyUnscopedRead,
source_id: string,
@@ -657,6 +696,7 @@ interface FactRowSqlShape {
embedded_at: Date | null;
created_at: Date;
fact_fingerprint?: string | null;
+ created_at_iso?: string | null;
}
/**
@@ -709,6 +749,7 @@ function rowToFact(raw: FactRowSqlShape): FactRow {
embedded_at: row.embedded_at,
created_at: row.created_at,
...(row.fact_fingerprint ? { fact_fingerprint: row.fact_fingerprint } : {}),
+ ...(row.created_at_iso ? { created_at_iso: row.created_at_iso } : {}),
};
}
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 6f4a71b874..51deedf279 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -343,9 +343,13 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
// Exact only when the cursor carries the column's microseconds: callers
// resume from `Page.updated_at_iso` (projected below), never from a JS
// Date, which would re-select every row in the last row's millisecond.
- ? sqlFragment`AND (p.updated_at > ${keyset.updatedAt}::timestamptz OR (p.updated_at = ${keyset.updatedAt}::timestamptz AND p.slug > ${keyset.slug}))`
+ // `::text::timestamptz`: a bare `::timestamptz` param is typed by the
+ // postgres.js driver, which serializes strings through a JS Date and
+ // truncates the cursor to milliseconds (re-selecting the whole
+ // millisecond; a >limit cluster inside one millisecond never drains).
+ ? sqlFragment`AND (p.updated_at > ${keyset.updatedAt}::text::timestamptz OR (p.updated_at = ${keyset.updatedAt}::text::timestamptz AND p.slug > ${keyset.slug}))`
: updatedAfter
- ? sqlFragment`AND p.updated_at > ${updatedAfter}::timestamptz`
+ ? sqlFragment`AND p.updated_at > ${updatedAfter}::text::timestamptz`
: sqlFragment``;
// slugPrefix uses the (source_id, slug) UNIQUE btree index for range scans.
// Escape LIKE metacharacters so the user prefix is treated as a literal.
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 2cbb524c14..cef81dc187 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -537,6 +537,8 @@ export interface FactRow {
created_at: Date;
/** Set only when the list call asked for `fingerprint` (#5888 hot-memory collapse). */
fact_fingerprint?: string;
+ /** Set by `listFactsKeyset`: created_at at the column's microsecond precision (ISO UTC). */
+ created_at_iso?: string;
}
/** Input for insertFact. source_id supplied via the ctx arg. */
@@ -2207,6 +2209,18 @@ export interface BrainEngine {
opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]>;
+ /**
+ * delta's facts arm: facts strictly after a `(created_at, id)` keyset
+ * (`id: null` = strictly after the timestamp), OLDEST first, each row with
+ * `created_at_iso` at column precision. Honors activeOnly, visibility,
+ * fingerprint and limit only.
+ */
+ listFactsKeyset(
+ source_id: string,
+ after: { createdAt: string; id: number | null } | null,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]>;
+
/** List facts captured under a session id within a source. */
listFactsBySession(
source_id: string,
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index ae61881b91..848fc3b0a5 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -112,6 +112,13 @@ export const CODES = {
cycle_failed: { class: 'server', summary: "The maintenance (dream) cycle failed, or a phase threw and was contained so later phases could run." },
d_sel_too_small: { class: 'caller', summary: "The selection split has too few tasks for meaningful validation." },
database_error: { class: 'server', summary: "The brain database could not be reached or refused the operation." },
+ delta_cursor_upgrade_required: {
+ class: 'caller',
+ summary: "A since/since_slug delta call reached more undelivered facts at one timestamp than that cursor can page; repeat the call with the opaque cursor.",
+ why: "The legacy cursor is a single timestamp, so facts that share one can only be paged by fact id, which next_cursor.cursor carries. Nothing was skipped and no cursor moved.",
+ suggestion: "Repeat the delta call with the cursor from fix (next_cursor.cursor) instead of since/since_slug, and keep passing next_cursor.cursor afterwards.",
+ docs: 'docs/guides/ambient-recall.md#replay-after-a-degraded-wake',
+ },
demo_graph_failed: { class: 'server', summary: "The fictional graph did not verify." },
demo_import_failed: { class: 'server', summary: "The fictional page did not import successfully." },
demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },
@@ -376,6 +383,7 @@ export const NOTICE_CODES = {
onboard_no_takes: { kind: 'coaching', summary: 'The brain holds no takes, so think and recall cannot cite the user\'s own views; the remedy is recording or extracting takes.' },
surface_env_invalid: { kind: 'info', summary: 'GBRAIN_SURFACE holds a value other than verbs, starter or full; the server ignored it and names the surface it serves.' },
features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },
+ delta_incomplete: { kind: 'degraded', summary: 'delta delivered less than is waiting and moved no cursor past it: an arm failed or the deadline fired (retry after a short wait; report after 3 consecutive wakes), or budget_tokens cannot fit one item (the fix names the budget that does).' },
post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },
facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },
facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
index 116a36f5a3..677c1117d3 100644
--- a/src/core/facts/capture-dedup.ts
+++ b/src/core/facts/capture-dedup.ts
@@ -237,7 +237,8 @@ export type CollapsedHotFact<R extends HotFactRow> = R & { entity_slugs?: string
* (fingerprint, entity) group; groups of different entities merge only when
* the claim names one of them. Input order is preserved by representative.
*/
-export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine, sourceId: string, rows: R[]): Promise<CollapsedHotFact<R>[]> {
+/** `members` (optional) receives raw row id -> emitted representative id, so delta can advance its facts keyset through raw rows. */
+export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine, sourceId: string, rows: R[], members?: Map<number, number>): Promise<CollapsedHotFact<R>[]> {
const byFingerprint = new Map<string, R[]>();
for (const row of rows) {
const key = row.fact_fingerprint ?? `id:${row.id}`;
@@ -264,6 +265,7 @@ export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine
if (emitted.has(cluster)) continue;
emitted.add(cluster);
const newest = cluster.reduce((a, b) => b.created_at.getTime() > a.created_at.getTime() || b.created_at.getTime() === a.created_at.getTime() && b.id > a.id ? b : a);
+ if (members) for (const r of cluster) members.set(r.id, newest.id);
const slugs = [...new Set([newest.entity_slug, ...cluster.map(r => r.entity_slug)].filter((s): s is string => !!s))];
out.push(slugs.length > 1 ? { ...newest, entity_slugs: slugs } : newest);
}
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index 959f06fd32..a11a7eccd7 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -23,7 +23,7 @@ export const COACHING_BUDGET_PER_SESSION = 2;
/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */
/** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */
export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);
-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index']);
+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete']);
export interface NoticeAudience {
transport: Transport;
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 40721fbc2a..b40f480a84 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -20,7 +20,8 @@ import { readHolders } from './context.ts';
*/
import type { Operation, OperationContext } from './contract.ts';
-import { OperationError, verbError } from './contract.ts';
+import type { Notice } from '../agent-output.ts';
+import { OperationError, opError, verbError } from './contract.ts';
import { invalidParam, paramUse } from './op-fix.ts';
import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, sourceScopeOpts, stampEvidenceSafe } from './context.ts';
import { markKeywordHits } from '../search/evidence.ts';
@@ -729,13 +730,14 @@ const delta: Operation = {
mutating: false,
idempotent: true,
outputRedaction: { retrieval: { localVerbatim: ['facts'] } },
- description: 'MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. Keep a cursor with session_id, or pass since.',
+ description: 'MEMORY VERB (v1): pages, facts, thread events changed since a cursor, zero LLM. Pass session_id, cursor or since.',
params: {
- since: { type: 'string', description: 'ISO 8601 cursor (or use session_id).' },
- since_slug: { type: 'string', description: 'next_cursor.slug from the previous response.' },
- entities: { type: 'string', description: 'Entity scope for thread events (max 8).' },
+ since: { type: 'string', description: 'ISO 8601 start time.' },
+ since_slug: { type: 'string', description: 'Legacy: next_cursor.slug.' },
+ cursor: { type: 'string', description: 'next_cursor.cursor (exact).' },
+ entities: { type: 'string', description: 'Entities for thread events (max 8).' },
budget_tokens: { type: 'number', description: 'Token budget; pages pack first.' },
- session_id: { type: 'string', description: 'Opaque session id; keeps a cursor.' },
+ session_id: { type: 'string', description: 'Session id; keeps a cursor.' },
include_private: { type: 'boolean', description: 'Local trusted callers only.' },
},
scope: 'read',
@@ -745,42 +747,48 @@ const delta: Operation = {
handler: async (ctx, p) => {
const { assembleDeltaContext, renderDelta, PACK_DEFAULT_MAX_ENTITIES, renderPageLine, renderFactLine, renderThreadLine, deltaHeaderCost } =
await import('../context/turn-context.ts');
- const { getSessionContextState, upsertSessionContextState } = await import('../context/session-state.ts');
+ const { readDeltaSessionState, upsertSessionContextState, gcSessionContextState } = await import('../context/session-state.ts');
+ const cur = await import('../context/delta-cursor.ts');
const sourceId = ctx.sourceId ?? 'default';
const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : null;
- if (rawSince !== null && !Number.isFinite(Date.parse(rawSince))) {
- throw verbError(
- 'invalid_params',
- `delta: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`,
- `Pass an ISO 8601 datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,
- );
- }
// NORMALIZE to ISO immediately (red-team F4): the raw string is echoed
// into the injectable `text` block, so an attacker-shaped-but-parseable
// `since` must never reach rendering verbatim. A value already in the
// canonical microsecond shape `listPages` projects (`next_cursor.since`
- // passed back) is kept verbatim: rounding it through a JS Date would
- // re-select every same-millisecond row on the resumed wake.
- // Date.parse normalizes dates such as Feb 31 into March. Check the ISO
- // calendar date before normalization, including cursors without the
- // microsecond passthrough shape.
- const isoDate = rawSince?.match(/^(\d{4})-(\d{2})-(\d{2})T/);
- const [year, month, day] = isoDate?.slice(1).map(Number) ?? [];
- const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
- const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
- if (rawSince !== null && isoDate && (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1])) {
- throw verbError(
- 'invalid_params',
- `delta: since is not a valid ISO 8601 calendar timestamp: "${rawSince.slice(0, 60)}"`,
- `Pass a real calendar datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,
- );
+ // passed back) is kept verbatim. Date.parse normalizes Feb 31 into March
+ // and accepts years 0 and 10000+ that Postgres timestamptz refuses, so the
+ // calendar date and the 0001-9999 range are checked on the parsed value.
+ let explicitSince: string | null = null;
+ if (rawSince !== null) {
+ const checked = cur.checkDeltaTimestamp(rawSince);
+ if (!checked.ok) {
+ throw verbError(
+ 'invalid_params',
+ checked.why === 'unparseable'
+ ? `delta: since is not a parseable timestamp: "${rawSince.slice(0, 60)}"`
+ : checked.why === 'calendar'
+ ? `delta: since is not a valid ISO 8601 calendar timestamp: "${rawSince.slice(0, 60)}"`
+ : `delta: since is outside the accepted range ${cur.DELTA_TIMESTAMP_RANGE}: "${rawSince.slice(0, 60)}"`,
+ checked.why === 'unparseable'
+ ? `Pass an ISO 8601 datetime, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`
+ : `Pass a real calendar datetime between years 0001 and 9999, e.g. ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,
+ );
+ }
+ explicitSince = checked.value;
+ }
+ const rawCursor = typeof p.cursor === 'string' && p.cursor.trim() ? p.cursor.trim() : null;
+ let cursorPos: import('../context/delta-cursor.ts').DeltaPosition | null = null;
+ if (rawCursor !== null) {
+ const decoded = cur.decodeDeltaCursor(rawCursor);
+ if (!decoded.ok) {
+ throw verbError(
+ 'invalid_params',
+ `delta: cursor is invalid: ${decoded.why}`,
+ `Pass next_cursor.cursor from a previous delta response unchanged, or omit cursor and pass ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,
+ );
+ }
+ cursorPos = decoded.pos;
}
- const explicitSince =
- rawSince === null
- ? null
- : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(rawSince)
- ? rawSince
- : new Date(Date.parse(rawSince)).toISOString();
const sessionId = typeof p.session_id === 'string' && p.session_id.trim() ? p.session_id : null;
// Cursor namespace (pre-landing review, fail-closed): 'local' is RESERVED
// for the trusted CLI/hook lane, gated on STRICT ctx.remote === false —
@@ -793,67 +801,82 @@ const delta: Operation = {
typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
? Math.floor(p.budget_tokens)
: null;
+ const explicitSlug = typeof p.since_slug === 'string' ? p.since_slug : undefined;
+ const read = sessionId ? await readDeltaSessionState(ctx.engine, sourceId, clientId, sessionId) : null;
- const state = sessionId ? await getSessionContextState(ctx.engine, sourceId, clientId, sessionId) : null;
- const effectiveSince = explicitSince ?? state?.last_wake_at ?? null;
+ // Start position. Explicit overrides replace WHOLE tuples: `cursor` sets
+ // both arms; `since` sets both arms to "strictly after since" with only the
+ // slug the caller supplied (never the session's slug for another time).
+ type Pos = import('../context/delta-cursor.ts').DeltaPosition;
+ const start: Pos | null = cur.resolveDeltaStart({ cursorPos, explicitSince, explicitSlug, session: read?.status === 'loaded' ? read.state : null });
+ const stateful = sessionId !== null;
+ const retryArgs: Record<string, unknown> = {
+ ...(stateful ? { session_id: sessionId } : { cursor: start ? cur.encodeDeltaCursor(start) : undefined }),
+ ...(typeof p.entities === 'string' ? { entities: p.entities } : {}),
+ ...(budgetTokens !== null ? { budget_tokens: budgetTokens } : {}),
+ ...(includePrivate ? { include_private: true } : {}),
+ };
+ const emitIncomplete = (reason: string, consecutive: number) =>
+ ctx.emitNotice?.(incompleteNotice(reason, stateful && consecutive >= DELTA_ESCALATE_AFTER, consecutive, retryArgs));
- if (!effectiveSince) {
+ if (!start) {
if (!sessionId) {
throw verbError(
'invalid_params',
- 'delta requires `since` (ISO 8601) or a `session_id` with an established cursor.',
+ 'delta requires `since` (ISO 8601), a `cursor`, or a `session_id` with an established cursor.',
`Pass ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')} for a stateless delta, or a stable ${paramUse(ctx, 'session_id', 'agent-main')} — the first call establishes the cursor and later calls return only newer changes.`,
);
}
- // First wake for this session: establish the cursor at now and report an
- // empty delta (there is no prior point to diff against yet). Opportunistic
- // GC on row creation bounds session-row accumulation on serve-less CLI
- // lanes and remote read callers minting session ids (pre-landing review).
- // AWAITED (v0.45.7): a floating engine promise here races the CLI lane's
- // engine teardown and wedges the process — `gbrain delta --session-id`
- // printed its response but never exited (the exact command the shipped
- // HEARTBEAT.md ambient-delta row tells agents to run). GC is two fast
- // DELETEs on a capped table and internally fail-open, so awaiting costs
- // one first-wake round-trip, never an error. The serve-boot call site
- // (src/mcp/server.ts) stays fire-and-forget — that process is long-lived.
+ if (read?.status === 'unavailable') {
+ // A failed state read is NOT a first wake: initializing at now would
+ // drop everything since the session's checkpoint. With no position
+ // there is nothing to deliver, so refuse retryably and move nothing.
+ throw sessionUnavailableError(ctx, bumpLocalDegraded(sourceId, clientId, sessionId, true) >= DELTA_ESCALATE_AFTER, retryArgs);
+ }
+ // First wake (no row, including a GC-expired session): establish the
+ // cursor at now and report an empty delta. Opportunistic GC on row
+ // creation bounds session-row accumulation. AWAITED (v0.45.7): a
+ // floating engine promise races the CLI lane's engine teardown.
const now = new Date().toISOString();
- const { gcSessionContextState } = await import('../context/session-state.ts');
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, { lastWakeAt: now });
+ const first: Pos = { pages: { since: now }, facts: { at: now, id: null } };
+ const wrote = await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
+ lastWakeAt: now, factsCursor: { at: now, id: null }, degradedWakes: 'reset',
+ });
await gcSessionContextState(ctx.engine);
+ ctx.emitNotice?.({
+ code: 'empty_retrieval',
+ kind: 'info',
+ why: `delta started this session's cursor now (${now}); this call and later calls return only changes after it. To read earlier changes, replay statelessly with since (no session_id), which leaves this cursor alone.`,
+ fix: { argv: ['gbrain', 'delta', '--since', '<since>'], mcp: { tool: 'delta', arguments: { since: '<since>' } },
+ inputs: [{ name: 'since', how: 'the ISO 8601 time to read changes from, e.g. 24 hours ago' }],
+ consent: [], actor: 'agent', requires_exclusive: false, why: 'Reads the changes before this session started without moving its cursor.', docs: DELTA_REPLAY_DOCS },
+ });
+ if (!wrote.ok) emitIncomplete('session_state', bumpLocalDegraded(sourceId, clientId, sessionId, true));
return {
protocol_version: MEMORY_VERBS_VERSION,
since: now, pages: [], facts: [], threads: [], text: '', has_more: false,
- next_cursor: { since: now, slug: '' },
- ...(budgetTokens !== null
- ? { budget_tokens: budgetTokens, budget_used: 0, dropped_count: 0 }
- : {}),
+ next_cursor: { since: now, slug: '', cursor: cur.encodeDeltaCursor(first) },
+ ...(wrote.ok ? {} : { degraded_reason: 'session_state' }),
+ ...(budgetTokens !== null ? { budget_tokens: budgetTokens, budget_used: 0, dropped_count: 0 } : {}),
};
}
- // Keyset cursor (red-team F1/F2 fix): pages page by (updated_at, slug), so
- // a >limit cluster at one timestamp is reachable and a delivered page never
- // re-appears unless it changes. The keyset slug lives in the session row
- // (surfaced_slugs[0]); an explicit-`since` caller has no stored slug and
- // resumes via the returned `next_cursor`.
- const cursorSlug = sessionId ? state?.surfaced_slugs?.[0] : undefined;
- const explicitSlug = typeof p.since_slug === 'string' ? p.since_slug : undefined;
- const sinceSlug = explicitSlug ?? cursorSlug;
-
+ const effectiveSince = start.pages.since;
const res = await assembleDeltaContext(ctx.engine, {
sourceId,
since: effectiveSince,
- ...(sinceSlug !== undefined ? { sinceSlug } : {}),
+ ...(start.pages.slug !== undefined ? { sinceSlug: start.pages.slug } : {}),
+ factsAfter: start.facts,
entities: parseEntityList(p.entities),
sessionId: sessionId ?? undefined,
includePrivate,
maxEntities: PACK_DEFAULT_MAX_ENTITIES,
});
- // Pages arrive OLDEST first by (updated_at, slug) — no client-side dedup
- // needed; the keyset already excludes everything at/before the cursor.
- // Pack, price and render the redacted presentation sets (one echo
- // dictionary). The cursor reads the raw page at the delivered index and
- // local callers get the delivered facts back raw below.
+ // Pages arrive OLDEST first by (updated_at, slug), facts OLDEST first by
+ // (created_at, id). Pack, price and render the redacted presentation sets
+ // (one echo dictionary). The cursors read the raw rows at the delivered
+ // index and local callers get the delivered facts back raw below.
const rawPages = res.deltaPages ?? [];
const rawFacts = res.facts ?? [];
const view = redactRetrievalOutput([{ pages: rawPages, facts: rawFacts, threads: res.openThreads ?? [] }], {}).results[0];
@@ -864,15 +887,15 @@ const delta: Operation = {
const threads = view.threads;
let droppedCount: number | undefined;
let factsDropped = 0;
+ let itemBudget = 0;
const fetchedPages = pages.length;
+ const fetchedFacts = facts.length;
if (budgetTokens !== null) {
// packToBudget keeps a contiguous PREFIX (order-preserving, stops at the
- // first overflow) — with oldest-first pages the kept set stays contiguous
- // from the cursor, which the advance logic below depends on.
- // #4761: reserve the envelope + headers (they embed `since`, so price per
- // call) AND every thread line, then cost each page/fact as its rendered
- // line — `text` fits the budget whenever the reserved part alone does.
- const itemBudget =
+ // first overflow), which both arms' delivered-prefix cursors depend on.
+ // #4761: reserve the envelope + headers and every thread line, then cost
+ // each page/fact as its rendered line.
+ itemBudget =
budgetTokens - deltaHeaderCost(effectiveSince) - threads.reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);
const pagePack = itemBudget > 0 ? packToBudget(pages, (pg) => lineCost(renderPageLine(pg)), itemBudget) : dropAll(pages);
pages = pagePack.items;
@@ -883,49 +906,96 @@ const delta: Operation = {
factsDropped = factPack.meta.dropped;
}
const pagesDropped = fetchedPages - pages.length;
- // has_more covers ALL undelivered content — fetch-limit overflow, budget-
- // dropped pages, AND budget-dropped facts (pre-landing review: facts were
- // silently lost when pages fit but facts overflowed).
- // ponytail: dropped facts keep the pre-existing ceiling — the cursor still
- // advances past delivered pages, so they re-surface only if their
- // created_at is after the new cursor; a per-arm cursor would fix it.
- const hasMore = res.deltaOverflow === true || pagesDropped > 0 || factsDropped > 0;
+ const factsOverflowRow = res.deltaFactsOverflowRow ?? null;
+ // has_more: more content is waiting (fetch-limit overflow on either arm or
+ // a budget drop). Failure is signalled by degraded_reason + the notice.
+ const hasMore = res.deltaOverflow === true || factsOverflowRow !== null || pagesDropped > 0 || factsDropped > 0;
+
+ // Per-arm advance (at-least-once): each arm moves through the prefix it
+ // DELIVERED and never past now() - lag; an arm whose read failed or never
+ // finished holds. Thread events follow the pages' time cursor, so an
+ // incomplete threads arm holds the pages arm too.
+ const arms = res.deltaArms ?? { pages: 'unknown', facts: 'unknown', threads: 'unknown' };
+ const horizon = cur.horizonIso();
+ const pagesNext = cur.nextPagesPos({
+ start: start.pages,
+ complete: arms.pages === 'ok' && arms.threads === 'ok',
+ delivered: rawPages.slice(0, pages.length),
+ undelivered: res.deltaOverflow === true || pagesDropped > 0,
+ horizon,
+ advanceOnEmpty: stateful,
+ });
+ const deliveredRepIds = new Set(rawFacts.slice(0, facts.length).map((f) => f.id));
+ const { next: factsNext, oldestUndelivered } = cur.nextFactsPos({
+ start: start.facts,
+ complete: arms.facts === 'ok',
+ raw: res.deltaFactsRaw ?? [],
+ overflowRow: factsOverflowRow,
+ deliveredRepIds,
+ horizon,
+ advanceOnEmpty: stateful,
+ });
+ const next: Pos = { pages: pagesNext, facts: factsNext };
- // Cursor advance (keyset, at-least-once): advance to the last DELIVERED
- // (updated_at, slug). The keyset's strict `>` means the next wake starts
- // exactly after it — a >limit same-timestamp cluster drains one page at a
- // time across wakes (F1), and a delivered page never re-appears (F2). On a
- // page-less wake with nothing dropped, advance the TIME cursor to now()
- // minus a safety lag (in-flight write txns stamp updated_at at txn START)
- // and clear the keyset slug. If nothing delivered but something dropped, do
- // NOT advance (deliver-before-advance; a too-small budget must not eat it).
- // P0 containment: a failed arm or a fired deadline (degradedReason) means
- // the delivered set is not known to be complete, so no cursor moves at
- // all; the next wake re-reads the same window (at-least-once).
+ // Conservative legacy `since`/`slug` for clients that do not send `cursor`.
const incomplete = res.degradedReason !== undefined;
- const nextCursor =
- pages.length > 0 && !incomplete
- ? { since: rawPages[pages.length - 1].updated_at, slug: rawPages[pages.length - 1].slug }
- : { since: effectiveSince, slug: sinceSlug ?? '' };
- if (sessionId && !incomplete) {
- if (pages.length > 0) {
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
- lastWakeAt: nextCursor.since,
- cursorSlug: nextCursor.slug,
- });
- } else if (!hasMore) {
- await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
- lastWakeAt: new Date(Date.now() - 2000).toISOString(),
- cursorSlug: '',
- });
- }
+ const { legacy, clamped } = cur.legacyDeltaCursor({
+ start, pagesNext, factsNext, oldestUndelivered, incomplete,
+ pagesDelivered: pages.length, factsDelivered: facts.length,
+ pagesQuiet: res.deltaOverflow !== true && pagesDropped === 0,
+ });
+ if (clamped && !stateful && cursorPos === null && cur.comparePages(legacy, start.pages) <= 0) {
+ // A legacy stateless caller at a boundary it cannot page (more undelivered
+ // facts at one timestamp than the fetch limit): advancing would skip
+ // them and holding would loop forever. Only the opaque cursor can page it.
+ const exact = cur.encodeDeltaCursor(next);
+ const e = opError(
+ 'delta_cursor_upgrade_required',
+ 'delta: more undelivered facts share one timestamp than a since/since_slug cursor can page.',
+ `Repeat the call with ${paramUse(ctx, 'cursor', exact)} instead of since/since_slug.`,
+ {
+ why: 'The legacy cursor is a single timestamp; facts that share it can only be paged by fact id, which the opaque cursor carries. Nothing was skipped and no cursor moved.',
+ fix: { argv: deltaArgv({ cursor: exact }), mcp: { tool: 'delta', arguments: { cursor: exact } }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Resumes both arms exactly; keep passing next_cursor.cursor on later calls.', docs: DELTA_REPLAY_DOCS },
+ },
+ );
+ e.protocolVersion = MEMORY_VERBS_VERSION;
+ throw e;
+ }
+
+ let degradedReason = res.degradedReason;
+ if (sessionId) {
+ const wrote = await upsertSessionContextState(ctx.engine, sourceId, clientId, sessionId, {
+ lastWakeAt: pagesNext.since,
+ cursorSlug: pagesNext.slug ?? '',
+ factsCursor: { at: factsNext.at, id: factsNext.id },
+ degradedWakes: incomplete ? 'increment' : 'reset',
+ });
+ if (!wrote.ok) degradedReason = degradedReason ? `${degradedReason},session_state` : 'session_state';
+ const consecutive = wrote.ok ? (bumpLocalDegraded(sourceId, clientId, sessionId, false), wrote.degradedWakes) : bumpLocalDegraded(sourceId, clientId, sessionId, true);
+ if (degradedReason) emitIncomplete(degradedReason, consecutive);
+ } else if (degradedReason) {
+ emitIncomplete(degradedReason, 1);
+ }
+
+ // A budget too small for even ONE waiting item would return has_more
+ // forever; say so with the budget that fits the next item.
+ if (budgetTokens !== null && pages.length === 0 && facts.length === 0 && (pagesDropped > 0 || factsDropped > 0)) {
+ const nextItem = fetchedPages > 0 ? lineCost(renderPageLine(view.pages[0])) : fetchedFacts > 0 ? lineCost(renderFactLine(view.facts[0])) : 0;
+ const needed = budgetTokens - itemBudget + nextItem;
+ const bigger = { ...retryArgs, budget_tokens: needed };
+ ctx.emitNotice?.({
+ code: 'delta_incomplete',
+ kind: 'degraded',
+ why: `budget_tokens ${budgetTokens} cannot fit even one waiting item (the next one needs ${needed}); repeating the call with the same budget returns has_more forever.`,
+ fix: { argv: deltaArgv(bigger), mcp: { tool: 'delta', arguments: bigger }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Repeat with budget_tokens ${needed} or more; nothing was skipped and no cursor moved.` },
+ });
}
// Re-render the injectable block from the FINAL sets (adversarial review):
// `text` must honor the budget AND the boundary-tie exclusion the
// structured arrays reflect — the assembler's render predates both.
- // budget_used reports that text; it exceeds budget_tokens only when the
- // header + the never-truncated threads alone do.
const text = renderDelta(pages, facts, threads, effectiveSince);
const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;
@@ -934,6 +1004,7 @@ const delta: Operation = {
since: effectiveSince,
pages,
facts: (ctx.remote === false ? rawFacts.slice(0, facts.length) : facts).map((f) => ({
+ id: f.id,
fact: f.fact,
kind: f.kind,
entity_slug: f.entity_slug,
@@ -945,10 +1016,15 @@ const delta: Operation = {
threads,
text,
has_more: hasMore,
- // Stateless resume: a caller with no session_id passes these back as
- // `since` + `since_slug` on the next call to page deterministically.
- next_cursor: nextCursor,
- ...(res.degradedReason ? { degraded_reason: res.degradedReason } : {}),
+ // Stateless resume: pass `cursor` back (exact, both arms). Older clients
+ // pass `since` + `since_slug` (conservative: may re-see, never skips).
+ next_cursor: { since: legacy.since, slug: legacy.slug ?? '', cursor: cur.encodeDeltaCursor(next) },
+ // Replay audit trail: where each arm started and where it resumes.
+ cursor_arms: {
+ pages: { start: { since: start.pages.since, slug: start.pages.slug ?? null }, next: { since: pagesNext.since, slug: pagesNext.slug ?? null } },
+ facts: { start: { since: start.facts.at, id: start.facts.id }, next: { since: factsNext.at, id: factsNext.id } },
+ },
+ ...(degradedReason ? { degraded_reason: degradedReason } : {}),
...(budgetTokens !== null
? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
: {}),
@@ -956,6 +1032,80 @@ const delta: Operation = {
},
};
+/** delta: consecutive incomplete wakes before the notice escalates from `wait` to `report`. */
+const DELTA_ESCALATE_AFTER = 3;
+const DELTA_RETRY_SECONDS = 30;
+const DELTA_REPLAY_DOCS = 'docs/guides/ambient-recall.md#replay-after-a-degraded-wake';
+
+/** The delta_incomplete notice: retry the same call after a short wait, or report once it keeps failing. */
+function incompleteNotice(reason: string, escalate: boolean, consecutive: number, retryArgs: Record<string, unknown>): Notice {
+ return {
+ code: 'delta_incomplete',
+ kind: 'degraded',
+ why: escalate
+ ? `delta has been incomplete on ${consecutive} consecutive wakes (${reason}); no cursor moved past content it did not deliver, but the store is not recovering on its own.`
+ : `delta could not complete this read (${reason}); no cursor moved past content it did not deliver. Retry the same call in about ${DELTA_RETRY_SECONDS} seconds and the held cursor re-reads the same window.`,
+ fix: escalate
+ ? { consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Tell the user delta keeps failing, then run gbrain doctor --json to find the failing store.',
+ verify: { argv: ['gbrain', 'doctor', '--json'] }, docs: DELTA_REPLAY_DOCS }
+ : { argv: deltaArgv(retryArgs), mcp: { tool: 'delta', arguments: retryArgs }, consent: [], actor: 'provider', requires_exclusive: false,
+ why: `Retry the same read after about ${DELTA_RETRY_SECONDS} seconds; nothing was skipped.`, docs: DELTA_REPLAY_DOCS },
+ };
+}
+
+/** A failed session-state read is NOT a first wake: refuse retryably, move nothing. */
+function sessionUnavailableError(ctx: OperationContext, escalate: boolean, retryArgs: Record<string, unknown>): OperationError {
+ const e = opError(
+ 'unavailable',
+ 'delta: the session cursor could not be read, so this wake delivered nothing and moved nothing.',
+ escalate
+ ? 'The session store has failed on several consecutive wakes: tell the user and run `gbrain doctor --json`.'
+ : `Retry the same call in about ${DELTA_RETRY_SECONDS} seconds, or replay statelessly with ${paramUse(ctx, 'since', '2026-08-11T00:00:00Z')}.`,
+ {
+ reason: 'session_state',
+ why: 'Treating a failed read as a new session would restart the cursor at now and silently skip everything since its checkpoint.',
+ fix: escalate
+ ? { consent: [], actor: 'agent', requires_exclusive: false, why: 'Tell the user the session store keeps failing, then run gbrain doctor --json.', verify: { argv: ['gbrain', 'doctor', '--json'] }, docs: DELTA_REPLAY_DOCS }
+ : { argv: deltaArgv(retryArgs), mcp: { tool: 'delta', arguments: retryArgs }, consent: [], actor: 'provider', requires_exclusive: false,
+ why: `Retry the same read after about ${DELTA_RETRY_SECONDS} seconds; the checkpoint is intact.`, docs: DELTA_REPLAY_DOCS },
+ },
+ );
+ e.protocolVersion = MEMORY_VERBS_VERSION;
+ return e;
+}
+
+/** CLI form of a delta call (flags mirror the params). */
+function deltaArgv(args: Record<string, unknown>): string[] {
+ const argv = ['gbrain', 'delta'];
+ for (const [k, v] of Object.entries(args)) {
+ if (v === undefined) continue;
+ const flag = `--${k.replace(/_/g, '-')}`;
+ if (v === true) argv.push(flag);
+ else argv.push(flag, String(v));
+ }
+ return argv;
+}
+
+/**
+ * In-process consecutive-incomplete counter: the fallback when the session
+ * store itself is down (the durable counter lives in session_context_state).
+ * Bounded; returns the count after the update.
+ */
+const localDegraded = new Map<string, number>();
+function bumpLocalDegraded(sourceId: string, clientId: string | null, sessionId: string, incomplete: boolean): number {
+ const key = `${sourceId}|${clientId ?? 'local'}|${sessionId}`;
+ if (!incomplete) {
+ localDegraded.delete(key);
+ return 0;
+ }
+ const n = (localDegraded.get(key) ?? 0) + 1;
+ localDegraded.delete(key);
+ localDegraded.set(key, n);
+ if (localDegraded.size > 1_000) localDegraded.delete(localDegraded.keys().next().value!);
+ return n;
+}
+
const forget_fact: Operation = {
name: 'forget_fact',
idempotent: true,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 866c00fd6f..c6c0d1b75e 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2410,6 +2410,14 @@ export class PGLiteEngine implements BrainEngine {
return factsImpl.listFactsSince(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, since, opts);
}
+ async listFactsKeyset(
+ source_id: string,
+ after: { createdAt: string; id: number | null } | null,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ return factsImpl.listFactsKeyset(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, after, opts);
+ }
+
async listFactsBySession(
source_id: string,
sessionId: string,
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index f96a47458e..2686343078 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -483,6 +483,9 @@ CREATE TABLE IF NOT EXISTS session_context_state (
surfaced_slugs JSONB NOT NULL DEFAULT '[]'::jsonb,
checkpoint_manifest JSONB NOT NULL DEFAULT '[]'::jsonb,
last_wake_at TIMESTAMPTZ,
+ facts_cursor_at TIMESTAMPTZ,
+ facts_cursor_id BIGINT,
+ degraded_wakes INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, client_id, session_id)
);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index f78782c35f..55039f1eac 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2139,6 +2139,14 @@ export class PostgresEngine implements BrainEngine {
return factsImpl.listFactsSince(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, since, opts);
}
+ async listFactsKeyset(
+ source_id: string,
+ after: { createdAt: string; id: number | null } | null,
+ opts?: FactListOpts,
+ ): Promise<FactRow[]> {
+ return factsImpl.listFactsKeyset(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, after, opts);
+ }
+
async listFactsBySession(
source_id: string,
sessionId: string,
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index a137e728f0..3bb3401842 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -890,6 +890,8 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (
-- per-session cursor + boundary-tie dedup for the \`delta\` verb + heartbeat
-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentinel
-- for CLI/hook, remote auth client id otherwise. jsonb DDL-literal defaults.
+-- facts_cursor_at/_id + degraded_wakes (migration v208): delta's per-arm facts
+-- keyset and its consecutive incomplete-wake counter.
CREATE TABLE IF NOT EXISTS session_context_state (
source_id TEXT NOT NULL,
client_id TEXT NOT NULL DEFAULT 'local',
@@ -898,6 +900,9 @@ CREATE TABLE IF NOT EXISTS session_context_state (
surfaced_slugs JSONB NOT NULL DEFAULT '[]'::jsonb,
checkpoint_manifest JSONB NOT NULL DEFAULT '[]'::jsonb,
last_wake_at TIMESTAMPTZ,
+ facts_cursor_at TIMESTAMPTZ,
+ facts_cursor_id BIGINT,
+ degraded_wakes INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, client_id, session_id)
);
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index c17cff3b80..aadccdd67a 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -208,6 +208,7 @@ import { v204 } from './v204-links-temporal-state.ts';
import { v205 } from './v205-minion-spend-authorization.ts';
import { v206 } from './v206-entity-mention-index.ts';
import { v207 } from './v207-retrieval-feedback.ts';
+import { v208 } from './v208-delta-per-arm-cursor.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -414,4 +415,5 @@ export const MIGRATIONS: Migration[] = [
v205,
v206,
v207,
+ v208,
];
diff --git a/src/core/schema-migrations/v208-delta-per-arm-cursor.ts b/src/core/schema-migrations/v208-delta-per-arm-cursor.ts
new file mode 100644
index 0000000000..47754da9e8
--- /dev/null
+++ b/src/core/schema-migrations/v208-delta-per-arm-cursor.ts
@@ -0,0 +1,27 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// delta per-arm cursor (contributor audit wave P0). Facts and pages used to
+// share one time cursor, so a facts read that failed, overflowed its limit or
+// lost a budget cut was skipped once the page cursor moved. The facts arm now
+// keeps its own keyset `(facts_cursor_at, facts_cursor_id)`, and
+// `degraded_wakes` counts consecutive incomplete wakes (the delta notice
+// escalates to `report` on the third). Existing rows start their facts cursor
+// at `last_wake_at` with id 0, which is what they effectively used before;
+// gaps skipped before the upgrade are not recoverable from here. Keep in sync
+// with src/schema.sql.
+export const v208: Migration = {
+ version: 208,
+ name: 'delta_per_arm_cursor',
+ idempotent: true,
+ sql: `
+ ALTER TABLE session_context_state ADD COLUMN IF NOT EXISTS facts_cursor_at TIMESTAMPTZ;
+ ALTER TABLE session_context_state ADD COLUMN IF NOT EXISTS facts_cursor_id BIGINT;
+ ALTER TABLE session_context_state ADD COLUMN IF NOT EXISTS degraded_wakes INTEGER NOT NULL DEFAULT 0;
+ UPDATE session_context_state
+ SET facts_cursor_at = last_wake_at, facts_cursor_id = 0
+ WHERE facts_cursor_at IS NULL AND last_wake_at IS NOT NULL;
+ `,
+};
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index f1a3634946..8257cc21fd 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -766,12 +766,16 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
properties: {
protocol_version: { type: 'integer', const: MEMORY_VERBS_VERSION },
since: { type: 'string', description: 'The ISO cursor this delta was computed against.' },
- has_more: { type: 'boolean', description: 'True when changes beyond the fetch limit or budget were NOT delivered; with session_id the cursor advanced only to the last delivered page, so the tail surfaces on the next wake.' },
+ has_more: { type: 'boolean', description: 'True when more content is waiting (a fetch limit or the budget); each arm advanced only through what it delivered, so the rest surfaces on the next wake. Failure is degraded_reason, never has_more.' },
next_cursor: {
type: 'object',
required: ['since', 'slug'],
- description: 'Keyset to resume from (stateless callers pass back as since + since_slug).',
- properties: { since: { type: 'string' }, slug: { type: 'string' } },
+ description: 'Where to resume. `cursor` (opaque, both arms exact) is passed back as cursor; older clients pass since + since_slug, which is conservative (may re-deliver, never skips): it holds while any arm failed and stays strictly before the oldest undelivered fact.',
+ properties: { since: { type: 'string' }, slug: { type: 'string' }, cursor: { type: 'string' } },
+ },
+ cursor_arms: {
+ type: 'object',
+ description: 'Replay audit trail: each arm\'s start and next keyset (pages: since + slug; facts: since + id).',
},
pages: {
type: 'array',
@@ -792,6 +796,7 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
type: 'object',
required: ['fact', 'kind'],
properties: {
+ id: { type: 'integer', description: 'Fact id (dedupe key for replay).' },
fact: { type: 'string' },
kind: { type: 'string' },
entity_slug: { type: ['string', 'null'] },
@@ -813,7 +818,7 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
},
text: { type: 'string' },
- degraded_reason: { type: 'string' },
+ degraded_reason: { type: 'string', description: 'Comma-joined incomplete parts: deadline, pages, facts, threads, session_state. No cursor moved past anything undelivered; a delta_incomplete notice carries the retry step.' },
budget_tokens: { type: 'integer' },
budget_used: { type: 'integer' },
dropped_count: { type: 'integer' },
diff --git a/src/schema.sql b/src/schema.sql
index 89b095cf22..f69f8d639b 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -886,6 +886,8 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (
-- per-session cursor + boundary-tie dedup for the `delta` verb + heartbeat
-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentinel
-- for CLI/hook, remote auth client id otherwise. jsonb DDL-literal defaults.
+-- facts_cursor_at/_id + degraded_wakes (migration v208): delta's per-arm facts
+-- keyset and its consecutive incomplete-wake counter.
CREATE TABLE IF NOT EXISTS session_context_state (
source_id TEXT NOT NULL,
client_id TEXT NOT NULL DEFAULT 'local',
@@ -894,6 +896,9 @@ CREATE TABLE IF NOT EXISTS session_context_state (
surfaced_slugs JSONB NOT NULL DEFAULT '[]'::jsonb,
checkpoint_manifest JSONB NOT NULL DEFAULT '[]'::jsonb,
last_wake_at TIMESTAMPTZ,
+ facts_cursor_at TIMESTAMPTZ,
+ facts_cursor_id BIGINT,
+ degraded_wakes INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, client_id, session_id)
);
diff --git a/test/ambient-recall-cli.test.ts b/test/ambient-recall-cli.test.ts
index 5413668c08..46013863f0 100644
--- a/test/ambient-recall-cli.test.ts
+++ b/test/ambient-recall-cli.test.ts
@@ -77,7 +77,8 @@ describe('gbrain delta (CLI)', () => {
expect(env.since).toBe('1970-01-01T00:00:00.000Z');
expect(env.pages).toEqual([]);
expect(env.has_more).toBe(false);
- expect(env.next_cursor).toEqual({ since: '1970-01-01T00:00:00.000Z', slug: '' });
+ expect(env.next_cursor).toMatchObject({ since: '1970-01-01T00:00:00.000Z', slug: '' });
+ expect(typeof env.next_cursor.cursor).toBe('string');
}, 60_000);
test('unparseable --since: exit 2 (usage), invalid_params rendering on stderr', () => {
diff --git a/test/ambient-recall.test.ts b/test/ambient-recall.test.ts
index 6c4798fe6d..6bea0222ce 100644
--- a/test/ambient-recall.test.ts
+++ b/test/ambient-recall.test.ts
@@ -481,12 +481,10 @@ describe('delta cursor lifecycle', () => {
// The state READ degrades to null, never a throw.
await expect(getSessionContextState(failing as never, 'default', null, 'outage')).resolves.toBeNull();
const ctx = { ...ctxFor({ remote: false }), engine: failing } as OperationContext;
- // First-wake path: cursor read + establish-write + GC all fail — the verb
- // still answers with a complete payload.
- const r1 = await call(del, ctx, { session_id: 'outage' });
- expect(r1.protocol_version).toBe(1);
- expect(r1.pages).toEqual([]);
- expect(r1.since).toMatch(/^\d{4}-\d{2}-\d{2}T.*Z$/);
+ // Session-state read failure with no explicit position: a failed read is
+ // NOT a first wake (contributor audit wave P0), so no cursor is
+ // initialized at now; the refusal is retryable and names the reason.
+ await expect(call(del, ctx, { session_id: 'outage' })).rejects.toMatchObject({ code: 'unavailable', reason: 'session_state' });
// Full delta path: assembly reads run fine; the cursor-advance write fails
// silently and the payload is still complete.
const r2 = await call(del, ctx, { session_id: 'outage', since: '1970-01-01T00:00:00Z' });
@@ -799,13 +797,13 @@ describe('budget packing + drop footer', () => {
await call(putPage, local, { slug: 'people/bob-example', content: '# Bob Example\n\nbody' });
const entityBeforeRemember = (await engine.readPageSnapshot('people/bob-example', { sourceId: 'default' }))!;
await new Promise((r) => setTimeout(r, 5));
- const since = new Date().toISOString();
+ let since = new Date().toISOString();
await new Promise((r) => setTimeout(r, 5));
for (const s of ['kc-a', 'kc-b']) {
await call(putPage, local, { slug: `notes/${s}`, content: `# ${s}\n\ncontent` });
}
await new Promise((r) => setTimeout(r, 5));
- const mid = new Date().toISOString();
+ let mid = new Date().toISOString();
await new Promise((r) => setTimeout(r, 5));
for (let i = 0; i < 3; i++) {
await call(remember, local, { fact: `kc-fact-${i} ${'z'.repeat(120)}`, provenance: 'test', visibility: 'world' });
@@ -825,6 +823,12 @@ describe('budget packing + drop footer', () => {
expect(entityBeforeRemember.page.updated_at.getTime()).toBeLessThan(Date.parse(since));
await engine.executeRaw('UPDATE pages SET updated_at = $1::timestamptz WHERE source_id = $2 AND slug = $3',
[entityBeforeRemember.page.updated_at.toISOString(), 'default', 'people/bob-example']);
+ // delta never advances a cursor past now() - 2 s (commit-visibility lag),
+ // so age the whole fixture a minute to keep the keyset assertions exact.
+ await engine.executeRaw(`UPDATE pages SET updated_at = updated_at - interval '1 minute'`);
+ await engine.executeRaw(`UPDATE facts SET created_at = created_at - interval '1 minute'`);
+ since = new Date(Date.parse(since) - 60_000).toISOString();
+ mid = new Date(Date.parse(mid) - 60_000).toISOString();
__resetHotMemoryCacheForTests();
const full = await call(del, local, { since, entities: 'people/bob-example' });
const pages = full.pages as Parameters<typeof renderPageLine>[0][];
@@ -833,7 +837,7 @@ describe('budget packing + drop footer', () => {
expect((full.threads as unknown[]).length).toBeGreaterThan(0);
// Unbudgeted: the cursor is the last delivered page, exactly as a
// stateless page-only call would report it.
- expect(full.next_cursor).toEqual({ since: pages[1].updated_at, slug: pages[1].slug });
+ expect(full.next_cursor).toMatchObject({ since: pages[1].updated_at, slug: pages[1].slug });
// Budget = header + every thread line + the first page line + a sliver:
// one page delivered, every fact dropped — the cursor is still that page.
const reserved =
@@ -848,17 +852,22 @@ describe('budget packing + drop footer', () => {
expect(r1.facts).toEqual([]);
expect((r1.threads as unknown[]).length).toBe((full.threads as unknown[]).length);
expect(r1.has_more).toBe(true);
- expect(r1.next_cursor).toEqual({ since: pages[0].updated_at, slug: pages[0].slug });
+ expect(r1.next_cursor).toMatchObject({ since: pages[0].updated_at, slug: pages[0].slug });
expect(estimateTokens(r1.text as string)).toBeLessThanOrEqual(r1.budget_tokens);
- // Page-less wake: facts/threads delivered (and some facts dropped) leave
- // the time cursor exactly where the caller put it.
+ // Page-less wake: facts/threads delivered and some facts dropped. The
+ // legacy time cursor moves to the delivered fact and stays strictly before
+ // the oldest dropped one, so an old client drains the rest instead of
+ // re-reading the same prefix (contributor audit wave P0).
const oneFact = estimateTokens(renderFactLine((full.facts as Parameters<typeof renderFactLine>[0][])[0]) + '\n');
const r2 = await call(del, local, { since: mid, entities: 'people/bob-example', budget_tokens: reserved + oneFact + 2 });
expect(r2.pages).toEqual([]);
expect((r2.facts as unknown[]).length).toBe(1);
expect((r2.threads as unknown[]).length).toBe((full.threads as unknown[]).length);
expect(r2.has_more).toBe(true);
- expect(r2.next_cursor).toEqual({ since: mid, slug: '' });
+ expect(r2.next_cursor.slug).toBe('');
+ expect(r2.next_cursor.since > mid).toBe(true);
+ const r3 = await call(del, local, { since: r2.next_cursor.since, since_slug: r2.next_cursor.slug, entities: 'people/bob-example', budget_tokens: reserved + oneFact + 2 });
+ expect((r3.facts as Array<{ fact: string }>)[0].fact).not.toBe((r2.facts as Array<{ fact: string }>)[0].fact);
});
test('forced overflow: dropped_count > 0 and budget_used stays within budget_tokens (v0.45.7)', async () => {
diff --git a/test/delta-cursor-integrity.test.ts b/test/delta-cursor-integrity.test.ts
index fc11a57d04..1d99be8931 100644
--- a/test/delta-cursor-integrity.test.ts
+++ b/test/delta-cursor-integrity.test.ts
@@ -11,7 +11,11 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operations, type OperationContext } from '../src/core/operations.ts';
import type { GBrainConfig } from '../src/core/config.ts';
-import { getSessionContextState } from '../src/core/context/session-state.ts';
+import { getSessionContextState, upsertSessionContextState } from '../src/core/context/session-state.ts';
+import { assembleDeltaContext } from '../src/core/context/turn-context.ts';
+import { renderNotice, type Notice, type RenderContext } from '../src/core/agent-output.ts';
+import { V208_SQL_FOR_TESTS } from './helpers/delta-v208.ts';
+import postgres from '#postgres';
import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -21,16 +25,33 @@ type R = Record<string, any>;
const del = operations.find((o) => o.name === 'delta')!;
const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };
-/** Methods made to throw on demand; everything else passes through. */
-interface Faults { failing: Set<string> }
+/**
+ * Methods made to throw on demand (`failing`: the call rejects; `throwOnAccess`:
+ * reading the property throws, which escapes `.catch()` chains); `sql`
+ * makes executeRaw reject for statements matching a pattern; `delayMs` adds
+ * latency to listPages. Everything else passes through.
+ */
+interface Faults { failing: Set<string>; throwOnAccess: Set<string>; sql: RegExp | null; delayMs: number }
function faulty(engine: BrainEngine, faults: Faults): BrainEngine {
return new Proxy(engine, {
get(t, k) {
const v = (t as unknown as Record<string | symbol, unknown>)[k];
+ if (typeof k === 'string' && faults.throwOnAccess.has(k)) throw new Error(`injected ${k} access failure`);
if (typeof k === 'string' && faults.failing.has(k)) {
return async () => { throw new Error(`injected ${k} failure`); };
}
+ if (k === 'executeRaw' && faults.sql) {
+ const re = faults.sql;
+ return (sql: string, params?: unknown[]) => {
+ if (re.test(sql)) return Promise.reject(new Error('injected session-state failure'));
+ return t.executeRaw(sql as never, params as never);
+ };
+ }
+ if (k === 'listPages' && faults.delayMs > 0) {
+ const ms = faults.delayMs;
+ return async (...a: unknown[]) => { await new Promise((r) => setTimeout(r, ms)); return (t.listPages as (...x: unknown[]) => unknown)(...a); };
+ }
return typeof v === 'function' && k !== 'constructor' ? (v as (...a: unknown[]) => unknown).bind(t) : v;
},
}) as BrainEngine;
@@ -40,13 +61,42 @@ for (const kind of testBackends()) {
describe(`delta cursor integrity (${kind})`, () => {
let engine: BrainEngine;
let close: () => Promise<void>;
- const faults: Faults = { failing: new Set() };
+ let databaseUrl = '';
+ const faults: Faults = { failing: new Set(), throwOnAccess: new Set(), sql: null, delayMs: 0 };
+ let notices: Notice[] = [];
const ctx = (): OperationContext => ({
engine: faulty(engine, faults), config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote: false, sourceId: 'default',
+ emitNotice: (n: Notice) => { notices.push(n); },
} as OperationContext);
const call = async (p: Record<string, unknown>): Promise<R> => (await del.handler(ctx(), p)) as R;
- const state = () => getSessionContextState(engine, 'default', null, 's1');
+ const state = (sid = 's1') => getSessionContextState(engine, 'default', null, sid);
+ const factsCursor = async (sid = 's1') =>
+ (await engine.executeRaw<{ at: string | null; id: string | number | null; n: string | number }>(
+ `SELECT to_char(facts_cursor_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS at, facts_cursor_id AS id, degraded_wakes AS n
+ FROM session_context_state WHERE session_id = $1`, [sid]))[0];
+ const incomplete = () => notices.filter((n) => n.code === 'delta_incomplete');
+ const stdio: RenderContext = { transport: 'stdio', isCallable: () => true, preapproved: () => false };
+ const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false };
+ const http: RenderContext = { transport: 'http', isCallable: () => true, preapproved: () => false };
+ /** Drain a delta loop, collecting every page slug and fact id it delivers. */
+ async function drain(first: Record<string, unknown>, nextArgs: (r: R) => Record<string, unknown>, cap = 40): Promise<{ slugs: Set<string>; ids: Set<number>; calls: number }> {
+ const slugs = new Set<string>();
+ const ids = new Set<number>();
+ let args = first;
+ for (let i = 0; i < cap; i++) {
+ const r = await call(args);
+ for (const p of r.pages) slugs.add(p.slug);
+ for (const f of r.facts) ids.add(f.id);
+ if (!r.has_more && !r.degraded_reason) return { slugs, ids, calls: i + 1 };
+ args = nextArgs(r);
+ }
+ throw new Error('delta loop did not terminate');
+ }
+ /** Move both arm cursors of every session back (a session that last woke `ago` ago). */
+ async function rewind(ago: string): Promise<void> {
+ await engine.executeRaw(`UPDATE session_context_state SET last_wake_at = now() - $1::interval, facts_cursor_at = now() - $1::interval, facts_cursor_id = 0`, [ago]);
+ }
async function page(slug: string, agoMs: number): Promise<void> {
await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `body of ${slug}` });
await engine.executeRaw(`UPDATE pages SET updated_at = now() - ($1 || ' milliseconds')::interval WHERE slug = $2`, [String(agoMs), slug]);
@@ -59,7 +109,7 @@ for (const kind of testBackends()) {
beforeAll(async () => {
if (kind === 'postgres') {
- ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ ({ engine, close, databaseUrl } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
} else {
engine = new PGLiteEngine();
await engine.connect({});
@@ -70,15 +120,19 @@ for (const kind of testBackends()) {
afterAll(async () => { await close?.(); });
beforeEach(async () => {
faults.failing.clear();
+ faults.throwOnAccess.clear();
+ faults.sql = null;
+ faults.delayMs = 0;
+ notices = [];
__resetHotMemoryCacheForTests();
await engine.executeRaw('DELETE FROM session_context_state');
await engine.executeRaw('DELETE FROM facts');
- await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'notes/%'`);
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'notes/%' OR slug LIKE 'people/%'`);
});
test('pages arm throws: neither the session nor the stateless cursor advances, and the next call delivers the page', async () => {
await call({ session_id: 's1' });
- await engine.executeRaw(`UPDATE session_context_state SET last_wake_at = now() - interval '10 seconds'`);
+ await rewind('10 seconds');
const before = (await state())!.last_wake_at;
await page('notes/missed-by-failed-read', 2_600);
@@ -98,21 +152,300 @@ for (const kind of testBackends()) {
expect(retry.pages.map((p: R) => p.slug)).toContain('notes/missed-by-failed-read');
});
- test('facts arm throws while pages are delivered: the facts recorded in the window still arrive on the next call', async () => {
+ test('facts arm throws while pages are delivered: pages advance, facts hold, and the facts arrive on the next call', async () => {
await call({ session_id: 's1' });
- await engine.executeRaw(`UPDATE session_context_state SET last_wake_at = now() - interval '10 seconds'`);
+ await rewind('10 seconds');
+ const factsBefore = await factsCursor();
await fact('fact recorded before the failed read', 5_000);
await page('notes/delivered-page', 3_000);
- faults.failing.add('listFactsSince');
faults.failing.add('listFactsKeyset');
const failed = await call({ session_id: 's1' });
expect(failed.degraded_reason).toContain('facts');
expect(failed.facts).toEqual([]);
+ expect(failed.pages.map((p: R) => p.slug)).toEqual(['notes/delivered-page']);
+ expect((await state())!.last_wake_at).toBe(failed.pages[0].updated_at);
+ expect(await factsCursor()).toMatchObject({ at: factsBefore.at });
+ // The legacy single cursor holds entirely while any arm failed.
+ expect(failed.next_cursor.since).toBe(failed.since);
faults.failing.clear();
const retry = await call({ session_id: 's1' });
expect(retry.facts.map((f: R) => f.fact)).toContain('fact recorded before the failed read');
+ expect(retry.pages).toEqual([]);
+ });
+
+ test('deadline: injected latency leaves every arm unknown in one snapshot, and an unknown arm holds its cursor', async () => {
+ await page('notes/slow-page', 5_000);
+ faults.delayMs = 300;
+ const res = await assembleDeltaContext(faulty(engine, faults), { sourceId: 'default', since: new Date(Date.now() - 60_000).toISOString(), deadlineMs: 40 });
+ expect(res.degradedReason).toBe('deadline');
+ expect(res.deltaArms).toEqual({ pages: 'unknown', facts: 'unknown', threads: 'unknown' });
+ await new Promise((r) => setTimeout(r, 400));
+ // The late completion never mutates the returned snapshot.
+ expect(res.deltaArms).toEqual({ pages: 'unknown', facts: 'unknown', threads: 'unknown' });
+ expect(res.deltaPages).toEqual([]);
+ });
+
+ test('budget-dropped facts re-surface; a duplicate cluster spanning the budget cut loses nothing', async () => {
+ await call({ session_id: 's1' });
+ await rewind('1 minute');
+ const long = 'x'.repeat(200);
+ await fact(`dup claim ${long}`, 50_000);
+ await fact(`distinct claim B ${long}`, 40_000);
+ await fact(`dup claim ${long}`, 30_000);
+ await fact(`distinct claim C ${long}`, 20_000);
+ const seen = new Set<string>();
+ for (let i = 0; i < 8; i++) {
+ const r = await call({ session_id: 's1', budget_tokens: 140 });
+ for (const f of r.facts) seen.add(f.fact.slice(0, 18));
+ if (!r.has_more) break;
+ }
+ expect([...seen].sort()).toEqual(['distinct claim B x', 'distinct claim C x', 'dup claim xxxxxxxx']);
+ });
+
+ test('a budget too small for one waiting item says so with the budget that fits, and moves no cursor', async () => {
+ await call({ session_id: 's1' });
+ await rewind('1 minute');
+ await fact(`oversized ${'y'.repeat(400)}`, 30_000);
+ const before = await factsCursor();
+ const r = await call({ session_id: 's1', budget_tokens: 40 });
+ expect(r.facts).toEqual([]);
+ expect(r.has_more).toBe(true);
+ expect(await factsCursor()).toMatchObject({ at: before.at, id: before.id });
+ const fix = incomplete()[0]?.fix;
+ expect(fix?.actor).toBe('agent');
+ const needed = Number(fix?.argv?.[fix.argv.indexOf('--budget-tokens') + 1]);
+ expect(needed).toBeGreaterThan(40);
+ const ok = await call({ session_id: 's1', budget_tokens: needed });
+ expect(ok.facts.map((f: R) => f.fact.slice(0, 9))).toEqual(['oversized']);
+ });
+
+ test('session-state read error: retryable refusal, checkpoint kept, the next wake delivers from it', async () => {
+ await call({ session_id: 's1' });
+ await rewind('10 seconds');
+ const before = (await state())!.last_wake_at;
+ await page('notes/after-checkpoint', 5_000);
+ faults.sql = /SELECT[\s\S]*session_context_state/;
+ await expect(call({ session_id: 's1' })).rejects.toMatchObject({ code: 'unavailable', reason: 'session_state' });
+ faults.sql = null;
+ expect((await state())!.last_wake_at).toBe(before);
+ const r = await call({ session_id: 's1' });
+ expect(r.pages.map((p: R) => p.slug)).toContain('notes/after-checkpoint');
+ });
+
+ test('session-state write error: session_state degraded with a stateless continuation', async () => {
+ await call({ session_id: 's1' });
+ await rewind('10 seconds');
+ await page('notes/write-fails', 5_000);
+ faults.sql = /INSERT INTO session_context_state/;
+ const r = await call({ session_id: 's1' });
+ expect(r.degraded_reason).toBe('session_state');
+ expect(r.pages.map((p: R) => p.slug)).toEqual(['notes/write-fails']);
+ expect(typeof r.next_cursor.cursor).toBe('string');
+ expect(incomplete()).toHaveLength(1);
+ faults.sql = null;
+ const resumed = await call({ cursor: r.next_cursor.cursor });
+ expect(resumed.pages).toEqual([]);
+ });
+
+ test('first wake (including a GC-expired session) says the cursor started now and how to replay', async () => {
+ await call({ session_id: 's1' });
+ await engine.executeRaw('DELETE FROM session_context_state');
+ notices = [];
+ const r = await call({ session_id: 's1' });
+ expect(r.pages).toEqual([]);
+ const n = notices.find((x) => x.code === 'empty_retrieval');
+ expect(n?.kind).toBe('info');
+ expect(n?.why).toContain('replay statelessly with since');
});
+
+ test('a thread builder throw marks threads degraded and holds the time cursor', async () => {
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example works on things.' });
+ await call({ session_id: 's1' });
+ await rewind('10 seconds');
+ const before = (await state())!.last_wake_at;
+ await page('notes/with-threads', 5_000);
+ faults.throwOnAccess.add('getLinks');
+ const r = await call({ session_id: 's1', entities: 'people/alice-example' });
+ expect(r.degraded_reason).toContain('threads');
+ expect((await state())!.last_wake_at).toBe(before);
+ });
+
+ test('escalation: wait on the first two degraded wakes, report on the third; rendered on CLI, stdio and HTTP', async () => {
+ await call({ session_id: 's1' });
+ faults.failing.add('listPages');
+ for (let i = 0; i < 3; i++) await call({ session_id: 's1' });
+ const [a, b, c] = incomplete();
+ for (const rc of [cli, stdio, http]) {
+ expect(renderNotice(a, rc).fix?.next).toBe('wait');
+ expect(renderNotice(b, rc).fix?.next).toBe('wait');
+ expect(renderNotice(c, rc).fix?.next).toBe('report');
+ }
+ expect(renderNotice(a, stdio).fix?.mcp).toEqual({ tool: 'delta', arguments: { session_id: 's1' } });
+ expect(renderNotice(a, cli).fix?.argv).toEqual(['gbrain', 'delta', '--session-id', 's1']);
+ expect(Number((await factsCursor()).n)).toBe(3);
+ faults.failing.clear();
+ await call({ session_id: 's1' });
+ expect(Number((await factsCursor()).n)).toBe(0);
+ });
+
+ test('stateless callers always get wait; concurrent degraded wakes count atomically', async () => {
+ faults.failing.add('listPages');
+ for (let i = 0; i < 3; i++) await call({ since: new Date(Date.now() - 60_000).toISOString() });
+ expect(incomplete().map((n) => renderNotice(n, stdio).fix?.next)).toEqual(['wait', 'wait', 'wait']);
+ await call({ session_id: 'atomic' });
+ await Promise.all(Array.from({ length: 5 }, () =>
+ upsertSessionContextState(engine, 'default', null, 'atomic', { degradedWakes: 'increment' })));
+ expect(Number((await factsCursor('atomic')).n)).toBe(5);
+ });
+
+ test('store down: the consecutive count falls back to the process and still escalates', async () => {
+ const sid = `down-${kind}`;
+ await call({ session_id: sid });
+ faults.failing.add('listPages');
+ faults.sql = /INSERT INTO session_context_state/;
+ for (let i = 0; i < 3; i++) await call({ session_id: sid });
+ expect(incomplete().map((n) => renderNotice(n, stdio).fix?.next)).toEqual(['wait', 'wait', 'report']);
+ });
+
+ test('120 facts since the cursor drain with none lost (session and stateless cursor)', async () => {
+ await call({ session_id: 's1' });
+ await rewind('10 minutes');
+ const ids: number[] = [];
+ for (let i = 0; i < 120; i++) ids.push(await fact(`bulk fact ${i}`, 300_000 - i * 10));
+ const session = await drain({ session_id: 's1' }, () => ({ session_id: 's1' }));
+ expect(session.ids.size).toBe(120);
+ expect(session.calls).toBeGreaterThanOrEqual(3);
+ const since = new Date(Date.now() - 600_000).toISOString();
+ const stateless = await drain({ since }, (r) => ({ cursor: r.next_cursor.cursor }));
+ expect([...stateless.ids].sort((x, y) => x - y)).toEqual([...ids].sort((x, y) => x - y));
+ });
+
+ test('old request shape (since + since_slug only) loses nothing and resets the slug when it clamps', async () => {
+ const ids: number[] = [];
+ for (let i = 0; i < 70; i++) ids.push(await fact(`legacy fact ${i}`, 300_000 - i * 10));
+ for (let i = 0; i < 3; i++) await page(`notes/legacy-page-${i}`, 100_000 - i * 10);
+ const since = new Date(Date.now() - 600_000).toISOString();
+ let clampedSlug = 'never clamped';
+ const res = await drain({ since }, (r) => {
+ if (r.has_more && r.next_cursor.slug === '') clampedSlug = '';
+ return { since: r.next_cursor.since, since_slug: r.next_cursor.slug };
+ });
+ expect(res.ids.size).toBe(70);
+ expect(res.slugs.size).toBe(3);
+ expect(clampedSlug).toBe('');
+ });
+
+ test('an unpageable same-timestamp boundary refuses legacy callers with delta_cursor_upgrade_required; the cursor drains it', async () => {
+ const at = new Date(Date.now() - 300_000).toISOString();
+ for (let i = 0; i < 60; i++) {
+ const id = await fact(`tied fact ${i}`, 0);
+ await engine.executeRaw(`UPDATE facts SET created_at = $1::text::timestamptz WHERE id = $2`, [at, id]);
+ }
+ const since = new Date(Date.now() - 600_000).toISOString();
+ const r1 = await call({ since });
+ expect(r1.facts).toHaveLength(50);
+ let refusal: R | null = null;
+ try {
+ await call({ since: r1.next_cursor.since, since_slug: r1.next_cursor.slug });
+ } catch (e) { refusal = e as R; }
+ expect(refusal?.code).toBe('delta_cursor_upgrade_required');
+ const cursor = refusal!.fix.mcp.arguments.cursor as string;
+ const factsArm = (c: string) => JSON.parse(Buffer.from(c, 'base64url').toString('utf8')).f;
+ expect(factsArm(cursor)).toEqual(factsArm(r1.next_cursor.cursor));
+ const res = await drain({ cursor }, (r) => ({ cursor: r.next_cursor.cursor }));
+ expect(res.ids.size + r1.facts.length).toBe(60);
+ });
+
+ test('replay: a gap larger than both arm limits drains statelessly without moving the session cursor', async () => {
+ await call({ session_id: 's1' });
+ await rewind('20 minutes');
+ const sessionBefore = (await state())!.last_wake_at;
+ for (let i = 0; i < 60; i++) await page(`notes/gap-page-${String(i).padStart(2, '0')}`, 600_000 - i * 10);
+ for (let i = 0; i < 60; i++) await fact(`gap fact ${i}`, 600_000 - i * 10);
+ const since = new Date(Date.now() - 1_200_000).toISOString();
+ const res = await drain({ since }, (r) => ({ cursor: r.next_cursor.cursor }));
+ expect(res.slugs.size).toBe(60);
+ expect(res.ids.size).toBe(60);
+ expect((await state())!.last_wake_at).toBe(sessionBefore);
+ });
+
+ test('a >limit page cluster inside ONE millisecond drains with no re-delivery (microsecond keyset binds exactly on both engines)', async () => {
+ for (let i = 0; i < 55; i++) {
+ const slug = `notes/ms-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: slug });
+ await engine.executeRaw(`UPDATE pages SET updated_at = '2026-08-10T12:00:00.000000Z'::timestamptz + ($1 || ' microseconds')::interval WHERE slug = $2`, [String(i + 1), slug]);
+ }
+ const delivered: string[] = [];
+ let args: Record<string, unknown> = { since: '2026-08-10T11:00:00Z' };
+ for (let i = 0; i < 6; i++) {
+ const r = await call(args);
+ delivered.push(...r.pages.map((p: R) => p.slug));
+ if (!r.has_more) break;
+ args = { since: r.next_cursor.since, since_slug: r.next_cursor.slug };
+ }
+ expect(delivered).toHaveLength(55);
+ expect(new Set(delivered).size).toBe(55);
+ });
+
+ test('cursor validation: malformed, out-of-range and non-integer ids are invalid_params', async () => {
+ const enc = (body: unknown) => Buffer.from(JSON.stringify(body)).toString('base64url');
+ for (const cursor of [
+ 'not a cursor!',
+ enc({ v: 2, p: ['2026-01-01T00:00:00Z', null], f: ['2026-01-01T00:00:00Z', 1] }),
+ enc({ v: 1, p: ['0000-01-01T00:00:00.000000Z', null], f: ['2026-01-01T00:00:00Z', 1] }),
+ enc({ v: 1, p: ['2026-02-31T00:00:00Z', null], f: ['2026-01-01T00:00:00Z', 1] }),
+ enc({ v: 1, p: ['2026-01-01T00:00:00Z', null], f: ['2026-01-01T00:00:00Z', 1.5] }),
+ enc({ v: 1, p: ['2026-01-01T00:00:00Z', null], f: ['2026-01-01T00:00:00Z', -1] }),
+ ]) {
+ await expect(call({ cursor })).rejects.toMatchObject({ code: 'invalid_params' });
+ }
+ });
+
+ test('since outside years 0001-9999 (year 0000, 10000, negative) is invalid_params naming the range', async () => {
+ for (const since of ['0000-01-01T00:00:00.000000Z', '0000-12-31T00:00:00Z', '+010000-01-01T00:00:00Z', '-000001-01-01T00:00:00Z', '0001-01-01T00:30:00+01:00']) {
+ await expect(call({ since })).rejects.toMatchObject({ code: 'invalid_params' });
+ }
+ await expect(call({ since: '0000-01-01T00:00:00.000000Z' })).rejects.toThrow(/0001-01-01/);
+ const ok = await call({ since: '0001-01-01T00:00:00Z' });
+ expect(ok.since).toBe('0001-01-01T00:00:00.000Z');
+ });
+
+ test('migration v208 initializes an existing row\'s facts cursor from last_wake_at', async () => {
+ await engine.executeRaw(`INSERT INTO session_context_state (source_id, client_id, session_id, last_wake_at) VALUES ('default', 'local', 'legacy-row', '2026-08-10T12:00:00.000123Z')`);
+ await engine.executeRaw(`UPDATE session_context_state SET facts_cursor_at = NULL, facts_cursor_id = NULL, degraded_wakes = 0 WHERE session_id = 'legacy-row'`);
+ for (const stmt of V208_SQL_FOR_TESTS) await engine.executeRaw(stmt);
+ expect(await factsCursor('legacy-row')).toMatchObject({ at: '2026-08-10T12:00:00.000123Z' });
+ expect(Number((await factsCursor('legacy-row')).id)).toBe(0);
+ });
+
+ if (kind === 'postgres') {
+ test('commit visibility: a transaction committing within the lag is delivered; beyond it, the documented bound', async () => {
+ const other = postgres(databaseUrl, { max: 1, prepare: false });
+ try {
+ await call({ session_id: 'vis' });
+ await engine.executeRaw(`UPDATE session_context_state SET last_wake_at = now() - interval '1 minute', facts_cursor_at = now() - interval '1 minute', facts_cursor_id = 0 WHERE session_id = 'vis'`);
+ // Within the lag: the row's created_at (transaction start) stays after the horizon the empty wake advances to.
+ await other.begin(async (tx) => {
+ await tx`INSERT INTO facts (source_id, fact, kind, visibility, source) VALUES ('default', 'late but within lag', 'fact', 'world', 'test')`;
+ await call({ session_id: 'vis' });
+ });
+ const within = await call({ session_id: 'vis' });
+ expect(within.facts.map((f: R) => f.fact)).toContain('late but within lag');
+ // Beyond the lag: a transaction that started before the horizon and commits after an empty wake is missed.
+ await engine.executeRaw(`UPDATE session_context_state SET facts_cursor_at = now(), facts_cursor_id = 0 WHERE session_id = 'vis'`);
+ await other.begin(async (tx) => {
+ await tx`INSERT INTO facts (source_id, fact, kind, visibility, source) VALUES ('default', 'late beyond lag', 'fact', 'world', 'test')`;
+ await new Promise((r) => setTimeout(r, 2_300));
+ await call({ session_id: 'vis' });
+ });
+ const beyond = await call({ session_id: 'vis' });
+ expect(beyond.facts.map((f: R) => f.fact)).not.toContain('late beyond lag');
+ } finally {
+ await other.end();
+ }
+ }, 30_000);
+ }
});
}
diff --git a/test/delta-cursor-microseconds.test.ts b/test/delta-cursor-microseconds.test.ts
index 00e6454531..041736fadb 100644
--- a/test/delta-cursor-microseconds.test.ts
+++ b/test/delta-cursor-microseconds.test.ts
@@ -84,7 +84,9 @@ describe('delta — cursor carries column-precision microseconds', () => {
const sid = 'us-session';
const r0 = await call(del, { session_id: sid });
expect(slugs(r0)).toEqual([]);
- // Stamp the pair just after the established cursor, inside its millisecond.
+ // Age the established cursor past delta's 2 s commit-visibility horizon,
+ // then stamp the pair just after it, inside its millisecond.
+ await engine.executeRaw(`UPDATE session_context_state SET last_wake_at = last_wake_at - interval '1 minute', facts_cursor_at = facts_cursor_at - interval '1 minute' WHERE session_id = $1`, [sid]);
await seedPair(`SELECT last_wake_at FROM session_context_state WHERE session_id = $1`, [sid]);
const r1 = await call(del, { session_id: sid });
expect(slugs(r1)).toEqual(['notes/us-a', 'notes/us-b']);
diff --git a/test/engine-sql-facts-keyset.test.ts b/test/engine-sql-facts-keyset.test.ts
new file mode 100644
index 0000000000..7188bb19e2
--- /dev/null
+++ b/test/engine-sql-facts-keyset.test.ts
@@ -0,0 +1,62 @@
+/**
+ * listFactsKeyset (delta's facts arm read contract): ascending
+ * `(created_at, id)` strictly after a keyset, column-precision
+ * `created_at_iso`, `id: null` = strictly after the timestamp. Both engines.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+for (const kind of testBackends()) {
+ describe(`listFactsKeyset (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ async function fact(text: string, at: string, visibility: 'world' | 'private' = 'world'): Promise<number> {
+ const { id } = await engine.insertFact({ fact: text, kind: 'fact', visibility, entity_slug: null, source: 'test' } as never, { source_id: 'default' });
+ await engine.executeRaw(`UPDATE facts SET created_at = $1::text::timestamptz WHERE id = $2`, [at, id]);
+ return id;
+ }
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => { await engine.executeRaw('DELETE FROM facts'); });
+
+ test('oldest first; same-microsecond rows tie-break by id; ids ordered differently from timestamps', async () => {
+ const late = await fact('k-late', '2026-08-10T12:00:00.000300Z');
+ const tieA = await fact('k-tie-a', '2026-08-10T12:00:00.000200Z');
+ const tieB = await fact('k-tie-b', '2026-08-10T12:00:00.000200Z');
+ const early = await fact('k-early', '2026-08-10T12:00:00.000100Z');
+ const rows = await engine.listFactsKeyset('default', null, { limit: 10 });
+ expect(rows.map((r) => r.id)).toEqual([early, tieA, tieB, late]);
+ expect(rows.map((r) => r.created_at_iso)).toEqual([
+ '2026-08-10T12:00:00.000100Z', '2026-08-10T12:00:00.000200Z', '2026-08-10T12:00:00.000200Z', '2026-08-10T12:00:00.000300Z',
+ ]);
+ const afterTieA = await engine.listFactsKeyset('default', { createdAt: '2026-08-10T12:00:00.000200Z', id: tieA }, { limit: 10 });
+ expect(afterTieA.map((r) => r.id)).toEqual([tieB, late]);
+ const strict = await engine.listFactsKeyset('default', { createdAt: '2026-08-10T12:00:00.000200Z', id: null }, { limit: 10 });
+ expect(strict.map((r) => r.id)).toEqual([late]);
+ });
+
+ test('limit, visibility and activeOnly apply before the keyset page', async () => {
+ await fact('v-private', '2026-08-10T12:00:00.000100Z', 'private');
+ const w1 = await fact('v-world-1', '2026-08-10T12:00:00.000200Z');
+ const w2 = await fact('v-world-2', '2026-08-10T12:00:00.000300Z');
+ await fact('v-expired', '2026-08-10T12:00:00.000400Z');
+ await engine.executeRaw(`UPDATE facts SET expired_at = now() WHERE fact = 'v-expired'`);
+ const page = await engine.listFactsKeyset('default', null, { limit: 1, visibility: ['world'], activeOnly: true });
+ expect(page.map((r) => r.id)).toEqual([w1]);
+ const rest = await engine.listFactsKeyset('default', { createdAt: page[0].created_at_iso!, id: page[0].id }, { limit: 10, visibility: ['world'] });
+ expect(rest.map((r) => r.id)).toEqual([w2]);
+ });
+ });
+}
diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.ts
index ac6776aaa1..d1b6680872 100644
--- a/test/engine-surface-coverage.test.ts
+++ b/test/engine-surface-coverage.test.ts
@@ -87,7 +87,7 @@ const INTERFACE_METHODS: readonly string[] = [
'getContradictionCacheEntry', 'putContradictionCacheEntry', 'sweepContradictionCache',
// Facts (hot memory)
'insertFact', 'insertFacts', 'deleteFactsForPage', 'expireFact', 'listFactsByEntity',
- 'listFactsSince', 'listFactsBySession', 'listSupersessions', 'countUnconsolidatedFacts',
+ 'listFactsSince', 'listFactsKeyset', 'listFactsBySession', 'listSupersessions', 'countUnconsolidatedFacts',
'findCandidateDuplicates', 'consolidateFact', 'findTrajectory', 'getFactsHealth',
// Versions
'createVersion', 'getVersions', 'revertToVersion',
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 36d195e47f..ba60c64160 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -2659,7 +2659,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index d116016abb..02d9e75928 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -2659,7 +2659,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index b3251b2bfb..e0b19d48d9 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -2655,7 +2655,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index 010b184832..80719198cb 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -1935,7 +1935,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index d093cf82ea..df42728943 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -1935,7 +1935,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index dc26789974..d4639a6d79 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -1934,7 +1934,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 1f0f2fbce0..7cb4aa665f 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -2007,7 +2007,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 7bb5f71b09..886a60d39b 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -2654,7 +2654,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index d075db3f1d..e640be2fe9 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -2654,7 +2654,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index a026f583ac..814cd86fe8 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -2650,7 +2650,10 @@
"5 surfaced_slugs jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"6 checkpoint_manifest jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",
"7 last_wake_at timestamp with time zone/timestamptz NULL",
- "8 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "8 facts_cursor_at timestamp with time zone/timestamptz NULL",
+ "9 facts_cursor_id bigint/int8 NULL",
+ "10 degraded_wakes integer/int4 NOT NULL DEFAULT 0",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 2fbdc0c446..e4859bb227 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": 203001,
- "stdoutSha256": "1c7a6e9584099345f3d0f2ef2756bce55121ef709144cc7e60a78ec9ee6c6e0d",
+ "stdoutBytes": 203079,
+ "stdoutSha256": "3f2a347db6f4a41890023a83565e4a811e9fb1127b881fad419a24f3365f3d21",
"toolNames": [
"remember",
"entity",
@@ -5411,13 +5411,14 @@
"scope": "read"
},
{
- "description": "MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. Keep a cursor with session_id, or pass since.",
+ "description": "MEMORY VERB (v1): pages, facts, thread events changed since a cursor, zero LLM. Pass session_id, cursor or since.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "delta",
"parameters": {
"budget_tokens": "number?",
+ "cursor": "string?",
"entities": "string?",
"include_private": "boolean?",
"session_id": "string?",
@@ -5431,8 +5432,12 @@
"description": "Token budget; pages pack first.",
"type": "number"
},
+ "cursor": {
+ "description": "next_cursor.cursor (exact).",
+ "type": "string"
+ },
"entities": {
- "description": "Entity scope for thread events (max 8).",
+ "description": "Entities for thread events (max 8).",
"type": "string"
},
"include_private": {
@@ -5440,15 +5445,15 @@
"type": "boolean"
},
"session_id": {
- "description": "Opaque session id; keeps a cursor.",
+ "description": "Session id; keeps a cursor.",
"type": "string"
},
"since": {
- "description": "ISO 8601 cursor (or use session_id).",
+ "description": "ISO 8601 start time.",
"type": "string"
},
"since_slug": {
- "description": "next_cursor.slug from the previous response.",
+ "description": "Legacy: next_cursor.slug.",
"type": "string"
}
},
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 58e75d1fc1..72f4004d0f 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -109,6 +109,7 @@
"listEvalCaptureFailures",
"listFactsByEntity",
"listFactsBySession",
+ "listFactsKeyset",
"listFactsSince",
"listFilesForPage",
"listLinkSources",
@@ -290,6 +291,7 @@
"listEvalCaptureFailures",
"listFactsByEntity",
"listFactsBySession",
+ "listFactsKeyset",
"listFactsSince",
"listFilesForPage",
"listLinkSources",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 22ec279499..b8e51e6e1c 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -143,6 +143,7 @@
"listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",
"listFactsByEntity: (source_id: string, entitySlug: string, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsBySession: (source_id: string, sessionId: string, opts?: FactListOpts) => Promise<FactRow[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",
"listFilesForPage: (pageId: number) => Promise<FileRow[]>",
"listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>",
@@ -1090,6 +1091,7 @@
"listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",
"listFactsByEntity: (source_id: string, entitySlug: string, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsBySession: (source_id: string, sessionId: string, opts?: FactListOpts) => Promise<FactRow[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",
"listFilesForPage: (pageId: number) => Promise<FileRow[]>",
"listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>",
@@ -3195,6 +3197,7 @@
"listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",
"listFactsByEntity: (source_id: string, entitySlug: string, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsBySession: (source_id: string, sessionId: string, opts?: FactListOpts) => Promise<FactRow[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",
"listFilesForPage: (pageId: number) => Promise<FileRow[]>",
"listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>",
@@ -3372,6 +3375,7 @@
"consolidated_into: number | null",
"context: string | null",
"created_at: Date",
+ "created_at_iso?: string | undefined",
"embedded_at: Date | null",
"embedded_text_hash?: string | null | undefined",
"embedding: Float32Array<ArrayBufferLike> | null",
@@ -5707,7 +5711,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
@@ -6001,6 +6005,7 @@
"listEvalCaptureFailures: (filter?: { since?: Date; }) => Promise<EvalCaptureFailure[]>",
"listFactsByEntity: (source_id: string, entitySlug: string, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsBySession: (source_id: string, sessionId: string, opts?: FactListOpts) => Promise<FactRow[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts) => Promise<FactRow[]>",
"listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",
"listFilesForPage: (pageId: number) => Promise<FileRow[]>",
"listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 3c041d8546..cfe9cbf0b3 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 202,
+ "count": 203,
"gaps": [
17,
18,
@@ -29,7 +29,7 @@
"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 207,
+ "latest": 208,
"records": [
{
"handler": {
@@ -3068,6 +3068,19 @@
"transaction": "absent",
"verify": "absent",
"version": 207
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "delta_per_arm_cursor",
+ "sql": {
+ "length": 449,
+ "sha256": "7ffafdab8ee63691d5fc45ad459540579285f21ad929e022a79100006e2e11e5"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 208
}
],
"versions": [
@@ -3272,7 +3285,8 @@
204,
205,
206,
- 207
+ 207,
+ 208
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index 9e9f019349..817dcfa7ae 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -4,7 +4,7 @@
"chunks": 14,
"cjk-search": 2,
"code-edges": 5,
- "facts": 18,
+ "facts": 19,
"files": 3,
"links": 12,
"out-of-scope:config": 5,
@@ -130,6 +130,7 @@
"listEvalCaptureFailures": "out-of-scope:eval-capture",
"listFactsByEntity": "facts",
"listFactsBySession": "facts",
+ "listFactsKeyset": "facts",
"listFactsSince": "facts",
"listFilesForPage": "files",
"listLinkSources": "links",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 15ca4cd4a3..2a412ae254 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -1604,6 +1604,41 @@
}
]
},
+ "listFactsKeyset": {
+ "default": [
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "keyset": [
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "strictTime": [
+ {
+ "paramCount": 4,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"listFactsSince": {
"allFilters": [
{
diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.json
index 6a20acea68..5d6d975dec 100644
--- a/test/fixtures/goldens/sql-text/facts.json
+++ b/test/fixtures/goldens/sql-text/facts.json
@@ -617,6 +617,46 @@
}
]
},
+ "listFactsKeyset": {
+ "default": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "number"
+ ],
+ "sql": "SELECT *, to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS created_at_iso FROM facts WHERE source_id = $1 AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) ORDER BY created_at ASC, id ASC LIMIT $2",
+ "textSha256": "0a40122b0f45781fe163473acc69c889aeb6c63e2fd366f2f15731229025b466"
+ }
+ ],
+ "keyset": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "string",
+ "string",
+ "number",
+ "number"
+ ],
+ "sql": "SELECT *, gbrain_fact_fingerprint(fact) AS fact_fingerprint, to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS created_at_iso FROM facts WHERE source_id = $1 AND (created_at > $2::text::timestamptz OR (created_at = $3::text::timestamptz AND id > $4)) ORDER BY created_at ASC, id ASC LIMIT $5",
+ "textSha256": "48e52d1c6898cb66b520371fe6e65624ccfca9643f2e6e4dcf8f30186bbbdd0f"
+ }
+ ],
+ "strictTime": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "string",
+ "array<string>",
+ "number"
+ ],
+ "sql": "SELECT *, to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS created_at_iso FROM facts WHERE source_id = $1 AND created_at > $2::text::timestamptz AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) AND visibility = ANY($3::text[]) ORDER BY created_at ASC, id ASC LIMIT $4",
+ "textSha256": "8918057b510da33d9b032fdefda14dfd7c9f5e67dd28b763ee8823cfa87b42f5"
+ }
+ ]
+ },
"listFactsSince": {
"allFilters": [
{
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index c72213bbc4..4c978d77ec 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -540,8 +540,8 @@
"number",
"number"
],
- "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND (p.updated_at > $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.slug > $3)) AND p.deleted_at IS NULL ORDER BY p.updated_at DESC LIMIT $4 OFFSET $5",
- "textSha256": "9a681698e0e8f5db467af463257f72afd33c8bf51ac91ae09b7119c8ace39e9c"
+ "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND (p.updated_at > $1::text::timestamptz OR (p.updated_at = $2::text::timestamptz AND p.slug > $3)) AND p.deleted_at IS NULL ORDER BY p.updated_at DESC LIMIT $4 OFFSET $5",
+ "textSha256": "e8c035bd6109b92df5e6f89080db721da06e12d57e58d3d7d7c98346d70a30af"
}
],
"updated_after": [
@@ -552,8 +552,8 @@
"number",
"number"
],
- "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND p.updated_at > $1::timestamptz AND p.deleted_at IS NULL ORDER BY p.updated_at DESC LIMIT $2 OFFSET $3",
- "textSha256": "1df2d216e9f3e7a7b13e7e2c765a1b87e086d9367ce7540d13b7de62be8bf004"
+ "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND p.updated_at > $1::text::timestamptz AND p.deleted_at IS NULL ORDER BY p.updated_at DESC LIMIT $2 OFFSET $3",
+ "textSha256": "98825ce723c789c3a2796f00c1fa36e988d6630803577600aed5a85adb258624"
}
]
},
diff --git a/test/helpers/delta-v208.ts b/test/helpers/delta-v208.ts
new file mode 100644
index 0000000000..6202dfadfd
--- /dev/null
+++ b/test/helpers/delta-v208.ts
@@ -0,0 +1,7 @@
+import { v208 } from '../../src/core/schema-migrations/v208-delta-per-arm-cursor.ts';
+
+/** The v208 migration's statements, split for executeRaw (one statement per call on both engines). */
+export const V208_SQL_FOR_TESTS: string[] = v208.sql
+ .split(';')
+ .map((s) => s.trim())
+ .filter(Boolean);
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index 119aa6a6e4..87dc89959c 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -112,7 +112,7 @@ export const DOMAIN_OF: Record<string, string> = {
'getEmbeddingsByChunkIds': 'chunks', 'getChunksWithEmbeddings': 'chunks',
// facts (incl. the ontology rows of the facts table)
'insertFact': 'facts', 'expireFact': 'facts', 'insertFacts': 'facts', 'deleteFactsForPage': 'facts',
- 'listFactsByEntity': 'facts', 'listFactsSince': 'facts', 'listFactsBySession': 'facts', 'listSupersessions': 'facts',
+ 'listFactsByEntity': 'facts', 'listFactsSince': 'facts', 'listFactsKeyset': 'facts', 'listFactsBySession': 'facts', 'listSupersessions': 'facts',
'countUnconsolidatedFacts': 'facts', 'findCandidateDuplicates': 'facts', 'consolidateFact': 'facts',
'findTrajectory': 'facts', 'getFactsHealth': 'facts', 'migrateFactsToCanonical': 'facts',
'mergeOntologyFact': 'facts', 'getOntology': 'facts', 'discoverOntologyDimensions': 'facts', 'findOntologyConflicts': 'facts',
@@ -582,6 +582,11 @@ export const SQL_CASES: SqlCase[] = [
['default', (e) => e.listFactsByEntity(SRC, SLUG)],
['allFilters', (e) => e.listFactsByEntity(SRC, SLUG, { activeOnly: false, unconsolidatedOnly: true, kinds: ['fact'], visibility: ['world'], excludeAuditRows: true, grep: 'acme' })],
]),
+ ...variants('listFactsKeyset', [
+ ['default', (e) => e.listFactsKeyset(SRC, null)],
+ ['strictTime', (e) => e.listFactsKeyset(SRC, { createdAt: '2026-08-10T12:00:00.000100Z', id: null }, { visibility: ['world'] })],
+ ['keyset', (e) => e.listFactsKeyset(SRC, { createdAt: '2026-08-10T12:00:00.000100Z', id: 7 }, { activeOnly: false, fingerprint: true, limit: 51 })],
+ ]),
...variants('listFactsSince', [
['default', (e) => e.listFactsSince(SRC, EPOCH)],
['allFilters', (e) => e.listFactsSince(SRC, EPOCH, { entitySlug: SLUG, sessionId: 's1', eventTime: true, activeOnly: false, unconsolidatedOnly: true, kinds: ['fact'], visibility: ['world'], excludeAuditRows: true, grep: 'acme' })],
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 77a917fb95..f769567eb8 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -50,7 +50,7 @@ import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-esti
const SERVED_STARTER_MAX_CHARS = 25_000;
const SERVED_STARTER_MAX_TOKENS = 5_700;
-/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need). */
+/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need; 26,679 with delta's opaque `cursor` param, paid for by trimming delta's own descriptions, model-visible 24,985). */
const SERVED_STARTER_MAX_JSON_CHARS = 26_700;
/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */
const INSTRUCTIONS_MAX_CHARS = 4_868; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms)
diff --git a/test/turn-context.test.ts b/test/turn-context.test.ts
index 9d73d036ff..f0e01fe3cb 100644
--- a/test/turn-context.test.ts
+++ b/test/turn-context.test.ts
@@ -263,7 +263,7 @@ describe('assembleDeltaContext read failures', () => {
await seedFact('WORLD-FACT remains available', 'world');
const partialEngine = {
listPages: async () => { throw new Error('private storage detail'); },
- listFactsSince: (...args: Parameters<BrainEngine['listFactsSince']>) => engine.listFactsSince(...args),
+ listFactsKeyset: (...args: Parameters<BrainEngine['listFactsKeyset']>) => engine.listFactsKeyset(...args),
} as unknown as BrainEngine;
const result = await assembleDeltaContext(partialEngine, {
@@ -281,7 +281,7 @@ describe('assembleDeltaContext read failures', () => {
await seedPage('notes/delta-readable', 'Readable page', 'A changed page.');
const partialEngine = {
listPages: (...args: Parameters<BrainEngine['listPages']>) => engine.listPages(...args),
- listFactsSince: async () => { throw new Error('private storage detail'); },
+ listFactsKeyset: async () => { throw new Error('private storage detail'); },
} as unknown as BrainEngine;
const result = await assembleDeltaContext(partialEngine, {
@@ -298,7 +298,7 @@ describe('assembleDeltaContext read failures', () => {
test('both failed read arms are reported together as a degraded empty result', async () => {
const partialEngine = {
listPages: async () => { throw new Error('private page detail'); },
- listFactsSince: async () => { throw new Error('private fact detail'); },
+ listFactsKeyset: async () => { throw new Error('private fact detail'); },
} as unknown as BrainEngine;
const result = await assembleDeltaContext(partialEngine, {