Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(delta): replay recipe, per-arm cursor contract, retry hint; TODOS for deferred items

garrytandfb2c80027e0
diff --git a/TODOS.md b/TODOS.md
index da9a86f27d..d4a3fb126b 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,22 @@
# TODOS
+## Contributor audit wave follow-ups (filed 2026-10-05, GBRA-40)
+
+### delta (owner: GBRA-49, core memory and retrieval)
+
+- [ ] **P2 — Commit-visibility watermark for delta.** **What:** rows are stamped with their transaction's start time, so a transaction that commits more than 2 s (`DELTA_COMMIT_LAG_MS`) after it started can be passed by an empty wake that advanced the cursor meanwhile. `test/delta-cursor-integrity.test.ts` ("commit visibility", Postgres) pins the bound. **Fix:** advance each arm only to a watermark below the oldest in-flight writer (e.g. `pg_snapshot_xmin` mapped to time, or a commit-sequence column), so the bound becomes zero. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Paginated thread arm.** **What:** thread events key on event date through `buildEntityCard`, which caps and swallows internally, so delta's threads are best-effort and follow the pages' time cursor. **Fix:** give threads their own keyset (event id or date + id) and an overflow signal like the pages and facts arms. **Effort:** M. **Priority:** P3.
+
+### Agent contract (former GBRA-42 hand-offs; owner: whoever picks up the next agent-contract wave)
+
+- [ ] **P2 — A structured retry delay on `Action`.** **What:** `fix.next: wait` is derived from `actor: provider`, and the delay lives only in prose (`why`: "Retry the same call in about 30 seconds"). delta's `delta_incomplete` notice and its `unavailable`/`session_state` refusal use it today (`src/core/ops/facts.ts` `incompleteNotice`, `sessionUnavailableError`). **Fix:** add an optional `retry_after_ms` (or `retry_after_s`) to `Action` in `src/core/agent-output.ts`, render it in the CLI `[AGENT]` block, the MCP notice block (`retry_after:` line) and `_meta`, extend the decision table in `docs/protocol/AGENT_OPERATOR_v1.md` ("`wait` → retry after `retry_after`"), regenerate the agent-operator goldens, and switch delta to it. Additive under contract v1. **Effort:** S. **Priority:** P2.
+- [ ] **P2 — `GrantError` family onto the why/fix contract.** **What:** `src/core/grants/cli.ts` throws about 19 `invalid_grant` `GrantError`s (two added by #6008 for `--operations all`) with a message only: no `code`-level `why`, no structured `fix`. **Fix:** convert the family together so the fix echoes the flag the user actually typed (`--operations`, `--allowed-operations`, `--profile`, `--takes-holders`), with a read-only verify (`gbrain auth clients --json`); keep `invalid_grant` as the code and add `reason` values instead of new codes. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Scanner rule for CLI parser usage errors.** **What:** #5942 and #6002 printed raw `console.error` usage lines and exited 1 instead of throwing `invalid_params` (exit 2); `scripts/check-agent-contract.ts` has no rule for it, so the audit found them by hand (fixed in this wave for `connectors sync` and `recall --limit`). **Fix:** a scanner rule flagging `console.error('Usage:` / `process.exit(1)` pairs in `src/commands/**` parsers, baselined at today's count. **Effort:** S. **Priority:** P3.
+
+### Measurement
+
+- [ ] **P3 — Paid retrieval-quality eval of #5783's smaller transcript parts.** **What:** the wave measured the free cost (pages ×6.75, chunks ×1.116, embedding tokens ×1.087 on a synthetic 1 MB session, `scripts/measure-transcript-split-cost.ts`) but not whether 45,000-byte parts retrieve better or worse. **Fix:** a gbrain-evals run on a transcript-heavy corpus at both part targets, newest frontier models only. **Effort:** M. **Priority:** P3.
+
## Test, eval and CI fix wave follow-ups (filed 2026-10-04, GBRA-47)
Context: `.github/nightly-known-red.tsv` rows point here; nightly-watch keeps their incidents open until the row is deleted. Scale-tier evidence: per-batch `vectors` lines and the phase watchdog in `scripts/scale/`.
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index dbc9f1368a..64f9ca7868 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -5,7 +5,7 @@
- `src/core/wsl-paths.ts` — WSL Windows-drive path translation shared by the doctor asset checks (`src/commands/doctor-asset-paths.ts`) and hook-transcript confinement (`confineTranscriptPath` above). Exports `WINDOWS_DRIVE_PATH_RE`, `translateWindowsPath(p, mountRoot)` (`C:\Users\x\file` → `<mountRoot>/c/Users/x/file`; null for non-drive input so callers keep the original untouched), `parseWslAutomountRoot(conf)` (the `/etc/wsl.conf` `[automount] root` value, default `/mnt`), and `detectWslMountRoot()` (null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases in `test/claude-code-jsonl.test.ts`.
- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. Hot-memory facts whose rendered line (without the drifting confidence) already appears in `priorContextText` are not re-injected, the same cross-turn contract as volunteered pages (#5591). In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off.
- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy: `startResolveIpcServer` connect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.
-- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off.
+- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off. delta's arms publish their results in one assignment each and the verb reads `deltaArms` (`ok`/`failed`/`unknown`) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm reads `listFactsKeyset` (ascending `(created_at, id)`, limit+1 probe) and returns the raw rows with their collapsed representative (`deltaFactsRaw`); a thread-builder throw marks `threads` failed. `session-state.ts` distinguishes absent, loaded and unavailable (`readDeltaSessionState`), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as `$n::text::timestamptz` so postgres.js cannot truncate them to milliseconds.
- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.
- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob. NOTE the deliberate asymmetry with the ambient-writeback TEMPLATE resolver (writeback-config.ts below): this READ/extract default fail-closes UNSET to private; write GUIDANCE treats unset as world (the `remember` verb's own default) because telling agents to write private-by-default on a default install makes their facts invisible to their own later remote sessions.
- **Ambient memory writeback cluster** (opt-in, `memory.auto_writeback = off|salient|all`, default off; guide `docs/guides/ambient-writeback.md`):
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 3573ca73fb..e2a772abb7 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -24,6 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
`fragment.ts` numbers placeholders at render time, so text is byte-identical to the tagged templates it replaced (`test/fixtures/goldens/sql-text/`). Capabilities (`maxBindParamsPerStatement`, `transactionAdvisoryLocks`, `probesEmbeddingCast`) carry the real engine differences; `docs/designs/refactor-wave-1/w1-inventory.md` classifies every method. Page-state orchestration stays in the engines: `putPage`'s transaction, page-key lock and revision check, and the `updateSlug` / `setPageAliases` transactions, call `pages.ts` on the transaction clone's executor; `getPage` / `readPageSnapshot` keep their SQL in `page-state/snapshot.ts`. Reads with an early return that must not open a scoped transaction (`listPrefixSampledPages`, `listCorpusSample`) take a `ScopedReadRunner`. Nothing here imports an engine façade (`check:layering`); SQL may splice only constant text (`check:engine-sql-dynamic`); brands are unforgeable (`check:engine-sql-brands`); engine SQL only shrinks (`check:engine-sql-ratchet`). Tests: docs/TESTING.md "Engine-sql".
+- `src/core/engine-sql/facts.ts` `listFactsKeyset` + `src/core/engine-sql/pages.ts` keyset predicates — delta's two keyset reads. Both bind the cursor timestamp as `${value}::text::timestamptz`: a bare `::timestamptz` param is typed by the postgres.js driver, which serializes a string through a JS Date and truncates it to milliseconds (on Postgres that re-selected the whole last millisecond every wake and never drained a >limit cluster inside one millisecond). `listFactsKeyset` reads ascending `(created_at, id)` strictly after the keyset (`id: null` = strictly after the timestamp) and projects `created_at_iso` at column precision; recall's newest-first `listFactsSince` is unchanged. `test/engine-sql-facts-keyset.test.ts`, `test/delta-cursor-integrity.test.ts` (both engines).
- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.
- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as in-scope link endpoints grouped per entity page (ties break by slug in code-point order). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are three functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer).
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 0641da9fe5..883b5c1f36 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -75,7 +75,8 @@ rejection of serve-only flags before a brain opens.
- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer.
-- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation.
+- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.
+- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.
- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process.
diff --git a/docs/guides/ambient-recall.md b/docs/guides/ambient-recall.md
index 8066278305..1705d847a5 100644
--- a/docs/guides/ambient-recall.md
+++ b/docs/guides/ambient-recall.md
@@ -82,18 +82,83 @@ pack can afford more than a heartbeat delta.
Pass a stable `session_id` to `delta` and the brain keeps a per-session cursor:
the first wake establishes it, each wake advances it. Dedup is **cursor-based**
— a delivered page reappears only if it changes again after delivery (and then
-it should). Delivery is **at-least-once**: pages arrive oldest-first, and when
-a budget or the fetch limit drops some, the response sets `has_more: true` and
-the cursor advances only to the newest *delivered* page, so the tail surfaces
-on the next wake — nothing is silently lost. With no `session_id` you can still
-pass an explicit `since` for a stateless delta. The cursor is namespaced per
+it should). Delivery is **at-least-once, per arm**: pages arrive oldest-first by
+`(updated_at, slug)` and facts oldest-first by `(created_at, id)`, each arm with
+its own cursor. When a budget or a fetch limit drops some, the response sets
+`has_more: true` and each arm advances only through what it *delivered*, so the
+tail surfaces on the next wake. An arm whose read failed (or never finished
+before a deadline) does not advance at all: the response carries
+`degraded_reason` and a `delta_incomplete` notice whose fix is to retry the same
+call in about 30 seconds (`fix.next: wait`); after three consecutive incomplete
+wakes on one session the fix becomes `report` (tell the user, run
+`gbrain doctor --json`). Neither arm advances past `now() - 2 s`, so a row
+delivered within the last two seconds can arrive once more on the next wake.
+Thread events are best-effort: they follow the pages' time cursor and are never
+budget-dropped. With no `session_id` you can still run a stateless delta:
+pass `since` on the first call and `next_cursor.cursor` afterwards. The cursor is namespaced per
caller (`(source_id, client_id, session_id)`; authenticated remotes use their
client id, auth-less remotes share a `remote` namespace, and `local` is
reserved for the trusted CLI/hook lane), so a remote harness can never read or
advance the local lane's cursor. Idle session cursors are garbage-collected
after **7 days** — a wake on an expired session re-establishes the cursor at
-now and returns an empty delta, so a harness returning from a long sleep
-should run one stateless `since`-based catch-up first.
+now, returns an empty delta and says so in an info notice, so a harness
+returning from a long sleep should run one stateless `since`-based catch-up
+first (the replay recipe below).
+
+**Guarantee, stated precisely.** Rows are stamped with their transaction's
+start time. A transaction that commits more than two seconds after it started
+can be passed by an empty wake that advanced the cursor in the meantime; every
+other row reaches the session at least once. A failed session-state read is
+never treated as a new session: delta refuses with `unavailable`
+(`reason: session_state`) and keeps the checkpoint, and a failed state write
+adds `session_state` to `degraded_reason` while the response still carries the
+stateless `next_cursor`.
+
+## Replay after a degraded wake
+
+If a response carried `degraded_reason`, nothing was skipped: the next wake
+re-reads the same window. To read that window right away (or to catch up after
+a long sleep), replay statelessly from that response's `since`, without
+`session_id`, so the session cursor is not moved:
+
+1. Call `delta` with the same `entities` (and `include_private`, if used) and
+ `since` set to the degraded response's `since`. Do not pass `session_id`.
+2. Read `pages`, `facts` and `threads`; dedupe pages by `slug` and facts by `id`.
+3. While `has_more` is true or `degraded_reason` is present, call again with
+ `cursor` set to the previous response's `next_cursor.cursor` (wait about 30
+ seconds first if it was degraded).
+4. Stop when `has_more` is false and no `degraded_reason` remains.
+
+MCP payloads:
+
+```json
+{"tool": "delta", "arguments": {"since": "2026-08-11T00:00:00.000000Z", "entities": "acme-example"}}
+{"tool": "delta", "arguments": {"cursor": "<next_cursor.cursor from the previous response>", "entities": "acme-example"}}
+```
+
+CLI equivalent:
+
+```bash
+gbrain delta --since 2026-08-11T00:00:00.000000Z --entities acme-example --json
+gbrain delta --cursor "$NEXT_CURSOR" --entities acme-example --json
+```
+
+Expected result: the loop ends with `has_more: false` and no `degraded_reason`;
+every page and fact changed after `since` has appeared at least once. A failure
+looks like `"degraded_reason": "facts"` with a `delta_incomplete` notice: wait
+and repeat the same call. Verify with one more call from the last
+`next_cursor.cursor`: it returns empty arrays.
+
+Replay returns the data the brain holds now (current page versions, active
+facts), not historical page versions. The session cursor columns added for the
+per-arm cursor start from each session's last wake, so gaps skipped before the
+upgrade are not recoverable by the session itself; replay from an older `since`
+reads them. `next_cursor.since` + `since_slug` still work for older clients:
+they are conservative (they may re-deliver, they never skip facts), and a
+legacy caller that reaches more undelivered facts at one timestamp than the
+fetch limit gets `delta_cursor_upgrade_required`, whose fix is the same call
+with `cursor`. Each response also carries `start_cursor`-equivalent detail in
+`cursor_arms` (each arm's start and next keyset) for audit.
## Example — a cold session start (pull)
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index 6f6f16cf17..59e9475318 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -748,7 +748,18 @@ final document.
is stateless, so dedupe is per authenticated client and session, and
`degraded` and `safety` notices ride every affected call. At most 2
`coaching` notices per session. Notices that describe one call's result
-(`empty_retrieval`, `unknown_param`, `listing_truncated`) are never deduped.
+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)
+are never deduped.
+
+**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`
+renders `next: wait`: repeat the same call (the fix carries it) after the delay
+the `why` states, in seconds. `delta_incomplete` uses it: delta moved no cursor
+past what it did not deliver, so the retry re-reads the same window. When the
+same session has been incomplete on three consecutive wakes, the fix has no
+command and renders `next: report`: tell the user and run
+`gbrain doctor --json`. Stateless callers always get `wait`. A session store
+that cannot be read at all refuses the call with `unavailable` (reason
+`session_state`) and the same wait/report fix.
**Mute.** `coaching` and `info` notices can be muted, plus one `ask`:
`first_run_decisions`, so an unanswered first-run bundle stays dismissible.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 61d67efada..8dfe3d7de1 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -582,7 +582,7 @@ degraded_reason?, budget_tokens?, budget_used?, dropped_count? }`. `text` is the
pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
rendered from the packed sets and never exceeds the declared budget.
-### delta(since?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
+### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
"What changed since T" for heartbeats — pages updated after
the cursor (oldest first) + facts recorded after the cursor + open-thread
@@ -599,16 +599,50 @@ namespaced by their auth client id, auth-less remotes share the `'remote'`
sentinel, and `'local'` is RESERVED for the trusted CLI/hook lane, so a remote
harness can never read or advance the local lane's cursor.
-Delivery is at-least-once via a **keyset cursor `(updated_at, slug)`**: a cluster
-of pages sharing one `updated_at` (bulk syncs stamp identical timestamps) pages
-deterministically by slug, so a >fetch-limit cluster drains across wakes instead
-of livelocking. Stateless callers resume by passing the response's
-`next_cursor.since` + `next_cursor.slug` back as `since` + `since_slug`;
-`session_id` callers get this automatically.
+Delivery is at-least-once **per arm**. Pages page by the keyset
+`(updated_at, slug)`, facts by `(created_at, id)`, both at column (microsecond)
+precision, each arm with its own cursor: a cluster sharing one timestamp (bulk
+syncs stamp identical timestamps) pages deterministically, so a >fetch-limit
+cluster drains across wakes instead of livelocking. **No-advance rule:** each
+arm advances through the prefix it delivered and no further; an arm whose read
+threw or did not finish before a deadline does not advance; neither arm
+advances past `now() - 2 s` (rows from a transaction that commits later than
+that lag can be passed by an empty wake; this is the documented bound).
+Duplicate facts collapse to their newest row, and the facts cursor is computed
+from the raw rows, so a duplicate cluster split by a budget cut loses nothing.
+Stateless callers resume by passing `next_cursor.cursor` back as `cursor`
+(exact, both arms); `session_id` callers get this automatically. Explicit
+overrides replace whole tuples: `since` without `since_slug` reads strictly
+after `since` on both arms, never with the session's stored slug.
+
+**Legacy cursor.** `next_cursor.since` + `next_cursor.slug` (passed back as
+`since` + `since_slug`) keep working and are conservative: they do not move
+while any arm failed, and they stay strictly before the oldest undelivered fact
+(the slug resets to `''` whenever `since` was clamped), so an older client may
+re-see pages but never skips facts. A legacy caller that reaches more
+undelivered facts at one timestamp than the fetch limit gets
+`delta_cursor_upgrade_required` with the same call using `cursor` as its fix.
+
+**Failure is not `has_more`.** `has_more` means more content is waiting.
+`degraded_reason` lists what did not complete, comma-joined: `deadline`,
+`pages`, `facts`, `threads` (only when the thread builder throws; threads are
+best-effort and follow the pages' time cursor), `session_state` (the session
+row could not be written; `next_cursor` is the stateless continuation). Every
+degraded response carries a `delta_incomplete` notice (kind `degraded`) whose
+fix retries the same call after about 30 seconds (`fix.next: wait`); on the
+third consecutive incomplete wake of one session it becomes `report`. A
+`budget_tokens` too small for even one waiting item gets the same notice code
+with a fix naming the budget that fits. A session whose state cannot be read is
+refused with `unavailable` (`reason: session_state`), never re-initialized at
+now; a first wake (no row, including a garbage-collected one) gets an
+`empty_retrieval` info notice explaining how to replay earlier changes.
Response: `{ protocol_version, since, pages[], facts[], threads[], text,
-has_more, next_cursor: { since, slug }, degraded_reason?, budget_tokens?,
-budget_used?, dropped_count? }`. `budget_tokens` applies to pages and facts
+has_more, next_cursor: { since, slug, cursor }, cursor_arms, degraded_reason?,
+budget_tokens?, budget_used?, dropped_count? }`. Each fact carries its `id` (the
+replay dedupe key); `cursor_arms` reports each arm's start and next keyset.
+`since` and the timestamps inside `cursor` must fall in 0001-01-01 to
+9999-12-31 on the parsed UTC value (`invalid_params` otherwise). `budget_tokens` applies to pages and facts
(pages pack first, then facts) — each item costs its rendered line and the
envelope + section headers are reserved first, so `text` (rendered from the
packed sets) fits the declared budget. **Threads are never truncated**: every
@@ -616,9 +650,9 @@ open-thread event after `since` is delivered and its line is reserved ahead of
pages and facts, so `dropped_count` / `has_more` count only pages and facts.
If the envelope + headers + threads alone exceed `budget_tokens`, all threads
are still returned and `budget_used` (the token estimate of `text`) reports the
-real rendered size, which then exceeds the budget. Cursor semantics are the v1
-page keyset alone — facts and threads never move `next_cursor`. `since` is
-always normalized ISO (never the raw input string).
+real rendered size, which then exceeds the budget. `since` is always
+normalized ISO (never the raw input string). Replay recipe:
+[ambient recall guide](../guides/ambient-recall.md#replay-after-a-degraded-wake).
## Latency classes (per verb)
diff --git a/llms-full.txt b/llms-full.txt
index 287f49a71d..7300ce7492 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -3878,7 +3878,18 @@ final document.
is stateless, so dedupe is per authenticated client and session, and
`degraded` and `safety` notices ride every affected call. At most 2
`coaching` notices per session. Notices that describe one call's result
-(`empty_retrieval`, `unknown_param`, `listing_truncated`) are never deduped.
+(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`)
+are never deduped.
+
+**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`
+renders `next: wait`: repeat the same call (the fix carries it) after the delay
+the `why` states, in seconds. `delta_incomplete` uses it: delta moved no cursor
+past what it did not deliver, so the retry re-reads the same window. When the
+same session has been incomplete on three consecutive wakes, the fix has no
+command and renders `next: report`: tell the user and run
+`gbrain doctor --json`. Stateless callers always get `wait`. A session store
+that cannot be read at all refuses the call with `unavailable` (reason
+`session_state`) and the same wait/report fix.
**Mute.** `coaching` and `info` notices can be muted, plus one `ask`:
`first_run_decisions`, so an unanswered first-run bundle stays dismissible.
@@ -9323,7 +9334,7 @@ degraded_reason?, budget_tokens?, budget_used?, dropped_count? }`. `text` is the
pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
rendered from the packed sets and never exceeds the declared budget.
-### delta(since?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
+### delta(since?, since_slug?, cursor?, entities?, budget_tokens?, session_id?, include_private?) — read, zero LLM
"What changed since T" for heartbeats — pages updated after
the cursor (oldest first) + facts recorded after the cursor + open-thread
@@ -9340,16 +9351,50 @@ namespaced by their auth client id, auth-less remotes share the `'remote'`
sentinel, and `'local'` is RESERVED for the trusted CLI/hook lane, so a remote
harness can never read or advance the local lane's cursor.
-Delivery is at-least-once via a **keyset cursor `(updated_at, slug)`**: a cluster
-of pages sharing one `updated_at` (bulk syncs stamp identical timestamps) pages
-deterministically by slug, so a >fetch-limit cluster drains across wakes instead
-of livelocking. Stateless callers resume by passing the response's
-`next_cursor.since` + `next_cursor.slug` back as `since` + `since_slug`;
-`session_id` callers get this automatically.
+Delivery is at-least-once **per arm**. Pages page by the keyset
+`(updated_at, slug)`, facts by `(created_at, id)`, both at column (microsecond)
+precision, each arm with its own cursor: a cluster sharing one timestamp (bulk
+syncs stamp identical timestamps) pages deterministically, so a >fetch-limit
+cluster drains across wakes instead of livelocking. **No-advance rule:** each
+arm advances through the prefix it delivered and no further; an arm whose read
+threw or did not finish before a deadline does not advance; neither arm
+advances past `now() - 2 s` (rows from a transaction that commits later than
+that lag can be passed by an empty wake; this is the documented bound).
+Duplicate facts collapse to their newest row, and the facts cursor is computed
+from the raw rows, so a duplicate cluster split by a budget cut loses nothing.
+Stateless callers resume by passing `next_cursor.cursor` back as `cursor`
+(exact, both arms); `session_id` callers get this automatically. Explicit
+overrides replace whole tuples: `since` without `since_slug` reads strictly
+after `since` on both arms, never with the session's stored slug.
+
+**Legacy cursor.** `next_cursor.since` + `next_cursor.slug` (passed back as
+`since` + `since_slug`) keep working and are conservative: they do not move
+while any arm failed, and they stay strictly before the oldest undelivered fact
+(the slug resets to `''` whenever `since` was clamped), so an older client may
+re-see pages but never skips facts. A legacy caller that reaches more
+undelivered facts at one timestamp than the fetch limit gets
+`delta_cursor_upgrade_required` with the same call using `cursor` as its fix.
+
+**Failure is not `has_more`.** `has_more` means more content is waiting.
+`degraded_reason` lists what did not complete, comma-joined: `deadline`,
+`pages`, `facts`, `threads` (only when the thread builder throws; threads are
+best-effort and follow the pages' time cursor), `session_state` (the session
+row could not be written; `next_cursor` is the stateless continuation). Every
+degraded response carries a `delta_incomplete` notice (kind `degraded`) whose
+fix retries the same call after about 30 seconds (`fix.next: wait`); on the
+third consecutive incomplete wake of one session it becomes `report`. A
+`budget_tokens` too small for even one waiting item gets the same notice code
+with a fix naming the budget that fits. A session whose state cannot be read is
+refused with `unavailable` (`reason: session_state`), never re-initialized at
+now; a first wake (no row, including a garbage-collected one) gets an
+`empty_retrieval` info notice explaining how to replay earlier changes.
Response: `{ protocol_version, since, pages[], facts[], threads[], text,
-has_more, next_cursor: { since, slug }, degraded_reason?, budget_tokens?,
-budget_used?, dropped_count? }`. `budget_tokens` applies to pages and facts
+has_more, next_cursor: { since, slug, cursor }, cursor_arms, degraded_reason?,
+budget_tokens?, budget_used?, dropped_count? }`. Each fact carries its `id` (the
+replay dedupe key); `cursor_arms` reports each arm's start and next keyset.
+`since` and the timestamps inside `cursor` must fall in 0001-01-01 to
+9999-12-31 on the parsed UTC value (`invalid_params` otherwise). `budget_tokens` applies to pages and facts
(pages pack first, then facts) — each item costs its rendered line and the
envelope + section headers are reserved first, so `text` (rendered from the
packed sets) fits the declared budget. **Threads are never truncated**: every
@@ -9357,9 +9402,9 @@ open-thread event after `since` is delivered and its line is reserved ahead of
pages and facts, so `dropped_count` / `has_more` count only pages and facts.
If the envelope + headers + threads alone exceed `budget_tokens`, all threads
are still returned and `budget_used` (the token estimate of `text`) reports the
-real rendered size, which then exceeds the budget. Cursor semantics are the v1
-page keyset alone — facts and threads never move `next_cursor`. `since` is
-always normalized ISO (never the raw input string).
+real rendered size, which then exceeds the budget. `since` is always
+normalized ISO (never the raw input string). Replay recipe:
+[ambient recall guide](../guides/ambient-recall.md#replay-after-a-degraded-wake).
## Latency classes (per verb)