Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P4.6a #5445: per-source Gmail label exclusion for loop extraction, fail closed on unresolved names

garrytan449a020912d0
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 90fa4e45e1..26f8bf623f 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -1,8 +1,8 @@
# Key files — per-file index (gbrain repo)
Read a file's entry before editing it. This page routes to bounded subsystem
-references; **do not load every file in the directory**. Entries retain the
-implementation evidence and test references from the former single-file index.
+references; **do not load every file in the directory**. Entries keep the
+implementation evidence and test references.
Find a specific path locally, then read that entry and its surrounding contract:
@@ -43,7 +43,7 @@ boundary and add its link here rather than raising the cap.
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/rss-default.ts` |
| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/run-child.ts` through `src/core/minions/worker.ts` |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` write journal, coordinator, effects, canonical projections and managed sync |
-| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoint validation, no-op kernel, accepted-pending receipts, verb types/errors, database-write, attribution, purge-deleted, fact retirement, single-write path |
+| [Core Persistence (continued)](key-files/core-persistence-continued.md) | `worktree-refresh*.ts`, `persistence/connector-*.ts`, `connectors/item-holds*.ts`, checkpoints, receipts, verb types/errors, database-write, attribution, purge-deleted, fact retirement, single-write path |
| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, its doctor finding |
| [Managed sync and persistence stalls](key-files/persistence-stalls.md) | preparation budgets, `claim-phase.ts`, `consumer.ts`, `group-publish.ts`, `journal.ts`, `diagnostics.ts`, `worktree-manifest.ts` |
| [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |
@@ -69,14 +69,15 @@ boundary and add its link here rather than raising the cap.
| [Shared brain skills](key-files/shared-skills.md) | Canonical catalog, enrollment, migration, publication and harness integration |
| [Skills](key-files/skills.md) | `src/core/audit-skill-brain-first.ts` through `src/core/skills-integrity.ts` |
| [Tooling And Tests](key-files/tooling-and-tests.md) | `.github/workflows/test.yml` through `test/remote-privacy-sweep.test.ts` |
-| [CI Health And Test Guards](key-files/ci-health-and-test-guards.md) | `.github/workflows/nightly-watch.yml` through `scripts/check-image-decoders-embedded.sh`, plus contributor audit, fix-wave gate |
+| [CI Health And Test Guards](key-files/ci-health-and-test-guards.md) | `.github/workflows/nightly-watch.yml` through `scripts/check-image-decoders-embedded.sh`, contributor audit, fix-wave gate |
| [BrainBench — in a sibling repo](key-files/brainbench.md) | Cross-file subsystem contract |
| [Hindsight calibration (key files cluster)](key-files/hindsight.md) | Cross-file subsystem contract |
| [Schema packs: mutation surface (key files cluster)](key-files/schema-mutation.md) | Cross-file subsystem contract |
| [Agent bootstrap cluster (the paste-in desktop-agent install)](key-files/agent-bootstrap.md) | Cross-file subsystem contract |
-| [Agent Bootstrap (continued)](key-files/agent-bootstrap-continued.md) | Remaining cross-file entries |
+| [Agent Bootstrap (continued)](key-files/agent-bootstrap-continued.md) | Remaining entries |
| [Google connector + open-loop engine (key files cluster)](key-files/google-and-loops.md) | Cross-file subsystem contract |
-| [Google And Loops (continued)](key-files/google-and-loops-continued.md) | Remaining cross-file entries |
+| [Google And Loops (continued)](key-files/google-and-loops-continued.md) | Remaining entries |
+| [Open-loop engine](key-files/open-loops-engine.md) | detection, exclusion, extraction, store, ops, CLI |
| [Always-loaded core memory (key files cluster)](key-files/core-memory.md) | Core tier, write-path guard and lock order, delivery lanes, pressure notice |
| [Workspace push and backup coverage (key files cluster)](key-files/workspace-push-and-backup.md) | Workspace push, hook push backstops, backup verdicts |
| [Ambient capture consent gate (key files cluster)](key-files/ambient-capture.md) | `memory.auto_writeback` capture lanes |
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index fdfd391376..2589b45ff7 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -6,7 +6,10 @@ User-facing contracts: `docs/guides/google-connect.md` (setup + the typed error
catalog) and `docs/guides/open-loops.md` (detection + close semantics).
Hosted-relay server design: `docs/designs/HOSTED_OAUTH_RELAY.md` (the CLI-side
seams are frozen in this repo; the server is gbrain.io's build). Agent-facing
-operation: `skills/google-loops/SKILL.md`.
+operation: `skills/google-loops/SKILL.md`. The open-loop engine's own files
+(`loops-exclusion.ts`, `loop-detect.ts`, `loops-extract.ts`, `loops-store.ts`,
+`ops/loops.ts`, `commands/loops.ts`) are in
+[open-loops-engine.md](open-loops-engine.md).
Historical Gmail repair selects explicit nested MIME metadata fields, excluding `body.data` at every depth. Depth-33 child sentinels preserve incomplete inspection beyond the depth-32 traversal bound. Its decoded HTTP response is capped at 2 MiB before JSON parsing; overflow cancels the stream and preserves the affected page/cursor. Ordinary sync's body requests remain unchanged.
@@ -19,7 +22,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/creds/redirect.ts` — how the authorization code gets back to us: `RedirectStrategy = 'loopback' | 'paste' | 'hosted-callback'`. Loopback is an ephemeral 127.0.0.1 listener; paste mode needs NO listener (the fixed `PASTE_REDIRECT_URI` fails to load, the user pastes the full address-bar URL back) and is auto-selected by `sniffHeadless` (SSH/WSL/container/no-display). Google's device-code flow is NOT an option — Gmail/Calendar/Contacts scopes are excluded from it; don't re-litigate.
- `src/core/creds/relay-client.ts` — the typed CLIENT half of the gbrain.io zero-retention consent relay (`createSession` → user clicks the consent URL → poll a one-time `claim`; the relay deletes tokens on first successful claim or at session TTL). Inert unless `GBRAIN_OAUTH_RELAY_URL` is set (unset = the BYO flow, which always works). `test/creds-relay-client.test.ts` is the server conformance spec — a server that round-trips those fixtures is compatible.
- `src/core/creds/export.ts` — versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.
-- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's. `GoogleSourceState.calendar_horizon_ms` is the ceiling of the last calendar list that reached it (calendar-window.ts); absent on state saved before it existed.
+- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's. `GoogleSourceState.calendar_horizon_ms` is the ceiling of the last calendar list that reached it (calendar-window.ts); absent on state saved before it existed. `GoogleSourceConfig.futureDays` (#5442) and `loopsExcludeLabels` (#5445) are optional and absent when their keys are unset; `source-config.ts` parses them (`g_future_days` 1..3650 floored, `g_loops_exclude_labels` through `parseExcludeLabelTokens`) and `googleTuningConfig` is the one writer of those keys plus `g_calendar_id`, each only when set, for `addSource`. Both `sources add` parsers accept `--future-days` and `--loops-exclude-labels`: the connected-source parser validates through the operation contract (`sources-lifecycle-args.ts`), the legacy parser through `commands/sources-google-flags.ts` (`parseGoogleAddFlag`, exit 2 on a bad value), so neither `runAdd` nor `addSource` grows for a new tuning key.
- `src/core/google/access.ts` — the pluggable Google-access seam: `GoogleAccessProvider` (`getAccessToken`/`forceRefresh`) with `CommandAccessProvider` (`--access command`: any CLI that prints a token — gog/gcloud/a gateway's mint command; parsed as a bare token line or JSON `{token|access_token, expiry|expires_in}`, cached until expiry with a 60s margin, 30s exec timeout, failures = `access_command_failed` carrying the stderr tail) and `EnvAccessProvider` (`--access env`: a live token read from a NAMED env var each call, refreshed outside gbrain; missing = `access_env_missing`). The vault flow's `GoogleTokenProvider` satisfies the same interface. The token command executes only in the locally-running sync (google config keys are unreachable over MCP; same trust class as recipe health-check argv).
- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.
- `src/core/google/gmail-categories.ts` — `BULK_CATEGORY_LABELS` (`CATEGORY_PROMOTIONS`/`SOCIAL`/`FORUMS`) and `hasBulkCategory`, the one list both open-loop lanes read (#5103): `loopExtractionEligibility` returns `bulk_category` and `detectThreadLoop` withholds an inbound open, in both cases unless the owner wrote a substantive message in the thread; `CATEGORY_UPDATES` is deliberately not in it. `isNoiseSender` additionally matches `GOOGLE_SYSTEM_SENDERS` (the Meet notes digest address) by equality only.
@@ -27,13 +30,8 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path. FILE MODES (every write, both paths): `writeGoogleState` writes `.google-source.json` through `atomicWriteFileSync(..., { mode: 0o600 })` under `mkdirPrivate(dir)`; a corrupt state file is chmod-ed 0600 and then renamed to `.corrupt`, and if either step fails stderr names the path, the failed step, the exposure and the fix (`chmod 600 <path>` or delete it) while the sync continues with empty cursors. A legacy page goes through `writePrivateTemp`: a stale `<page>.tmp` is removed with `lstat` (never followed; a stale `.tmp` directory fails that item with `Stale temporary path <path> is a directory; remove it and re-run the sync.`), the temp file is created `wx` at 0600 and fchmod-ed past the umask, imported, then renamed over the page; page directories come from `mkdirPrivate(dirname(page), cfg.dir)`. 0600 is reasserted on every rewrite, so a looser mode set by hand is reverted on the next rewrite (unchanged pages are not rewritten). Managed pages get the same modes through `publishMode` (see the persistence coordinator). Mode assertions are skipped on win32. Tests: `test/google-file-modes.test.ts` (child process under umask 0000, `test/helpers/google-file-modes-child.ts`). The loops enqueue runs on every non-aborted sweep in both persistence modes (`--no-extract` gates only the inline link/timeline extract), logs every skip reason and reports `loops_enqueue { enqueued, deferred, skipped_reason }` in the sync result; job payloads carry the page revision (`newestMs`). After the delta and item-hold passes the sweep seeds and settles grace holds, and a managed sweep runs the 30-day catch-up (both in `loop-catchup.ts`); a partial managed run publishes that state with its item holds (`publishHolds` extra), never the Gmail cursor.
- `src/core/google/calendar-window.ts` — which calendar events a google source keeps pages for: `[now - historyDays, now + futureDays]` (`g_future_days`, 1..3650, default `CALENDAR_HORIZON_DAYS` = 60; the parsed `futureDays` leaf exists only when the key is set, so an unset knob leaves every existing source's connector identity unchanged), checked by the sweep itself on every list because a syncToken delta cannot carry timeMin/timeMax. `CalendarSyncWindow` is built once per sweep: `side(start, end)` follows Google's rule (an event is `before` when it ends at or before the floor, `after` when it starts at or past the ceiling, unparseable dates stay `inside`); `coverageStartMs(horizon, listedWholeWindow)` says where the catch-up list for unchanged instances crossing the leading edge starts (none after a whole-window list, now for state without `calendar_horizon_ms`, the recorded horizon once the ceiling is a day past it); `startsInside` and `startsAfter` are the `--full` reconcile tests. `planCalendarPage` maps one listed event to a page change (a cancellation removes its page anywhere, aged-out history is left as it is, a page past the horizon is removed, otherwise write after removing a copy at an older path). `unlistedCalendarPages` returns sweep pages (with an `event_id`) starting inside the window that a complete `--full` list did not name; `staleCalendarPages` adds the sweep pages starting at or past the ceiling, which no windowed list can name (#5442), and is what the `--full` reconcile deletes through. `people-calendar-sweep.ts` (the contacts and calendar sweeps, peeled from `google-source.ts`) performs the changes with `importRendered`/`deletePageByRelPath`, discards the catch-up list's sync token, advances `calendar_horizon_ms` only after a list reached the ceiling, and sends reconcile deletes through the >200 mass-delete guard (a refusal marks the run partial). Tests: `test/google-calendar-window.test.ts` (pure rules), `test/google-source-reconcile.test.ts` (calendar window suite).
- `src/core/google/file-modes.ts` — detection and tightening for group/world-readable files gbrain wrote under a Google source directory outside `~/.gbrain` (inside it the 0700 home already protects them). `scanGoogleFileModes(engine, { sourceIds? })` reads non-archived Google sources, skips dirs inside the home (`outsideGbrainHome`, realpath-aware), and inspects only gbrain's own layout: `.google-source.json*` in the root, every recorded page `source_path` under `emails/`, `calendar/`, `people/` (malformed paths ignored), each page's `.tmp`, and the directories between the root and those pages. Each path is `lstat`-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted in `skipped`, never followed); an entry is loose when `mode & 0o077`. `tightenGoogleEntry(root, entry)` re-checks the path, opens the leaf `O_NOFOLLOW` (`O_DIRECTORY` for dirs), re-checks the owner on the fd and `fchmod`s `mode & ~0o077`, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set. `googleFileModesPreviewCommand`/`googleFileModesApplyCommand` build the `gbrain repair google-file-modes --source <id> [--apply]` strings every surface prints. win32: scan returns nothing. Tests: `test/google-file-modes-repair.test.ts`.
-- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions.
-- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.
-- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.
-- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `loops_close` retires a commitment loop's fact through `persistence/loop-fact-retirement.ts` and returns `{ closed, id, status, fact_expired, retryable, reason? }` from the real publication outcome; a loop already closed whose fact is still active re-attempts the retirement. `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. Ranking and rendered ages use one reference time, `as_of` (ISO, default now, echoed in the grouped result; `gbrain waiting --as-of`), so a published order is reproducible (N7-5). An optional `id` (positive safe integer, else `invalid_params` through `invalidParam` without echoing the value) finds one loop at any status unless `status` is given; explicit filters still intersect, scope and redaction are unchanged, so an out-of-scope id returns exactly what a missing id returns, and an id lookup carries no `text` digest. The result carries per-source last-successful-sync ages + a `stale` flag (>24h): all stale sources remain a refusal condition for `gbrain waiting`, while a mixed fresh/stale set continues with a warning naming stale sources (`stale_sources` in JSON). Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly. #5871: grouped output ranks people only; loops with neither a counterparty slug nor an email return in `no_counterparty` (`loop_count`, `by_type`, shown loops, `loops_omitted`; null when none), never ranked or counted by `limit`, and the digest lists them last and never says "You are clean" while they exist; each group shows at most `LOOPS_PER_GROUP` (5) loops, due-soonest then most recently active, with `loops_omitted` (`test/ops-loops.test.ts`, `test/loops-cli.test.ts`).
- `src/commands/google.ts` — `gbrain google connect|status|calendars|disconnect` (+ `setup` and `attachments` dispatch). Agent-first contract: every subcommand supports `--json` emitting `{ ok, status, next_action: { command?, user_message? }, error? }` (`calendars` adds `account` + `calendars[]` — id/summary/primary/accessRole — and carries the `sources add --calendar-id` template in `next_action.command`; it resolves a lone connected account, exits 2 when there are none or several without `--account`, and throws `not_connected` for an unknown `--account`); human copy the harness must relay verbatim is fenced in `[SHOW USER] ... [/SHOW USER]` blocks; secret intake is `--client-json <path|->` (preferred) / env `GOOGLE_CLIENT_ID`+`GOOGLE_CLIENT_SECRET` / TTY prompt, with raw argv flags accepted but documented last-resort; connect is an idempotent state machine (detects what exists, performs only the missing step — re-running is the documented fix for most errors). Credential commands are engine-free; `status` has a best-effort linked-sources listing, while `attachments backfill` requires the explicitly selected local managed brain. Funnel events append to `~/.gbrain/integrations/google/heartbeat.jsonl`; account addresses are hashed to a short non-reversible tag, never raw. The vault entry's `meta.scopes` records what Google ACTUALLY granted (the token response's `scope` — the consent screen lets users uncheck scopes; the requested set is only the fallback), which is what lets downstream preflights report `scope_missing` instead of opaque per-sweep 403s.
- `src/commands/creds.ts` — `gbrain creds list|remove|export|import`: the provider-agnostic vault surface; never prints a secret (list is always redacted). Provider-SPECIFIC connect flows live in their own commands. Export custody: a loud per-credential warning when a byo Google entry's consent screen is not known published-to-Production (its 7-day Testing expiry travels with the tokens).
-- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported); when only some sources are stale, it continues with the warning and source ids from `open_loops`. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. `loops show <id>` passes the id to `open_loops` (any status and rank); a missing positive id is a usage error (exit 2) and an unknown id renders `not_found` with the `gbrain loops list` fix (exit 1). An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.
- `src/commands/google-setup.ts` + `google-setup-tail.ts` — the one-command orchestrator behind `gbrain google setup`: connect (skipped when tokens exist) → source registration (skipped when registered) → first bounded sync under a wall-clock budget (the newest-first backfill floor means whatever lands is the NEWEST mail — exactly what `waiting` needs; the remainder resumes on every later sync, and setup says so honestly) → the first `gbrain waiting` digest in the same session as consent. Split in two so the connect half stays engine-free. Every step idempotent; re-running resumes wherever the last run stopped.
- `src/commands/doctor/checks/google-oauth.ts` — the `google_oauth` doctor check: zero-network vault health (live refresh probes belong to `gbrain google status`; doctor stays fast and offline-safe). fail: a connected account with an expired access token AND no successful refresh in >2 days (refresh is broken — revoked, rotated client, or the Testing-mode expiry already hit); warn: a consent screen not known Production whose last proof of life is ≥5 days old (the proactive day-6 re-auth demand, cheaper than a dead pipeline on day 8); ok: accounts healthy or nothing connected (the connector is optional, not an error).
- `src/commands/doctor/checks/google-file-modes.ts` — the `google_file_modes` doctor check (ops category; a `WAVE_CHECKS` entry in `src/commands/doctor/wave-checks.ts`, `resolution: 'repair'`, host-only so remote doctor never sees host paths). Detection only: warns per Google source dir outside `~/.gbrain` with `loose_files`/`loose_dirs` counts and the exact preview and apply commands (`details.sources[]`, `details.count`, `repair: 'google-file-modes'`); never prints file names, because Gmail page names embed subject words. A scan error is `warn` with `count: 'unknown'`, never ok. Remediation runs the `google-file-modes` repair kind.
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.md
new file mode 100644
index 0000000000..593a3fe630
--- /dev/null
+++ b/docs/architecture/key-files/open-loops-engine.md
@@ -0,0 +1,14 @@
+# Open-loop engine (key files cluster)
+
+[Subsystem index](../KEY_FILES.md) · [Google connector entries](google-and-loops.md).
+
+User-facing contract: `docs/guides/open-loops.md` (detection, exclusion and
+close semantics). The Gmail sweep that feeds both lanes is in
+`google-and-loops.md` (`google-source.ts`, `loop-catchup.ts`, `loops-enqueue.ts`).
+
+- `src/core/google/loops-exclusion.ts` — the user's own label exclusion for the open-loop engine (#5445). `excludedLabelTokens` reads the source's `g_loops_exclude_labels`, else the brain-wide `loops.extraction_exclude_labels` (no merge); `resolveExcludedLabels` matches tokens against the account's label catalog (id verbatim, name case-insensitively; with no catalog only id-shaped tokens resolve) into a `LoopsExclusionPolicy { tokens, ids, unresolved }`, where a non-empty `unresolved` means FAIL CLOSED for new paid extraction. `resolveSweepExclusion` (`loops-enqueue.ts`) runs it once per Gmail sweep (one `GmailClient.getLabels` call when anything is configured), logs each unresolved name, and `storeLoopsExclusion` keeps the resolution in `op_checkpoints` (op `loops-exclusion`, keyed like the loop outcomes) so `loadLoopsExclusionPolicy` can apply the policy without a Gmail client at the two late sites: `runLoopsExtract` (skips `excluded_label`, throws retryable `excluded_label_unresolved`) and `openDueGraceHold` (`'excluded'` drops the hold, `'deferred'` keeps it). A stored resolution is reused only for the same token list; changed tokens fall back to id-only until the next sweep. The policy gates `loopExtractionEligibility` right after SPAM/TRASH and before the owner override (reasons `excluded_label` / `excluded_label_unresolved` in the sweep's counters), `withLabelExclusion` strips the opens from a `detectThreadLoop` verdict (closes untouched), `recordGraceVerdict` records no hold for an excluded thread, `runLoopsCatchup` skips with `excluded_label_unresolved`, and `enqueueLoopsExtraction` reports the same `skipped_reason` ahead of `no_candidates`. The leaf is `excluded` from connector identity. Tests: `test/loops-exclusion.test.ts`, `test/google-source-reconcile.test.ts` ("label exclusion (#5445)"), `test/loops-extract-run.serial.test.ts` ("#5445 execution-time").
+- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions.
+- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.
+- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.
+- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `loops_close` retires a commitment loop's fact through `persistence/loop-fact-retirement.ts` and returns `{ closed, id, status, fact_expired, retryable, reason? }` from the real publication outcome; a loop already closed whose fact is still active re-attempts the retirement. `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. Ranking and rendered ages use one reference time, `as_of` (ISO, default now, echoed in the grouped result; `gbrain waiting --as-of`), so a published order is reproducible (N7-5). An optional `id` (positive safe integer, else `invalid_params` through `invalidParam` without echoing the value) finds one loop at any status unless `status` is given; explicit filters still intersect, scope and redaction are unchanged, so an out-of-scope id returns exactly what a missing id returns, and an id lookup carries no `text` digest. The result carries per-source last-successful-sync ages + a `stale` flag (>24h): all stale sources remain a refusal condition for `gbrain waiting`, while a mixed fresh/stale set continues with a warning naming stale sources (`stale_sources` in JSON). Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly. #5871: grouped output ranks people only; loops with neither a counterparty slug nor an email return in `no_counterparty` (`loop_count`, `by_type`, shown loops, `loops_omitted`; null when none), never ranked or counted by `limit`, and the digest lists them last and never says "You are clean" while they exist; each group shows at most `LOOPS_PER_GROUP` (5) loops, due-soonest then most recently active, with `loops_omitted` (`test/ops-loops.test.ts`, `test/loops-cli.test.ts`).
+- `src/commands/loops.ts` — `gbrain waiting [--top N] [--json] [--stale-ok]` + `gbrain loops list|show|done|drop|mute`: all paths dispatch through the trusted-local op layer (`handleToolCall`, remote:false) so CLI and MCP share one behavior. `waiting` REFUSES when EVERY google source has gone >24h without a successful sync and prints the exact fix (`--stale-ok` bypasses; per-source sync ages are always reported); when only some sources are stale, it continues with the warning and source ids from `open_loops`. Output per counterparty: what's owed, evidence quotes, Gmail deep links, entity-card context, a paste-ready digest. Reads default to the `__all__` brain span (loops live in google sources, not `default` — a default-scoped read would say "all clean" while people wait); `--source <id>` narrows explicitly. `loops show <id>` passes the id to `open_loops` (any status and rank); a missing positive id is a usage error (exit 2) and an unknown id renders `not_found` with the `gbrain loops list` fix (exit 1). An unqualified `mute`/`unmute` resolves the brain's google source (never `default`) through the SAME resolution — an unmute can never aim at a different source than the mute it reverses — and refuses with the exact fix when none or multiple exist. `unmute sender <email> | thread <id>` is exact and forward-only; a repeated unmute is a no-op success (`removed: false`, exit 0) so scripts can call it unconditionally.
diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.md
index 3a1a367919..526c43a505 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -130,8 +130,9 @@ the brain until you remove them — they are not reconciled automatically.
## Calendar window
Calendar pages cover events from `--history-days` ago up to 60 days from
-now (`--future-days`, the `g_future_days` config key, 1..3650, moves that
-horizon per source), and each sweep applies that range on its own. That matters for
+now (`gbrain sources add … --future-days <n>`, stored as the source's
+`g_future_days`, 1..3650, moves that horizon per source), and each sweep
+applies that range on its own. That matters for
incremental syncs: after any edit to a recurring series, Google sends back
the series' instances for years before and after, and only those inside the
range are kept. Because the 60-day edge moves forward daily, the sweep also
@@ -205,7 +206,11 @@ calendar pages."*
On a managed brain the first sweep also runs a one-time catch-up over email
threads whose newest message is from the last 30 days, so threads synced
before extraction was queued are analyzed once; it finishes over later
- sweeps when the enqueue ceiling binds.
+ sweeps when the enqueue ceiling binds. Threads under a label you listed in
+ `g_loops_exclude_labels` (or the brain-wide `loops.extraction_exclude_labels`)
+ are never queued and open no deterministic loop; an unknown label name
+ fails closed with `excluded_label_unresolved` until you fix it. See
+ [open loops](open-loops.md#which-threads-reach-the-extractor).
- **Quiet threads.** A thread still inside its waiting window (24 h for
inbound, 72 h for your own question) is re-checked when the window ends,
even if no new mail arrives, and opens its loop then. See
diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.md
index 167fc3fd87..c20d992e9c 100644
--- a/docs/guides/open-loops.md
+++ b/docs/guides/open-loops.md
@@ -111,6 +111,7 @@ calls nor crowds real correspondence out of the sweep:
| `CATEGORY_PROMOTIONS` / `CATEGORY_SOCIAL` / `CATEGORY_FORUMS` (one shared list, `gmail-categories.ts`, applied by both lanes) | no, unless the owner joined in |
| `List-Unsubscribe` bulk | no, unless the owner joined in |
| `CATEGORY_UPDATES` | **yes** — invoices, contracts and document requests live there |
+| a label you excluded (`g_loops_exclude_labels` on the source, else the brain-wide `loops.extraction_exclude_labels`) | no — even when you joined in (`excluded_label`) |
| ordinary human correspondence | yes |
The owner-participated rule is the load-bearing one: your own outbound
@@ -122,6 +123,43 @@ vendor list to maintain. The sweep logs per-reason counts
(`loops_extract eligibility:`) so a run can be audited for over-filtering
without mail content reaching the logs.
+**Your own exclusions** (#5445). Some mail is yours and still not a
+commitment: a recruiting agency's label, a vendor-notification label, a
+newsletter label you never unsubscribe from. Name those labels once and
+no thread under them enters paid extraction or opens a deterministic
+loop:
+
+```bash
+gbrain sources add <id> --kind google --account [email protected] \
+ --loops-exclude-labels "Newsletters, Recruiting/Agencies" # per source (g_loops_exclude_labels)
+gbrain config set loops.extraction_exclude_labels "Label_7" # brain-wide, for every source without its own list
+```
+
+Names or Gmail label ids both work (a source's own list wins over the
+brain-wide key; the lists do not merge). The brain-wide key is the way to
+change the exclusion of a source that already exists, and it takes effect on
+the next sweep. Every sweep resolves the names
+against the account's labels exactly once, stores the resolution, and
+applies it at **all three** points a thread can reach the extractor: the
+sweep's own enqueue, the managed catch-up, and the job itself when it
+runs (so a label you add after a job was queued still stops it before the
+model call, `skipped: excluded_label`). The deterministic detector withholds
+new opens on an excluded thread and a grace hold that comes due under a now
+excluded label is dropped without opening; a close is never withheld, an
+already-open loop is never touched, and the email page still imports. The
+exclusion sits above the owner-participated override: replying inside an
+excluded label does not buy the thread back.
+
+A name that is not one of the account's labels, or a label list Gmail
+would not return this sweep, **fails closed**: the sweep logs
+`"<name>" is not a label of <account>`, every candidate counts as
+`excluded_label_unresolved`, nothing is queued (`loops_enqueue.skipped_reason`
+says why), a queued job retries instead of running, and a due grace hold is
+kept for the next sweep. Fix the name (or delete the token) and the next
+sweep picks up where it left off; nothing was spent in between. An id-shaped
+token (`Label_12`, `CATEGORY_FORUMS`) still applies when the list cannot be
+read.
+
**Every eligible thread is queued** (newest first — ordering only, nothing is
dropped for being older). The MinionQueue is the backlog and the worker's
concurrency is the rate limit (a thread only re-candidates when it changes,
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index d4645d58cb..5aabb5158f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -30,13 +30,13 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch; +7 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms read once and passed to the oneshot and gateway-loop paths (resolver lives in minions/handler-timeouts.ts)
src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)
-src/commands/sources.ts 2054 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row
+src/commands/sources.ts 2077 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts); +4 #6188: uncommitted legacy fence-repair notices in sources status (logic in fence-repair/uncommitted.ts); +7 #6317: data_moving/movement_state on sources status and its human line (reader in persistence/sync-movement.ts), writer movement help row; +23 W14 P4.2/P4.6a (#5442, #5445): `sources add --future-days` and `--loops-exclude-labels` on the legacy google parser plus their help line (validation constants live in google/calendar-window.ts and google/loops-exclusion.ts)
src/core/link-extraction.ts 2358 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +1 fix wave 11 #6191: imports targetTakesVerb (role-verb target guard lives in link-target-roles.ts); v0.60.105.0 merge: #5984 Phase 5 link preparation (+6) re-summed over wave 11 at 2211; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkType; +4 U3: board-seat rule split out of INVESTED_RE (same verb and precedence) and investor-prior/link offsets passed to unit vetoes; +11 U2: locateLink shared by attachedVerb and the U2 post-pass in traceLinkType; -11 lowered: Q2 verdict reverted U2 (locateLink and the post-pass)
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1926 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import
src/core/chunkers/code.ts 1598 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate)
-src/core/config.ts 1932 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
+src/core/config.ts 1935 ratchet +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +3 W14 P4.6a #5445: loops.extraction_exclude_labels key row (resolver in google/loops-exclusion.ts)
src/core/bootstrap/harness.ts 2610 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 683 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
diff --git a/src/commands/sources-google-flags.ts b/src/commands/sources-google-flags.ts
new file mode 100644
index 0000000000..4a45066529
--- /dev/null
+++ b/src/commands/sources-google-flags.ts
@@ -0,0 +1,57 @@
+/**
+ * The Google-kind tuning flags of the legacy `gbrain sources add` parser
+ * (`--history-days`, `--future-days`, `--loops-exclude-labels`,
+ * `--calendar-id`): one value each, validated the moment they are read.
+ * The connected-source parser (sources-lifecycle-args.ts) validates the same
+ * flags through the operation contract; this module keeps the legacy path's
+ * exit-2 behaviour without growing runAdd.
+ */
+import { CALENDAR_FUTURE_DAYS_MAX } from '../core/google/calendar-window.ts';
+import { parseExcludeLabelTokens } from '../core/google/loops-exclusion.ts';
+import { DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
+
+export interface GoogleAddTuning {
+ historyDays: number;
+ calendarId: string;
+ futureDays?: number;
+ loopsExcludeLabels?: string[];
+}
+
+export const defaultGoogleAddTuning = (): GoogleAddTuning => ({ historyDays: 90, calendarId: DEFAULT_CALENDAR_ID });
+
+const refuse = (message: string): never => {
+ console.error(message);
+ process.exit(2);
+};
+
+/** Consumes `flag` with its `value` into `tuning`; false when the flag is not a Google tuning flag. */
+export function parseGoogleAddFlag(flag: string, value: string | undefined, tuning: GoogleAddTuning): boolean {
+ switch (flag) {
+ case '--history-days': {
+ const v = Number(value);
+ if (!Number.isInteger(v) || v <= 0) refuse('--history-days must be a positive integer.');
+ tuning.historyDays = v;
+ return true;
+ }
+ case '--future-days': {
+ const v = Number(value);
+ if (!Number.isInteger(v) || v <= 0 || v > CALENDAR_FUTURE_DAYS_MAX) refuse(`--future-days must be a whole number between 1 and ${CALENDAR_FUTURE_DAYS_MAX}.`);
+ tuning.futureDays = v;
+ return true;
+ }
+ case '--loops-exclude-labels': {
+ const labels = parseExcludeLabelTokens(value);
+ if (labels.length === 0) refuse('--loops-exclude-labels needs a comma-separated list of Gmail label names or ids.');
+ tuning.loopsExcludeLabels = labels;
+ return true;
+ }
+ case '--calendar-id': {
+ const v = (value ?? '').trim();
+ if (!v) refuse('--calendar-id needs a value (see: gbrain google calendars).');
+ tuning.calendarId = v;
+ return true;
+ }
+ default:
+ return false;
+ }
+}
diff --git a/src/commands/sources-lifecycle-args.ts b/src/commands/sources-lifecycle-args.ts
index 35920f61ae..9ee53b3275 100644
--- a/src/commands/sources-lifecycle-args.ts
+++ b/src/commands/sources-lifecycle-args.ts
@@ -9,6 +9,8 @@ import { isWriteRequestId } from '../core/persistence/types.ts';
import { defaultCloneDir, type AddSourceOpts } from '../core/sources-ops.ts';
import { isValidRepoName } from '../core/github-source.ts';
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
+import { CALENDAR_FUTURE_DAYS_MAX, CALENDAR_HORIZON_DAYS } from '../core/google/calendar-window.ts';
+import { parseExcludeLabelTokens } from '../core/google/loops-exclusion.ts';
export const SOURCE_LIFECYCLE_COMMANDS = ['add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'] as const;
export function isSourceLifecycleCommand(value: string): boolean {
@@ -38,7 +40,7 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
'federated', 'no-federated', 'no-federate', 'refederate', 'no-harden']);
const valued = new Set(['request-id', 'expected-incarnation', 'brain', 'path', 'url', 'name', 'clone-dir',
'pat-file', 'kind', 'account', 'access', 'token-command', 'token-env', 'services', 'history-days',
- 'calendar-id', 'scope', 'repos', 'dir', 'app-id', 'app-pem', 'app-install']);
+ 'future-days', 'loops-exclude-labels', 'calendar-id', 'scope', 'repos', 'dir', 'app-id', 'app-pem', 'app-install']);
for (let i = 0; i < rest.length; i++) {
const token = rest[i];
if (!token.startsWith('-')) { positionals.push(token); continue; }
@@ -103,7 +105,7 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
'Pass --kind github or --kind google; a directory or Git remote source uses --path or --url instead of --kind.');
if ([values.has('path'), values.has('url'), kind !== undefined].filter(Boolean).length > 1) throw invalid('--path, --url and --kind are mutually exclusive.',
'Give exactly one of --path (a local directory), --url (an https Git remote) or --kind (github or google).');
- const googleOnly = ['account', 'access', 'token-command', 'services', 'history-days', 'calendar-id'];
+ const googleOnly = ['account', 'access', 'token-command', 'services', 'history-days', 'future-days', 'loops-exclude-labels', 'calendar-id'];
const githubOnly = ['scope', 'repos', 'app-id', 'app-pem', 'app-install'];
const kindOptions = [...googleOnly, ...githubOnly, 'dir', 'token-env'];
for (const key of kindOptions) if (values.has(key) && !kind) throw invalid(`--${key} requires --kind github or google.`,
@@ -150,7 +152,14 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
throw invalid('Google access must be vault, command with --token-command, or env with --token-env.',
'Use --access vault (the default, with no token flags), --access command with --token-command, or --access env with --token-env.');
}
+ const futureDays = number('future-days');
+ if (futureDays !== undefined && futureDays > CALENDAR_FUTURE_DAYS_MAX) throw invalid(`--future-days must be at most ${CALENDAR_FUTURE_DAYS_MAX}.`,
+ `Pass --future-days between 1 and ${CALENDAR_FUTURE_DAYS_MAX} (days ahead the calendar sweep covers; default ${CALENDAR_HORIZON_DAYS}).`);
+ const loopsExcludeLabels = parseExcludeLabelTokens(values.get('loops-exclude-labels'));
+ if (values.has('loops-exclude-labels') && loopsExcludeLabels.length === 0) throw invalid('--loops-exclude-labels needs at least one label.',
+ 'Pass --loops-exclude-labels as a comma-separated list of Gmail label names or ids, e.g. --loops-exclude-labels "Newsletters,Label_7".');
opts.google = { account, services, historyDays: number('history-days', 90)!, calendarId: values.get('calendar-id') ?? DEFAULT_CALENDAR_ID,
+ ...(futureDays !== undefined ? { futureDays } : {}), ...(loopsExcludeLabels.length > 0 ? { loopsExcludeLabels } : {}),
dir: absolute(values.get('dir') ?? defaultCloneDir(`${id}-google`)), access: access as 'vault' | 'command' | 'env',
tokenCommand: values.get('token-command'), tokenEnv: values.get('token-env') };
}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 26c28ed4a8..382f5dc988 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -55,6 +55,7 @@ import {
} from '../core/sources-ops.ts';
import { isValidRepoName } from '../core/github-source.ts';
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID } from '../core/google/types.ts';
+import { defaultGoogleAddTuning, parseGoogleAddFlag } from './sources-google-flags.ts';
import {
resolveSourceWithTier,
SOURCE_TIER_NAMES,
@@ -143,7 +144,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
'[--repos owner/name,...] [--dir <path>] ' +
'[--app-id <n> --app-pem <path>] [--app-install <n>]\n' +
' google kind: --account <email> [--services gmail,calendar,contacts] ' +
- '[--history-days <n>] [--calendar-id <id>] [--dir <path>] (connect first: gbrain google connect)\n' +
+ '[--history-days <n>] [--future-days <n>] [--loops-exclude-labels <a,b>] [--calendar-id <id>] [--dir <path>] (connect first: gbrain google connect)\n' +
' [--access vault|command|env] [--token-command "<cmd>"] [--token-env <VAR>] (non-vault Google access: gog/gcloud/gateway)',
);
process.exit(2);
@@ -173,8 +174,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
let gTokenCommand: string | undefined;
let gTokenEnv: string | undefined;
let gServices: string[] = ['gmail', 'calendar', 'contacts'];
- let gHistoryDays = 90;
- let gCalendarId: string = DEFAULT_CALENDAR_ID;
+ const gTuning = defaultGoogleAddTuning();
for (let i = 1; i < args.length; i++) {
const a = args[i];
@@ -218,24 +218,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
.filter(Boolean);
continue;
}
- if (a === '--history-days') {
- const v = Number(args[++i]);
- if (!Number.isInteger(v) || v <= 0) {
- console.error('--history-days must be a positive integer.');
- process.exit(2);
- }
- gHistoryDays = v;
- continue;
- }
- if (a === '--calendar-id') {
- const v = (args[++i] ?? '').trim();
- if (!v) {
- console.error('--calendar-id needs a value (see: gbrain google calendars).');
- process.exit(2);
- }
- gCalendarId = v;
- continue;
- }
+ if (parseGoogleAddFlag(a, args[i + 1], gTuning)) { i++; continue; }
if (a === '--scope') {
const scope = args[++i];
if (scope !== 'auto' && scope !== 'repos') {
@@ -327,7 +310,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
// one calendar per source is how secondary calendars are ingested.
const existingCal =
typeof c.g_calendar_id === 'string' && c.g_calendar_id.trim() ? c.g_calendar_id.trim() : DEFAULT_CALENDAR_ID;
- if (existingCal !== gCalendarId) overlap = overlap.filter((s) => s !== 'calendar');
+ if (existingCal !== gTuning.calendarId) overlap = overlap.filter((s) => s !== 'calendar');
if (overlap.length === 0) return false;
overlapNote = overlap.join(', ');
return true;
@@ -432,8 +415,7 @@ async function runAdd(engine: BrainEngine, args: string[]): Promise<void> {
google: {
account: gAccount!,
services: gServices,
- historyDays: gHistoryDays,
- calendarId: gCalendarId,
+ ...gTuning,
dir: ghDir ?? defaultCloneDir(`${id}-google`),
access: (gAccess ?? 'vault') as 'vault' | 'command' | 'env',
tokenCommand: gTokenCommand,
diff --git a/src/core/config.ts b/src/core/config.ts
index ae149dc029..090595a80c 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1453,6 +1453,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// google-source email pages (default ON for google sources; deterministic
// thread detection is unaffected). `gbrain config set loops.extraction_enabled false`.
'loops.extraction_enabled',
+ // #5445: brain-wide Gmail labels (names or ids, comma/JSON list) whose threads
+ // never enter paid loop extraction; a source's g_loops_exclude_labels wins.
+ 'loops.extraction_exclude_labels',
// #2113: output-token cap for the per-turn facts extractor (default 4000).
'facts.extraction_max_tokens',
// Automatic facts drain caps (src/core/facts/drain.ts FACTS_DRAIN_KEYS).
diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.ts
index f80534c966..d88140f00b 100644
--- a/src/core/google/google-clients.ts
+++ b/src/core/google/google-clients.ts
@@ -324,6 +324,12 @@ export class GmailClient extends GoogleApiClient {
return this.fetchJSON(`${GMAIL_BASE}/users/me/profile`, 'gmail', opts);
}
+ /** The account's labels (system and user), for resolving `g_loops_exclude_labels` names to ids once per sweep (#5445). */
+ async getLabels(opts: { signal?: AbortSignal } = {}): Promise<Array<{ id: string; name: string; type: string }>> {
+ const body = await this.fetchJSON<{ labels?: Array<{ id?: string; name?: string; type?: string }> }>(`${GMAIL_BASE}/users/me/labels`, 'gmail', opts);
+ return (body.labels ?? []).flatMap((l) => typeof l.id === 'string' && typeof l.name === 'string' ? [{ id: l.id, name: l.name, type: l.type ?? 'user' }] : []);
+ }
+
/** Message ids matching a Gmail search query (includes SENT; excludes SPAM/TRASH). */
async listMessageIds(
q: string,
diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.ts
index 8a27df36ef..710c715cc2 100644
--- a/src/core/google/google-source.ts
+++ b/src/core/google/google-source.ts
@@ -44,7 +44,8 @@ import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';
import { importRendered, myAddressSet, type ActivePack, type GoogleSyncDeps, type GoogleSyncSummary } from './sweep-shared.ts';
export { myAddressSet } from './sweep-shared.ts';
import { sweepCalendar, sweepContacts } from './people-calendar-sweep.ts';
-import { applyLoopDetection, enqueueLoopsExtraction } from './loops-enqueue.ts';
+import { applyLoopDetection, enqueueLoopsExtraction, resolveSweepExclusion } from './loops-enqueue.ts';
+import { NO_EXCLUSION } from './loops-exclusion.ts';
import {
CalendarClient,
GmailClient,
@@ -185,7 +186,7 @@ async function processThread(
}
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);
+ if (verdict && deps.loopState) recordGraceVerdict(deps.loopState, thread, verdict, slug, myAddressSet(deps.entry), deps.log, deps.exclusion);
// 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;
@@ -194,7 +195,7 @@ async function processThread(
// Structural eligibility, not "everything recent": bulk mail the owner
// never joined would otherwise both pay for model calls AND crowd real
// threads out of the sweep.
- const verdict = loopExtractionEligibility(thread, myAddressSet(deps.entry));
+ const verdict = loopExtractionEligibility(thread, myAddressSet(deps.entry), deps.exclusion);
summary.extractEligibility[verdict.reason] =
(summary.extractEligibility[verdict.reason] ?? 0) + 1;
if (verdict.eligible) {
@@ -450,7 +451,7 @@ async function settleGraceHolds(g: GmailSweep): Promise<'aborted' | void> {
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) => {
+ exclusion: deps.exclusion, processed: deps.processedThreads, refetch: async (tid) => {
try {
await processThread(deps, g.gmail, tid, g.activePack, g.summary, g.countedSlugs);
return 'ok';
@@ -729,7 +730,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
const people = new PeopleClient(...clientArgs);
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
const tick = (note: string): void => progress.tick(1, note);
- const deps: GoogleSyncDeps = { engine, sourceId, cfg, opts, entry, log, tick, extractCandidates: [], managed, processedThreads: new Set() };
+ const deps: GoogleSyncDeps = { engine, sourceId, cfg, opts, entry, log, tick, exclusion: NO_EXCLUSION, extractCandidates: [], managed, processedThreads: new Set() };
const summary: GoogleSyncSummary = {
status: 'synced',
@@ -827,6 +828,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
if (activeServices.includes('gmail')) {
const stop = startHeartbeat(progress, 'gmail sweep');
try {
+ deps.exclusion = await resolveSweepExclusion(deps, gmail);
// sweepGmail reports thread-level failures via its return value —
// they exit through normal returns, not throws, and stamping
// last_sync_at over them would blind the staleness gate (H1).
@@ -860,7 +862,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go
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)),
+ exclusion: deps.exclusion, 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; }
diff --git a/src/core/google/loop-catchup.ts b/src/core/google/loop-catchup.ts
index c740a8b8c4..c8d1005871 100644
--- a/src/core/google/loop-catchup.ts
+++ b/src/core/google/loop-catchup.ts
@@ -35,6 +35,7 @@ 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 { NO_EXCLUSION, type LoopsExclusionPolicy } from './loops-exclusion.ts';
import type { GmailThreadData, GoogleSourceState, LoopGraceHold } from './types.ts';
export const GRACE_HOLDS_CAP = 2_000;
@@ -49,9 +50,9 @@ type Log = (msg: string) => void;
/** 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 {
+ slug: string | null, myAddresses: Set<string>, log: Log, exclusion: LoopsExclusionPolicy = NO_EXCLUSION): void {
const holds = state.loop_grace_holds ??= {};
- if (verdict.held && loopExtractionEligibility(thread, myAddresses).eligible) {
+ if (verdict.held && loopExtractionEligibility(thread, myAddresses, exclusion).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,
@@ -108,7 +109,7 @@ export type GraceRefetch = (threadId: string) => Promise<'ok' | 'gone' | 'failed
*/
export async function settleDueGraceHolds(ctx: {
engine: BrainEngine; sourceId: string; state: GoogleSourceState; log: Log; signal?: AbortSignal;
- processed: Set<string>; refetch: GraceRefetch; now?: number;
+ processed: Set<string>; refetch: GraceRefetch; now?: number; exclusion?: LoopsExclusionPolicy;
}): Promise<{ opened: number; refetched: number; deferred: number } | 'aborted'> {
const holds = ctx.state.loop_grace_holds ?? {};
const now = ctx.now ?? Date.now();
@@ -117,7 +118,10 @@ export async function settleDueGraceHolds(ctx: {
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++;
+ // #5445: an unresolved exclusion keeps the hold (and its spec) for the next sweep; nothing is published.
+ const outcome = await openDueGraceHold(ctx.engine, ctx.sourceId, tid, hold.spec, hold.slug, ctx.exclusion ?? NO_EXCLUSION);
+ if (outcome === 'deferred') { result.deferred++; continue; }
+ if (outcome === 'opened') result.opened++;
delete holds[tid];
continue;
}
@@ -221,6 +225,8 @@ export async function runLoopsCatchup(ctx: {
myAddresses: Set<string>; fetchThread: (threadId: string) => Promise<GmailThreadData | null>; now?: number;
/** Pages this sweep already queues through the normal enqueue. */
inFlight: Set<string>;
+ /** #5445: the sweep's resolved label exclusion; unresolved fails closed for every candidate. */
+ exclusion?: LoopsExclusionPolicy;
}): Promise<LoopsEnqueueReport | null> {
if (ctx.state.loops_catchup?.done) return null;
const now = ctx.now ?? Date.now();
@@ -229,6 +235,10 @@ export async function runLoopsCatchup(ctx: {
return { enqueued: 0, deferred: 0, skipped_reason: reason };
};
if (!(await isLoopsExtractionEnabled(ctx.engine))) return skip('extraction_disabled', 'loops.extraction_enabled is off');
+ const exclusion = ctx.exclusion ?? NO_EXCLUSION;
+ if (exclusion.unresolved.length > 0) {
+ return skip('excluded_label_unresolved', `loop exclusion labels ${exclusion.unresolved.map((t) => JSON.stringify(t)).join(', ')} did not resolve`);
+ }
const { isAvailable } = await import('../ai/gateway.ts');
if (!isAvailable('chat')) return skip('chat_unavailable', 'no configured chat model / API key');
@@ -288,7 +298,7 @@ export async function runLoopsCatchup(ctx: {
continue;
}
if (!thread) { await settle(c.slug, c.rev, 'skipped:thread_not_found'); continue; }
- const verdict = loopExtractionEligibility(thread, ctx.myAddresses);
+ const verdict = loopExtractionEligibility(thread, ctx.myAddresses, exclusion);
if (!verdict.eligible) { await settle(c.slug, c.rev, `skipped:ineligible_${verdict.reason}`); continue; }
await enqueue(c, key);
unsettled++;
diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.ts
index 2966c66980..28585001cf 100644
--- a/src/core/google/loop-detect.ts
+++ b/src/core/google/loop-detect.ts
@@ -44,6 +44,7 @@ import {
} from '../loops/loops-store.ts';
import { isCalendarSystemMail, isNoiseSender } from './google-render.ts';
import { hasBulkCategory } from './gmail-categories.ts';
+import { isExcludedByLabels, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';
import type { GmailMessageMeta, GmailThreadData } from './types.ts';
export const INBOUND_GRACE_HOURS = 24;
@@ -289,13 +290,15 @@ export async function applyThreadLoopVerdict(
myAddresses: Set<string>,
pageSlug: string | null,
now: Date = new Date(),
+ exclusion: LoopsExclusionPolicy = NO_EXCLUSION,
): 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
// type); `open` is suppression-filtered. A held loop (grace window,
// CC-only nudge, muted sender) is neither opened nor closed.
- const verdict = detectThreadLoop(thread, myAddresses, now, suppressions);
+ const verdict = withLabelExclusion(detectThreadLoop(thread, myAddresses, now, suppressions), exclusion,
+ thread.messages.flatMap((m) => m.labelIds));
const desired = new Set(verdict.open.map((s) => s.loopType));
const toClose = verdict.close.filter((t) => !desired.has(t));
@@ -307,10 +310,23 @@ export async function applyThreadLoopVerdict(
return verdict;
}
+/**
+ * #5445: the label exclusion applied to a verdict. An excluded thread opens
+ * nothing and holds nothing; an unresolved policy withholds the same way
+ * (fail closed) until a sweep resolves it. Closes are never touched: the
+ * exclusion withholds opens, it does not fabricate replies.
+ */
+export function withLabelExclusion(verdict: ThreadLoopVerdict, exclusion: LoopsExclusionPolicy, labelIds: Iterable<string>): ThreadLoopVerdict {
+ if (!isExcludedByLabels(exclusion, labelIds) && exclusion.unresolved.length === 0) return verdict;
+ return { open: [], close: verdict.close };
+}
+
/**
* #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.
+ * thread, from the spec its last detection produced. Suppressions and the
+ * label exclusion are re-read so a mute or a label added during the hold
+ * still withholds the open (`'excluded'`); an unresolved exclusion keeps the
+ * hold for the next sweep (`'deferred'`).
*/
export async function openDueGraceHold(
engine: BrainEngine,
@@ -318,11 +334,17 @@ export async function openDueGraceHold(
threadId: string,
spec: ThreadLoopSpec,
pageSlug: string | null,
-): Promise<boolean> {
+ exclusion: LoopsExclusionPolicy = NO_EXCLUSION,
+): Promise<'opened' | 'suppressed' | 'excluded' | 'deferred'> {
const suppressions = await suppressionsFor(engine, sourceId);
- if (suppressions.threads.has(threadId) || suppressions.senders.has(spec.counterpartyEmail)) return false;
+ if (suppressions.threads.has(threadId) || suppressions.senders.has(spec.counterpartyEmail)) return 'suppressed';
+ if (exclusion.ids.size > 0 || exclusion.unresolved.length > 0) {
+ const page = pageSlug ? await engine.getPage(pageSlug, { sourceId }) : null;
+ if (isExcludedByLabels(exclusion, pageLabelIds(page?.frontmatter as Record<string, unknown> | undefined))) return 'excluded';
+ if (exclusion.unresolved.length > 0) return 'deferred';
+ }
await upsertThreadLoop(engine, sourceId, threadId, spec, pageSlug);
- return true;
+ return 'opened';
}
async function upsertThreadLoop(
diff --git a/src/core/google/loops-enqueue.ts b/src/core/google/loops-enqueue.ts
index d248eea84e..b924e4e364 100644
--- a/src/core/google/loops-enqueue.ts
+++ b/src/core/google/loops-enqueue.ts
@@ -7,6 +7,37 @@ import type { GmailThreadData } from './types.ts';
import type { ThreadLoopVerdict } from './loop-detect.ts';
import { pendingLoopsExtractDepth, type LoopsEnqueueReport } from './loop-catchup.ts';
import { myAddressSet, type GoogleSyncDeps } from './sweep-shared.ts';
+import type { GmailClient } from './google-clients.ts';
+import { excludedLabelTokens, NO_EXCLUSION, resolveExcludedLabels, storeLoopsExclusion, type LoopsExclusionPolicy } from './loops-exclusion.ts';
+
+/**
+ * #5445: resolves the source's loop exclusion labels once per sweep (one
+ * `getLabels` call when anything is configured), stores the resolution for
+ * the job handler and the hold publication, and names every unresolved
+ * label on stderr. A failed label list resolves id tokens only, so names
+ * stay unresolved and the sweep fails closed for new paid extraction.
+ */
+export async function resolveSweepExclusion(deps: Pick<GoogleSyncDeps, 'engine' | 'sourceId' | 'cfg' | 'opts' | 'log'>, gmail: Pick<GmailClient, 'getLabels'>): Promise<LoopsExclusionPolicy> {
+ const tokens = await excludedLabelTokens(deps.engine, deps.cfg);
+ if (tokens.length === 0) return NO_EXCLUSION;
+ let catalog: Array<{ id: string; name: string }> | null = null;
+ try {
+ catalog = await gmail.getLabels(deps.opts.signal ? { signal: deps.opts.signal } : {});
+ } catch (e) {
+ deps.log(`[google] loop exclusion: could not read the account's labels (${e instanceof Error ? e.message : String(e)}); label names stay unresolved this sweep`);
+ }
+ const policy = resolveExcludedLabels(tokens, catalog);
+ if (policy.unresolved.length > 0) {
+ deps.log(`[google] loop exclusion: ${policy.unresolved.map((t) => JSON.stringify(t)).join(', ')} ${policy.unresolved.length === 1 ? 'is not a label' : 'are not labels'} of ${deps.cfg.account}; ` +
+ 'no new loop extraction runs for this source until the names resolve (excluded_label_unresolved)');
+ }
+ try {
+ await storeLoopsExclusion(deps.engine, deps.sourceId, policy);
+ } catch (e) {
+ deps.log(`[google] loop exclusion: could not store the resolution (${e instanceof Error ? e.message : String(e)})`);
+ }
+ return policy;
+}
/**
* Enqueue loops_extract jobs for every eligible candidate in this sweep, in
@@ -15,6 +46,12 @@ import { myAddressSet, type GoogleSyncDeps } from './sweep-shared.ts';
*/
export async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<LoopsEnqueueReport> {
const report: LoopsEnqueueReport = { enqueued: 0, deferred: 0, skipped_reason: null };
+ // #5445: an unresolved exclusion never reaches the queue; the report names
+ // the real reason rather than the empty candidate list it produced.
+ if (deps.exclusion.unresolved.length > 0) {
+ deps.log('[google] loops_extract: exclusion labels unresolved — nothing enqueued this sweep (excluded_label_unresolved)');
+ return { ...report, skipped_reason: 'excluded_label_unresolved' };
+ }
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' };
@@ -113,7 +150,7 @@ export async function applyLoopDetection(
): Promise<ThreadLoopVerdict | null> {
try {
const { applyThreadLoopVerdict } = await import('./loop-detect.ts');
- return await applyThreadLoopVerdict(deps.engine, deps.sourceId, thread, myAddressSet(deps.entry), pageSlug);
+ return await applyThreadLoopVerdict(deps.engine, deps.sourceId, thread, myAddressSet(deps.entry), pageSlug, new Date(), deps.exclusion);
} 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)}`);
diff --git a/src/core/google/loops-exclusion.ts b/src/core/google/loops-exclusion.ts
new file mode 100644
index 0000000000..7d766235e3
--- /dev/null
+++ b/src/core/google/loops-exclusion.ts
@@ -0,0 +1,144 @@
+/**
+ * loops-exclusion — the Gmail-label exclusion policy for the open-loop engine
+ * (#5445). A user labels threads the engine must leave alone (mailbox warm-up
+ * mail the owner's own address sends, automated outreach) and names those
+ * labels per source (`g_loops_exclude_labels`, comma-separated label names or
+ * ids) or brain-wide (`loops.extraction_exclude_labels`, the fallback when
+ * the source sets nothing).
+ *
+ * The policy is resolved ONCE per sweep (`GmailClient.getLabels()` turns
+ * names into ids) and the resolution is stored next to the source
+ * (`op_checkpoints`, op `loops-exclusion`), so the two places that run
+ * without a Gmail client, the paid `loops_extract` job and the due-grace-hold
+ * publication, apply the policy that is current at THEIR time, not the one
+ * current at enqueue: a label added after a job was queued still stops it.
+ *
+ * Fail closed: a label name the account does not have, or a label list that
+ * could not be read, leaves the policy `unresolved`. While it is, no NEW paid
+ * extraction runs for that source (`excluded_label_unresolved`, visible in
+ * the sweep's eligibility counters and retried on the next sweep), and the
+ * deterministic lane withholds new opens the same way. Closes, ingestion and
+ * already-open loops are never touched by this policy.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { connectorStateKey } from '../persistence/connector-state.ts';
+import type { GoogleSourceConfig } from './types.ts';
+
+export const LOOPS_EXCLUDE_LABELS_CONFIG_KEY = 'loops.extraction_exclude_labels';
+export const LOOPS_EXCLUSION_OP = 'loops-exclusion';
+
+export interface LoopsExclusionPolicy {
+ /** The configured tokens (names or ids), in config order, de-duplicated. */
+ tokens: string[];
+ /** Label ids the policy excludes. */
+ ids: ReadonlySet<string>;
+ /** Tokens that could not be matched to a label; non-empty means fail closed. */
+ unresolved: string[];
+}
+
+/** The policy of a source with nothing configured. */
+export const NO_EXCLUSION: LoopsExclusionPolicy = Object.freeze({ tokens: [], ids: new Set<string>(), unresolved: [] });
+
+/** Gmail's fixed system label ids; every other id is a user label `Label_<n>`. */
+const SYSTEM_LABEL_IDS = new Set(['INBOX', 'SENT', 'DRAFT', 'SPAM', 'TRASH', 'UNREAD', 'STARRED', 'IMPORTANT', 'CHAT',
+ 'CATEGORY_PERSONAL', 'CATEGORY_SOCIAL', 'CATEGORY_PROMOTIONS', 'CATEGORY_UPDATES', 'CATEGORY_FORUMS']);
+/** A token that is certainly a label id, so it resolves without a catalog. */
+const isLabelId = (token: string): boolean => /^Label_\d+$/.test(token) || SYSTEM_LABEL_IDS.has(token);
+
+/** Splits a raw config value (comma-separated, or an array) into trimmed, de-duplicated tokens. */
+export function parseExcludeLabelTokens(raw: unknown): string[] {
+ const parts = Array.isArray(raw) ? raw.map(String) : typeof raw === 'string' ? raw.split(',') : [];
+ return [...new Set(parts.map((t) => t.trim()).filter((t) => t.length > 0))];
+}
+
+/** The tokens in force for a source: its own `g_loops_exclude_labels`, else the brain-wide key. */
+export async function excludedLabelTokens(engine: Pick<BrainEngine, 'getConfig'>, cfg: Pick<GoogleSourceConfig, 'loopsExcludeLabels'>): Promise<string[]> {
+ if (cfg.loopsExcludeLabels && cfg.loopsExcludeLabels.length > 0) return [...cfg.loopsExcludeLabels];
+ try {
+ return parseExcludeLabelTokens(await engine.getConfig(LOOPS_EXCLUDE_LABELS_CONFIG_KEY));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Matches tokens against the account's label catalog: an id token is kept
+ * verbatim; a name token matches a label name case-insensitively. With no
+ * catalog (the label list failed), only id-shaped tokens resolve and every
+ * name stays unresolved.
+ */
+export function resolveExcludedLabels(tokens: string[], catalog: ReadonlyArray<{ id: string; name: string }> | null): LoopsExclusionPolicy {
+ const ids = new Set<string>();
+ const unresolved: string[] = [];
+ const byId = new Set((catalog ?? []).map((l) => l.id));
+ const byName = new Map((catalog ?? []).map((l) => [l.name.toLowerCase(), l.id] as const));
+ for (const token of tokens) {
+ if (byId.has(token)) { ids.add(token); continue; }
+ const named = byName.get(token.toLowerCase());
+ if (named !== undefined) { ids.add(named); continue; }
+ if (catalog === null && isLabelId(token)) { ids.add(token); continue; }
+ unresolved.push(token);
+ }
+ return { tokens: [...tokens], ids, unresolved };
+}
+
+/** Whether a thread carrying `labelIds` is excluded by the policy. */
+export function isExcludedByLabels(policy: LoopsExclusionPolicy, labelIds: Iterable<string>): boolean {
+ if (policy.ids.size === 0) return false;
+ for (const id of labelIds) if (policy.ids.has(id)) return true;
+ return false;
+}
+
+/** The label ids a rendered email page carries (`labels:` frontmatter). */
+export function pageLabelIds(frontmatter: Record<string, unknown> | null | undefined): string[] {
+ const labels = frontmatter?.labels;
+ return Array.isArray(labels) ? labels.filter((l): l is string => typeof l === 'string') : [];
+}
+
+interface StoredResolution { version: 1; tokens: string[]; ids: string[]; unresolved: string[]; at: string }
+
+async function resolutionKey(engine: Pick<BrainEngine, 'executeRaw'>, 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;
+}
+
+/** Stores the sweep's resolution so the job handler and hold publication can apply it without a Gmail call. */
+export async function storeLoopsExclusion(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, policy: LoopsExclusionPolicy): Promise<void> {
+ const key = await resolutionKey(engine, sourceId);
+ if (!key) return;
+ const stored: StoredResolution = { version: 1, tokens: policy.tokens, ids: [...policy.ids], unresolved: policy.unresolved, at: new Date().toISOString() };
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,jsonb_build_array($3::text::jsonb))
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=jsonb_build_array($3::text::jsonb), updated_at=now()`,
+ [LOOPS_EXCLUSION_OP, key, JSON.stringify(stored)]);
+}
+
+/**
+ * The policy in force for a source right now, without a Gmail client: the
+ * configured tokens, resolved through the sweep's stored resolution when it
+ * was made for the same tokens. Tokens changed since the last sweep resolve
+ * by id shape only; their names stay unresolved (fail closed) until a sweep
+ * re-reads the label list.
+ */
+export async function loadLoopsExclusionPolicy(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceId: string,
+ cfg?: Pick<GoogleSourceConfig, 'loopsExcludeLabels'>): Promise<LoopsExclusionPolicy> {
+ let sourceCfg = cfg;
+ if (!sourceCfg) {
+ const [row] = await engine.executeRaw<{ config: Record<string, unknown> | string | null }>('SELECT config FROM sources WHERE id=$1', [sourceId]);
+ const raw = typeof row?.config === 'string' ? JSON.parse(row.config) as Record<string, unknown> : row?.config ?? {};
+ sourceCfg = { loopsExcludeLabels: parseExcludeLabelTokens(raw.g_loops_exclude_labels) };
+ }
+ const tokens = await excludedLabelTokens(engine, sourceCfg);
+ if (tokens.length === 0) return NO_EXCLUSION;
+ const key = await resolutionKey(engine, sourceId);
+ const [row] = key ? await engine.executeRaw<{ stored: StoredResolution | null }>(
+ 'SELECT completed_keys->0 AS stored FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [LOOPS_EXCLUSION_OP, key]) : [];
+ const stored = row?.stored;
+ if (stored?.version === 1 && sameTokens(stored.tokens, tokens)) {
+ return { tokens, ids: new Set(stored.ids), unresolved: [...stored.unresolved] };
+ }
+ return resolveExcludedLabels(tokens, null);
+}
+
+function sameTokens(a: string[], b: string[]): boolean {
+ return a.length === b.length && a.every((t, i) => t === b[i]);
+}
diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.ts
index dddd404a68..d19e6948bf 100644
--- a/src/core/google/loops-extract.ts
+++ b/src/core/google/loops-extract.ts
@@ -29,6 +29,7 @@ import { managedFactWritePreflight } from '../facts/managed-fact-write.ts';
import { loadSuppressions, upsertOpenLoop, type LoopType } from '../loops/loops-store.ts';
import { isCalendarSystemMail, isNoiseSender, sha8 } from './google-render.ts';
import { hasBulkCategory } from './gmail-categories.ts';
+import { isExcludedByLabels, loadLoopsExclusionPolicy, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';
import { bareAddress, type GmailMessageMeta, type GmailThreadData } from './types.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
import { deriveTrust } from '../trust/taint.ts';
@@ -76,7 +77,9 @@ export interface ExtractEligibility {
| 'spam_or_trash'
| 'no_substantive_messages'
| 'bulk_category'
- | 'list_mail';
+ | 'list_mail'
+ | 'excluded_label'
+ | 'excluded_label_unresolved';
}
/**
@@ -100,10 +103,18 @@ export interface ExtractEligibility {
*
* CATEGORY_UPDATES is deliberately NOT excluded: invoices, contracts and
* document requests land there, and they carry real obligations.
+ *
+ * #5445: a thread under one of the user's excluded labels (`exclusion`) is
+ * never extracted, and this beats the owner override: warm-up mail is sent
+ * FROM the owner's address, which is exactly why no mute can exclude it. A
+ * policy that could not be resolved (an unknown label name, a failed label
+ * list) fails CLOSED for new paid extraction: `excluded_label_unresolved`,
+ * counted in the sweep summary and retried on the next sweep.
*/
export function loopExtractionEligibility(
thread: GmailThreadData,
myAddresses: Set<string> = new Set(),
+ exclusion: LoopsExclusionPolicy = NO_EXCLUSION,
): ExtractEligibility {
const messages = thread.messages;
if (messages.length === 0) return { eligible: false, reason: 'no_substantive_messages' };
@@ -116,6 +127,10 @@ export function loopExtractionEligibility(
return { eligible: false, reason: 'spam_or_trash' };
}
+ // The user's own exclusion, before the owner override (see above).
+ if (isExcludedByLabels(exclusion, labels)) return { eligible: false, reason: 'excluded_label' };
+ if (exclusion.unresolved.length > 0) return { eligible: false, reason: 'excluded_label_unresolved' };
+
// Machine mail carries no commitments: pure noise senders, and Calendar's
// invitation/response notices (which come FROM a real colleague, so the
// sender check alone cannot see them). Computed FIRST: the owner override
@@ -288,7 +303,7 @@ export interface LoopsExtractResult {
*/
export class LoopsExtractRetryableError extends Error {
constructor(
- readonly reason: 'llm_unavailable' | 'truncated' | 'parse_barrier',
+ readonly reason: 'llm_unavailable' | 'truncated' | 'parse_barrier' | 'excluded_label_unresolved',
message: string,
) {
super(message);
@@ -338,6 +353,20 @@ export async function runLoopsExtract(
return { ...empty, reason: 'suppressed' };
}
+ // #5445: the label exclusion in force NOW, not at enqueue — a label the user
+ // added after this job was queued still stops it before the model call.
+ // An unresolved policy is retryable (the next sweep re-reads the labels),
+ // never a paid run.
+ const exclusion = await loadLoopsExclusionPolicy(engine, payload.sourceId);
+ if (isExcludedByLabels(exclusion, pageLabelIds(fm))) return { ...empty, reason: 'excluded_label' };
+ if (exclusion.unresolved.length > 0) {
+ throw new LoopsExtractRetryableError(
+ 'excluded_label_unresolved',
+ `loops_extract: the loop exclusion labels ${exclusion.unresolved.map((t) => JSON.stringify(t)).join(', ')} are not labels of this account ` +
+ '(or the label list could not be read); no model call is made until a sweep resolves them — retryable',
+ );
+ }
+
// Managed brains publish the commitment fact through the coordinator; its
// authority and canonical owner are checked here, before the model call.
await managedFactWritePreflight(engine, payload.sourceId);
diff --git a/src/core/google/source-config.ts b/src/core/google/source-config.ts
index 47c3a26dbf..9e14ebf2eb 100644
--- a/src/core/google/source-config.ts
+++ b/src/core/google/source-config.ts
@@ -1,6 +1,7 @@
/** Parse a Google connector source's `sources.config`. Dependency-light so migrations and the connector identity can import it. */
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID, type GoogleService, type GoogleSourceConfig } from './types.ts';
import { CALENDAR_FUTURE_DAYS_MAX } from './calendar-window.ts';
+import { parseExcludeLabelTokens } from './loops-exclusion.ts';
export function parseGoogleSourceConfig(
config: Record<string, unknown>,
@@ -28,6 +29,7 @@ export function parseGoogleSourceConfig(
config.g_future_days <= CALENDAR_FUTURE_DAYS_MAX
? Math.floor(config.g_future_days)
: undefined;
+ const loopsExcludeLabels = parseExcludeLabelTokens(config.g_loops_exclude_labels);
const calendarId =
typeof config.g_calendar_id === 'string' && config.g_calendar_id.trim().length > 0
? config.g_calendar_id.trim()
@@ -41,6 +43,7 @@ export function parseGoogleSourceConfig(
services: services.length > 0 ? services : [...ALL_GOOGLE_SERVICES],
historyDays,
...(futureDays !== undefined ? { futureDays } : {}),
+ ...(loopsExcludeLabels.length > 0 ? { loopsExcludeLabels } : {}),
calendarId,
dir,
access,
@@ -52,3 +55,17 @@ export function parseGoogleSourceConfig(
: {}),
};
}
+
+/**
+ * The per-source tuning keys `sources add` writes, each only when set so an
+ * existing source's config keeps its exact shape (`DEFAULT_CALENDAR_ID` and
+ * `CALENDAR_HORIZON_DAYS` stay parse-time fallbacks): `g_calendar_id`
+ * (#5296), `g_future_days` (#5442), `g_loops_exclude_labels` (#5445).
+ */
+export function googleTuningConfig(google: { calendarId?: string; futureDays?: number; loopsExcludeLabels?: string[] }): Record<string, unknown> {
+ return {
+ ...(google.calendarId && google.calendarId !== DEFAULT_CALENDAR_ID ? { g_calendar_id: google.calendarId } : {}),
+ ...(google.futureDays !== undefined ? { g_future_days: google.futureDays } : {}),
+ ...(google.loopsExcludeLabels && google.loopsExcludeLabels.length > 0 ? { g_loops_exclude_labels: google.loopsExcludeLabels.join(',') } : {}),
+ };
+}
diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.ts
index 9947dce3e1..050cc98fb3 100644
--- a/src/core/google/sweep-shared.ts
+++ b/src/core/google/sweep-shared.ts
@@ -14,6 +14,7 @@ import { connectorRender } from '../connectors/connector-text.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { mkdirPrivate } from '../atomic-write.ts';
import type { GoogleSourceConfig, GoogleSourceState } from './types.ts';
+import type { LoopsExclusionPolicy } from './loops-exclusion.ts';
/** The "my addresses" identity set: account + Gmail sendAs aliases. */
export function myAddressSet(entry: CredentialEntry): Set<string> {
@@ -59,6 +60,8 @@ export interface GoogleSyncDeps {
* killed at the hard deadline.
*/
tick: (note: string) => void;
+ /** #5445: the label exclusion resolved once for this sweep (see loops-exclusion.ts). */
+ exclusion: LoopsExclusionPolicy;
/** 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 }>;
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index 849d6911da..49f519c2a7 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -27,6 +27,14 @@ export interface GoogleSourceConfig {
* CALENDAR_HORIZON_DAYS.
*/
futureDays?: number;
+ /**
+ * Gmail label names or ids whose threads the open-loop engine leaves alone
+ * (`g_loops_exclude_labels`, comma-separated; #5445). Present only when the
+ * source sets it; the brain-wide `loops.extraction_exclude_labels` is the
+ * fallback. Not part of the connector identity: it changes what is
+ * extracted, not which pages exist.
+ */
+ loopsExcludeLabels?: string[];
/** Calendar swept by this source (default DEFAULT_CALENDAR_ID). One calendar per
* source so each keeps its own sync token — point a second source at a
* secondary calendar id to ingest it too. */
diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.ts
index fa1304d37e..5b04cdbefa 100644
--- a/src/core/persistence/connector-identity.ts
+++ b/src/core/persistence/connector-identity.ts
@@ -37,7 +37,7 @@ const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'a
export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass>; github: Record<string, Rule> } = {
google: {
account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', dir: 'identity',
- access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded',
+ access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded', loopsExcludeLabels: 'excluded',
},
github: {
scope: 'identity', repos: 'identity', dir: 'identity',
diff --git a/src/core/sources-ops.ts b/src/core/sources-ops.ts
index 3a3bef0bd2..49807cae8f 100644
--- a/src/core/sources-ops.ts
+++ b/src/core/sources-ops.ts
@@ -56,7 +56,7 @@ import {
} from './git-remote.ts';
import { gbrainPath } from './config.ts';
import { isValidSourceId } from './source-id.ts';
-import { DEFAULT_CALENDAR_ID } from './google/types.ts';
+import { googleTuningConfig } from './google/source-config.ts';
import { resolveSourceWithTier, type SourceTier } from './source-resolver.ts';
import { deleteSourceRow } from './source-delete.ts';
@@ -196,6 +196,10 @@ export interface AddSourceOpts {
historyDays: number;
/** Calendar swept by this source (default DEFAULT_CALENDAR_ID). */
calendarId?: string;
+ /** #5442: days ahead the calendar sweep covers (`g_future_days`; default CALENDAR_HORIZON_DAYS when absent). */
+ futureDays?: number;
+ /** #5445: Gmail label names/ids whose threads never enter loop extraction (`g_loops_exclude_labels`). */
+ loopsExcludeLabels?: string[];
/** Managed dir where pages are materialized. */
dir: string;
/** Token acquisition: gbrain vault (default), a token-printing command, or an env var. */
@@ -659,9 +663,7 @@ export async function addSource(
g_history_days: opts.google.historyDays,
// Only written when non-default so every existing source's config keeps
// its exact shape (DEFAULT_CALENDAR_ID stays the parse-time fallback).
- ...(opts.google.calendarId && opts.google.calendarId !== DEFAULT_CALENDAR_ID
- ? { g_calendar_id: opts.google.calendarId }
- : {}),
+ ...googleTuningConfig(opts.google),
// Non-vault access (v0.47): 'command' runs g_token_command locally at
// sync time (same trust class as recipe health_check argv — the google
// kind is hard-rejected on remote sources_add and these keys are not
diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.ts
index 5e4b79e2c1..22c5395410 100644
--- a/test/google-source-reconcile.test.ts
+++ b/test/google-source-reconcile.test.ts
@@ -115,6 +115,8 @@ interface FakeGoogle {
contactsFullLists: number;
calls: string[];
threadFetches: number;
+ /** #5445: the account's label catalog (`users/me/labels`); `'fail'` answers the list with HTTP 500. */
+ labels: Array<{ id: string; name: string; type: string }> | 'fail';
}
function emptyFx(): FakeGoogle {
@@ -136,6 +138,7 @@ function emptyFx(): FakeGoogle {
contactsFullLists: 0,
calls: [],
threadFetches: 0,
+ labels: [],
};
}
@@ -176,6 +179,11 @@ function buildFetch(fx: FakeGoogle): FetchImpl {
});
}
+ if (u.pathname.endsWith('/users/me/labels')) {
+ if (fx.labels === 'fail') return json({ error: { code: 500, message: 'backend error' } }, 500);
+ return json({ labels: fx.labels });
+ }
+
if (u.pathname.endsWith('/users/me/history')) {
return json({
historyId: fx.historyResponseId,
@@ -1366,6 +1374,97 @@ describe('loops_extract enqueue completeness', () => {
}
}, 120_000);
+ describe('label exclusion (#5445)', () => {
+ const seedThreads = (fx: FakeGoogle) => {
+ fx.labels = [{ id: 'INBOX', name: 'INBOX', type: 'system' }, { id: 'Label_7', name: 'Newsletters', type: 'user' }];
+ fx.messages.push(
+ gmsg('18ff55000000a201', '17ee55000000a101', hoursAgoMs(1), {
+ headers: { From: 'Peer Example <[email protected]>', To: '[email protected]', Subject: 'Excluded topic' },
+ body: 'Could you look at the attached draft?', labelIds: ['INBOX', 'Label_7'],
+ }),
+ gmsg('18ff55000000a202', '17ee55000000a102', hoursAgoMs(2), {
+ headers: { From: 'Peer Example <[email protected]>', To: '[email protected]', Subject: 'Plain topic' },
+ body: 'Could you confirm the plan?', labelIds: ['INBOX'],
+ }),
+ );
+ };
+ const jobCount = async () => Number((await engine.executeRaw<{ n: string }>(`SELECT count(*)::text AS n FROM minion_jobs WHERE name = 'loops_extract'`))[0].n);
+ /** The per-reason counts the sweep logs (`loops_extract eligibility: a=1 b=2`). */
+ const eligibilityCounts = (err: string): Record<string, number> => {
+ const line = /loops_extract eligibility: ([^\n]+)/.exec(err)?.[1] ?? '';
+ return Object.fromEntries(line.trim().split(/\s+/).filter(Boolean).map((kv) => { const [k, v] = kv.split('='); return [k, Number(v)]; }));
+ };
+
+ test('a name resolves once per sweep: one labels call, the labelled thread is excluded_label and not queued, the plain one is queued', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-excl-'));
+ const fx = emptyFx();
+ const vault = makeVault();
+ seedThreads(fx);
+ try {
+ await insertGoogleSource(dir);
+ await withHome(async () => {
+ const { result: res, err } = await capturedStderr(() => sweep(dir, fx, vault, {}, 'gmail', { cfg: { g_loops_exclude_labels: 'newsletters' } }));
+ expect(res.added).toBe(2);
+ expect(fx.calls.filter((c) => c.includes('/users/me/labels'))).toHaveLength(1);
+ expect(eligibilityCounts(err)).toEqual({ excluded_label: 1, human_correspondence: 1 });
+ expect(res.loops_enqueue).toMatchObject({ enqueued: 1, skipped_reason: null });
+ expect(await jobCount()).toBe(1);
+ expect(err).not.toContain('excluded_label_unresolved');
+ const stored = await engine.executeRaw<{ s: { ids: string[]; unresolved: string[] } }>(
+ `SELECT completed_keys->0 AS s FROM op_checkpoints WHERE op = 'loops-exclusion'`);
+ expect(stored[0]?.s).toMatchObject({ ids: ['Label_7'], unresolved: [] });
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 120_000);
+
+ test('an unknown name fails closed: every thread counts excluded_label_unresolved, nothing is queued, stderr names the label', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-excl-unres-'));
+ const fx = emptyFx();
+ const vault = makeVault();
+ seedThreads(fx);
+ try {
+ await insertGoogleSource(dir);
+ await withHome(async () => {
+ const { result: res, err } = await capturedStderr(() => sweep(dir, fx, vault, {}, 'gmail', { cfg: { g_loops_exclude_labels: 'Newsletters, Vendor-Noise' } }));
+ expect(res.added).toBe(2);
+ expect(eligibilityCounts(err)).toEqual({ excluded_label: 1, excluded_label_unresolved: 1 });
+ expect(res.loops_enqueue).toMatchObject({ enqueued: 0, skipped_reason: 'excluded_label_unresolved' });
+ expect(await jobCount()).toBe(0);
+ expect(err).toContain('"Vendor-Noise" is not a label of [email protected]');
+ expect(err).toContain('excluded_label_unresolved');
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 120_000);
+
+ test('a failed label list resolves ids only: names stay unresolved this sweep and the brain-wide key is the fallback', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-excl-fail-'));
+ const fx = emptyFx();
+ const vault = makeVault();
+ seedThreads(fx);
+ fx.labels = 'fail';
+ try {
+ await insertGoogleSource(dir);
+ await engine.setConfig('loops.extraction_exclude_labels', 'Label_7');
+ await withHome(async () => {
+ const { result: byId, err: errById } = await capturedStderr(() => sweep(dir, fx, vault));
+ expect(eligibilityCounts(errById)).toEqual({ excluded_label: 1, human_correspondence: 1 });
+ expect(byId.loops_enqueue).toMatchObject({ enqueued: 1 });
+ await engine.setConfig('loops.extraction_exclude_labels', 'Newsletters');
+ const { result: byName, err } = await capturedStderr(() => sweep(dir, fx, vault, { full: true }));
+ expect(byName.loops_enqueue).toMatchObject({ enqueued: 0, skipped_reason: 'excluded_label_unresolved' });
+ expect(err).toContain("could not read the account's labels");
+ });
+ } finally {
+ await engine.setConfig('loops.extraction_exclude_labels', '');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }, 120_000);
+ });
+
test(`>${LOOPS_EXTRACT_MAX_PER_SWEEP} eligible threads → EVERY one is queued exactly once`, async () => {
const dir = mkdtempSync(join(tmpdir(), 'gsrc-cap-'));
const fx = emptyFx();
diff --git a/test/loops-exclusion.test.ts b/test/loops-exclusion.test.ts
new file mode 100644
index 0000000000..2c6bdcca5a
--- /dev/null
+++ b/test/loops-exclusion.test.ts
@@ -0,0 +1,242 @@
+/**
+ * #5445 — per-source Gmail label exclusion for loop extraction
+ * (src/core/google/loops-exclusion.ts and its three eligibility sites).
+ *
+ * - tokens resolve once against the label catalog; a name nobody has is
+ * unresolved and the policy FAILS CLOSED (`excluded_label_unresolved`);
+ * - the eligibility gate sits before the owner override: replying inside an
+ * excluded label does not buy the thread back;
+ * - the deterministic lane withholds new opens on an excluded thread and
+ * still closes answered loops;
+ * - a grace hold published before the policy changed is re-checked when it
+ * comes due: excluded → dropped without opening, unresolved → kept;
+ * - the catch-up skips with the visible reason while anything is unresolved;
+ * - the stored resolution is reused for the same tokens only.
+ *
+ * Synthetic data only. PGLite in memory; no model call anywhere.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import {
+ isExcludedByLabels,
+ loadLoopsExclusionPolicy,
+ LOOPS_EXCLUDE_LABELS_CONFIG_KEY,
+ NO_EXCLUSION,
+ pageLabelIds,
+ parseExcludeLabelTokens,
+ resolveExcludedLabels,
+ storeLoopsExclusion,
+ type LoopsExclusionPolicy,
+} from '../src/core/google/loops-exclusion.ts';
+import { loopExtractionEligibility } from '../src/core/google/loops-extract.ts';
+import { applyThreadLoopVerdict, detectThreadLoop, openDueGraceHold, withLabelExclusion, __clearSuppressionCacheForTests } from '../src/core/google/loop-detect.ts';
+import { recordGraceVerdict, runLoopsCatchup, settleDueGraceHolds } from '../src/core/google/loop-catchup.ts';
+import { parseGoogleSourceConfig } from '../src/core/google/source-config.ts';
+import { listOpenLoops } from '../src/core/loops/loops-store.ts';
+import type { GmailMessageMeta, GmailThreadData, GoogleSourceState } from '../src/core/google/types.ts';
+
+const CATALOG = [
+ { id: 'INBOX', name: 'INBOX' },
+ { id: 'Label_7', name: 'Newsletters' },
+ { id: 'Label_12', name: 'Recruiting/Agencies' },
+];
+const EXCLUDE_7: LoopsExclusionPolicy = { tokens: ['Newsletters'], ids: new Set(['Label_7']), unresolved: [] };
+const UNRESOLVED: LoopsExclusionPolicy = { tokens: ['Nope'], ids: new Set(), unresolved: ['Nope'] };
+
+const NOW = new Date('2026-08-25T12:00:00Z');
+const MY = new Set(['[email protected]']);
+let seq = 0;
+
+function msg(spec: { from: string; to?: string[]; ageHours: number; labels?: string[]; body?: string; threadId?: string }): GmailMessageMeta {
+ const internalDateMs = NOW.getTime() - spec.ageHours * 3_600_000;
+ seq += 1;
+ return {
+ id: `18c2f4a9b3d2${(0x3000 + seq).toString(16)}`,
+ threadId: spec.threadId ?? '18c2f4a9b3d21e07',
+ from: spec.from,
+ fromAddress: spec.from.toLowerCase(),
+ to: (spec.to ?? ['[email protected]']).map((a) => a.toLowerCase()),
+ cc: [],
+ subject: 'Quarterly plan',
+ dateIso: new Date(internalDateMs).toISOString(),
+ internalDateMs,
+ labelIds: spec.labels ?? (spec.from === '[email protected]' ? ['SENT'] : ['INBOX']),
+ listUnsubscribe: false,
+ bodyText: spec.body ?? 'Can you review the plan?',
+ };
+}
+const thread = (messages: GmailMessageMeta[], threadId = '18c2f4a9b3d21e07'): GmailThreadData => ({ threadId, account: '[email protected]', messages });
+
+describe('#5445 resolution', () => {
+ test('tokens parse from a comma list or an array, trimmed and de-duplicated', () => {
+ expect(parseExcludeLabelTokens(' Newsletters, Label_7 ,, Newsletters')).toEqual(['Newsletters', 'Label_7']);
+ expect(parseExcludeLabelTokens(['Recruiting/Agencies', 'INBOX'])).toEqual(['Recruiting/Agencies', 'INBOX']);
+ expect(parseExcludeLabelTokens(undefined)).toEqual([]);
+ });
+
+ test('a name resolves case-insensitively to its id, an id passes through, an unknown name stays unresolved', () => {
+ const p = resolveExcludedLabels(['newsletters', 'Label_12', 'Nope'], CATALOG);
+ expect([...p.ids].sort()).toEqual(['Label_12', 'Label_7']);
+ expect(p.unresolved).toEqual(['Nope']);
+ });
+
+ test('without a catalog only id-shaped tokens resolve; names fail closed', () => {
+ const p = resolveExcludedLabels(['Label_7', 'CATEGORY_FORUMS', 'Newsletters'], null);
+ expect([...p.ids].sort()).toEqual(['CATEGORY_FORUMS', 'Label_7']);
+ expect(p.unresolved).toEqual(['Newsletters']);
+ });
+
+ test('an id the catalog no longer has is unresolved (a deleted label is not silently ignored)', () => {
+ expect(resolveExcludedLabels(['Label_99'], CATALOG).unresolved).toEqual(['Label_99']);
+ });
+
+ test('isExcludedByLabels and pageLabelIds', () => {
+ expect(isExcludedByLabels(EXCLUDE_7, ['INBOX', 'Label_7'])).toBe(true);
+ expect(isExcludedByLabels(EXCLUDE_7, ['INBOX'])).toBe(false);
+ expect(isExcludedByLabels(NO_EXCLUSION, ['Label_7'])).toBe(false);
+ expect(pageLabelIds({ labels: ['INBOX', 'Label_7', 3] })).toEqual(['INBOX', 'Label_7']);
+ expect(pageLabelIds({})).toEqual([]);
+ });
+
+ test('g_loops_exclude_labels parses onto the source config and is absent when unset', () => {
+ const base = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_history_days: 90, g_dir: '/tmp/x' };
+ expect(parseGoogleSourceConfig(base, '/tmp/x').loopsExcludeLabels).toBeUndefined();
+ expect(parseGoogleSourceConfig({ ...base, g_loops_exclude_labels: 'Newsletters, Label_12' }, '/tmp/x').loopsExcludeLabels).toEqual(['Newsletters', 'Label_12']);
+ });
+});
+
+describe('#5445 eligibility gate', () => {
+ const inbound = thread([msg({ from: '[email protected]', ageHours: 48, labels: ['INBOX', 'Label_7'] })]);
+
+ test('a thread under an excluded label is ineligible with excluded_label', () => {
+ expect(loopExtractionEligibility(inbound, MY, EXCLUDE_7)).toEqual({ eligible: false, reason: 'excluded_label' });
+ expect(loopExtractionEligibility(inbound, MY).eligible).toBe(true);
+ });
+
+ test('the owner replying inside the excluded label does not rescue the thread (gate precedes the owner override)', () => {
+ const replied = thread([
+ ...inbound.messages,
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 20, labels: ['SENT', 'Label_7'], body: 'Yes, I will review it tomorrow and send notes.' }),
+ ]);
+ expect(loopExtractionEligibility(replied, MY, EXCLUDE_7).reason).toBe('excluded_label');
+ });
+
+ test('an unresolved policy fails closed for every thread, with the visible retryable reason', () => {
+ const plain = thread([msg({ from: '[email protected]', ageHours: 48 })]);
+ expect(loopExtractionEligibility(plain, MY, UNRESOLVED)).toEqual({ eligible: false, reason: 'excluded_label_unresolved' });
+ });
+});
+
+describe('#5445 deterministic lane and holds (PGLite)', () => {
+ let engine: PGLiteEngine;
+ const SRC = 'g1';
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => { await engine.disconnect(); });
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ __clearSuppressionCacheForTests();
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('g1', 'g1', '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+ });
+
+ const openLoops = async () => listOpenLoops(engine, { sourceIds: [SRC], status: 'open' });
+
+ test('withLabelExclusion withholds opens and keeps closes; an unresolved policy withholds the same way', () => {
+ const asked = thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, labels: ['SENT', 'Label_7'] })]);
+ const verdict = detectThreadLoop(asked, MY, NOW);
+ expect(verdict.open.length).toBe(1);
+ expect(withLabelExclusion(verdict, EXCLUDE_7, ['SENT', 'Label_7'])).toEqual({ open: [], close: verdict.close });
+ expect(withLabelExclusion(verdict, UNRESOLVED, ['SENT'])).toEqual({ open: [], close: verdict.close });
+ expect(withLabelExclusion(verdict, EXCLUDE_7, ['SENT'])).toBe(verdict);
+ });
+
+ test('an excluded thread opens nothing, and the exclusion never blocks the close of a loop opened earlier', async () => {
+ const asked = thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200 })]);
+ await applyThreadLoopVerdict(engine, SRC, asked, MY, null, NOW);
+ expect((await openLoops()).length).toBe(1);
+ const answered = thread([...asked.messages, msg({ from: '[email protected]', ageHours: 10, labels: ['INBOX', 'Label_7'], body: 'Reviewed, looks good to me.' })]);
+ await applyThreadLoopVerdict(engine, SRC, answered, MY, null, NOW, EXCLUDE_7);
+ expect((await openLoops()).length).toBe(0);
+ const fresh = thread([msg({ from: '[email protected]', ageHours: 60, labels: ['INBOX', 'Label_7'], threadId: '18c2f4a9b3d21e08' })], '18c2f4a9b3d21e08');
+ await applyThreadLoopVerdict(engine, SRC, fresh, MY, null, NOW, EXCLUDE_7);
+ expect((await openLoops()).length).toBe(0);
+ await applyThreadLoopVerdict(engine, SRC, fresh, MY, null, NOW);
+ expect((await openLoops()).length).toBe(1);
+ });
+
+ async function heldThread(labels: string[]): Promise<{ t: GmailThreadData; state: GoogleSourceState; slug: string }> {
+ const t = thread([msg({ from: '[email protected]', ageHours: 2, labels, threadId: '18c2f4a9b3d21e09' })], '18c2f4a9b3d21e09');
+ const slug = 'emails/2026/08/2026-08-25-quarterly-plan-18c2f4a9';
+ await engine.putPage(slug, { type: 'email', title: 'Quarterly plan', compiled_truth: 'Can you review the plan?',
+ frontmatter: { thread_id: t.threadId, message_id: t.messages[0].id, labels } }, { sourceId: SRC });
+ const verdict = detectThreadLoop(t, MY, NOW);
+ expect(verdict.held).toBeDefined();
+ const state = { loop_grace_holds: {} } as unknown as GoogleSourceState;
+ recordGraceVerdict(state, t, verdict, slug, MY, () => {});
+ expect(state.loop_grace_holds?.[t.threadId]?.spec).toBeDefined();
+ return { t, state, slug };
+ }
+
+ test('policy flipped after the hold: a due hold under a now-excluded label is dropped without opening', async () => {
+ const { t, state, slug } = await heldThread(['INBOX', 'Label_7']);
+ const hold = state.loop_grace_holds![t.threadId];
+ expect(await openDueGraceHold(engine, SRC, t.threadId, hold.spec!, slug, EXCLUDE_7)).toBe('excluded');
+ expect((await openLoops()).length).toBe(0);
+ expect(await openDueGraceHold(engine, SRC, t.threadId, hold.spec!, slug)).toBe('opened');
+ expect((await openLoops()).length).toBe(1);
+ });
+
+ test('policy unresolved when the hold comes due: the hold is kept (deferred), nothing is published', async () => {
+ const { t, state, slug } = await heldThread(['INBOX']);
+ const hold = state.loop_grace_holds![t.threadId];
+ expect(hold.slug).toBe(slug);
+ const r = await settleDueGraceHolds({ engine, sourceId: SRC, state, log: () => {}, processed: new Set(), now: hold.due_ms + 1,
+ refetch: async () => 'ok', exclusion: UNRESOLVED });
+ expect(r).toEqual({ opened: 0, refetched: 0, deferred: 1 });
+ expect(state.loop_grace_holds?.[t.threadId]).toBeDefined();
+ expect((await openLoops()).length).toBe(0);
+ const again = await settleDueGraceHolds({ engine, sourceId: SRC, state, log: () => {}, processed: new Set(), now: hold.due_ms + 1,
+ refetch: async () => 'ok' });
+ expect(again).toEqual({ opened: 1, refetched: 0, deferred: 0 });
+ expect(state.loop_grace_holds?.[t.threadId]).toBeUndefined();
+ });
+
+ test('a thread held while excluded is not recorded as a grace hold', async () => {
+ const t = thread([msg({ from: '[email protected]', ageHours: 2, labels: ['INBOX', 'Label_7'] })]);
+ const state = { loop_grace_holds: {} } as unknown as GoogleSourceState;
+ recordGraceVerdict(state, t, detectThreadLoop(t, MY, NOW), 'emails/x', MY, () => {}, EXCLUDE_7);
+ expect(state.loop_grace_holds?.[t.threadId]).toBeUndefined();
+ });
+
+ test('the catch-up skips with excluded_label_unresolved while any name is unresolved', async () => {
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ const state = {} as GoogleSourceState;
+ const r = await runLoopsCatchup({ engine, sourceId: SRC, state, log: () => {}, myAddresses: MY, inFlight: new Set(),
+ fetchThread: async () => null, exclusion: UNRESOLVED });
+ expect(r?.skipped_reason).toBe('excluded_label_unresolved');
+ expect(r?.enqueued).toBe(0);
+ });
+
+ test('the stored resolution is reused for the same tokens; changed tokens fall back to id-only (names unresolved)', async () => {
+ await engine.setConfig(LOOPS_EXCLUDE_LABELS_CONFIG_KEY, 'Newsletters');
+ expect((await loadLoopsExclusionPolicy(engine, SRC)).unresolved).toEqual(['Newsletters']);
+ await storeLoopsExclusion(engine, SRC, resolveExcludedLabels(['Newsletters'], CATALOG));
+ const loaded = await loadLoopsExclusionPolicy(engine, SRC);
+ expect([...loaded.ids]).toEqual(['Label_7']);
+ expect(loaded.unresolved).toEqual([]);
+ await engine.setConfig(LOOPS_EXCLUDE_LABELS_CONFIG_KEY, 'Newsletters, Recruiting/Agencies');
+ const changed = await loadLoopsExclusionPolicy(engine, SRC);
+ expect(changed.unresolved).toEqual(['Newsletters', 'Recruiting/Agencies']);
+ const sourceWins = await loadLoopsExclusionPolicy(engine, SRC, { loopsExcludeLabels: ['Label_12'] });
+ expect([...sourceWins.ids]).toEqual(['Label_12']);
+ expect(sourceWins.unresolved).toEqual([]);
+ await engine.setConfig(LOOPS_EXCLUDE_LABELS_CONFIG_KEY, '');
+ expect(await loadLoopsExclusionPolicy(engine, SRC)).toBe(NO_EXCLUSION);
+ });
+});
diff --git a/test/loops-extract-run.serial.test.ts b/test/loops-extract-run.serial.test.ts
index 9cf5b5e04a..e5553bb2ea 100644
--- a/test/loops-extract-run.serial.test.ts
+++ b/test/loops-extract-run.serial.test.ts
@@ -50,7 +50,7 @@ mock.module('../src/core/ai/gateway.ts', () => ({
}));
const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');
-const { runLoopsExtract, isLoopsExtractionEnabled } = await import(
+const { runLoopsExtract, isLoopsExtractionEnabled, LoopsExtractRetryableError } = await import(
'../src/core/google/loops-extract.ts'
);
const { normalizeAlias } = await import('../src/core/search/alias-normalize.ts');
@@ -721,6 +721,50 @@ describe('runLoopsExtract', () => {
expect(byType['owes_to']).toBe('Send Alice the compliance checklist');
for (const e of edges) expect(e.context).not.toContain('compliance checklist by Tuesday');
});
+
+ describe('#5445 execution-time label exclusion (the policy in force when the job RUNS, not when it was queued)', () => {
+ const LABELLED_SLUG = 'emails/2026/08/2026-08-21-labelled-thread-0a1b2c3d';
+ beforeAll(async () => {
+ await engine.putPage(LABELLED_SLUG, {
+ type: 'email', title: 'A labelled synthetic thread',
+ compiled_truth: 'Me: I will send the summary on Monday.\nPeer: Thanks, which deck should I read first?\n',
+ frontmatter: { thread_id: 'thread-0a1b2c3d', date: '2026-08-21T10:00:00Z', labels: ['INBOX', 'Label_7'] },
+ effective_date: new Date('2026-08-21T10:00:00Z'),
+ }, { sourceId: SRC });
+ });
+
+ test('a label excluded after enqueue skips the job before any model call (excluded_label)', async () => {
+ const before = chatCalls;
+ await engine.setConfig('loops.extraction_exclude_labels', 'Label_7');
+ try {
+ const r = await runLoopsExtract(engine, { slug: LABELLED_SLUG, sourceId: SRC });
+ expect(r.status).toBe('skipped');
+ expect(r.reason).toBe('excluded_label');
+ expect(chatCalls).toBe(before);
+ const other = await runLoopsExtract(engine, { slug: EMAIL_SLUG, sourceId: SRC });
+ expect(other.status).not.toBe('skipped');
+ expect(chatCalls).toBe(before + 1);
+ } finally {
+ await engine.setConfig('loops.extraction_exclude_labels', '');
+ }
+ });
+
+ test('a name no sweep has resolved fails closed: retryable excluded_label_unresolved, zero model calls, for every page', async () => {
+ const before = chatCalls;
+ await engine.setConfig('loops.extraction_exclude_labels', 'Newsletters');
+ try {
+ for (const slug of [LABELLED_SLUG, EMAIL_SLUG]) {
+ const thrown = await runLoopsExtract(engine, { slug, sourceId: SRC }).then(() => null, (e: unknown) => e);
+ expect(thrown).toBeInstanceOf(LoopsExtractRetryableError);
+ expect((thrown as InstanceType<typeof LoopsExtractRetryableError>).reason).toBe('excluded_label_unresolved');
+ expect((thrown as Error).message).toContain('"Newsletters"');
+ }
+ expect(chatCalls).toBe(before);
+ } finally {
+ await engine.setConfig('loops.extraction_exclude_labels', '');
+ }
+ });
+ });
});
describe('#5586: fact projection failure', () => {
diff --git a/test/persistence-source-cli.test.ts b/test/persistence-source-cli.test.ts
index ed8bd1bafa..1915e55dbb 100644
--- a/test/persistence-source-cli.test.ts
+++ b/test/persistence-source-cli.test.ts
@@ -38,6 +38,13 @@ describe('source lifecycle CLI', () => {
'--access', 'env', '--token-env', 'EXAMPLE_TOKEN', '--services', 'calendar', '--dir', '.'], id);
expect(google.params).toMatchObject({ request_id: id, options: { id: 'example', requestId: id,
google: { tokenEnv: 'EXAMPLE_TOKEN', access: 'env', services: ['calendar'], dir: process.cwd() } } });
+ // #5442 / #5445: the per-source calendar horizon and loop exclusion labels ride the same add.
+ const tuned = parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]',
+ '--future-days', '365', '--loops-exclude-labels', 'Newsletters, Label_7', '--dir', '.'], id);
+ expect(tuned.params).toMatchObject({ options: { google: { futureDays: 365, loopsExcludeLabels: ['Newsletters', 'Label_7'] } } });
+ expect(google.params).not.toHaveProperty('options.google.futureDays');
+ expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--future-days', '0'])).toThrow('positive integer');
+ expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--future-days', '4000'])).toThrow('3650');
expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'github', '--scope', 'repos'])).toThrow('valid owner/name');
expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--access', 'command'])).toThrow('access');
});