Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(recall): page --since-last-run past a full --limit window (#6945)

time-attackbd74407644ed
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index 727176f92b..e3a78a5bf0 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/trust.ts` — `gbrain trust review|confirm|release|drop|revert|explain|allow|disable` (#5575 DX-7; `backfill` is dispatched by `src/cli/commands/trust.ts`). `runOwnerAction` previews, asks for the typed token when the action raises trust, then applies bound to the preview; `review --accept-all` needs a filter and takes one confirmation (DX-15). The backend is the local engine, or `maybeDelegateTrust` (called from `src/cli.ts` before connecting) routes through a resident PGLite owner's administration socket with the prompt in the invoking CLI (DX-2). `confirmTierCrossingAccepts` puts tier-crossing `decide proposals accept` through the same rule; `quarantine release|drop` are aliases (`src/cli/commands/quarantine.ts`). Refusals render through `writeCliError` (exit 3 for consent refusals).
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`. #6259: `clear` reads one snapshot (page, tags, revision) and, on a managed brain, publishes through `submitPageMutation` with that `expected_revision` (a concurrent edit is a `revision_conflict`, a pending receipt is reported as pending); `--force` writes a `quarantine_override` (see `src/core/quarantine-override.ts`) instead of disabling the gate, never mutation `force`. `scan --apply` refuses `writer_coordinator_required` on a managed brain. `scan` does not re-check a segmented page (it would hold the whole body as one string): it lists it in `skipped` (`page_body_segmented`) and goes on. It is a router (`QUARANTINE_SUBCOMMANDS`, `printUsage`). Tests: `test/quarantine-override.serial.test.ts`, `test/quarantine-cli.test.ts`.
-- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Its help (`RECALL_HELP`, printed before the engine via `SELF_HELP_WITHOUT_ENGINE`) names `--question` for natural-language questions. Cat 41 run 4: `keylessQuestionFallback` — on a brain whose fact recall is keyword-only (`factRecallIsKeywordOnly`, `src/core/facts/keyword-only.ts`: embedding opted out or no provider), a multi-word positional that matched no entity and no fact text (#4720's fallback) is ranked as a question through `runRecallVerb`, with a stderr note; brains with embeddings keep their output and get a `--question` hint (`test/recall-keyless-question-fallback.test.ts`). `--question <q>` (or `--question=<q>`) is the question, never an entity: it routes through the recall op like `--budget-policy` (thin clients call the remote recall, an answer without `facts_order` prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each `relevance` and `facts_degraded` (`test/recall-question-cli.test.ts`). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). `--since` parses with `parseSinceParam` (`src/core/facts/since-parse.ts`, the parser the recall op uses); an unreadable or missing `--since` value and a `--session`/`--session-id` with no ID throw `invalid_params` from `parseFlags` (the bad value echoed, the accepted grammar in `why`) instead of dropping the bound (#6944, `test/recall-bounds-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.
+- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Its help (`RECALL_HELP`, printed before the engine via `SELF_HELP_WITHOUT_ENGINE`) names `--question` for natural-language questions. Cat 41 run 4: `keylessQuestionFallback` — on a brain whose fact recall is keyword-only (`factRecallIsKeywordOnly`, `src/core/facts/keyword-only.ts`: embedding opted out or no provider), a multi-word positional that matched no entity and no fact text (#4720's fallback) is ranked as a question through `runRecallVerb`, with a stderr note; brains with embeddings keep their output and get a `--question` hint (`test/recall-keyless-question-fallback.test.ts`). `--question <q>` (or `--question=<q>`) is the question, never an entity: it routes through the recall op like `--budget-policy` (thin clients call the remote recall, an answer without `facts_order` prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each `relevance` and `facts_degraded` (`test/recall-question-cli.test.ts`). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). `--since` parses with `parseSinceParam` (`src/core/facts/since-parse.ts`, the parser the recall op uses); an unreadable or missing `--since` value and a `--session`/`--session-id` with no ID throw `invalid_params` from `parseFlags` (the bad value echoed, the accepted grammar in `why`) instead of dropping the bound (#6944, `test/recall-bounds-envelope.test.ts`). `--since-last-run` on a local brain pages oldest-first through `listFactsKeyset` (`fetchRowsSinceCursor`, the same entity/text-fallback, session, grep and audit-row filters before LIMIT): a full `--limit` window writes the newest delivered row's `(created_at, id)` into the cursor (`src/core/recall-cursor-state.ts`, `readCursorPosition`; still `schema_version: 1`, the keyset fields optional and trusted only when they agree with `last_run_iso`), so the next run resumes after it instead of skipping the overflow; a caught-up run writes the wall-clock start as before. Thin-client and `--supersessions` keep the newest-N window and print a stderr warning when it is full (#6945, `test/recall-since-last-run-overflow.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.
- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:` (written via `engine.setPageAliases`) and, for linkable entity pages, rewrites the derived title-subject and declared rows (`writeDerivedAliases`, coordinated on managed brains). Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. A segmented linkable page derives from its body read back as strings (`materializedPage`); one over the single-string ceiling gets frontmatter and subject aliases only, as its streamed import did, and is listed in `body_not_scanned`; a per-page `page_body_segmented` refusal is listed in `skipped`. Pinned by `test/search/reindex-aliases.test.ts`.
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index e6d0239fb6..a99d712101 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -33,11 +33,12 @@
*/
import type { BrainEngine, FactRow, FactKind } from '../core/engine.ts';
+import { clampSearchLimit } from '../core/engine.ts';
import { effectiveConfidence } from '../core/facts/decay.ts';
import { resolveEntitySlug } from '../core/entities/resolve.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-client.ts';
-import { readCursor, writeCursor } from '../core/recall-cursor-state.ts';
+import { readCursorPosition, writeCursor, positionFromTime, type CursorPosition } from '../core/recall-cursor-state.ts';
import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';
import { usageError } from '../cli/cli-error.ts';
import { parseSinceParam, SINCE_GRAMMAR } from '../core/facts/since-parse.ts';
@@ -290,6 +291,10 @@ positional is an entity name, then a literal piece of fact text.
gbrain recall --since "8 hours ago" facts from a time window (--today: today, rendered by kind)
gbrain recall --session <id> facts from one session
+--since-last-run shows facts created since the previous run. When more than
+--limit facts arrived, it shows the oldest --limit of them and the next run
+continues after the last one shown (local brains; a thin client warns instead).
+
--since takes an ISO 8601 date or datetime, a duration ("8 hours ago", "30m",
"2d") or a relative phrase ("6 weeks ago", "last month"). An unreadable
--since or a --session with no ID is refused (invalid_params, exit 2).
@@ -501,23 +506,23 @@ async function runRecallOnce(
sourceId: string,
thinClient: boolean,
cursorVariant: 'briefing' | 'watch',
- cursorOverride?: Date | null,
-): Promise<Date> {
+ cursorOverride?: CursorPosition | null,
+): Promise<CursorPosition> {
// Codex round 1 #2: T_start is captured BEFORE the first read SQL fires.
// Facts inserted during render/write get included by the next run.
const tStart = new Date();
let resolvedSince: Date | null = flags.since;
+ let position: CursorPosition | null = null;
if (flags.sinceLastRun) {
- if (cursorOverride !== undefined) {
- resolvedSince = cursorOverride;
- } else {
- resolvedSince = readCursor(sourceId, cursorVariant);
- }
- if (!resolvedSince) {
- resolvedSince = new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000);
- }
+ position = (cursorOverride !== undefined ? cursorOverride : readCursorPosition(sourceId, cursorVariant))
+ ?? positionFromTime(new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000));
+ resolvedSince = new Date(position.createdAt);
}
+ // The local cursor arm pages oldest-first through a (created_at, id)
+ // keyset; thin-client and --supersessions have no keyset read and keep the
+ // newest-N window.
+ const paged = flags.sinceLastRun && !thinClient && !flags.supersessions;
let rows: FactRow[];
let pendingCount: number | undefined;
@@ -569,8 +574,10 @@ async function runRecallOnce(
}
}
} else {
- rows = await fetchRowsLocal(engine, flags, sourceId, resolvedSince);
- if (rows.length === 0 && cursorVariant === 'briefing' && await keylessQuestionFallback(engine, flags, sourceId)) return tStart;
+ rows = paged
+ ? await fetchRowsSinceCursor(engine, flags, sourceId, position!)
+ : await fetchRowsLocal(engine, flags, sourceId, resolvedSince);
+ if (rows.length === 0 && cursorVariant === 'briefing' && await keylessQuestionFallback(engine, flags, sourceId)) return positionFromTime(tStart);
if (flags.pending) {
pendingCount = await engine.countUnconsolidatedFacts(sourceId);
}
@@ -609,10 +616,62 @@ async function runRecallOnce(
}
if (flags.sinceLastRun) {
+ // A full window may have left older unseen rows behind. Paged: resume
+ // strictly after the newest DELIVERED row instead of jumping to tStart,
+ // which would skip them for good. Caught up: tStart, as before.
+ const windowFull = rows.length >= clampSearchLimit(flags.limit, 50);
+ if (paged && windowFull) {
+ const newest = rows[0];
+ const next = { createdAt: newest.created_at_iso ?? newest.created_at.toISOString(), id: newest.id };
+ writeCursor(sourceId, newest.created_at, cursorVariant, next);
+ return next;
+ }
+ if (windowFull) {
+ process.stderr.write(
+ `[recall] ${rows.length} facts filled the --limit window; older facts since the last run may not be shown` +
+ `${thinClient ? ' (thin-client recall cannot page the cursor)' : ''}. Re-run with a larger --limit.\n`,
+ );
+ }
writeCursor(sourceId, tStart, cursorVariant);
}
- return tStart;
+ return positionFromTime(tStart);
+}
+
+/**
+ * `--since-last-run` on the local engine: the OLDEST `limit` rows strictly
+ * after the cursor position, returned newest-first for rendering. Same
+ * filters as fetchRowsLocal's cursor arms (entity + text fallback, session,
+ * grep, audit rows), applied in SQL before LIMIT.
+ */
+async function fetchRowsSinceCursor(
+ engine: BrainEngine,
+ flags: ParsedFlags,
+ sourceId: string,
+ position: CursorPosition,
+): Promise<FactRow[]> {
+ const opts = {
+ activeOnly: !flags.includeExpired,
+ limit: flags.limit,
+ grep: flags.grep ?? undefined,
+ excludeAuditRows: true,
+ sessionId: flags.sessionId || undefined,
+ };
+ let rows: FactRow[];
+ if (flags.entity) {
+ const slug = (await resolveEntitySlug(engine, sourceId, flags.entity)) ?? flags.entity;
+ rows = await engine.listFactsKeyset(sourceId, position, { ...opts, entitySlug: slug });
+ if (entityTextFallbackApplies(flags, rows.length)) {
+ const textRows = await engine.listFactsKeyset(sourceId, position, { ...opts, grep: flags.entity.toLowerCase() });
+ if (textRows.length > 0) {
+ noteEntityTextFallback(flags.entity, textRows.length);
+ rows = textRows;
+ }
+ }
+ } else {
+ rows = await engine.listFactsKeyset(sourceId, position, opts);
+ }
+ return rows.reverse();
}
async function fetchRowsLocal(
@@ -777,10 +836,8 @@ async function runWatchLoop(
}
try {
- let priorTickStart: Date | null = readCursor(sourceId, 'watch');
- if (!priorTickStart) {
- priorTickStart = new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000);
- }
+ let priorTickStart: CursorPosition = readCursorPosition(sourceId, 'watch')
+ ?? positionFromTime(new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000));
const effectiveFlags: ParsedFlags = { ...flags, sinceLastRun: true };
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 4d8600f852..fc6784835a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -904,8 +904,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
- // Wave 20 lane 1 (#6944).
+ // Wave 20 lane 1 (#6944 #6945).
{ since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },
+ { since: '0.60.307.0', text: '`gbrain recall --since-last-run` (and `--watch`) on a local brain no longer skips facts when more than `--limit` of them arrived since the last run. A run that fills the window now shows the OLDEST `--limit` new facts (newest first within the page) and the next run continues right after the last one shown, until it catches up; before, it showed the newest `--limit` and the rest were never shown. The cursor file keeps `schema_version: 1` and gains two optional fields, so cursor files from earlier versions keep working. A thin client cannot page yet: when its window is full it prints a warning to raise `--limit`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 42490ef95e..bcb50f9b03 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--since-last-run', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -74,7 +74,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index a198df689b..6283fb3fe5 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -459,11 +459,18 @@ export async function listFactsKeyset(
exec: LegacyUnscopedRead,
source_id: string,
after: { createdAt: string; id: number | null } | null,
- opts?: FactListOpts,
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): 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;
+ // `recall --since-last-run` pages its cursor through this keyset, so it
+ // needs the same pre-LIMIT filters as its listFactsSince arms. All opt-in:
+ // delta passes none of them and its query is unchanged.
+ const entitySlug = opts?.entitySlug ?? null;
+ const sessionId = opts?.sessionId ?? null;
+ const excludeAuditRows = opts?.excludeAuditRows === true;
+ const grepPat = grepPattern(opts);
const afterCondition = after === null
? sqlFragment``
: after.id === null
@@ -475,8 +482,12 @@ export async function listFactsKeyset(
FROM facts
WHERE source_id = ${source_id}
${afterCondition}
+ ${entitySlug ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}
+ ${sessionId ? sqlFragment`AND source_session = ${sessionId}` : sqlFragment``}
${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``}${privacyClause(opts)}${eligibilityClause(opts)}
+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
+ ${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}
+ ${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}${eligibilityClause(opts)}
ORDER BY created_at ASC, id ASC
LIMIT ${limit}
`)).rows;
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 663a046058..9c9315877d 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2286,12 +2286,12 @@ export interface BrainEngine {
* 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.
+ * fingerprint, limit, and opt-in entitySlug / sessionId / grep / excludeAuditRows filters (recall paging).
*/
listFactsKeyset(
source_id: string,
after: { createdAt: string; id: number | null } | null,
- opts?: FactListOpts,
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]>;
/** List facts captured under a session id within a source. */
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index f32d573b9a..71798bc91f 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2469,7 +2469,7 @@ export class PGLiteEngine implements BrainEngine {
async listFactsKeyset(
source_id: string,
after: { createdAt: string; id: number | null } | null,
- opts?: FactListOpts,
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
return factsImpl.listFactsKeyset(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, after, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 89819c9371..bcb6ddf93c 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2270,7 +2270,7 @@ export class PostgresEngine implements BrainEngine {
async listFactsKeyset(
source_id: string,
after: { createdAt: string; id: number | null } | null,
- opts?: FactListOpts,
+ opts?: FactListOpts & { entitySlug?: string; sessionId?: string },
): Promise<FactRow[]> {
return factsImpl.listFactsKeyset(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, after, opts);
}
diff --git a/src/core/recall-cursor-state.ts b/src/core/recall-cursor-state.ts
index 45a7677b67..377daa5753 100644
--- a/src/core/recall-cursor-state.ts
+++ b/src/core/recall-cursor-state.ts
@@ -13,6 +13,14 @@
* into place. Failure is non-fatal (stderr warn + return). Read failures
* (missing / corrupt JSON / future-shifted timestamp) return null; caller
* falls back to the documented 24h default.
+ *
+ * File format: schema_version stays 1. A run that delivered a full --limit
+ * window adds optional after_created_at/after_id (the keyset of the newest
+ * delivered row) and sets last_run_iso to that row's created_at. A file
+ * without them (every file an older gbrain wrote) reads as the inclusive
+ * wall-clock position, and an older gbrain reading a paged file uses
+ * last_run_iso, so either direction can only re-deliver rows, never skip
+ * them (#6945).
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from 'node:fs';
@@ -25,8 +33,30 @@ export type CursorVariant = 'briefing' | 'watch';
interface CursorRecord {
schema_version: 1;
last_run_iso: string;
+ /**
+ * Set only when a run delivered a FULL --limit window: the `(created_at, id)`
+ * of the newest row it delivered, at column precision. The next run pages
+ * strictly after it, so rows beyond one window are delivered later instead
+ * of being skipped. Optional, so older readers keep using last_run_iso
+ * (which then trails the keyset and only re-delivers, never skips).
+ */
+ after_created_at?: string;
+ after_id?: number;
+}
+
+/** Where `--since-last-run` resumes: rows strictly after `(createdAt, id)`. */
+export interface CursorPosition {
+ createdAt: string;
+ id: number;
+}
+
+/** A wall-clock cursor is inclusive (`created_at >= t`): id 0 sorts before every row. */
+export function positionFromTime(t: Date): CursorPosition {
+ return { createdAt: t.toISOString(), id: 0 };
}
+const COLUMN_ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
+
const CURSOR_DIR_SEGMENT = 'recall-cursors';
function cursorPath(sourceId: string, variant: CursorVariant): string {
@@ -76,6 +106,33 @@ export function readCursor(sourceId: string, variant: CursorVariant = 'briefing'
return new Date(ms);
}
+/**
+ * The resume position for a (source, variant): the paged keyset when the
+ * last run delivered a full window, else the wall-clock cursor as an
+ * inclusive position. Null exactly when readCursor is null.
+ *
+ * The keyset is trusted only when it names the same millisecond as the
+ * validated last_run_iso (writeCursor stores both from one row). A future,
+ * malformed or inconsistent keyset falls back to the inclusive wall-clock
+ * cursor, which can only re-deliver rows, never skip them.
+ */
+export function readCursorPosition(sourceId: string, variant: CursorVariant = 'briefing'): CursorPosition | null {
+ const t = readCursor(sourceId, variant);
+ if (!t) return null;
+ let rec: Partial<CursorRecord>;
+ try {
+ rec = JSON.parse(readFileSync(cursorPath(sourceId, variant), 'utf8')) as Partial<CursorRecord>;
+ } catch {
+ return positionFromTime(t);
+ }
+ if (typeof rec.after_created_at === 'string' && COLUMN_ISO_RE.test(rec.after_created_at)
+ && rec.after_created_at.slice(0, 23) === t.toISOString().slice(0, 23)
+ && Number.isSafeInteger(rec.after_id) && (rec.after_id as number) >= 0) {
+ return { createdAt: rec.after_created_at, id: rec.after_id as number };
+ }
+ return positionFromTime(t);
+}
+
/**
* Write the cursor for a (source, variant). Atomic via mkdirSync(recursive)
* + write-to-tmp + rename(2). Tmp filename includes pid + random suffix so
@@ -85,7 +142,12 @@ export function readCursor(sourceId: string, variant: CursorVariant = 'briefing'
* Failure is non-fatal: stderr warn and return. The cursor advance is a
* best-effort durability hint, not a correctness invariant.
*/
-export function writeCursor(sourceId: string, t: Date, variant: CursorVariant = 'briefing'): void {
+export function writeCursor(
+ sourceId: string,
+ t: Date,
+ variant: CursorVariant = 'briefing',
+ after?: CursorPosition,
+): void {
const path = cursorPath(sourceId, variant);
const dir = dirname(path);
try {
@@ -94,7 +156,11 @@ export function writeCursor(sourceId: string, t: Date, variant: CursorVariant =
process.stderr.write(`[recall] cursor mkdir failed at ${dir}: ${(e as Error).message}\n`);
return;
}
- const rec: CursorRecord = { schema_version: 1, last_run_iso: t.toISOString() };
+ const rec: CursorRecord = {
+ schema_version: 1,
+ last_run_iso: t.toISOString(),
+ ...(after ? { after_created_at: after.createdAt, after_id: after.id } : {}),
+ };
const suffix = `${process.pid}.${randomBytes(6).toString('hex')}`;
const tmp = `${path}.tmp.${suffix}`;
try {
diff --git a/test/e2e/recall-since-last-run-overflow-postgres.test.ts b/test/e2e/recall-since-last-run-overflow-postgres.test.ts
new file mode 100644
index 0000000000..027beff0e5
--- /dev/null
+++ b/test/e2e/recall-since-last-run-overflow-postgres.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../recall-since-last-run-overflow.test.ts'));
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index b48f112e49..c7ff1eaa18 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -154,7 +154,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[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => 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; }[]>",
@@ -1155,7 +1155,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[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => 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; }[]>",
@@ -3443,7 +3443,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[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => 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; }[]>",
@@ -6704,7 +6704,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[]>",
+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => 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/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.json
index 59fa2900c4..bec89549c6 100644
--- a/test/fixtures/goldens/sql-text/facts.json
+++ b/test/fixtures/goldens/sql-text/facts.json
@@ -545,7 +545,7 @@
"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"
+ "textSha256": "cee718b762ca32b32a58496f29aca859d09564455972111d638dcf4cf4370505"
}
],
"keyset": [
@@ -559,7 +559,7 @@
"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"
+ "textSha256": "18c359183438ec8502d1ba989ffc538cc25b5583b8b3b802bb7ee590b2f5b28b"
}
],
"strictTime": [
@@ -572,7 +572,7 @@
"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"
+ "textSha256": "c208edc8fe2014a70a2ca0b6b1d363fb175dc4a1ca1e42894d2c28df579f7162"
}
]
},
diff --git a/test/recall-since-last-run-overflow.test.ts b/test/recall-since-last-run-overflow.test.ts
new file mode 100644
index 0000000000..b6630fa411
--- /dev/null
+++ b/test/recall-since-last-run-overflow.test.ts
@@ -0,0 +1,233 @@
+/**
+ * `gbrain recall --since-last-run` must not skip facts when more than one
+ * --limit window of new facts arrives between runs.
+ *
+ * Before this fix the cursor arm reads the NEWEST `limit` rows created
+ * since the cursor, then writes the cursor as the run's wall-clock start. The
+ * older rows past the window are behind the new cursor and never surface.
+ *
+ * Every case drives the real `runRecall` entrypoint against a real engine
+ * (PGLite here, Postgres through the e2e twin); created_at is pinned with SQL
+ * so ordering and ties are exact.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { readCursor, writeCursor, _cursorPathForTests } from '../src/core/recall-cursor-state.ts';
+import { runRecall } from '../src/commands/recall.ts';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+
+for (const backend of testBackends()) describe(`recall --since-last-run paging (${backend})`, () => {
+ let engine: BrainEngine;
+
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const { setupDB, getEngine } = await import('./e2e/helpers.ts');
+ await setupDB();
+ engine = getEngine();
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }
+ }, 120_000);
+ afterAll(async () => {
+ if (backend === 'postgres') {
+ const { teardownDB } = await import('./e2e/helpers.ts');
+ await teardownDB();
+ } else await engine?.disconnect();
+ });
+ beforeEach(async () => {
+ if (backend === 'postgres') await engine.executeRaw('DELETE FROM facts');
+ else await resetPgliteState(engine as PGLiteEngine);
+ });
+
+ const origWrite = process.stdout.write.bind(process.stdout);
+ afterEach(() => { process.stdout.write = origWrite; });
+
+ function tmpHome(): string {
+ const dir = join(tmpdir(), `gbrain-recall-overflow-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
+ mkdirSync(dir, { recursive: true });
+ return dir;
+ }
+
+ /** One `gbrain recall` call; returns the delivered fact texts. */
+ async function recall(args: string[]): Promise<string[]> {
+ let out = '';
+ process.stdout.write = ((chunk: string | Uint8Array) => { out += chunk.toString(); return true; }) as typeof process.stdout.write;
+ try {
+ await runRecall(engine, args);
+ } finally {
+ process.stdout.write = origWrite;
+ }
+ return (JSON.parse(out).facts as Array<{ fact: string }>).map(f => f.fact);
+ }
+
+ /** Insert facts with an exact created_at each (ISO, microsecond precision allowed). */
+ async function seed(
+ rows: Array<{ fact: string; createdAt: string; validFrom?: Date; source?: string; entity?: string }>,
+ ): Promise<void> {
+ for (const r of rows) {
+ const { id } = await engine.insertFact(
+ { fact: r.fact, kind: 'fact', entity_slug: r.entity ?? 'e/overflow', source: 'unit', ...(r.validFrom ? { valid_from: r.validFrom } : {}) },
+ { source_id: r.source ?? 'default' },
+ );
+ await engine.executeRaw('UPDATE facts SET created_at = $1::timestamptz WHERE id = $2', [r.createdAt, id]);
+ }
+ }
+
+ const base = Date.now() - 60 * 60 * 1000; // an hour ago
+ const at = (sec: number) => new Date(base + sec * 1000).toISOString();
+
+ async function drain(args: string[], maxRuns: number): Promise<string[][]> {
+ const runs: string[][] = [];
+ for (let i = 0; i < maxRuns; i++) runs.push(await recall(args));
+ return runs;
+ }
+
+ describe('--since-last-run never skips facts past one --limit window', () => {
+ test('7 facts, --limit 3: successive runs deliver every fact exactly once', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ await seed(Array.from({ length: 7 }, (_, i) => ({ fact: `f${i}`, createdAt: at(i + 1) })));
+
+ const runs = await drain(['--since-last-run', '--json', '--limit', '3'], 4);
+ const delivered = runs.flat();
+ expect(delivered.sort()).toEqual(['f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6']);
+ expect(runs.every(r => r.length <= 3)).toBe(true); // output stays bounded
+ expect(runs[3]).toEqual([]); // caught up
+ });
+ });
+
+ test('timestamp ties across the window boundary are neither skipped nor repeated', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ // Five rows share one microsecond-precision created_at.
+ const tie = new Date(base + 5000).toISOString().replace('Z', '').padEnd(23, '0') + '123Z';
+ await seed(Array.from({ length: 5 }, (_, i) => ({ fact: `tie${i}`, createdAt: tie })));
+
+ const delivered = (await drain(['--since-last-run', '--json', '--limit', '2'], 4)).flat();
+ expect(delivered.sort()).toEqual(['tie0', 'tie1', 'tie2', 'tie3', 'tie4']);
+ });
+ });
+
+ test('a backdated (old valid_from) fact in the overflow still surfaces', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
+ await seed([
+ { fact: 'backdated', createdAt: at(1), validFrom: twoDaysAgo },
+ ...Array.from({ length: 4 }, (_, i) => ({ fact: `new${i}`, createdAt: at(i + 2) })),
+ ]);
+ const delivered = (await drain(['--since-last-run', '--json', '--limit', '2'], 3)).flat();
+ expect(delivered).toContain('backdated');
+ expect(delivered.length).toBe(5);
+ });
+ });
+
+ test('facts arriving between runs while a backlog drains are not starved or skipped', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ await seed(Array.from({ length: 4 }, (_, i) => ({ fact: `old${i}`, createdAt: at(i + 1) })));
+ const first = await recall(['--since-last-run', '--json', '--limit', '2']);
+ await seed([{ fact: 'arrived', createdAt: new Date().toISOString() }]);
+ const rest = (await drain(['--since-last-run', '--json', '--limit', '2'], 3)).flat();
+ expect([...first, ...rest].sort()).toEqual(['arrived', 'old0', 'old1', 'old2', 'old3']);
+ });
+ });
+
+ test('a failed render does not advance the cursor', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ await seed(Array.from({ length: 3 }, (_, i) => ({ fact: `r${i}`, createdAt: at(i + 1) })));
+ const before = readFileSync(_cursorPathForTests('default', 'briefing'), 'utf8');
+ process.stdout.write = (() => { throw new Error('EPIPE'); }) as typeof process.stdout.write;
+ await expect(runRecall(engine, ['--since-last-run', '--json', '--limit', '2'])).rejects.toThrow('EPIPE');
+ process.stdout.write = origWrite;
+ expect(readFileSync(_cursorPathForTests('default', 'briefing'), 'utf8')).toBe(before);
+ const delivered = (await drain(['--since-last-run', '--json', '--limit', '2'], 3)).flat();
+ expect(delivered.sort()).toEqual(['r0', 'r1', 'r2']);
+ });
+ });
+
+ test('source isolation and briefing/watch custody hold while paging', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING`);
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ await seed([
+ ...Array.from({ length: 3 }, (_, i) => ({ fact: `d${i}`, createdAt: at(i + 1) })),
+ { fact: 'other-source', createdAt: at(2), source: 'other' },
+ ]);
+ const delivered = (await drain(['--since-last-run', '--json', '--limit', '2', '--source', 'default'], 3)).flat();
+ expect(delivered.sort()).toEqual(['d0', 'd1', 'd2']);
+ expect(existsSync(_cursorPathForTests('default', 'watch'))).toBe(false);
+ expect(existsSync(_cursorPathForTests('other', 'briefing'))).toBe(false);
+ });
+ });
+
+ test('entity and --grep filters apply before the window while paging', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ // Other-entity rows interleave and outnumber the target entity's rows.
+ await seed(Array.from({ length: 9 }, (_, i) => ({
+ fact: i % 3 === 0 ? `target needle ${i}` : `noise ${i}`,
+ createdAt: at(i + 1),
+ entity: i % 3 === 0 ? 'e/target' : 'e/noise',
+ })));
+ const byEntity = (await drain(['e/target', '--since-last-run', '--json', '--limit', '2'], 3)).flat();
+ expect(byEntity.sort()).toEqual(['target needle 0', 'target needle 3', 'target needle 6']);
+
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ const byGrep = (await drain(['--grep', 'needle', '--since-last-run', '--json', '--limit', '2'], 3)).flat();
+ expect(byGrep.sort()).toEqual(['target needle 0', 'target needle 3', 'target needle 6']);
+ });
+ });
+
+ test('a future or inconsistent keyset cannot skip the backlog (falls back to the legacy cursor)', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ await seed([{ fact: 'unseen', createdAt: at(1) }]);
+ const path = _cursorPathForTests('default', 'briefing');
+ const legacy = new Date(base - 1000).toISOString();
+ writeCursor('default', new Date(legacy), 'briefing'); // creates the cursor dir
+ const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().replace('Z', '000Z');
+ writeFileSync(path, JSON.stringify({ schema_version: 1, last_run_iso: legacy, after_created_at: tomorrow, after_id: 1 }) + '\n');
+ const delivered = (await drain(['--since-last-run', '--json', '--limit', '2'], 2)).flat();
+ expect(delivered).toEqual(['unseen']);
+ });
+ });
+
+ test('caught-up run keeps the legacy wall-clock cursor and newest-first order', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing');
+ await seed(Array.from({ length: 3 }, (_, i) => ({ fact: `c${i}`, createdAt: at(i + 1) })));
+ const t0 = Date.now();
+ const delivered = await recall(['--since-last-run', '--json', '--limit', '5']);
+ expect(delivered).toEqual(['c2', 'c1', 'c0']);
+ const rec = JSON.parse(readFileSync(_cursorPathForTests('default', 'briefing'), 'utf8'));
+ expect(Object.keys(rec).sort()).toEqual(['last_run_iso', 'schema_version']);
+ expect(readCursor('default', 'briefing')!.getTime()).toBeGreaterThanOrEqual(t0 - 5);
+ });
+ });
+ test('a cursor file written before the keyset existed keeps working, and a paged file stays readable by it', async () => {
+ await withEnv({ GBRAIN_HOME: tmpHome() }, async () => {
+ writeCursor('default', new Date(base - 1000), 'briefing'); // creates the cursor dir
+ const path = _cursorPathForTests('default', 'briefing');
+ // The exact bytes an older gbrain wrote: schema_version 1, wall clock only.
+ writeFileSync(path, JSON.stringify({ schema_version: 1, last_run_iso: new Date(base - 1000).toISOString() }) + '\n');
+ await seed(Array.from({ length: 3 }, (_, i) => ({ fact: `v1-${i}`, createdAt: at(i + 1) })));
+ expect(await recall(['--since-last-run', '--json', '--limit', '2'])).toEqual(['v1-1', 'v1-0']);
+ // The paged record is still schema_version 1; its last_run_iso is the newest
+ // delivered row, so an older reader only re-delivers from there, never skips.
+ const rec = JSON.parse(readFileSync(path, 'utf8'));
+ expect(rec.schema_version).toBe(1);
+ expect(readCursor('default', 'briefing')!.toISOString()).toBe(at(2));
+ expect(await recall(['--since-last-run', '--json', '--limit', '2'])).toEqual(['v1-2']);
+ });
+ });
+ });
+});