Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(recall): reimplement --since-last-run keyset paging (#6945)
time-attackb9426be4af26
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex e3a78a5bf0..c79d2f23e5 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`). `--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/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` (`fetchCursorPage`; `recallNarrowing` in `engine-sql/facts.ts` gives it the entity, session, grep and audit-row filters `listFactsSince` uses). `advanceCursor` records a full `--limit` window with `writePagedCursor` (the newest delivered row's `(created_at, id)`; `readRecallCursor` in `src/core/recall-cursor-state.ts` trusts it only when it matches `last_run_iso`; still `schema_version: 1`), so the next run resumes after it; a caught-up run writes the wall-clock start. Thin-client and `--supersessions` keep the newest-N window and warn on stderr when it is full (#6945, `test/recall-since-last-run-overflow.test.ts`, thin warning in `test/recall-budget-policy-thin-cli.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.tsindex a99d712101..58c0e4e9fb 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -38,7 +38,7 @@ 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 { readCursorPosition, writeCursor, positionFromTime, type CursorPosition } from '../core/recall-cursor-state.ts';+import { readRecallCursor, writeCursor, writePagedCursor, type RecallCursor } 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';@@ -506,23 +506,19 @@ async function runRecallOnce(sourceId: string,thinClient: boolean,cursorVariant: 'briefing' | 'watch',- cursorOverride?: CursorPosition | null,-): Promise<CursorPosition> {+ cursorOverride?: RecallCursor | null,+): Promise<RecallCursor> {// 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) {- 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;+ const cursor: RecallCursor | null = flags.sinceLastRun+ ? (cursorOverride !== undefined ? cursorOverride : readRecallCursor(sourceId, cursorVariant)) ?? wallClockCursor(defaultCursorStart())+ : null;+ const resolvedSince: Date | null = cursor ? cursor.since : flags.since;+ // #6945: only the local cursor read can page (oldest first, by keyset);+ // thin-client and --supersessions keep the newest-N window.+ const pageable = cursor !== null && !thinClient && !flags.supersessions;let rows: FactRow[];let pendingCount: number | undefined;@@ -574,10 +570,10 @@ async function runRecallOnce(}}} else {- rows = paged- ? await fetchRowsSinceCursor(engine, flags, sourceId, position!)+ rows = pageable+ ? await fetchCursorPage(engine, flags, sourceId, cursor!): await fetchRowsLocal(engine, flags, sourceId, resolvedSince);- if (rows.length === 0 && cursorVariant === 'briefing' && await keylessQuestionFallback(engine, flags, sourceId)) return positionFromTime(tStart);+ if (rows.length === 0 && cursorVariant === 'briefing' && await keylessQuestionFallback(engine, flags, sourceId)) return wallClockCursor(tStart);if (flags.pending) {pendingCount = await engine.countUnconsolidatedFacts(sourceId);}@@ -615,63 +611,74 @@ 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 cursor ? advanceCursor(sourceId, cursorVariant, rows, flags.limit, pageable, thinClient, tStart) : wallClockCursor(tStart);+}- return positionFromTime(tStart);+function wallClockCursor(since: Date): RecallCursor {+ return { since, resumeAfter: null };+}++function defaultCursorStart(): Date {+ return new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000);}/**- * `--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.+ * Move the --since-last-run cursor past what this run showed. A run that+ * filled its --limit window may have older unseen facts behind it: a pageable+ * run resumes strictly after the newest fact it delivered (moving to tStart+ * would skip the rest for good); any other full run warns. A run with room to+ * spare is caught up and records tStart.*/-async function fetchRowsSinceCursor(- engine: BrainEngine,- flags: ParsedFlags,+function advanceCursor(sourceId: string,- position: CursorPosition,-): Promise<FactRow[]> {- const opts = {+ variant: 'briefing' | 'watch',+ rows: FactRow[],+ limit: number,+ pageable: boolean,+ thinClient: boolean,+ tStart: Date,+): RecallCursor {+ const windowFull = rows.length >= clampSearchLimit(limit, 50);+ if (windowFull && pageable) {+ const newest = rows[0];+ const resumeAfter = { createdAt: newest.created_at_iso ?? newest.created_at.toISOString(), id: newest.id };+ writePagedCursor(sourceId, variant, resumeAfter);+ return { since: new Date(Date.parse(resumeAfter.createdAt)), resumeAfter };+ }+ 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, variant);+ return wallClockCursor(tStart);+}++/**+ * One --since-last-run page from the local engine: the oldest `limit` facts+ * after the cursor (inclusive of `since` when there is no keyset; id 0 sorts+ * before every fact), rendered newest-first. Entity with its text fallback,+ * session, --grep and audit rows narrow in SQL before LIMIT, as in+ * fetchRowsLocal's cursor arms.+ */+async function fetchCursorPage(engine: BrainEngine, flags: ParsedFlags, sourceId: string, cursor: RecallCursor): Promise<FactRow[]> {+ const after = cursor.resumeAfter ?? { createdAt: cursor.since.toISOString(), id: 0 };+ const page = (narrow: { entitySlug?: string; grep?: string }) => engine.listFactsKeyset(sourceId, after, {activeOnly: !flags.includeExpired,limit: flags.limit,- grep: flags.grep ?? undefined,excludeAuditRows: true,+ grep: flags.grep ?? undefined,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();+ ...narrow,+ });+ if (!flags.entity) return (await page({})).reverse();+ const entityRows = await page({ entitySlug: (await resolveEntitySlug(engine, sourceId, flags.entity)) ?? flags.entity });+ if (!entityTextFallbackApplies(flags, entityRows.length)) return entityRows.reverse();+ const textRows = await page({ grep: flags.entity.toLowerCase() });+ if (textRows.length === 0) return entityRows.reverse();+ noteEntityTextFallback(flags.entity, textRows.length);+ return textRows.reverse();}async function fetchRowsLocal(@@ -836,8 +843,7 @@ async function runWatchLoop(}try {- let priorTickStart: CursorPosition = readCursorPosition(sourceId, 'watch')- ?? positionFromTime(new Date(Date.now() - DEFAULT_FALLBACK_HOURS * 60 * 60 * 1000));+ let priorTickStart: RecallCursor = readRecallCursor(sourceId, 'watch') ?? wallClockCursor(defaultCursorStart());const effectiveFlags: ParsedFlags = { ...flags, sinceLastRun: true };diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.tsindex 6283fb3fe5..0956ab835c 100644--- a/src/core/engine-sql/facts.ts+++ b/src/core/engine-sql/facts.ts@@ -15,7 +15,7 @@*/import type {FactRow, FactKind, FactVisibility, FactInsertStatus, FactAttribution,- NewFact, FactListOpts, FactsHealth,+ NewFact, FactListOpts, RecallFactReadOpts, FactsHealth,} from '../engine.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';import { tryParseEmbedding } from '../utils.ts';@@ -64,6 +64,19 @@ function grepPattern(opts: FactListOpts | undefined): string | null {return (opts?.grep && opts.grep.trim()) ? '%' + escapeLikePattern(opts.grep.trim()) + '%' : null;}+/**+ * The pre-LIMIT narrowing both recall cursor reads apply (listFactsSince and,+ * for --since-last-run paging, listFactsKeyset): entity, session, audit rows+ * and --grep. Each part is opt-in, so a caller passing none (delta) gets none.+ */+function recallNarrowing(opts: RecallFactReadOpts | undefined) {+ const grep = grepPattern(opts);+ return sqlFragment`${opts?.entitySlug != null ? sqlFragment` AND entity_slug = ${opts.entitySlug}` : sqlFragment``}${+ opts?.sessionId ? sqlFragment` AND source_session = ${opts.sessionId}` : sqlFragment``}${+ opts?.excludeAuditRows ? sqlFragment` AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}${+ grep ? sqlFragment` AND fact ILIKE ${grep} ESCAPE '\\'` : sqlFragment``}`;+}+export async function insertFact(exec: SqlExecutor,resolveCast: ResolveEmbeddingCast | undefined,@@ -413,7 +426,7 @@ export async function listFactsSince(exec: LegacyUnscopedRead,source_id: string,since: Date,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): Promise<FactRow[]> {const limit = clampSearchLimit(opts?.limit, 50, MAX_SEARCH_LIMIT);const offset = Math.max(0, opts?.offset ?? 0);@@ -421,23 +434,15 @@ export async function listFactsSince(const unconsolidatedOnly = opts?.unconsolidatedOnly === true;const kinds = (opts?.kinds && opts.kinds.length > 0) ? opts.kinds : null;const visibility = (opts?.visibility && opts.visibility.length > 0) ? opts.visibility : null;- const entitySlug = opts?.entitySlug ?? null;- const sessionId = opts?.sessionId ?? null;const eventTime = opts?.eventTime === true;- const excludeAuditRows = opts?.excludeAuditRows === true;- const grepPat = grepPattern(opts);const rows = (await exec.run<FactRowSqlShape>(sqlFragment`SELECT *${opts?.fingerprint ? sqlFragment`, gbrain_fact_fingerprint(fact) AS fact_fingerprint` : sqlFragment``} FROM factsWHERE source_id = ${source_id}- AND ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} >= ${since}- ${entitySlug != null ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}- ${sessionId ? sqlFragment`AND source_session = ${sessionId}` : sqlFragment``}+ AND ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} >= ${since}${recallNarrowing(opts)}${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}- ${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)}+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${eligibilityClause(opts)}ORDER BY ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} DESC, id DESCLIMIT ${limit} OFFSET ${offset}`)).rows;@@ -459,18 +464,11 @@ export async function listFactsKeyset(exec: LegacyUnscopedRead,source_id: string,after: { createdAt: string; id: number | null } | null,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): 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@@ -481,13 +479,9 @@ export async function listFactsKeyset(to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS created_at_isoFROM factsWHERE source_id = ${source_id}- ${afterCondition}- ${entitySlug ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}- ${sessionId ? sqlFragment`AND source_session = ${sessionId}` : sqlFragment``}+ ${afterCondition}${recallNarrowing(opts)}${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)}- ${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}- ${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}${eligibilityClause(opts)}+ ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${eligibilityClause(opts)}ORDER BY created_at ASC, id ASCLIMIT ${limit}`)).rows;diff --git a/src/core/engine.ts b/src/core/engine.tsindex 9c9315877d..cf45e69609 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -681,6 +681,9 @@ export interface FactListOpts {excludePrivate?: boolean;}+/** FactListOpts plus the entity the recall cursor reads (listFactsSince, listFactsKeyset) narrow to before LIMIT. */+export type RecallFactReadOpts = FactListOpts & { entitySlug?: string };+/** Per-source operational health snapshot consumed by `gbrain doctor`. */export interface FactsHealth {source_id: string;@@ -2279,19 +2282,19 @@ export interface BrainEngine {listFactsSince(source_id: string,since: Date,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): Promise<FactRow[]>;/*** delta's facts arm: facts strictly after a `(created_at, id)` keyset* (`id: null` = strictly after the timestamp), OLDEST first, each row with* `created_at_iso` at column precision. Honors activeOnly, visibility,- * fingerprint, limit, and opt-in entitySlug / sessionId / grep / excludeAuditRows filters (recall paging).+ * fingerprint, limit, and the opt-in recall narrowing (entitySlug, sessionId, grep, excludeAuditRows) that --since-last-run paging uses.*/listFactsKeyset(source_id: string,after: { createdAt: string; id: number | null } | null,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): 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.tsindex 71798bc91f..066d197824 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -54,7 +54,7 @@ import type {TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,FactRow, FactInsertStatus,- NewFact, FactListOpts, FactsHealth,+ NewFact, FactListOpts, RecallFactReadOpts, FactsHealth,SourceRow,} from './engine.ts';import { DREAM_VERDICT_TTL_SECONDS, clampSearchLimit, type TransactionOptions } from './engine.ts';@@ -2461,7 +2461,7 @@ export class PGLiteEngine implements BrainEngine {async listFactsSince(source_id: string,since: Date,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): Promise<FactRow[]> {return factsImpl.listFactsSince(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, since, opts);}@@ -2469,7 +2469,7 @@ export class PGLiteEngine implements BrainEngine {async listFactsKeyset(source_id: string,after: { createdAt: string; id: number | null } | null,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): 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.tsindex bcb6ddf93c..af1b260aba 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -35,7 +35,7 @@ import type {TakeResolution, SynthesisEvidenceInput,TakesScorecard, TakesScorecardOpts, CalibrationBucket, CalibrationCurveOpts,FactRow, FactInsertStatus,- NewFact, FactListOpts, FactsHealth,+ NewFact, FactListOpts, RecallFactReadOpts, FactsHealth,SourceRow,} from './engine.ts';// Engine-path imports stay static unless a call site carries an explicit@@ -2262,7 +2262,7 @@ export class PostgresEngine implements BrainEngine {async listFactsSince(source_id: string,since: Date,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): Promise<FactRow[]> {return factsImpl.listFactsSince(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, since, opts);}@@ -2270,7 +2270,7 @@ export class PostgresEngine implements BrainEngine {async listFactsKeyset(source_id: string,after: { createdAt: string; id: number | null } | null,- opts?: FactListOpts & { entitySlug?: string; sessionId?: string },+ opts?: RecallFactReadOpts,): 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.tsindex 377daa5753..e44c52f989 100644--- a/src/core/recall-cursor-state.ts+++ b/src/core/recall-cursor-state.ts@@ -14,13 +14,12 @@* (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).+ * #6945: the record stays schema_version 1. After a full --limit window it+ * also carries after_created_at/after_id, the keyset of the newest fact shown,+ * and last_run_iso holds that fact's created_at. Files without the keyset+ * (all older ones) read as an inclusive wall-clock cursor; an older gbrain+ * reading a keyset file uses last_run_iso. Either way the worst case is a+ * repeat, never a skipped fact.*/import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, unlinkSync } from 'node:fs';@@ -33,30 +32,26 @@ 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).- */+ /** Written only after a full --limit window: the keyset of the newest delivered row (#6945). */after_created_at?: string;after_id?: number;}-/** Where `--since-last-run` resumes: rows strictly after `(createdAt, id)`. */-export interface CursorPosition {+/** The `(created_at, id)` of a delivered fact, created_at at column (microsecond) precision. */+export interface RecallResumePoint {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 };+/**+ * Where `--since-last-run` picks up: `since` (inclusive wall clock) and, when+ * the last run filled its window, `resumeAfter`, the row to page strictly past.+ */+export interface RecallCursor {+ since: Date;+ resumeAfter: RecallResumePoint | null;}-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 {@@ -107,30 +102,25 @@ export function readCursor(sourceId: string, variant: CursorVariant = 'briefing'}/**- * 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.+ * readCursor plus the stored keyset; null exactly when readCursor is null.+ * The keyset counts only when it is well formed and names the same+ * millisecond as the validated last_run_iso (writePagedCursor writes both+ * from one row). Anything else drops it, leaving the inclusive wall-clock+ * cursor, which can re-deliver rows but never skip them.*/-export function readCursorPosition(sourceId: string, variant: CursorVariant = 'briefing'): CursorPosition | null {- const t = readCursor(sourceId, variant);- if (!t) return null;+export function readRecallCursor(sourceId: string, variant: CursorVariant = 'briefing'): RecallCursor | null {+ const since = readCursor(sourceId, variant);+ if (!since) return null;let rec: Partial<CursorRecord>;try {rec = JSON.parse(readFileSync(cursorPath(sourceId, variant), 'utf8')) as Partial<CursorRecord>;} catch {- return positionFromTime(t);+ return { since, resumeAfter: null };}- 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);+ const { after_created_at: createdAt, after_id: id } = rec;+ const trusted = typeof createdAt === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/.test(createdAt)+ && Date.parse(createdAt) === since.getTime() && Number.isSafeInteger(id) && id! >= 0;+ return { since, resumeAfter: trusted ? { createdAt, id: id! } : null };}/**@@ -142,12 +132,25 @@ export function readCursorPosition(sourceId: string, variant: CursorVariant = 'b* 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',- after?: CursorPosition,-): void {+export function writeCursor(sourceId: string, t: Date, variant: CursorVariant = 'briefing'): void {+ writeRecord(sourceId, variant, { schema_version: 1, last_run_iso: t.toISOString() });+}++/**+ * Record a full --limit window: the next run pages strictly after+ * `resumeAfter`. last_run_iso is that row's created_at (to the millisecond),+ * so a reader that ignores the keyset only re-delivers from there.+ */+export function writePagedCursor(sourceId: string, variant: CursorVariant, resumeAfter: RecallResumePoint): void {+ writeRecord(sourceId, variant, {+ schema_version: 1,+ last_run_iso: new Date(Date.parse(resumeAfter.createdAt)).toISOString(),+ after_created_at: resumeAfter.createdAt,+ after_id: resumeAfter.id,+ });+}++function writeRecord(sourceId: string, variant: CursorVariant, rec: CursorRecord): void {const path = cursorPath(sourceId, variant);const dir = dirname(path);try {@@ -156,11 +159,6 @@ export function writeCursor(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(),- ...(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/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex d5770673fe..eb3549074b 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -154,8 +154,8 @@"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 & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",- "listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: RecallFactReadOpts) => Promise<FactRow[]>",+ "listFactsSince: (source_id: string, since: Date, opts?: RecallFactReadOpts) => Promise<FactRow[]>","listFilesForPage: (pageId: number) => Promise<FileRow[]>","listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>","listPages: (filters?: PageFilters) => Promise<Page[]>",@@ -1156,8 +1156,8 @@"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 & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",- "listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: RecallFactReadOpts) => Promise<FactRow[]>",+ "listFactsSince: (source_id: string, since: Date, opts?: RecallFactReadOpts) => Promise<FactRow[]>","listFilesForPage: (pageId: number) => Promise<FileRow[]>","listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>","listPages: (filters?: PageFilters) => Promise<Page[]>",@@ -3452,8 +3452,8 @@"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 & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",- "listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: RecallFactReadOpts) => Promise<FactRow[]>",+ "listFactsSince: (source_id: string, since: Date, opts?: RecallFactReadOpts) => Promise<FactRow[]>","listFilesForPage: (pageId: number) => Promise<FileRow[]>","listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>","listPages: (filters?: PageFilters) => Promise<Page[]>",@@ -3857,6 +3857,13 @@],"name": "PageWriteOptions"},+ {+ "kind": "type",+ "name": "RecallFactReadOpts",+ "signature": [+ "FactListOpts & { entitySlug?: string; }"+ ]+ },{"kind": "interface","members": [@@ -6723,8 +6730,8 @@"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 & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",- "listFactsSince: (source_id: string, since: Date, opts?: FactListOpts & { entitySlug?: string; sessionId?: string; }) => Promise<FactRow[]>",+ "listFactsKeyset: (source_id: string, after: { createdAt: string; id: number | null; } | null, opts?: RecallFactReadOpts) => Promise<FactRow[]>",+ "listFactsSince: (source_id: string, since: Date, opts?: RecallFactReadOpts) => Promise<FactRow[]>","listFilesForPage: (pageId: number) => Promise<FileRow[]>","listLinkSources: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<{ link_source: string | null; count: number; }[]>","listPages: (filters?: PageFilters) => Promise<Page[]>",diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.jsonindex bec89549c6..349b58373b 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": "cee718b762ca32b32a58496f29aca859d09564455972111d638dcf4cf4370505"+ "textSha256": "0a40122b0f45781fe163473acc69c889aeb6c63e2fd366f2f15731229025b466"}],"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": "18c359183438ec8502d1ba989ffc538cc25b5583b8b3b802bb7ee590b2f5b28b"+ "textSha256": "48e52d1c6898cb66b520371fe6e65624ccfca9643f2e6e4dcf8f30186bbbdd0f"}],"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": "c208edc8fe2014a70a2ca0b6b1d363fb175dc4a1ca1e42894d2c28df579f7162"+ "textSha256": "8918057b510da33d9b032fdefda14dfd7c9f5e67dd28b763ee8823cfa87b42f5"}]},@@ -586,14 +586,14 @@"string","string","array<string>",+ "string","array<string>","array<string>",- "string","number","number"],- "sql": "SELECT * FROM facts WHERE source_id = $1 AND COALESCE(valid_from, created_at) >= $2 AND entity_slug = $3 AND source_session = $4 AND consolidated_at IS NULL AND kind = ANY($5::text[]) AND visibility = ANY($6::text[]) AND source != ALL($7::text[]) AND fact ILIKE $8 ESCAPE '\\' ORDER BY COALESCE(valid_from, created_at) DESC, id DESC LIMIT $9 OFFSET $10",- "textSha256": "a635199e1e8bc1742eaa0209a8bc5b296098640ab38aa287635fe9195fa696ae"+ "sql": "SELECT * FROM facts WHERE source_id = $1 AND COALESCE(valid_from, created_at) >= $2 AND entity_slug = $3 AND source_session = $4 AND source != ALL($5::text[]) AND fact ILIKE $6 ESCAPE '\\' AND consolidated_at IS NULL AND kind = ANY($7::text[]) AND visibility = ANY($8::text[]) ORDER BY COALESCE(valid_from, created_at) DESC, id DESC LIMIT $9 OFFSET $10",+ "textSha256": "1b9e94f79ae9ab62cb04bc9501d94a5b3c7e02b6b208f25f3ec7c840e9d2e978"}],"default": [@@ -606,7 +606,7 @@"number"],"sql": "SELECT * FROM facts WHERE source_id = $1 AND created_at >= $2 AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) ORDER BY created_at DESC, id DESC LIMIT $3 OFFSET $4",- "textSha256": "3f0a5fa0e5e1a4338c4d9a10f70015aef0d1d34504c0161ce43eae3a104f6beb"+ "textSha256": "b91c27c57a63ae4eeed4b01a43c5b9c43bc16d06e7960e87a68898d91577d0ac"}]},