Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(loops): Meet notes digest and Gmail bulk categories open no deterministic loops (#5103)
garrytan8b8f3b1d672d
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 0f49f09511..fdfd391376 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -22,6 +22,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `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/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.- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `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).diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.mdindex 2c571ae017..167fc3fd87 100644--- a/docs/guides/open-loops.md+++ b/docs/guides/open-loops.md@@ -38,9 +38,14 @@ zero LLM, free, always on). For every synced Gmail thread:Precision rules (pinned by a labeled fixture corpus in`test/google-loop-detect.test.ts` — every false-positive class gets a-fixture before its fix): noise senders (noreply/notifications), list mail-(`List-Unsubscribe`), CC-only delivery, FYI/forwards without a question,-self-threads, and muted senders/threads never open loops. Sent-mail+fixture before its fix): noise senders (noreply/notifications, and Google's+own system addresses such as the Meet notes digest, matched by exact address+only), list mail (`List-Unsubscribe`), Gmail's bulk categories+(`CATEGORY_PROMOTIONS` / `CATEGORY_SOCIAL` / `CATEGORY_FORUMS`, unless you+wrote a substantive message in the thread; `CATEGORY_UPDATES` is not bulk),+CC-only delivery, FYI/forwards without a question, self-threads, and muted+senders/threads never open loops. None of these gates closes a loop: only a+turn flip does. Sent-mailingestion is what makes "unanswered" honest — your own replies are thenegative filter.@@ -103,7 +108,7 @@ calls nor crowds real correspondence out of the sweep:| `SPAM` / `TRASH` | no — whoever wrote them || a substantive message the account owner wrote (`SENT` label or a known owner address; a calendar RSVP or other noise does not count) | **yes, overriding every rule below** || pure noise senders / pure calendar notices | no |-| `CATEGORY_PROMOTIONS` / `CATEGORY_SOCIAL` / `CATEGORY_FORUMS` | no, unless the owner joined in |+| `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 || ordinary human correspondence | yes |diff --git a/src/core/google/gmail-categories.ts b/src/core/google/gmail-categories.tsnew file mode 100644index 0000000000..3072d6c27a--- /dev/null+++ b/src/core/google/gmail-categories.ts@@ -0,0 +1,16 @@+/**+ * gmail-categories — the Gmail category labels both open-loop lanes treat as+ * bulk by construction (#5103). The deterministic detector (loop-detect.ts)+ * and the extraction eligibility gate (loops-extract.ts) import this one+ * list, so the rule lives once: a thread under one of these categories opens+ * nothing unless the account owner wrote a substantive message in it.+ * `CATEGORY_UPDATES` is deliberately absent: invoices, contracts and document+ * requests land there and carry real obligations.+ */+export const BULK_CATEGORY_LABELS: readonly string[] = ['CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS'];++/** Whether any of `labelIds` is a bulk category. */+export function hasBulkCategory(labelIds: Iterable<string>): boolean {+ for (const label of labelIds) if (BULK_CATEGORY_LABELS.includes(label)) return true;+ return false;+}diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.tsindex 9745925657..396c4ef30c 100644--- a/src/core/google/google-render.ts+++ b/src/core/google/google-render.ts@@ -30,9 +30,16 @@ const NOISE_SENDER_SUBSTRINGS = ['do-not-reply',];+/**+ * Fixed Google system addresses that carry no human obligation (#5103: the+ * Meet notes digest). Matched by EQUALITY, never as a substring, so a+ * lookalike address on another domain is still treated as a person.+ */+const GOOGLE_SYSTEM_SENDERS: ReadonlySet<string> = new Set(['[email protected]']);+export function isNoiseSender(fromAddress: string): boolean {const f = fromAddress.toLowerCase();- return NOISE_SENDER_SUBSTRINGS.some((p) => f.includes(p));+ return GOOGLE_SYSTEM_SENDERS.has(f) || NOISE_SENDER_SUBSTRINGS.some((p) => f.includes(p));}/**diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.tsindex 944953cfe3..2966c66980 100644--- a/src/core/google/loop-detect.ts+++ b/src/core/google/loop-detect.ts@@ -43,6 +43,7 @@ import {type SuppressionSet,} from '../loops/loops-store.ts';import { isCalendarSystemMail, isNoiseSender } from './google-render.ts';+import { hasBulkCategory } from './gmail-categories.ts';import type { GmailMessageMeta, GmailThreadData } from './types.ts';export const INBOUND_GRACE_HOURS = 24;@@ -192,6 +193,13 @@ export function detectThreadLoop(// ── Last word is theirs: do I owe a reply? ──// List mail never owes a reply.if (last.listUnsubscribe) return { open: [], close };+ // #5103: bulk by Gmail's own classification (promotions, social, forums)+ // owes no reply either, unless the owner wrote a substantive message in+ // the thread — the same rule the extraction lane applies. CATEGORY_UPDATES+ // is not bulk here: invoices and document requests live there.+ if (hasBulkCategory(messages.flatMap((m) => m.labelIds)) && !substantive.some((m) => isMine(m, myAddresses))) {+ return { open: [], close };+ }// CC-only (or bcc/list delivery with no To: match) does not owe a reply.const inTo = last.to.some((a) => myAddresses.has(a));if (!inTo) return { open: [], close };diff --git a/src/core/google/loops-extract.ts b/src/core/google/loops-extract.tsindex 192edd4e41..dddd404a68 100644--- a/src/core/google/loops-extract.ts+++ b/src/core/google/loops-extract.ts@@ -28,6 +28,7 @@ import type { BrainEngine } from '../engine.ts';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 { bareAddress, type GmailMessageMeta, type GmailThreadData } from './types.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { deriveTrust } from '../trust/taint.ts';@@ -64,8 +65,7 @@ export const LOOPS_EXTRACT_WINDOW_DAYS = 30;const LOOPS_EXTRACT_MAX_TOKENS = 2048;const LOOPS_EXTRACT_RETRY_MAX_TOKENS = 8192;-/** Gmail categories that are bulk by construction. */-const BULK_CATEGORY_LABELS = ['CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS'];+export { BULK_CATEGORY_LABELS } from './gmail-categories.ts';export interface ExtractEligibility {eligible: boolean;@@ -136,7 +136,7 @@ export function loopExtractionEligibility(if (substantive.some(ownerWrote)) return { eligible: true, reason: 'owner_participated' };// Bulk by Gmail's own classification, and the owner never joined in.- if (BULK_CATEGORY_LABELS.some((l) => labels.has(l))) {+ if (hasBulkCategory(labels)) {return { eligible: false, reason: 'bulk_category' };}diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.tsindex a176bc3e6b..2eb4968dcd 100644--- a/test/google-loop-detect.test.ts+++ b/test/google-loop-detect.test.ts@@ -21,6 +21,8 @@ import {type ThreadLoopVerdict,} from '../src/core/google/loop-detect.ts';import type { SuppressionSet } from '../src/core/loops/loops-store.ts';+import { BULK_CATEGORY_LABELS } from '../src/core/google/gmail-categories.ts';+import { BULK_CATEGORY_LABELS as EXTRACT_LANE_BULK_CATEGORY_LABELS } from '../src/core/google/loops-extract.ts';import type { GmailMessageMeta, GmailThreadData } from '../src/core/google/types.ts';// Frozen clock — every age below is relative to this instant, so the corpus@@ -48,6 +50,8 @@ interface MsgSpec {autoSubmitted?: boolean;/** Explicit internalDateMs override (0 = the all-zero-date case). */dateMs?: number;+ /** Extra Gmail label ids (categories) beside SENT/INBOX. */+ labels?: string[];}function msg(spec: MsgSpec): GmailMessageMeta {@@ -66,7 +70,7 @@ function msg(spec: MsgSpec): GmailMessageMeta {internalDateMs,calendarMethod: spec.calendarMethod ?? null,...(spec.autoSubmitted !== undefined ? { autoSubmitted: spec.autoSubmitted } : {}),- labelIds: spec.sent ? ['SENT'] : ['INBOX'],+ labelIds: [spec.sent ? 'SENT' : 'INBOX', ...(spec.labels ?? [])],listUnsubscribe: spec.listUnsub ?? false,bodyText: spec.body ?? 'Can you review the plan?',};@@ -864,3 +868,60 @@ describe('google calendar system mail', () => {expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);});});++describe('#5103: Google system senders and bulk categories in the deterministic lane', () => {+ const detect = (messages: GmailMessageMeta[]): ThreadLoopVerdict => detectThreadLoop(thread(messages), MY, NOW);++ test('both lanes read one bulk-category constant', () => {+ expect(EXTRACT_LANE_BULK_CATEGORY_LABELS).toBe(BULK_CATEGORY_LABELS);+ expect([...BULK_CATEGORY_LABELS]).toEqual(['CATEGORY_PROMOTIONS', 'CATEGORY_SOCIAL', 'CATEGORY_FORUMS']);+ });++ test('a Meet notes digest from [email protected] opens no inbound loop', () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Notes: weekly sync', body: 'Here are the notes. Any corrections?' })]);+ expect(v.open).toEqual([]);+ });++ test('a lookalike address is matched by equality only, so it still opens a loop', () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48 })]);+ expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);+ });++ for (const label of BULK_CATEGORY_LABELS) {+ test(`${label} inbound the owner never joined → no loop`, () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: [label] })]);+ expect(v.open).toEqual([]);+ });+ }++ test('a PROMOTIONS thread the owner wrote a substantive message in still opens the reply-owed loop', () => {+ const v = detect([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 200, labels: ['CATEGORY_PROMOTIONS'], body: 'Spring sale is on.' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 150, sent: true, labels: ['CATEGORY_PROMOTIONS'], body: 'Is the blue model still available in size 10?' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_PROMOTIONS'], body: 'Yes, could you confirm your shipping address?' }),+ ]);+ expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);+ });++ test('CATEGORY_UPDATES without an owner reply still opens (invoices and document requests live there)', () => {+ const v = detect([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_UPDATES'], body: 'Could you approve the attached invoice?' })]);+ expect(v.open.map((o) => o.loopType)).toEqual(['unanswered_inbound']);+ });++ test('a bulk category never fabricates a close: my reply still closes, and their reply still closes my outbound loop', () => {+ const v = detect([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, labels: ['CATEGORY_PROMOTIONS'] }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 2, sent: true, labels: ['CATEGORY_PROMOTIONS'], body: 'Done, thanks for the details.' }),+ ]);+ expect(v.close).toEqual(['unanswered_inbound']);+ expect(v.open).toEqual([]);+ });++ test('a mixed thread: the system digest is ignored and the human message to me opens the loop', () => {+ const v = detect([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 60, subject: 'Notes: planning' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, subject: 'Re: planning', body: 'Can you send the budget sheet?' }),+ ]);+ expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);+ });+});diff --git a/test/google-render.test.ts b/test/google-render.test.tsindex 3777668d6e..a377b37696 100644--- a/test/google-render.test.ts+++ b/test/google-render.test.ts@@ -157,6 +157,13 @@ describe('isNoiseSender', () => {expect(isNoiseSender('[email protected]')).toBe(false);expect(isNoiseSender('[email protected]')).toBe(false);});++ test('#5103: Google system senders match by exact address, never by substring', () => {+ expect(isNoiseSender('[email protected]')).toBe(true);+ expect(isNoiseSender('[email protected]')).toBe(true);+ expect(isNoiseSender('[email protected]')).toBe(false);+ expect(isNoiseSender('[email protected]')).toBe(false);+ });});describe('isCalendarSystemMail', () => {