Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(google): managed sweeps enqueue loops_extract; grace-held threads are re-evaluated (#5867, #5868)

garrytanb7b12842ecec
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index db97eb054a..7374bfe23a 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -30,7 +30,7 @@ export interface SyncResult {
/** Pages re-embedded during this sync's auto-embed step. 0 if --no-embed or skipped. */
embedded: number;
embedDeferralReason?: 'large_sync';
- pagesAffected: string[];
+ pagesAffected: string[]; /** #5867: a Google sweep's loops_extract enqueue (sweep plus managed catch-up). */ loops_enqueue?: { enqueued: number; deferred: number; skipped_reason: string | null };
failedFiles?: number; // count of parse failures (Bug 9)
/**
* #3875: code breakdown of the blocking failures (set on
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 747fe5fbd1..b195f12a7d 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -66,6 +66,8 @@ import {
type GoogleSourceState,
} from './types.ts';
import { LOOPS_EXTRACT_WINDOW_DAYS, loopExtractionEligibility } from './loops-extract.ts';
+import type { ThreadLoopVerdict } from './loop-detect.ts';
+import { pendingLoopsExtractDepth, recordGraceVerdict, runLoopsCatchup, seedGraceBackfill, settleDueGraceHolds, type LoopsEnqueueReport } from './loop-catchup.ts';
export type { GoogleSourceConfig } from './types.ts';
export { runGoogleAttachmentBackfill } from './attachment-backfill.ts';
@@ -217,6 +219,10 @@ interface GoogleSyncDeps {
/** Threads whose newest message falls in the recent window — LLM
* extraction candidates, enqueued (capped) after the sweep. */
extractCandidates: Array<{ slug: string; threadId: string; newestMs: number }>;
+ /** #5868: the run's state (grace holds are recorded on it) and the threads detection ran on. */
+ loopState?: GoogleSourceState;
+ processedThreads: Set<string>;
+ graceBackfillSeeded?: boolean;
}
type ActivePack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string> }> } | undefined;
@@ -226,6 +232,12 @@ async function saveGoogleState(deps: GoogleSyncDeps, state: GoogleSourceState):
else writeGoogleState(deps.cfg.dir, state);
}
+/** #5867/#5868 state a partial managed run still publishes (E20): never the Gmail cursor. */
+function loopRecoveryState(state: GoogleSourceState): Record<string, unknown> {
+ const fields = { loop_grace_holds: state.loop_grace_holds, loop_grace_backfill_done: state.loop_grace_backfill_done, loops_catchup: state.loops_catchup };
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
+}
+
function assertContained(dir: string, path: string): void {
if (!isWriteTargetContained(path, dir)) {
throw new Error(`Path escapes managed dir: "${path}"`);
@@ -534,7 +546,9 @@ async function processThread(
const state = message.attachmentInspection?.state ?? 'not_inspected';
summary.attachmentInspection[state] = (summary.attachmentInspection[state] ?? 0) + 1;
}
- await applyLoopDetection(deps, thread, slug);
+ deps.processedThreads.add(thread.threadId);
+ const verdict = await applyLoopDetection(deps, thread, slug);
+ if (verdict && deps.loopState) recordGraceVerdict(deps.loopState, thread, verdict, slug, myAddressSet(deps.entry), deps.log);
// LLM extraction candidates: trickle + the bounded recent window only —
// the deep historical backfill is never extracted (spend honesty, F9).
const newestMs = thread.messages[thread.messages.length - 1]?.internalDateMs ?? 0;
@@ -553,12 +567,23 @@ async function processThread(
return thread;
}
-/** Enqueue loops_extract jobs for every eligible candidate in this sweep. */
-async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<void> {
- if (deps.extractCandidates.length === 0) return;
+/**
+ * Enqueue loops_extract jobs for every eligible candidate in this sweep, in
+ * both persistence modes (#5867: `--no-extract` gates only the inline
+ * link/timeline extract). Every skip logs its reason.
+ */
+async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<LoopsEnqueueReport> {
+ const report: LoopsEnqueueReport = { enqueued: 0, deferred: 0, skipped_reason: null };
+ if (deps.extractCandidates.length === 0) {
+ deps.log('[google] loops_extract: no eligible thread in this sweep; nothing to enqueue');
+ return { ...report, skipped_reason: 'no_candidates' };
+ }
try {
const { isLoopsExtractionEnabled, LOOPS_EXTRACT_JOB, LOOPS_EXTRACT_ENQUEUE_CEILING } = await import('./loops-extract.ts');
- if (!(await isLoopsExtractionEnabled(deps.engine))) return;
+ if (!(await isLoopsExtractionEnabled(deps.engine))) {
+ deps.log(`[google] loops_extract: extraction disabled (loops.extraction_enabled) — skipped enqueue of ${deps.extractCandidates.length} eligible thread(s)`);
+ return { ...report, skipped_reason: 'extraction_disabled' };
+ }
// No chat provider (keyless install, outage) → enqueue NOTHING. A job the
// handler cannot run would fail-and-die and burn its revision-keyed
// idempotency slot for nothing; the eligible threads stay unconsumed and
@@ -571,7 +596,7 @@ async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<void> {
`skipped enqueue of ${deps.extractCandidates.length} eligible thread(s); they are queued on ` +
`their next touch (or \`gbrain sync --source ${deps.sourceId} --full\`) once a provider is configured`,
);
- return;
+ return { ...report, skipped_reason: 'chat_unavailable' };
}
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(deps.engine);
@@ -599,22 +624,14 @@ async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<void> {
// The depth is PER SOURCE (payload `sourceId`, the key this enqueue
// writes): a brain-wide count let one Google account's stalled backlog
// pin every other source's budget at 0 forever.
- const ordered = [...deps.extractCandidates].sort((a, b) => b.newestMs - a.newestMs);
+ // One candidate per page revision: a thread re-landed in one sweep is queued once.
+ const ordered = [...new Map(deps.extractCandidates.map((c) => [`${c.slug}:${c.newestMs}`, c])).values()].sort((a, b) => b.newestMs - a.newestMs);
// Depth = every PENDING row, not just 'waiting': during a provider outage
// each claimed job fails and parks as 'delayed' (retry backoff), and rows
// in flight are 'active'. Counting 'waiting' alone read ~0 mid-outage and
// let every sweep stack another ceiling's worth of jobs on the backlog.
- let waitingDepth = 0;
- try {
- const rows = await deps.engine.executeRaw<{ n: string }>(
- `SELECT count(*)::text AS n FROM minion_jobs
- WHERE name = $1 AND status IN ('waiting', 'delayed', 'active') AND data->>'sourceId' = $2`,
- [LOOPS_EXTRACT_JOB, deps.sourceId],
- );
- waitingDepth = parseInt(rows[0]?.n ?? '0', 10) || 0;
- } catch {
- // Fail-open: a missing table / transient error must never block enqueue.
- }
+ // Fail-open: a missing table / transient error must never block enqueue.
+ const waitingDepth = await pendingLoopsExtractDepth(deps.engine, deps.sourceId);
const budget = Math.max(0, LOOPS_EXTRACT_ENQUEUE_CEILING - waitingDepth);
const picked = ordered.slice(0, budget);
const dropped = ordered.length - picked.length;
@@ -629,7 +646,7 @@ async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<void> {
for (const c of picked) {
await queue.add(
LOOPS_EXTRACT_JOB,
- { slug: c.slug, sourceId: deps.sourceId, threadId: c.threadId },
+ { slug: c.slug, sourceId: deps.sourceId, threadId: c.threadId, newestMs: c.newestMs },
{
priority: 5,
// Page-revision keyed: a re-sweep of an unchanged thread is a no-op,
@@ -640,8 +657,10 @@ async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<void> {
);
}
deps.log(`[google] loops_extract: enqueued ${picked.length} eligible thread(s)`);
+ return { enqueued: picked.length, deferred: dropped, skipped_reason: null };
} catch (e) {
deps.log(`[google] loops_extract enqueue failed: ${e instanceof Error ? e.message : String(e)}`);
+ return { ...report, skipped_reason: 'enqueue_failed' };
}
}
@@ -650,13 +669,14 @@ async function applyLoopDetection(
deps: GoogleSyncDeps,
thread: GmailThreadData,
pageSlug: string,
-): Promise<void> {
+): Promise<ThreadLoopVerdict | null> {
try {
const { applyThreadLoopVerdict } = await import('./loop-detect.ts');
- await applyThreadLoopVerdict(deps.engine, deps.sourceId, thread, myAddressSet(deps.entry), pageSlug);
+ return await applyThreadLoopVerdict(deps.engine, deps.sourceId, thread, myAddressSet(deps.entry), pageSlug);
} catch (e) {
// Detection must never fail a sync; it re-runs on the next touch.
deps.log(`[google] loop detection failed for ${thread.threadId}: ${e instanceof Error ? e.message : String(e)}`);
+ return null;
}
}
@@ -868,6 +888,7 @@ async function sweepGmail(g: GmailSweep, onCurrent?: () => Promise<void>): Promi
if (deps.opts.signal?.aborted) return false;
await attemptThread(g, tid, null);
}
+ if (await settleGraceHolds(g) === 'aborted') return false;
const isCurrent = (): boolean => {
if (delta !== 'done' || state.gmail_gap_floor_ms != null) return false;
if (state.gmail_backfill_done) return true;
@@ -892,6 +913,34 @@ async function sweepGmail(g: GmailSweep, onCurrent?: () => Promise<void>): Promi
return isCurrent();
}
+/**
+ * #5868: seeds the one-shot grace backfill, then settles due grace holds.
+ * A re-fetch goes straight through processThread (never the item holds), so
+ * a failed grace re-fetch keeps the grace hold and is not an item failure.
+ */
+async function settleGraceHolds(g: GmailSweep): Promise<'aborted' | void> {
+ const { deps, state } = g;
+ try {
+ await seedGraceBackfill(deps.engine, deps.sourceId, state, deps.log);
+ deps.graceBackfillSeeded = true;
+ } catch (e) {
+ deps.log(`[google] loop grace backfill failed (retried next sweep): ${e instanceof Error ? e.message : String(e)}`);
+ }
+ const settled = await settleDueGraceHolds({ engine: deps.engine, sourceId: deps.sourceId, state, log: deps.log, signal: deps.opts.signal,
+ processed: deps.processedThreads, refetch: async (tid) => {
+ try {
+ await processThread(deps, g.gmail, tid, g.activePack, g.summary, g.countedSlugs);
+ return 'ok';
+ } catch (e) {
+ if (e instanceof GoogleCursorExpiredError && e.status === 404) return 'gone';
+ if (deps.managed) rethrowConnectorWriteError(e);
+ deps.log(`[google] grace re-check of thread ${tid} failed (kept for the next sweep): ${e instanceof Error ? e.message : String(e)}`);
+ return 'failed';
+ }
+ } });
+ if (settled === 'aborted') return 'aborted';
+}
+
/** Opens (or widens) the gap window `[after, floor)` that the floor walk drains newest→oldest. */
function openGmailGap(state: GoogleSourceState, cutoffMs: number): void {
const after = (state.gmail_newest_ms ?? cutoffMs) - 86_400_000;
@@ -1155,7 +1204,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
const gmail = new GmailClient(...clientArgs);
const calendar = new CalendarClient(...clientArgs);
const people = new PeopleClient(...clientArgs);
- const deps: GoogleSyncDeps = { engine, sourceId, cfg, opts, entry, log, extractCandidates: [], managed };
+ const deps: GoogleSyncDeps = { engine, sourceId, cfg, opts, entry, log, extractCandidates: [], managed, processedThreads: new Set() };
const summary: GoogleSyncSummary = {
status: 'synced',
@@ -1207,6 +1256,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
}
const state = managed ? managed.state(emptyState()) : readGoogleState(cfg.dir);
+ deps.loopState = state;
const firstRun = !state.gmail_backfill_done && state.gmail_history_id === null;
// Fix wave 4: the Gmail poison ledger is read once and carried into the item holds.
const holds = await ConnectorHoldSession.open(engine, sourceId, managed, emptyState() as unknown as Record<string, unknown>,
@@ -1280,21 +1330,42 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
if (opts.signal?.aborted) summary.status = 'partial';
if (opts.full && summary.status === 'synced') state.last_full_at = new Date().toISOString();
+ // #5867 managed-only 30-day catch-up and the #5868 one-shot backfill marker; never on an aborted sweep.
+ let catchup: LoopsEnqueueReport | null = null;
+ if (activeServices.includes('gmail') && !opts.signal?.aborted) {
+ if (deps.graceBackfillSeeded) state.loop_grace_backfill_done = true;
+ if (managed) {
+ try {
+ catchup = await runLoopsCatchup({ engine, sourceId, state, log, signal: opts.signal, myAddresses: myAddressSet(entry),
+ inFlight: new Set(deps.extractCandidates.map(c => c.slug)),
+ fetchThread: async (tid) => {
+ try { return await gmail.getThread(tid, cfg.account, opts.signal ? { signal: opts.signal } : {}); }
+ catch (e) { if (e instanceof GoogleCursorExpiredError && e.status === 404) return null; throw e; }
+ } });
+ } catch (e) {
+ log(`[google] loops catch-up failed (retried next sweep): ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+ }
+
// Per-service cursors were advanced in-place only on success; persist.
// Throws connector_holds_exhausted before any save, so the cursor stays.
state.item_holds = holds.finish();
if (managed) {
if (summary.status !== 'partial' && gmailSweepOk) await managed.saveState(state, true, new Date(state.gmail_newest_ms ?? Date.now()).toISOString());
- // A partial run keeps the cursor its mid-run checkpoints committed and publishes only changed holds.
- else if (!opts.signal?.aborted) await managed.publishHolds(emptyState() as unknown as Record<string, unknown>, state.item_holds);
+ // A partial run keeps the cursor its mid-run checkpoints committed and publishes changed holds plus the loop recovery state (#5867/#5868).
+ else if (!opts.signal?.aborted) await managed.publishHolds(emptyState() as unknown as Record<string, unknown>, state.item_holds, loopRecoveryState(state));
} else writeGoogleState(cfg.dir, state);
await holds.complete();
// An aborted run (wall-clock budget, serve-delegation timeout) skips the
// extract/embed/extraction tails — the deferred backfill machinery picks
// them up on the next full run instead of overshooting the budget.
+ let loopsEnqueue: LoopsEnqueueReport | undefined;
if (!opts.signal?.aborted) {
await runExtractAndEmbed(deps, summary);
- if (!managed || !opts.noExtract) await enqueueLoopsExtraction(deps);
+ const enqueued = await enqueueLoopsExtraction(deps);
+ loopsEnqueue = catchup ? { enqueued: enqueued.enqueued + catchup.enqueued, deferred: enqueued.deferred + catchup.deferred,
+ skipped_reason: enqueued.skipped_reason } : enqueued;
// Auditable per-reason counts (loopExtractionEligibility) — no
// addresses, subjects or body text ever reach the log.
if (Object.keys(summary.extractEligibility).length > 0) {
@@ -1349,6 +1420,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
embedded: summary.embedded,
pagesAffected: summary.pagesAffected,
...(summary.failedFiles > 0 ? { failedFiles: summary.failedFiles } : {}),
+ ...(loopsEnqueue ? { loops_enqueue: loopsEnqueue } : {}),
...connectorHoldsResult(sourceId, holds.summary()),
};
} finally {
diff --git a/src/core/google/loop-catchup.ts b/src/core/google/loop-catchup.ts
new file mode 100644
index 0000000000..c740a8b8c4
--- /dev/null
+++ b/src/core/google/loop-catchup.ts
@@ -0,0 +1,301 @@
+/**
+ * loop-catchup — recovery passes for the open-loop engine that the Gmail
+ * sweep runs besides its normal per-thread detection.
+ *
+ * Grace holds (#5868). `detectThreadLoop` withholds a loop while its grace
+ * window (inbound 24h, outbound 72h) runs, and Gmail history never re-lists a
+ * quiet thread, so a held thread used to stay unevaluated forever. The sweep
+ * now records each grace hold in connector state (`loop_grace_holds`, capped
+ * at GRACE_HOLDS_CAP, oldest pruned and logged) with the loop spec the
+ * detection produced. Once due, an unchanged thread (the page still carries
+ * the newest message id the spec was computed from) opens its loop from the
+ * stored spec with no Gmail call; a changed or missing page, or a backfill
+ * seed with no spec, is re-fetched (at most GRACE_REFETCH_PER_SWEEP per
+ * sweep). Grace holds are not connector item holds: they never count as
+ * failures, `connector_held_items` or `waiting` coverage. A one-shot backfill
+ * seeds holds for email pages active in the last GRACE_BACKFILL_DAYS that
+ * have no open deterministic loop, from stored pages only.
+ *
+ * Catch-up (#5867). Managed connector syncs never enqueued `loops_extract`
+ * before this wave, so a managed source's recent threads were never analyzed.
+ * A one-shot, managed-only pass re-candidates the source's email pages whose
+ * newest message falls in the last LOOPS_EXTRACT_WINDOW_DAYS. Evidence that a
+ * thread is done is a revision-bound outcome, not a completed job: the
+ * `loops_extract` handler records `extracted` or `skipped:<reason>` per page
+ * revision (`recordLoopsExtractOutcome`). A candidate is settled when its
+ * current revision was `extracted`, when the catch-up itself produced an
+ * outcome for it, or when it is not eligible. Dead-lettered catch-up jobs get
+ * one retry, then are logged and settled. The done marker is written only
+ * when every candidate is settled; the enqueue ceiling defers the rest to the
+ * next sweep.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { sanitizeForJsonb } from '../batch-rows.ts';
+import { connectorStateKey } from '../persistence/connector-state.ts';
+import { LOOPS_EXTRACT_ENQUEUE_CEILING, LOOPS_EXTRACT_JOB, LOOPS_EXTRACT_WINDOW_DAYS, isLoopsExtractionEnabled, loopExtractionEligibility } from './loops-extract.ts';
+import { openDueGraceHold, type ThreadLoopVerdict } from './loop-detect.ts';
+import type { GmailThreadData, GoogleSourceState, LoopGraceHold } from './types.ts';
+
+export const GRACE_HOLDS_CAP = 2_000;
+export const GRACE_BACKFILL_DAYS = 14;
+export const GRACE_REFETCH_PER_SWEEP = 100;
+export const LOOPS_OUTCOMES_OP = 'loops-extract-outcomes';
+const DAY_MS = 86_400_000;
+
+type Log = (msg: string) => void;
+
+// ── Grace holds (#5868) ──────────────────────────────────────────────────────
+
+/** Records or clears one thread's grace hold from its fresh detection verdict. */
+export function recordGraceVerdict(state: GoogleSourceState, thread: GmailThreadData, verdict: ThreadLoopVerdict,
+ slug: string | null, myAddresses: Set<string>, log: Log): void {
+ const holds = state.loop_grace_holds ??= {};
+ if (verdict.held && loopExtractionEligibility(thread, myAddresses).eligible) {
+ // Message prose reaches the connector checkpoint's jsonb: sanitize it as the page render does.
+ const spec = verdict.held.spec;
+ holds[thread.threadId] = { due_ms: verdict.held.untilMs, slug, rev: thread.messages[thread.messages.length - 1]?.id ?? null,
+ spec: { ...spec, summary: sanitizeForJsonb(spec.summary), counterpartyEmail: sanitizeForJsonb(spec.counterpartyEmail),
+ evidence: spec.evidence.map(e => ({ ...e, ...(e.quote !== undefined ? { quote: sanitizeForJsonb(e.quote) } : {}) })) } };
+ pruneGraceHolds(holds, log);
+ } else {
+ delete holds[thread.threadId];
+ }
+}
+
+function pruneGraceHolds(holds: Record<string, LoopGraceHold>, log: Log): void {
+ const ids = Object.keys(holds);
+ if (ids.length <= GRACE_HOLDS_CAP) return;
+ const excess = ids.sort((a, b) => holds[a].due_ms - holds[b].due_ms).slice(0, ids.length - GRACE_HOLDS_CAP);
+ for (const id of excess) delete holds[id];
+ log(`[google] loop grace holds over the ${GRACE_HOLDS_CAP} cap: pruned ${excess.length} oldest hold(s); those threads are re-evaluated when they change`);
+}
+
+/**
+ * One-shot backfill: seeds a due hold (no spec, so it is re-fetched) for every
+ * email page with activity in the last 14 days and no open deterministic
+ * loop. Reads stored pages only. The caller sets `loop_grace_backfill_done`
+ * after a non-aborted sweep.
+ */
+export async function seedGraceBackfill(engine: BrainEngine, sourceId: string, state: GoogleSourceState, log: Log, now = Date.now()): Promise<number> {
+ if (state.loop_grace_backfill_done) return 0;
+ const rows = await engine.executeRaw<{ slug: string; thread_id: string }>(
+ `SELECT p.slug, p.frontmatter->>'thread_id' AS thread_id FROM pages p
+ WHERE p.source_id=$1 AND p.type='email' AND p.deleted_at IS NULL
+ AND p.frontmatter->>'thread_id' IS NOT NULL AND p.frontmatter->>'date' >= $2
+ AND NOT EXISTS (SELECT 1 FROM open_loops l WHERE l.source_id=p.source_id AND l.thread_id=p.frontmatter->>'thread_id'
+ AND l.status='open' AND l.loop_type IN ('unanswered_inbound','unanswered_outbound'))`,
+ [sourceId, new Date(now - GRACE_BACKFILL_DAYS * DAY_MS).toISOString()]);
+ const holds = state.loop_grace_holds ??= {};
+ let seeded = 0;
+ for (const row of rows) {
+ if (holds[row.thread_id]) continue;
+ holds[row.thread_id] = { due_ms: now, slug: row.slug, rev: null, spec: null };
+ seeded++;
+ }
+ pruneGraceHolds(holds, log);
+ log(`[google] loop grace backfill: ${seeded} thread(s) from the last ${GRACE_BACKFILL_DAYS} days held for re-evaluation`);
+ return seeded;
+}
+
+export type GraceRefetch = (threadId: string) => Promise<'ok' | 'gone' | 'failed'>;
+
+/**
+ * Settles due grace holds. Threads the sweep already processed this run were
+ * re-detected there. An unchanged thread opens from its stored spec; others
+ * are re-fetched through `refetch` (which re-records or clears the hold). A
+ * failed re-fetch keeps the hold due for the next sweep.
+ */
+export async function settleDueGraceHolds(ctx: {
+ engine: BrainEngine; sourceId: string; state: GoogleSourceState; log: Log; signal?: AbortSignal;
+ processed: Set<string>; refetch: GraceRefetch; now?: number;
+}): Promise<{ opened: number; refetched: number; deferred: number } | 'aborted'> {
+ const holds = ctx.state.loop_grace_holds ?? {};
+ const now = ctx.now ?? Date.now();
+ const due = Object.entries(holds).filter(([tid, h]) => h.due_ms <= now && !ctx.processed.has(tid)).sort((a, b) => a[1].due_ms - b[1].due_ms);
+ const result = { opened: 0, refetched: 0, deferred: 0 };
+ for (const [tid, hold] of due) {
+ if (ctx.signal?.aborted) return 'aborted';
+ if (hold.spec && hold.slug && await pageRevision(ctx.engine, ctx.sourceId, hold.slug) === hold.rev) {
+ if (await openDueGraceHold(ctx.engine, ctx.sourceId, tid, hold.spec, hold.slug)) result.opened++;
+ delete holds[tid];
+ continue;
+ }
+ if (result.refetched >= GRACE_REFETCH_PER_SWEEP) { result.deferred++; continue; }
+ result.refetched++;
+ const outcome = await ctx.refetch(tid);
+ if (outcome === 'gone') delete holds[tid];
+ else if (outcome === 'ok' && holds[tid] === hold) delete holds[tid];
+ }
+ if (due.length > 0) {
+ ctx.log(`[google] loop grace holds: ${due.length} due — ${result.opened} opened from stored data, ${result.refetched} re-fetched`
+ + (result.deferred > 0 ? `, ${result.deferred} deferred to the next sweep` : ''));
+ }
+ return result;
+}
+
+async function pageRevision(engine: BrainEngine, sourceId: string, slug: string): Promise<string | null | undefined> {
+ const page = await engine.getPage(slug, { sourceId });
+ if (!page) return undefined;
+ const id = (page.frontmatter as Record<string, unknown> | undefined)?.message_id;
+ return typeof id === 'string' ? id : null;
+}
+
+// ── Revision-bound loops_extract outcomes (#5867, E9) ────────────────────────
+
+export interface LoopsExtractOutcome {
+ rev: number;
+ outcome: string;
+ catchup: boolean;
+ at: string;
+}
+
+async function outcomesKey(engine: BrainEngine, sourceId: string): Promise<string | null> {
+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ return row ? connectorStateKey(sourceId, row.incarnation) : null;
+}
+
+/**
+ * Records one page revision's extraction outcome in one statement (no race
+ * with the sync lease holder), pruning entries older than the extraction
+ * window so the row stays bounded.
+ */
+export async function recordLoopsExtractOutcome(engine: BrainEngine, sourceId: string, slug: string,
+ entry: { rev: number; outcome: string; catchup: boolean }): Promise<void> {
+ const key = await outcomesKey(engine, sourceId);
+ if (!key) return;
+ const value = JSON.stringify({ ...entry, at: new Date().toISOString() });
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ VALUES($1,$2,jsonb_build_array(jsonb_build_object('version',1,'outcomes',jsonb_build_object($3::text,$4::text::jsonb))))
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array(jsonb_build_object('version',1,'outcomes',
+ COALESCE((SELECT jsonb_object_agg(e.key,e.value) FROM jsonb_each(op_checkpoints.completed_keys->0->'outcomes') e
+ WHERE e.key<>$3::text AND (e.value->>'at')::timestamptz > now() - ($5::text || ' days')::interval),'{}'::jsonb)
+ || jsonb_build_object($3::text,$4::text::jsonb))), updated_at=now()`,
+ [LOOPS_OUTCOMES_OP, key, slug, value, String(LOOPS_EXTRACT_WINDOW_DAYS + 1)]);
+}
+
+export async function readLoopsExtractOutcomes(engine: BrainEngine, sourceId: string): Promise<Record<string, LoopsExtractOutcome>> {
+ const key = await outcomesKey(engine, sourceId);
+ if (!key) return {};
+ const [row] = await engine.executeRaw<{ outcomes: Record<string, LoopsExtractOutcome> | null }>(
+ `SELECT completed_keys->0->'outcomes' AS outcomes FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`, [LOOPS_OUTCOMES_OP, key]);
+ return row?.outcomes ?? {};
+}
+
+/** The page revision a loops_extract job analyzed: its payload, else the page's newest message date. */
+export async function loopsExtractRevision(engine: BrainEngine, sourceId: string, slug: string, payloadRev: unknown): Promise<number | null> {
+ if (typeof payloadRev === 'number' && Number.isFinite(payloadRev)) return payloadRev;
+ const page = await engine.getPage(slug, { sourceId });
+ const date = (page?.frontmatter as Record<string, unknown> | undefined)?.date;
+ const ms = typeof date === 'string' ? Date.parse(date) : NaN;
+ return Number.isFinite(ms) ? ms : null;
+}
+
+// ── Managed 30-day catch-up (#5867) ──────────────────────────────────────────
+
+export interface LoopsEnqueueReport {
+ enqueued: number;
+ deferred: number;
+ skipped_reason: string | null;
+}
+
+/** The pending loops_extract depth for one source (waiting, delayed, active). */
+export async function pendingLoopsExtractDepth(engine: BrainEngine, sourceId: string): Promise<number> {
+ try {
+ const rows = await engine.executeRaw<{ n: string }>(
+ `SELECT count(*)::text AS n FROM minion_jobs
+ WHERE name = $1 AND status IN ('waiting', 'delayed', 'active') AND data->>'sourceId' = $2`, [LOOPS_EXTRACT_JOB, sourceId]);
+ return parseInt(rows[0]?.n ?? '0', 10) || 0;
+ } catch {
+ return 0;
+ }
+}
+
+/**
+ * One catch-up pass for a managed source. Returns null when the catch-up is
+ * already done. Never throws for an individual candidate: a failed Gmail read
+ * leaves the candidate for the next sweep.
+ */
+export async function runLoopsCatchup(ctx: {
+ engine: BrainEngine; sourceId: string; state: GoogleSourceState; log: Log; signal?: AbortSignal;
+ myAddresses: Set<string>; fetchThread: (threadId: string) => Promise<GmailThreadData | null>; now?: number;
+ /** Pages this sweep already queues through the normal enqueue. */
+ inFlight: Set<string>;
+}): Promise<LoopsEnqueueReport | null> {
+ if (ctx.state.loops_catchup?.done) return null;
+ const now = ctx.now ?? Date.now();
+ const skip = (reason: string, message: string): LoopsEnqueueReport => {
+ ctx.log(`[google] loops catch-up skipped (${reason}): ${message}; nothing queued, it runs on a later sweep`);
+ return { enqueued: 0, deferred: 0, skipped_reason: reason };
+ };
+ if (!(await isLoopsExtractionEnabled(ctx.engine))) return skip('extraction_disabled', 'loops.extraction_enabled is off');
+ const { isAvailable } = await import('../ai/gateway.ts');
+ if (!isAvailable('chat')) return skip('chat_unavailable', 'no configured chat model / API key');
+
+ const cu = ctx.state.loops_catchup ??= { version: 1, floor_ms: now - LOOPS_EXTRACT_WINDOW_DAYS * DAY_MS, retried: [], done: false };
+ const pages = await ctx.engine.executeRaw<{ slug: string; thread_id: string; date: string }>(
+ `SELECT slug, frontmatter->>'thread_id' AS thread_id, frontmatter->>'date' AS date FROM pages
+ WHERE source_id=$1 AND type='email' AND deleted_at IS NULL AND frontmatter->>'thread_id' IS NOT NULL AND frontmatter->>'date' >= $2
+ ORDER BY frontmatter->>'date' DESC`, [ctx.sourceId, new Date(cu.floor_ms).toISOString()]);
+ const outcomes = await readLoopsExtractOutcomes(ctx.engine, ctx.sourceId);
+ const keyOf = (slug: string, rev: number) => `loops-catchup:${ctx.sourceId}:${slug}:${rev}`;
+ const candidates = pages.map(p => ({ ...p, rev: Date.parse(p.date) })).filter(p => Number.isFinite(p.rev));
+ const jobRows = candidates.length === 0 ? [] : await ctx.engine.executeRaw<{ idempotency_key: string; status: string }>(
+ 'SELECT idempotency_key, status FROM minion_jobs WHERE idempotency_key = ANY($1::text[])',
+ [candidates.flatMap(c => [keyOf(c.slug, c.rev), `${keyOf(c.slug, c.rev)}:retry`, `loops:${ctx.sourceId}:${c.slug}:${c.rev}`])]);
+ const jobs = new Map(jobRows.map(r => [r.idempotency_key, r.status]));
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(ctx.engine);
+ let budget = Math.max(0, LOOPS_EXTRACT_ENQUEUE_CEILING - await pendingLoopsExtractDepth(ctx.engine, ctx.sourceId));
+ const report: LoopsEnqueueReport = { enqueued: 0, deferred: 0, skipped_reason: null };
+ let unsettled = 0;
+ const settle = (slug: string, rev: number, outcome: string) => recordLoopsExtractOutcome(ctx.engine, ctx.sourceId, slug, { rev, outcome, catchup: true });
+ const enqueue = async (c: { slug: string; thread_id: string; rev: number }, key: string) => {
+ await queue.add(LOOPS_EXTRACT_JOB, { slug: c.slug, sourceId: ctx.sourceId, threadId: c.thread_id, newestMs: c.rev, catchup: true },
+ { priority: 6, idempotency_key: key });
+ budget--;
+ report.enqueued++;
+ };
+ for (const c of candidates) {
+ if (ctx.signal?.aborted) { unsettled++; break; }
+ const prior = outcomes[c.slug];
+ if (prior && prior.rev === c.rev && (prior.outcome === 'extracted' || (prior.catchup && prior.outcome !== 'skipped:extraction_disabled'))) continue;
+ const sweepStatus = jobs.get(`loops:${ctx.sourceId}:${c.slug}:${c.rev}`);
+ if (ctx.inFlight.has(c.slug) || sweepStatus === 'waiting' || sweepStatus === 'delayed' || sweepStatus === 'active') { unsettled++; continue; }
+ const key = keyOf(c.slug, c.rev);
+ const status = jobs.get(`${key}:retry`) ?? jobs.get(key);
+ if (status === 'completed') continue;
+ if (status === 'dead' || status === 'failed' || status === 'cancelled') {
+ if (cu.retried.includes(c.slug) || jobs.has(`${key}:retry`)) {
+ ctx.log(`[google] loops catch-up: ${c.slug} dead-lettered after its retry; giving up on this revision`);
+ await settle(c.slug, c.rev, 'skipped:dead_letter');
+ continue;
+ }
+ if (budget <= 0) { report.deferred++; unsettled++; continue; }
+ cu.retried.push(c.slug);
+ await enqueue(c, `${key}:retry`);
+ unsettled++;
+ continue;
+ }
+ if (status !== undefined) { unsettled++; continue; }
+ if (budget <= 0) { report.deferred++; unsettled++; continue; }
+ let thread: GmailThreadData | null;
+ try {
+ thread = await ctx.fetchThread(c.thread_id);
+ } catch (e) {
+ ctx.log(`[google] loops catch-up: could not read thread for ${c.slug} (${e instanceof Error ? e.message : String(e)}); retried next sweep`);
+ unsettled++;
+ continue;
+ }
+ if (!thread) { await settle(c.slug, c.rev, 'skipped:thread_not_found'); continue; }
+ const verdict = loopExtractionEligibility(thread, ctx.myAddresses);
+ if (!verdict.eligible) { await settle(c.slug, c.rev, `skipped:ineligible_${verdict.reason}`); continue; }
+ await enqueue(c, key);
+ unsettled++;
+ }
+ if (unsettled === 0) cu.done = true;
+ ctx.log(`[google] loops catch-up (last ${LOOPS_EXTRACT_WINDOW_DAYS} days): enqueued ${report.enqueued} thread(s)`
+ + (report.deferred > 0 ? `, deferred ${report.deferred} to a later sweep (enqueue ceiling ${LOOPS_EXTRACT_ENQUEUE_CEILING})` : '')
+ + (cu.done ? '; catch-up complete' : `; ${unsettled} thread(s) not settled yet`));
+ return report;
+}
diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.ts
index eae436eb60..47ddf25552 100644
--- a/src/core/google/loop-detect.ts
+++ b/src/core/google/loop-detect.ts
@@ -69,6 +69,12 @@ export interface ThreadLoopVerdict {
* counterparty was most impatient).
*/
close: Array<'unanswered_inbound' | 'unanswered_outbound'>;
+ /**
+ * #5868: a grace window withheld this loop. It opens at `untilMs` with
+ * `spec` unless the thread changes first; the sweep records it as a grace
+ * hold because Gmail history never re-lists a quiet thread.
+ */
+ held?: { untilMs: number; spec: ThreadLoopSpec };
}
function isMine(m: GmailMessageMeta, myAddresses: Set<string>): boolean {
@@ -187,23 +193,21 @@ export function detectThreadLoop(
if (!inTo) return { open: [], close };
if (threadSuppressed || suppressions?.senders.has(last.fromAddress)) return { open: [], close };
const owedSince = run.find((m) => m.to.some((a) => myAddresses.has(a))) ?? last;
- if (ageHours(owedSince.internalDateMs, now) < INBOUND_GRACE_HOURS) return { open: [], close };
- return {
- open: [
- {
- loopType: 'unanswered_inbound',
- // No age in the stored summary — it would freeze at detection time
- // and lie on the trust-critical surface; readers render age from
- // last_activity_at.
- summary: `Reply owed to ${last.fromAddress}: "${subject}"`,
- counterpartyEmail: last.fromAddress,
- evidence: [{ message_id: last.id, quote: quote(last) }],
- lastActivityMs: last.internalDateMs,
- openedMs: owedSince.internalDateMs,
- },
- ],
- close,
+ const spec: ThreadLoopSpec = {
+ loopType: 'unanswered_inbound',
+ // No age in the stored summary — it would freeze at detection time
+ // and lie on the trust-critical surface; readers render age from
+ // last_activity_at.
+ summary: `Reply owed to ${last.fromAddress}: "${subject}"`,
+ counterpartyEmail: last.fromAddress,
+ evidence: [{ message_id: last.id, quote: quote(last) }],
+ lastActivityMs: last.internalDateMs,
+ openedMs: owedSince.internalDateMs,
};
+ if (ageHours(owedSince.internalDateMs, now) < INBOUND_GRACE_HOURS) {
+ return { open: [], close, held: { untilMs: owedSince.internalDateMs + INBOUND_GRACE_HOURS * 3_600_000, spec } };
+ }
+ return { open: [spec], close };
}
// ── Last word is mine: am I waiting on them? ──
@@ -214,20 +218,18 @@ export function detectThreadLoop(
const counterparty = recipients[0];
if (threadSuppressed || suppressions?.senders.has(counterparty)) return { open: [], close };
const askedSince = run.find((m) => asksQuestion(m.bodyText)) ?? last;
- if (ageHours(askedSince.internalDateMs, now) < OUTBOUND_GRACE_HOURS) return { open: [], close };
- return {
- open: [
- {
- loopType: 'unanswered_outbound',
- counterpartyEmail: counterparty,
- summary: `Waiting on ${counterparty}: "${subject}"`,
- evidence: [{ message_id: last.id, quote: quote(last) }],
- lastActivityMs: last.internalDateMs,
- openedMs: askedSince.internalDateMs,
- },
- ],
- close,
+ const spec: ThreadLoopSpec = {
+ loopType: 'unanswered_outbound',
+ counterpartyEmail: counterparty,
+ summary: `Waiting on ${counterparty}: "${subject}"`,
+ evidence: [{ message_id: last.id, quote: quote(last) }],
+ lastActivityMs: last.internalDateMs,
+ openedMs: askedSince.internalDateMs,
};
+ if (ageHours(askedSince.internalDateMs, now) < OUTBOUND_GRACE_HOURS) {
+ return { open: [], close, held: { untilMs: askedSince.internalDateMs + OUTBOUND_GRACE_HOURS * 3_600_000, spec } };
+ }
+ return { open: [spec], close };
}
// Suppression sets are cheap but per-thread queries add up on a backfill;
@@ -275,7 +277,7 @@ export async function applyThreadLoopVerdict(
myAddresses: Set<string>,
pageSlug: string | null,
now: Date = new Date(),
-): Promise<void> {
+): Promise<ThreadLoopVerdict> {
const suppressions = await suppressionsFor(engine, sourceId);
// One verdict, two lanes: `close` is the turn-flip set (suppression- and
// grace-independent — only a genuine reply closes, and only the answered
@@ -289,30 +291,57 @@ export async function applyThreadLoopVerdict(
await closeThreadLoops(engine, sourceId, thread.threadId, 'reply_detected', toClose);
}
- for (const spec of verdict.open) {
- let counterpartySlug: string | null = null;
- try {
- const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
- const resolved = await resolveEntitySlugWithSource(engine, sourceId, spec.counterpartyEmail);
- // Only alias-exact/high-confidence resolutions count — a slugify
- // fallback would fabricate a person that doesn't exist.
- if (resolved && resolved.source !== 'fallback_slugify') counterpartySlug = resolved.slug;
- } catch {
- /* resolution is best-effort */
- }
- await upsertOpenLoop(engine, {
- sourceId,
- dedupKey: `thread:${thread.threadId}:${spec.loopType}`,
- loopType: spec.loopType,
- counterpartySlug,
- counterpartyEmail: spec.counterpartyEmail,
- summary: spec.summary,
- evidence: spec.evidence.map((e) => ({ ...e, ...(pageSlug ? { page_slug: pageSlug } : {}) })),
- threadId: thread.threadId,
- pageSlug,
- detector: 'deterministic_thread',
- lastActivityAt: new Date(spec.lastActivityMs).toISOString(),
- openedAt: new Date(spec.openedMs).toISOString(),
- });
+ for (const spec of verdict.open) await upsertThreadLoop(engine, sourceId, thread.threadId, spec, pageSlug);
+ return verdict;
+}
+
+/**
+ * #5868: opens a grace-held loop whose deadline passed on an unchanged
+ * thread, from the spec its last detection produced. Suppressions are
+ * re-read so a mute added during the hold still withholds the open.
+ */
+export async function openDueGraceHold(
+ engine: BrainEngine,
+ sourceId: string,
+ threadId: string,
+ spec: ThreadLoopSpec,
+ pageSlug: string | null,
+): Promise<boolean> {
+ const suppressions = await suppressionsFor(engine, sourceId);
+ if (suppressions.threads.has(threadId) || suppressions.senders.has(spec.counterpartyEmail)) return false;
+ await upsertThreadLoop(engine, sourceId, threadId, spec, pageSlug);
+ return true;
+}
+
+async function upsertThreadLoop(
+ engine: BrainEngine,
+ sourceId: string,
+ threadId: string,
+ spec: ThreadLoopSpec,
+ pageSlug: string | null,
+): Promise<void> {
+ let counterpartySlug: string | null = null;
+ try {
+ const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
+ const resolved = await resolveEntitySlugWithSource(engine, sourceId, spec.counterpartyEmail);
+ // Only alias-exact/high-confidence resolutions count — a slugify
+ // fallback would fabricate a person that doesn't exist.
+ if (resolved && resolved.source !== 'fallback_slugify') counterpartySlug = resolved.slug;
+ } catch {
+ /* resolution is best-effort */
}
+ await upsertOpenLoop(engine, {
+ sourceId,
+ dedupKey: `thread:${threadId}:${spec.loopType}`,
+ loopType: spec.loopType,
+ counterpartySlug,
+ counterpartyEmail: spec.counterpartyEmail,
+ summary: spec.summary,
+ evidence: spec.evidence.map((e) => ({ ...e, ...(pageSlug ? { page_slug: pageSlug } : {}) })),
+ threadId,
+ pageSlug,
+ detector: 'deterministic_thread',
+ lastActivityAt: new Date(spec.lastActivityMs).toISOString(),
+ openedAt: new Date(spec.openedMs).toISOString(),
+ });
}
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index 03e74b7a78..25ed63bb19 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -80,6 +80,16 @@ export interface GoogleSourceState {
gmail_fail_counts?: Record<string, number>;
/** Fix wave 4: connector item holds (src/core/connectors/item-holds.ts). */
item_holds?: unknown;
+ /**
+ * #5868: threads whose loop a grace window withheld, keyed by thread id
+ * (src/core/google/loop-catchup.ts). Separate from `item_holds`: never a
+ * failure, never counted by doctor `connector_held_items` or `waiting`.
+ */
+ loop_grace_holds?: Record<string, LoopGraceHold>;
+ /** #5868: one-shot 14-day grace-hold backfill done (set after a non-aborted sweep). */
+ loop_grace_backfill_done?: boolean;
+ /** #5867: managed-source 30-day loops_extract catch-up progress. */
+ loops_catchup?: LoopsCatchupState;
calendar_sync_token: string | null;
/**
* Calendar id `calendar_sync_token` was minted for. A token is only valid
@@ -120,6 +130,33 @@ export function deriveSourceId(account: string): string {
return id || 'gmail';
}
+/**
+ * #5868: one grace-held thread. `spec` is the loop its last detection would
+ * open at `due_ms`; `rev` is the page's newest message id it was computed
+ * from. A backfill seed has neither and is re-fetched once due.
+ */
+export interface LoopGraceHold {
+ due_ms: number;
+ slug: string | null;
+ rev: string | null;
+ spec: {
+ loopType: 'unanswered_inbound' | 'unanswered_outbound';
+ counterpartyEmail: string;
+ summary: string;
+ evidence: Array<{ message_id?: string; page_slug?: string; quote?: string }>;
+ lastActivityMs: number;
+ openedMs: number;
+ } | null;
+}
+
+/** #5867: the managed catch-up's window floor, its one-retry set and its done marker. */
+export interface LoopsCatchupState {
+ version: 1;
+ floor_ms: number;
+ retried: string[];
+ done: boolean;
+}
+
export interface GmailMessageMeta {
id: string;
threadId: string;
diff --git a/src/core/minions/handlers/loops-extract.ts b/src/core/minions/handlers/loops-extract.ts
index 9534166e04..8615ee48aa 100644
--- a/src/core/minions/handlers/loops-extract.ts
+++ b/src/core/minions/handlers/loops-extract.ts
@@ -17,6 +17,20 @@ export function makeLoopsExtractHandler(engine: BrainEngine): MinionHandler {
if (!slug || !sourceId) throw new Error('loops_extract job requires data.slug and data.sourceId');
const threadId = typeof job.data.threadId === 'string' ? job.data.threadId : undefined;
const { runLoopsExtract } = await import('../../google/loops-extract.ts');
- return await runLoopsExtract(engine, { slug, sourceId, ...(threadId ? { threadId } : {}) });
+ const result = await runLoopsExtract(engine, { slug, sourceId, ...(threadId ? { threadId } : {}) });
+ // #5867 (E9): the revision-bound outcome is the catch-up's evidence, not job completion.
+ // A failed record never fails the job (that would repeat a paid extraction); the catch-up then re-checks the thread.
+ try {
+ const { loopsExtractRevision, recordLoopsExtractOutcome } = await import('../../google/loop-catchup.ts');
+ const rev = await loopsExtractRevision(engine, sourceId, slug, job.data.newestMs);
+ if (rev !== null) {
+ await recordLoopsExtractOutcome(engine, sourceId, slug, {
+ rev, outcome: result.status === 'extracted' ? 'extracted' : `${result.status}:${result.reason ?? 'unknown'}`, catchup: job.data.catchup === true,
+ });
+ }
+ } catch (e) {
+ console.warn(`[loops_extract] could not record the outcome for ${slug}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ return result;
};
}
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 20d2fd07c4..d74a2dbf38 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -637,12 +637,14 @@ export class ManagedConnectorSync {
* committed cursor state plus the updated `item_holds`, so the cursor never
* moves past an uncommitted receipt. A stale publication is refused by the
* `checkpointBefore` digest; any failure records nothing and returns false.
+ * `extra` carries connector bookkeeping that is not a cursor (#5867/#5868
+ * loop recovery state) and is published with the holds.
*/
- async publishHolds(empty: Record<string, unknown>, holds: unknown): Promise<boolean> {
+ async publishHolds(empty: Record<string, unknown>, holds: unknown, extra: Record<string, unknown> = {}): Promise<boolean> {
if (this.resetRequested || this.stopped) return false;
const committed = (this.checkpoint[0] as { state?: Record<string, unknown> | null } | undefined)?.state ?? null;
- if (digest(committed?.item_holds ?? { version: 1, items: {} }) === digest(holds)) return true;
- const state = { ...empty, ...(committed ?? {}), item_holds: holds };
+ const state = { ...empty, ...(committed ?? {}), ...extra, item_holds: holds };
+ if (digest({ ...(committed ?? {}), item_holds: committed?.item_holds ?? { version: 1, items: {} } }) === digest({ ...(committed ?? {}), ...extra, item_holds: holds })) return true;
const next = [{ generation: Number((this.checkpoint[0] as { generation?: number } | undefined)?.generation ?? 0) + 1, state }];
try {
await this.submit('connector_v2_checkpoint', CHECKPOINT_SLUG, null, { checkpointAfter: next, receipts: [], fresh: false });
diff --git a/test/e2e/google-loops-recovery-postgres.test.ts b/test/e2e/google-loops-recovery-postgres.test.ts
new file mode 100644
index 0000000000..aa69cdd79f
--- /dev/null
+++ b/test/e2e/google-loops-recovery-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../google-loops-recovery.serial.test.ts'));
diff --git a/test/google-loops-recovery.serial.test.ts b/test/google-loops-recovery.serial.test.ts
new file mode 100644
index 0000000000..943b167936
--- /dev/null
+++ b/test/google-loops-recovery.serial.test.ts
@@ -0,0 +1,303 @@
+/**
+ * #5867 (managed Gmail sweeps enqueue loops_extract; managed 30-day catch-up)
+ * and #5868 (grace-held threads are re-evaluated after their deadline).
+ *
+ * Authoring gate. (1) Protects open-loop coverage for Gmail sources: managed
+ * autopilot syncs must queue commitment extraction, threads missed before
+ * this fix are analyzed once, and a quiet thread inside its grace window opens
+ * its loop once the window passes. (2) Fails on the baseline: a managed sweep
+ * with the autopilot `noExtract` default queued nothing, there was no
+ * catch-up, and a held thread with no new Gmail history never opened. (3) The
+ * existing connector tests cover delta/backfill cursors and item holds, never
+ * the loop engine's lifecycle across sweeps. (4) Serial: the clock is moved
+ * with setSystemTime and the chat transport is the gateway's process-global
+ * seam.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';
+import { readGoogleState } from '../src/core/google/google-source.ts';
+import { GRACE_REFETCH_PER_SWEEP } from '../src/core/google/loop-catchup.ts';
+import { makeLoopsExtractHandler } from '../src/core/minions/handlers/loops-extract.ts';
+import { connectorHeldItemsCheck } from '../src/commands/doctor/checks/connector-holds.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { __clearSuppressionCacheForTests } from '../src/core/google/loop-detect.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { createConnectorFixture, options, json, googleConfig, sourceCheckpoint, withGoogleAccount } from './helpers/connector-fixture.ts';
+import type { GoogleSourceState } from '../src/core/google/types.ts';
+
+const fixture = createConnectorFixture();
+const { engines, env, source } = fixture;
+beforeAll(fixture.setup, 120_000);
+afterAll(async () => { __setChatTransportForTests(null); resetGateway(); await fixture.teardown(); });
+afterEach(() => setSystemTime());
+
+const b64url = (s: string) => Buffer.from(s, 'utf-8').toString('base64url');
+const HOUR = 3_600_000;
+const DAY = 24 * HOUR;
+const usage = { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 };
+
+function chatReady(): void {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({ text: JSON.stringify({ commitments: [], decisions_pending: [] }),
+ blocks: [], stopReason: 'end', usage, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }));
+}
+
+interface FakeThread { tid: string; ms: number; body?: string }
+
+async function captureStderr<T>(fn: () => Promise<T>): Promise<{ result: T; lines: string[] }> {
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ process.stderr.write = ((chunk: unknown) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try { return { result: await fn(), lines }; } finally { process.stderr.write = write; }
+}
+
+/** A minimal Gmail: profile, sendAs, windowed listing, a history cursor and thread reads (counted). */
+function fakeGmail(account: string, threads: FakeThread[]) {
+ const gmail = { historyId: '1000', flagged: [] as string[], threadReads: [] as string[], threads, unlisted: new Set<string>() };
+ const fetcher = async (url: string) => {
+ const u = new URL(url);
+ if (u.pathname.endsWith('/settings/sendAs')) return json({ sendAs: [] });
+ if (u.pathname.endsWith('/users/me/profile')) return json({ emailAddress: account, historyId: gmail.historyId });
+ if (u.pathname.endsWith('/users/me/messages')) {
+ const q = u.searchParams.get('q') ?? '';
+ const after = Number(/after:(\d+)/.exec(q)?.[1] ?? 0);
+ const before = Number(/before:(\d+)/.exec(q)?.[1] ?? Infinity);
+ const hits = gmail.threads.filter((t) => !gmail.unlisted.has(t.tid) && t.ms / 1000 >= after && t.ms / 1000 < before).sort((a, b) => b.ms - a.ms);
+ return json({ messages: hits.map((t) => ({ id: `m${t.tid}`, threadId: t.tid })) });
+ }
+ if (u.pathname.endsWith('/users/me/history')) {
+ const records = u.searchParams.get('startHistoryId') === gmail.historyId ? [] : [{ messages: gmail.flagged.map((threadId) => ({ threadId })) }];
+ return json({ historyId: gmail.historyId, history: records });
+ }
+ const m = u.pathname.match(/\/users\/me\/threads\/([^/]+)$/);
+ if (m) {
+ gmail.threadReads.push(m[1]);
+ const t = gmail.threads.find((x) => x.tid === m[1]);
+ if (!t) return json({ error: { code: 404, message: 'Requested entity was not found.' } }, 404);
+ return json({ id: t.tid, messages: [{ id: `m${t.tid}`, threadId: t.tid, labelIds: ['INBOX'], internalDate: String(t.ms),
+ payload: { mimeType: 'text/plain', headers: [{ name: 'From', value: 'Peer Example <[email protected]>' },
+ { name: 'To', value: account }, { name: 'Subject', value: `Topic ${t.tid}` }],
+ body: { data: b64url(t.body ?? `Can you review the plan for ${t.tid}?`) } } }] });
+ }
+ return json({ error: { message: 'unexpected fixture route' } }, 400);
+ };
+ return { gmail, fetcher };
+}
+
+async function gmailSource(engine: BrainEngine, managed: boolean) {
+ const config = { ...googleConfig, g_services: 'gmail', g_history_days: 90 };
+ const f = await source(engine, config);
+ if (!managed) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ return { ...f, cfg: parseGoogleSourceConfig(config, f.dir) };
+}
+
+async function restoreManaged(engine: BrainEngine) {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+}
+
+async function googleState(engine: BrainEngine, f: { id: string; dir: string }, managed: boolean): Promise<GoogleSourceState | undefined> {
+ if (!managed) return readGoogleState(f.dir);
+ await disposePersistenceConsumer(engine);
+ const [row] = await sourceCheckpoint(engine, f.id) as { completed_keys: { state?: GoogleSourceState }[] }[];
+ return row?.completed_keys[0]?.state;
+}
+
+const loopsJobs = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ id: number; data: Record<string, unknown>; status: string; idempotency_key: string }>(
+ "SELECT id, data, status, idempotency_key FROM minion_jobs WHERE name='loops_extract' AND data->>'sourceId'=$1 ORDER BY id", [sourceId]);
+
+/** Runs every waiting loops_extract job of the source through the real handler and completes it. */
+async function drainLoopsJobs(engine: BrainEngine, sourceId: string): Promise<void> {
+ const handler = makeLoopsExtractHandler(engine);
+ for (const job of await loopsJobs(engine, sourceId)) {
+ if (job.status !== 'waiting') continue;
+ await handler({ id: job.id, data: job.data } as never);
+ await engine.executeRaw("UPDATE minion_jobs SET status='completed' WHERE id=$1", [job.id]);
+ }
+}
+
+describe('#5867 managed Gmail sweeps enqueue loops_extract', () => {
+ test('an autopilot-shaped managed sweep (noExtract) queues the eligible thread and reports loops_enqueue', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ const f = await gmailSource(engine, true);
+ const { gmail, fetcher } = fakeGmail(f.cfg.account, [{ tid: '17aa00000000e001', ms: Date.now() - 2 * DAY }]);
+ const result = await runGoogleSync(engine, f.id, f.cfg, { ...options, noExtract: true }, withGoogleAccount(fetcher, f.cfg.account));
+ const jobs = await loopsJobs(engine, f.id);
+ expect(jobs.filter((j) => j.idempotency_key.startsWith('loops:'))).toHaveLength(1);
+ expect(jobs.map((j) => j.data.slug)).toEqual([jobs[0].data.slug]);
+ expect((result as { loops_enqueue?: unknown }).loops_enqueue).toMatchObject({ enqueued: 1, deferred: 0, skipped_reason: null });
+ expect(gmail.threadReads.length).toBeGreaterThan(0);
+ await disposePersistenceConsumer(engine);
+ }
+ }), 180_000);
+
+ test('the kill switch logs a skip and queues nothing on the sweep or the catch-up', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ const f = await gmailSource(engine, true);
+ const { fetcher } = fakeGmail(f.cfg.account, [{ tid: '17aa00000000e101', ms: Date.now() - 2 * DAY }]);
+ const { result, lines: logs } = await captureStderr(() =>
+ runGoogleSync(engine, f.id, f.cfg, { ...options, noExtract: true }, withGoogleAccount(fetcher, f.cfg.account)));
+ expect(await loopsJobs(engine, f.id)).toHaveLength(0);
+ expect(logs.some((l) => l.includes('loops_extract: extraction disabled'))).toBe(true);
+ expect(logs.some((l) => l.includes('loops catch-up skipped (extraction_disabled)'))).toBe(true);
+ expect((result as { loops_enqueue?: unknown }).loops_enqueue).toMatchObject({ enqueued: 0, skipped_reason: 'extraction_disabled' });
+ expect((await googleState(engine, f, true))?.loops_catchup?.done ?? false).toBe(false);
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ }
+ }), 180_000);
+
+ test('catch-up analyzes a thread whose job ran while extraction was disabled, including one with a deterministic loop row, once', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ const f = await gmailSource(engine, true);
+ const tid = '17aa00000000e201';
+ const { fetcher } = fakeGmail(f.cfg.account, [{ tid, ms: Date.now() - 3 * DAY }]);
+ const sync = () => runGoogleSync(engine, f.id, f.cfg, { ...options, noExtract: true }, withGoogleAccount(fetcher, f.cfg.account));
+ // Sweep 1 queues the thread through the normal enqueue; its job then runs while extraction is off.
+ await sync();
+ expect(await engine.executeRaw("SELECT 1 FROM open_loops WHERE source_id=$1 AND loop_type='unanswered_inbound' AND status='open'", [f.id])).toHaveLength(1);
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ await drainLoopsJobs(engine, f.id);
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ // Sweep 2 (no new mail): the catch-up re-candidates it under its own key.
+ await sync();
+ let jobs = await loopsJobs(engine, f.id);
+ expect(jobs.filter((j) => j.idempotency_key.startsWith('loops-catchup:'))).toHaveLength(1);
+ await drainLoopsJobs(engine, f.id);
+ // Sweep 3 settles the catch-up; sweep 4 does not repeat it.
+ await sync();
+ expect((await googleState(engine, f, true))?.loops_catchup?.done).toBe(true);
+ await sync();
+ jobs = await loopsJobs(engine, f.id);
+ expect(jobs).toHaveLength(2);
+ }
+ }), 240_000);
+
+ test('a dead-lettered catch-up job is retried once, then given up', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ const f = await gmailSource(engine, true);
+ const { fetcher } = fakeGmail(f.cfg.account, [{ tid: '17aa00000000e301', ms: Date.now() - 4 * DAY }]);
+ const sync = () => runGoogleSync(engine, f.id, f.cfg, { ...options, noExtract: true }, withGoogleAccount(fetcher, f.cfg.account));
+ await sync(); // imports the page; nothing queued
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ await sync();
+ const kill = async () => engine.executeRaw("UPDATE minion_jobs SET status='dead' WHERE name='loops_extract' AND data->>'sourceId'=$1 AND status='waiting'", [f.id]);
+ await kill();
+ await sync();
+ expect((await loopsJobs(engine, f.id)).map((j) => j.idempotency_key.endsWith(':retry'))).toEqual([false, true]);
+ await kill();
+ await sync();
+ expect(await loopsJobs(engine, f.id)).toHaveLength(2);
+ expect((await googleState(engine, f, true))?.loops_catchup?.done).toBe(true);
+ }
+ }), 240_000);
+
+ test('an aborted sweep leaves the catch-up and backfill markers unset', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ const f = await gmailSource(engine, true);
+ const { fetcher } = fakeGmail(f.cfg.account, [{ tid: '17aa00000000e401', ms: Date.now() - 2 * DAY }]);
+ const controller = new AbortController();
+ controller.abort();
+ await runGoogleSync(engine, f.id, f.cfg, { ...options, signal: controller.signal }, withGoogleAccount(fetcher, f.cfg.account)).catch(() => null);
+ const state = await googleState(engine, f, true);
+ expect(state?.loops_catchup?.done ?? false).toBe(false);
+ expect(state?.loop_grace_backfill_done ?? false).toBe(false);
+ expect(await loopsJobs(engine, f.id)).toHaveLength(0);
+ }
+ }), 120_000);
+});
+
+describe('#5868 grace-held threads are re-evaluated after their deadline', () => {
+ for (const managed of [true, false]) {
+ test(`${managed ? 'managed' : 'unmanaged'}: a quiet held thread opens its loop on the sweep after its deadline with no Gmail read`, async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ const f = await gmailSource(engine, managed);
+ __clearSuppressionCacheForTests(engine);
+ const tid = '17aa00000000f001';
+ const { gmail, fetcher } = fakeGmail(f.cfg.account, [{ tid, ms: Date.now() - 2 * HOUR }]);
+ const sync = () => runGoogleSync(engine, f.id, f.cfg, { ...options }, withGoogleAccount(fetcher, f.cfg.account));
+ await sync();
+ const openLoops = () => engine.executeRaw<{ loop_type: string }>("SELECT loop_type FROM open_loops WHERE source_id=$1 AND status='open'", [f.id]);
+ expect(await openLoops()).toHaveLength(0);
+ const held = (await googleState(engine, f, managed))?.loop_grace_holds?.[tid];
+ expect(held?.spec?.loopType).toBe('unanswered_inbound');
+ setSystemTime(new Date(Date.now() + 26 * HOUR));
+ gmail.threadReads.length = 0;
+ await sync();
+ expect((await openLoops()).map((r) => r.loop_type)).toEqual(['unanswered_inbound']);
+ expect(gmail.threadReads).toEqual([]);
+ expect((await googleState(engine, f, managed))?.loop_grace_holds?.[tid]).toBeUndefined();
+ setSystemTime();
+ if (!managed) await restoreManaged(engine);
+ }
+ }), 180_000);
+ }
+
+ test('a 500-thread backfill is bounded per sweep, never exhausts item holds, and leaves connector_held_items unchanged', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ const f = await gmailSource(engine, false);
+ const threads = Array.from({ length: 500 }, (_, i) => ({ tid: `17ab0000000${String(i).padStart(5, '0')}`, ms: Date.now() - (5 * DAY + i * 60_000) }));
+ // Pages exist from before the fix (no holds recorded); Gmail lists none of them again.
+ for (const t of threads) {
+ await engine.putPage(`emails/${t.tid}`, { title: `Topic ${t.tid}`, type: 'email', compiled_truth: 'Synthetic body.',
+ frontmatter: { thread_id: t.tid, message_id: `m${t.tid}`, date: new Date(t.ms).toISOString() } }, { sourceId: f.id });
+ }
+ const { gmail, fetcher } = fakeGmail(f.cfg.account, threads);
+ for (const t of threads) gmail.unlisted.add(t.tid);
+ const before = await connectorHeldItemsCheck(engine, [f.id]);
+ const result = await runGoogleSync(engine, f.id, f.cfg, { ...options }, withGoogleAccount(fetcher, f.cfg.account));
+ expect(result.status).not.toBe('partial');
+ expect(gmail.threadReads).toHaveLength(GRACE_REFETCH_PER_SWEEP);
+ const state = readGoogleState(f.dir);
+ expect(state.loop_grace_backfill_done).toBe(true);
+ expect(Object.keys(state.loop_grace_holds ?? {}).length).toBe(500 - GRACE_REFETCH_PER_SWEEP);
+ expect((await connectorHeldItemsCheck(engine, [f.id])).status).toBe(before.status);
+ expect((await connectorHeldItemsCheck(engine, [f.id])).message).toBe(before.message);
+ // Each re-fetched thread is past its grace window, so it opened; the rest wait for later sweeps.
+ expect((await engine.executeRaw("SELECT 1 FROM open_loops WHERE source_id=$1 AND status='open'", [f.id])).length).toBe(GRACE_REFETCH_PER_SWEEP);
+ await restoreManaged(engine);
+ }
+ }), 240_000);
+
+ test('E20: a partial managed sweep still publishes grace holds and the catch-up cursor', async () => withEnv(env, async () => {
+ chatReady();
+ for (const engine of engines) {
+ await engine.setConfig('loops.extraction_enabled', 'false');
+ const f = await gmailSource(engine, true);
+ const good = { tid: '17aa00000000f101', ms: Date.now() - 2 * HOUR };
+ const { gmail, fetcher } = fakeGmail(f.cfg.account, []);
+ await runGoogleSync(engine, f.id, f.cfg, { ...options }, withGoogleAccount(fetcher, f.cfg.account));
+ expect((await googleState(engine, f, true))?.loops_catchup).toBeUndefined();
+ gmail.threads.push(good);
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ // Sweep 2: history flags the held thread plus one that fails to read → a partial run.
+ gmail.historyId = '1010';
+ gmail.flagged = [good.tid, '17aa00000000f1ff'];
+ const failing = async (url: string, init?: RequestInit) => url.includes('17aa00000000f1ff')
+ ? json({ error: { message: 'fixture failure' } }, 400) : fetcher(url);
+ const result = await runGoogleSync(engine, f.id, f.cfg, { ...options }, withGoogleAccount(failing, f.cfg.account));
+ expect(result.status).toBe('partial');
+ const state = await googleState(engine, f, true);
+ // Written after the sweep's last mid-run checkpoint, so only the partial-run publication carries them.
+ expect(state?.loop_grace_holds?.[good.tid]?.spec?.loopType).toBe('unanswered_inbound');
+ expect(state?.loops_catchup).toMatchObject({ done: false });
+ expect(state?.loop_grace_backfill_done).toBe(true);
+ }
+ }), 180_000);
+});