Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(google): one bad contact or event no longer stops its sweep, Gmail or the sync token (GBRA-130 A-3)
garrytanee0dee1e3871
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 0bcaefbbf9..60c24744af 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -27,7 +27,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `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`; any other 400 on such a request is a `GoogleSyncTokenRejectedError` (a `CredentialError('upstream')` subclass the contacts sweep alone treats as cursor-invalid, #6324); initial-list requests and other APIs remain plain upstream failures. `CONTACT_PERSON_FIELDS` (`names,emailAddresses,organizations,phoneNumbers,memberships`) is the one People field mask, repeated on every page of a list; `ContactData` carries deduplicated E.164 `phones` and user-group `groups` (`{id, name: null}`, system groups dropped), and `listContactGroups()` walks `contactGroups` for at most ten 1000-row pages and reports `complete: false` past that. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. The Gmail mapper also captures `precedence` (lower-cased), `listId` (present or not) and `replyTo` for the automated-mail loop rule (#5012). A 403 that is not API-disabled, rate-limit or quota is `GoogleForbiddenError` (still `CredentialError` `upstream`); `calendarUnreadableStatus(e)` maps it and a 404 `GoogleCursorExpiredError` to 403/404, and `CalendarClient.probeCalendar(id)` is one `maxResults=1` read. Pinned by injected-response tests in `test/google-clients.test.ts`, `test/contacts-phone-only-groups-6324.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` — `isPositivelyAutomated(meta)` (#5012): `Precedence: bulk|list|junk`, a `List-Id`, a noise From or a noise Reply-To. 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). `renderPersonPage` (#6324) renders a contact with emails OR phones: `emails:` always, `phones:` and `groups:` (names, or the raw `contactGroups/<id>` when unresolved) only when non-empty, phones never in `aliases`; a contact with neither name nor email lives at `contactIdSlug` = `<dir>/contact-<sha8(resourceName)>`, which `personSlugFromContact` returns for a phone-only nameless contact and the sweep's tombstone path lists as a delete candidate. Pinned by `test/google-render.test.ts` and `test/contacts-phone-only-groups-6324.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/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 sweep left no failing item that is not yet held (410 GONE drops the token and re-runs windowed); GBRA-130 A-3: `people-calendar-sweep.ts` sends each contact (`contact:<resourceName>`) and event (`event:<calendarId>:<eventId>`) through the connector item holds, so one failing item is reported while its siblings and Gmail land (only a content-class failure counts toward a hold; a transient one, and on a managed brain a failed coordinator write, keep their old paths), a held item stops pinning the token, a held item that retry-held re-admits and no listing returns is re-fetched by id (`PeopleClient.getContact`, `CalendarClient.getEvent`), an identity field carrying a NUL or lone surrogate is refused `invalid_connector_text` before any lookup, and Gmail's held-thread pass and `gbrain waiting` coverage skip those keys (`isGmailHoldKey`, pinned by `test/pathological/a3-google-items.test.ts`); 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). Its contacts cursor contract (#6324): `contacts_sync_token` and `contacts_person_fields` (the mask that minted it) commit together after the whole sweep, never on abort or import failure; a recorded mask other than `CONTACT_PERSON_FIELDS` (legacy state has none) drops the token for one full list; an expired or `GoogleSyncTokenRejectedError` token gets exactly one full-list attempt and a second failure propagates with the token nulled, not blessed; a full list that returns no replacement token leaves `contacts_sync_token` null when the mask changed (another full list follows) and keeps the old token when it did not. `resolveContactGroups` reads the directory only when a listed contact carries a user group, replaces the `contact_groups` state cache on a complete read, merges and logs on an incomplete one, and falls back to the cache when the read fails; unresolved groups render as raw ids. Pinned by `test/contacts-phone-only-groups-6324.test.ts`; the migration-176 test in `test/connector-wave3.test.ts` asserts the resumed legacy token is NOT reused (first sweep lists without it, the second reuses the fresh one). 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/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. `status` reports each linked source's calendar readability (`google-calendar-status.ts`, live probe unless `--no-probe`); an unreadable calendar makes the JSON `ok: false` and the exit 1.diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex e205ee7299..d4ff4681bf 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -349,6 +349,21 @@ skipped silently:- for Gmail, `gbrain waiting` returns `completeness: "partial"` and names eachheld thread from the last 14 days (or with an unknown date).+Contacts and Calendar items are held the same way, keyed+`contact:<resource name>` and `event:<calendar id>:<event id>`. One failing+contact or event no longer stops its sweep: the other contacts and events, and+the Gmail sweep, still land. Only a failure that repeats until the item changes+(for example a contact email or event attendee carrying text the brain cannot+store, `invalid_connector_text`) counts toward a hold; a transient failure is+retried on the next sync and never held. While the failing item is not held,+that service's sync token stays where it is, so the next sync lists the item+again; once it is held, the token moves past it. On a managed brain a failed+coordinator write still ends the run, as before, and `--retry-failed`+re-admits it. Because a sync token never lists an+unchanged item again, `gbrain sources retry-held` re-fetches a held contact or+event by its id on the next sync. Contacts and Calendar holds do not change the+coverage `gbrain waiting` reports, which is about mail.+A held item does not block the source's freshness stamp. To re-attempt:```bashdiff --git a/src/core/connectors/connector-hold-session.ts b/src/core/connectors/connector-hold-session.tsindex d3ede884e8..5078be21ab 100644--- a/src/core/connectors/connector-hold-session.ts+++ b/src/core/connectors/connector-hold-session.ts@@ -20,7 +20,7 @@ import { clearHoldRetryKeys, readHoldRetryKeys, writeHeldRetryPointer } from './import { holdsExhaustedError, ItemHoldsRun, type ClassifiedConnectorError, type ItemHoldMeta, type ItemHoldsFinish, type ItemHoldsState } from './item-holds.ts';/** Errors a managed connector must not absorb (the run aborts). Refusals raised before submission are counted instead. */-function abortsManagedRun(error: unknown): boolean {+export function abortsManagedRun(error: unknown): boolean {if (error instanceof LockStolenError || (error as { name?: string } | null)?.name === 'ConnectorWaitBudgetStop') return true;if (!(error instanceof OperationError)) return false;return !(error.code === 'invalid_connector_text' && !error.writeRequest);diff --git a/src/core/connectors/connector-text.ts b/src/core/connectors/connector-text.tsindex 4aedbb562e..3b1cdce6cd 100644--- a/src/core/connectors/connector-text.ts+++ b/src/core/connectors/connector-text.ts@@ -28,10 +28,15 @@ const cleanIdentity = (value: string) => value.isWellFormed() && !value.includes* changes prose only.*/export function connectorRender(markdown: string, identity: Record<string, string | readonly string[] | null | undefined>): string {+ assertConnectorIdentity(identity);+ return sanitizeForJsonb(markdown);+}++/** Refuses an identity field carrying a NUL or a lone surrogate (`invalid_connector_text`), before it reaches a lookup or a page. */+export function assertConnectorIdentity(identity: Record<string, string | readonly string[] | null | undefined>): void {for (const [field, value] of Object.entries(identity)) {for (const item of value == null ? [] : typeof value === 'string' ? [value] : value) {if (!cleanIdentity(item)) throw invalidConnectorText(field);}}- return sanitizeForJsonb(markdown);}diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.tsindex 542c6361c9..97b1f3d5b0 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -512,6 +512,7 @@ export class GmailClient extends GoogleApiClient {interface RawCalendarEvent {id: string;+ etag?: string;status?: string;summary?: string;description?: string;@@ -524,6 +525,30 @@ interface RawCalendarEvent {htmlLink?: string;}+function calendarEvent(e: RawCalendarEvent, account: string): CalendarEventData {+ return {+ id: e.id,+ ...(e.etag ? { etag: e.etag } : {}),+ summary: e.summary ?? '(no title)',+ description: e.description ?? '',+ startIso: e.start?.dateTime ?? (e.start?.date ? `${e.start.date}T00:00:00Z` : ''),+ endIso: e.end?.dateTime ?? (e.end?.date ? `${e.end.date}T00:00:00Z` : ''),+ allDay: Boolean(e.start?.date),+ organizer: e.organizer?.email?.toLowerCase() ?? null,+ attendees: (e.attendees ?? []).map((a) => ({+ email: (a.email ?? '').toLowerCase(),+ displayName: a.displayName ?? null,+ self: a.self ?? false,+ responseStatus: a.responseStatus ?? null,+ })),+ location: e.location ?? null,+ hangoutLink: e.hangoutLink ?? null,+ htmlLink: e.htmlLink ?? null,+ status: e.status ?? 'confirmed',+ account,+ };+}+export class CalendarClient extends GoogleApiClient {/*** Incremental when syncToken is set; windowed otherwise. Throws@@ -568,27 +593,21 @@ export class CalendarClient extends GoogleApiClient {'calendar-json',opts,);- const events = raw.map((e): CalendarEventData => ({- id: e.id,- summary: e.summary ?? '(no title)',- description: e.description ?? '',- startIso: e.start?.dateTime ?? (e.start?.date ? `${e.start.date}T00:00:00Z` : ''),- endIso: e.end?.dateTime ?? (e.end?.date ? `${e.end.date}T00:00:00Z` : ''),- allDay: Boolean(e.start?.date),- organizer: e.organizer?.email?.toLowerCase() ?? null,- attendees: (e.attendees ?? []).map((a) => ({- email: (a.email ?? '').toLowerCase(),- displayName: a.displayName ?? null,- self: a.self ?? false,- responseStatus: a.responseStatus ?? null,- })),- location: e.location ?? null,- hangoutLink: e.hangoutLink ?? null,- htmlLink: e.htmlLink ?? null,- status: e.status ?? 'confirmed',- account,- }));- return { events, nextSyncToken };+ return { events: raw.map((e) => calendarEvent(e, account)), nextSyncToken };+ }++ /**+ * GBRA-130 A-3: one event by id, for re-attempting a held event that no+ * listing of this run returns. Null when the event is gone (404/410).+ */+ async getEvent(account: string, calendarId: string, eventId: string, opts: { signal?: AbortSignal } = {}): Promise<CalendarEventData | null> {+ const calId = encodeURIComponent(calendarId.trim() || DEFAULT_CALENDAR_ID);+ try {+ return calendarEvent(await this.fetchJSON<RawCalendarEvent>(`${CALENDAR_BASE}/calendars/${calId}/events/${encodeURIComponent(eventId)}`, 'calendar-json', opts), account);+ } catch (e) {+ if (e instanceof GoogleCursorExpiredError) return null;+ throw e;+ }}/**@@ -646,6 +665,7 @@ export class CalendarClient extends GoogleApiClient {interface RawPerson {resourceName: string;+ etag?: string;names?: Array<{ displayName?: string; metadata?: { primary?: boolean } }>;emailAddresses?: Array<{ value?: string }>;phoneNumbers?: Array<{ value?: string; canonicalForm?: string }>;@@ -677,6 +697,29 @@ const SYSTEM_CONTACT_GROUPS = new Set(/** Bounded directory walk: 1000 groups a page, ten pages; past that the result is explicitly incomplete. */const CONTACT_GROUP_PAGES = 10;+function contactData(p: RawPerson): ContactData {+ const primaryName = p.names?.find((n) => n.metadata?.primary) ?? p.names?.[0];+ const primaryOrg = p.organizations?.find((o) => o.metadata?.primary) ?? p.organizations?.[0];+ return {+ resourceName: p.resourceName,+ ...(p.etag ? { etag: p.etag } : {}),+ displayName: primaryName?.displayName ?? null,+ emails: (p.emailAddresses ?? [])+ .map((e) => (e.value ?? '').trim().toLowerCase())+ .filter((e) => e.includes('@')),+ phones: [...new Set((p.phoneNumbers ?? [])+ .map((n) => (n.canonicalForm ?? n.value ?? '').trim())+ .filter((n) => n.length > 0))],+ organization: primaryOrg?.name ?? null,+ title: primaryOrg?.title ?? null,+ groups: [...new Set((p.memberships ?? [])+ .map((m) => m.contactGroupMembership?.contactGroupResourceName ?? '')+ .filter((g) => g.startsWith('contactGroups/') && !SYSTEM_CONTACT_GROUPS.has(g)))]+ .map((id) => ({ id, name: null })),+ deleted: p.metadata?.deleted ?? false,+ };+}+export class PeopleClient extends GoogleApiClient {/** Incremental with syncToken; full otherwise. 410 → GoogleCursorExpiredError. */async listConnections(opts: {@@ -705,28 +748,21 @@ export class PeopleClient extends GoogleApiClient {'people',opts,);- const contacts = raw.map((p): ContactData => {- const primaryName = p.names?.find((n) => n.metadata?.primary) ?? p.names?.[0];- const primaryOrg = p.organizations?.find((o) => o.metadata?.primary) ?? p.organizations?.[0];- return {- resourceName: p.resourceName,- displayName: primaryName?.displayName ?? null,- emails: (p.emailAddresses ?? [])- .map((e) => (e.value ?? '').trim().toLowerCase())- .filter((e) => e.includes('@')),- phones: [...new Set((p.phoneNumbers ?? [])- .map((n) => (n.canonicalForm ?? n.value ?? '').trim())- .filter((n) => n.length > 0))],- organization: primaryOrg?.name ?? null,- title: primaryOrg?.title ?? null,- groups: [...new Set((p.memberships ?? [])- .map((m) => m.contactGroupMembership?.contactGroupResourceName ?? '')- .filter((g) => g.startsWith('contactGroups/') && !SYSTEM_CONTACT_GROUPS.has(g)))]- .map((id) => ({ id, name: null })),- deleted: p.metadata?.deleted ?? false,- };- });- return { contacts, nextSyncToken };+ return { contacts: raw.map(contactData), nextSyncToken };+ }++ /**+ * GBRA-130 A-3: one contact by resource name, for re-attempting a held+ * contact that no listing of this run returns. Null when it is gone (404/410).+ */+ async getContact(resourceName: string, opts: { signal?: AbortSignal } = {}): Promise<ContactData | null> {+ const path = resourceName.split('/').map(encodeURIComponent).join('/');+ try {+ return contactData(await this.fetchJSON<RawPerson>(`${PEOPLE_BASE}/${path}?personFields=${CONTACT_PERSON_FIELDS}`, 'people', opts));+ } catch (e) {+ if (e instanceof GoogleCursorExpiredError) return null;+ throw e;+ }}/**diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex 4989bba2f9..7228350204 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -56,6 +56,7 @@ import {import { renderThreadPage, threadRelPath } from './google-render.ts';import {ALL_GOOGLE_SERVICES,+ isGmailHoldKey,type GmailThreadData,type GoogleService,type GoogleSourceConfig,@@ -411,7 +412,7 @@ async function sweepGmail(g: GmailSweep, onCurrent?: () => Promise<void>): Promi// Held threads no listing of this run reached: re-attempt those retry-held// asked for or whose transient reconsideration is due. A failure keeps the// hold and never blocks the cursor.- for (const tid of g.holds.dueHeldKeys()) {+ for (const tid of g.holds.dueHeldKeys().filter(isGmailHoldKey)) {if (deps.opts.signal?.aborted) return false;await attemptThread(g, tid, null);}@@ -806,7 +807,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Goif (activeServices.includes('contacts')) {const stop = startHeartbeat(progress, 'contacts sweep');try {- await sweepContacts(deps, people, state, activePack, summary, countedSlugs);+ await sweepContacts(deps, people, state, activePack, summary, countedSlugs, holds);} catch (e) {if (managed) rethrowConnectorWriteError(e);serviceErrors.push(`contacts: ${e instanceof Error ? e.message : String(e)}`);@@ -821,7 +822,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Goif (activeServices.includes('calendar')) {const stop = startHeartbeat(progress, 'calendar sweep');try {- await sweepCalendar(deps, calendar, state, activePack, summary, countedSlugs);+ await sweepCalendar(deps, calendar, state, activePack, summary, countedSlugs, holds);} catch (e) {if (managed) rethrowConnectorWriteError(e);serviceErrors.push(`calendar: ${e instanceof Error ? e.message : String(e)}`);diff --git a/src/core/google/people-calendar-sweep.ts b/src/core/google/people-calendar-sweep.tsindex 764fe3f17d..7bbdfd9f93 100644--- a/src/core/google/people-calendar-sweep.ts+++ b/src/core/google/people-calendar-sweep.ts@@ -3,14 +3,28 @@* source kind (peeled from google-source.ts). Cursor discipline per service:* the syncToken is committed only after that service's fully-successful* sweep; an expired token drops it and re-lists windowed.+ *+ * GBRA-130 A-3: each contact (`contact:<resourceName>`) and each event+ * (`event:<calendarId>:<eventId>`) goes through the connector item holds+ * (connectors/connector-hold-session.ts). An item-scoped failure is reported+ * and the sweep goes on; only a content-class one counts toward a hold.+ * While a failing item is not held the service's token stays where it is, so+ * the next sync lists it again; once it is held the token moves past it. A held item that retry-held or a due+ * reconsideration re-admits and no listing returns is re-fetched by id.+ * Run-scoped failures stop the sweep as before.*/import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';+import { abortsManagedRun, type ConnectorHoldSession } from '../connectors/connector-hold-session.ts';+import { classifyConnectorError } from '../connectors/item-holds.ts';+import { assertConnectorIdentity } from '../connectors/connector-text.ts';+import { classifyItemFailure } from '../item-failure.ts';+import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, staleCalendarPages } from './calendar-window.ts';import { CalendarClient, calendarUnreadableStatus, CONTACT_PERSON_FIELDS, GoogleCursorExpiredError, GoogleSyncTokenRejectedError, PeopleClient } from './google-clients.ts';import { calendarRelPath, contactIdSlug, personSlugFromContact, renderCalendarEventPage, renderPersonPage } from './google-render.ts';-import { DEFAULT_CALENDAR_ID, type CalendarEventData, type ContactData, type GoogleSourceState } from './types.ts';+import { contactHoldKey, DEFAULT_CALENDAR_ID, eventHoldKey, type CalendarEventData, type ContactData, type GoogleSourceState } from './types.ts';import { deletePageByRelPath, importRendered, type ActivePack, type GoogleSyncDeps, type GoogleSyncSummary } from './sweep-shared.ts';// ── Contacts sweep ───────────────────────────────────────────────────────────@@ -22,6 +36,7 @@ export async function sweepContacts(activePack: ActivePack,summary: GoogleSyncSummary,countedSlugs: Set<string>,+ holds?: ConnectorHoldSession,): Promise<void> {const signal = deps.opts.signal ? { signal: deps.opts.signal } : {};// #6324: a syncToken is only valid with the request parameters that minted@@ -45,69 +60,22 @@ export async function sweepContacts(result = await people.listConnections({ syncToken: null, ...signal });}const groupNames = await resolveContactGroups(deps, people, state, result.contacts);- // Ownership is keyed on google_contact_id, not path alone: a page owned by- // a DIFFERENT contact (name collision — two "John Smith"s) must neither be- // rewritten nor deleted; the colliding contact gets a disambiguated slug.- const ownerOf = async (relPath: string): Promise<string | null> => {- if (deps.managed) {- const page = await deps.managed.page(relPath.replace(/\.md$/, ''));- if (!page) return null;- return typeof page.frontmatter.google_contact_id === 'string' ? page.frontmatter.google_contact_id : 'hand-authored';- }- const filePath = join(deps.cfg.dir, relPath);- if (!existsSync(filePath)) return null;- const m = readFileSync(filePath, 'utf-8').match(/^google_contact_id:\s*"([^"]+)"/m);- return m ? m[1] : 'hand-authored';- };- const contactsDir = deps.cfg.contactsDir;+ const sweep = { activePack, summary, countedSlugs, groupNames };+ let blocked = false;for (const c of result.contacts) {if (deps.opts.signal?.aborted) return;- // DB lookup by contact id FIRST, in any directory: deletion tombstones- // typically carry only resourceName + deleted (no names/emails — slug- // derivation yields null), a renamed contact's current name derives a- // DIFFERENT slug than the page it owns, and a changed `g_contacts_dir`- // (#4845) moves every page. All three need the id-keyed path (mirror of- // the calendar sweep's event_id keying).- const existingPath = await contactPageRelPathByContactId(deps, c.resourceName);- if (c.deleted) {- if (existingPath && await ownerOf(existingPath) === c.resourceName) {- await deletePageByRelPath(deps, existingPath, summary);- } else {- // Page not (yet) in the DB — fall back to slug candidates, guarded- // by file ownership. Delete only the page THIS contact owns.- for (const slug of [personSlugFromContact(c, false, contactsDir), personSlugFromContact(c, true, contactsDir), contactIdSlug(c.resourceName, contactsDir)]) {- if (slug && await ownerOf(`${slug}.md`) === c.resourceName) {- await deletePageByRelPath(deps, `${slug}.md`, summary);- }- }- }- continue;- }- const baseSlug = personSlugFromContact(c, false, contactsDir);- if (!baseSlug) continue;- const baseOwner = await ownerOf(`${baseSlug}.md`);- const collides = baseOwner !== null && baseOwner !== 'hand-authored' && baseOwner !== c.resourceName;- const rendered = renderPersonPage(- { ...c, groups: c.groups.map((g) => ({ id: g.id, name: groupNames[g.id] ?? null })) },- collides,- contactsDir,- );- if (!rendered) continue;- const owner = await ownerOf(rendered.relPath);- if (owner === 'hand-authored') {- deps.log(`[google] skipping hand-authored ${rendered.relPath}`);- continue;- }- // Staged rename: this contact previously rendered elsewhere (a rename, or- // a changed contacts directory). The new page lands first, then the page- // it owned at the old path is retired, so a sweep that dies in between- // leaves the contact with a page rather than none.- await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs);- if (existingPath && existingPath !== rendered.relPath && await ownerOf(existingPath) === c.resourceName) {- await deletePageByRelPath(deps, existingPath, summary);- }- deps.tick(`contact ${c.resourceName}`);+ const item = { key: contactHoldKey(c.resourceName), version: c.etag ?? null, title: c.displayName };+ if (!await throughHolds(deps, summary, holds, item, () => applyContact(deps, c, sweep))) blocked = true;}+ const prefix = contactHoldKey('');+ for (const key of holds?.dueHeldKeys().filter(k => k.startsWith(prefix)) ?? []) {+ if (deps.opts.signal?.aborted) return;+ await throughHolds(deps, summary, holds, { key, version: null, title: null }, async () => {+ const c = await people.getContact(key.slice(prefix.length), signal);+ if (c) await applyContact(deps, c, sweep);+ });+ }+ if (blocked) return;// Cursor and the mask it was minted under commit together, only after the// whole sweep succeeded. A full list that returned no replacement token// leaves no cursor behind (the next sweep lists fully again); a same-mask@@ -117,6 +85,120 @@ export async function sweepContacts(state.contacts_person_fields = CONTACT_PERSON_FIELDS;}+/**+ * One contact applied to the brain: a tombstone retires the page this+ * contact owns, anything else renders (disambiguated on a name collision)+ * and lands, retiring the page it owned at an older path.+ */+async function applyContact(deps: GoogleSyncDeps, c: ContactData,+ sweep: { activePack: ActivePack; summary: GoogleSyncSummary; countedSlugs: Set<string>; groupNames: Record<string, string> }): Promise<void> {+ assertConnectorIdentity({ google_contact_id: c.resourceName, emails: c.emails });+ const contactsDir = deps.cfg.contactsDir;+ // DB lookup by contact id FIRST, in any directory: deletion tombstones+ // typically carry only resourceName + deleted (no names/emails — slug+ // derivation yields null), a renamed contact's current name derives a+ // DIFFERENT slug than the page it owns, and a changed `g_contacts_dir`+ // (#4845) moves every page. All three need the id-keyed path (mirror of+ // the calendar sweep's event_id keying).+ const existingPath = await contactPageRelPathByContactId(deps, c.resourceName);+ if (c.deleted) {+ if (existingPath && await contactOwner(deps, existingPath) === c.resourceName) {+ await deletePageByRelPath(deps, existingPath, sweep.summary);+ } else {+ // Page not (yet) in the DB — fall back to slug candidates, guarded+ // by file ownership. Delete only the page THIS contact owns.+ for (const slug of [personSlugFromContact(c, false, contactsDir), personSlugFromContact(c, true, contactsDir), contactIdSlug(c.resourceName, contactsDir)]) {+ if (slug && await contactOwner(deps, `${slug}.md`) === c.resourceName) {+ await deletePageByRelPath(deps, `${slug}.md`, sweep.summary);+ }+ }+ }+ return;+ }+ const baseSlug = personSlugFromContact(c, false, contactsDir);+ if (!baseSlug) return;+ const baseOwner = await contactOwner(deps, `${baseSlug}.md`);+ const collides = baseOwner !== null && baseOwner !== 'hand-authored' && baseOwner !== c.resourceName;+ const rendered = renderPersonPage(+ { ...c, groups: c.groups.map((g) => ({ id: g.id, name: sweep.groupNames[g.id] ?? null })) },+ collides,+ contactsDir,+ );+ if (!rendered) return;+ const owner = await contactOwner(deps, rendered.relPath);+ if (owner === 'hand-authored') {+ deps.log(`[google] skipping hand-authored ${rendered.relPath}`);+ return;+ }+ // Staged rename: this contact previously rendered elsewhere (a rename, or+ // a changed contacts directory). The new page lands first, then the page+ // it owned at the old path is retired, so a sweep that dies in between+ // leaves the contact with a page rather than none.+ await importRendered(deps, rendered.relPath, rendered.markdown, sweep.activePack, sweep.summary, sweep.countedSlugs);+ if (existingPath && existingPath !== rendered.relPath && await contactOwner(deps, existingPath) === c.resourceName) {+ await deletePageByRelPath(deps, existingPath, sweep.summary);+ }+ deps.tick(`contact ${c.resourceName}`);+}++/**+ * Ownership is keyed on google_contact_id, not path alone: a page owned by+ * a DIFFERENT contact (name collision — two "John Smith"s) must neither be+ * rewritten nor deleted; the colliding contact gets a disambiguated slug.+ */+async function contactOwner(deps: GoogleSyncDeps, relPath: string): Promise<string | null> {+ if (deps.managed) {+ const page = await deps.managed.page(relPath.replace(/\.md$/, ''));+ if (!page) return null;+ return typeof page.frontmatter.google_contact_id === 'string' ? page.frontmatter.google_contact_id : 'hand-authored';+ }+ const filePath = join(deps.cfg.dir, relPath);+ if (!existsSync(filePath)) return null;+ const m = readFileSync(filePath, 'utf-8').match(/^google_contact_id:\s*"([^"]+)"/m);+ return m ? m[1] : 'hand-authored';+}++/**+ * One contact or event through the connector item holds. A held item is+ * skipped unless re-admitted; an item-scoped failure is reported and the+ * sweep goes on, and only a content-class one (the item fails the same way+ * until it changes) counts toward a hold; a run-scoped failure, and on a+ * managed brain a failed coordinator write, stop the sweep uncounted as+ * before. Returns false+ * when the item failed and was not already held: the service's token must+ * not move past it.+ */+async function throughHolds(deps: GoogleSyncDeps, summary: GoogleSyncSummary, holds: ConnectorHoldSession | undefined,+ item: { key: string; version: string | null; title: string | null }, apply: () => Promise<void>): Promise<boolean> {+ if (!holds) {+ await apply();+ return true;+ }+ if (!holds.shouldAttempt(item.key, item.version)) {+ deps.tick(`${item.key} held`);+ return true;+ }+ try {+ await apply();+ holds.succeed(item.key);+ return true;+ } catch (e) {+ // A failed managed write keeps its own path (the run ends; `--retry-failed` re-admits it), as before.+ if (classifyItemFailure(e).scope === 'run' || deps.managed && abortsManagedRun(e)) throw e;+ const classified = classifyConnectorError(e);+ if (classified.scope !== 'item') throw e;+ const wasHeld = holds.isHeld(item.key);+ // Only a failure the item will repeat until it changes counts toward a hold; a transient one is retried next sync.+ if (classified.class === 'content') await holds.fail(item.key, e, { version: item.version, meta: { title: item.title } });+ summary.failedFiles++;+ deps.log(`[google] ${JSON.stringify(item.key)} failed (${classified.code}): ${classified.message}; `+ + (classified.class === 'content' ? `counted toward a hold (see: gbrain sources status ${deps.sourceId})` : 'retried on the next sync'));+ if (wasHeld) return true;+ summary.status = 'partial';+ return false;+ }+}+/*** #6324: group names for this sweep's pages. Read the directory only when a* listed contact carries a user group; a complete read replaces the cache (a@@ -191,6 +273,7 @@ export async function sweepCalendar(activePack: ActivePack,summary: GoogleSyncSummary,countedSlugs: Set<string>,+ holds?: ConnectorHoldSession,): Promise<void> {const range = new CalendarSyncWindow(Date.now(), deps.cfg.historyDays, deps.cfg.futureDays ?? CALENDAR_HORIZON_DAYS);const list = (query: { syncToken: string } | { timeMinIso: string; timeMaxIso: string }) =>@@ -227,10 +310,11 @@ export async function sweepCalendar(}}state.calendar_unreadable = null;- const tally = { outside: 0 };- const sweepCtx = { activePack, summary, countedSlugs };+ const tally = { outside: 0, blocked: 0 };+ const sweepCtx = { activePack, summary, countedSlugs, holds };if (!await applyCalendarList(deps, result.events, range, sweepCtx, tally)) return;- if (result.nextSyncToken) {+ // A failing event that is not held yet keeps the token here, so the next sync lists it again.+ if (result.nextSyncToken && !tally.blocked) {state.calendar_sync_token = result.nextSyncToken;state.calendar_id = deps.cfg.calendarId;}@@ -243,7 +327,15 @@ export async function sweepCalendar(const caughtUp = await list(range.listBounds(catchUpFrom));if (!await applyCalendarList(deps, caughtUp.events, range, sweepCtx, tally)) return;}- if (wholeWindow || catchUpFrom !== null) state.calendar_horizon_ms = range.ceilMs;+ if (!tally.blocked && (wholeWindow || catchUpFrom !== null)) state.calendar_horizon_ms = range.ceilMs;+ const prefix = eventHoldKey(deps.cfg.calendarId, '');+ for (const key of holds?.dueHeldKeys().filter(k => k.startsWith(prefix)) ?? []) {+ if (deps.opts.signal?.aborted) return;+ await throughHolds(deps, summary, holds, { key, version: null, title: null }, async () => {+ const ev = await calendar.getEvent(deps.cfg.account, deps.cfg.calendarId, key.slice(prefix.length), deps.opts.signal ? { signal: deps.opts.signal } : {});+ if (ev) await applyEvent(deps, ev, range, sweepCtx, tally);+ });+ }if (tally.outside > 0) {deps.log(`[google] calendar: ${tally.outside} listed event(s) outside the sync window (${deps.cfg.historyDays} days back, ${range.futureDays} ahead) were not imported`);}@@ -269,30 +361,42 @@ function recordCalendarUnreadable(deps: GoogleSyncDeps, state: GoogleSourceStatereturn true;}+type CalendarSweepCtx = { activePack: ActivePack; summary: GoogleSyncSummary; countedSlugs: Set<string>; holds?: ConnectorHoldSession };+/**- * Apply one calendar list to the brain, event by event. Returns false when- * the sweep was aborted part-way, so the caller commits no cursor state.+ * Apply one calendar list to the brain, event by event, each through the+ * item holds (`tally.blocked` counts failing events not held yet). Returns+ * false when the sweep was aborted part-way, so the caller commits no cursor+ * state.*/async function applyCalendarList(deps: GoogleSyncDeps, events: CalendarEventData[], range: CalendarSyncWindow,- ctx: { activePack: ActivePack; summary: GoogleSyncSummary; countedSlugs: Set<string> }, tally: { outside: number }): Promise<boolean> {+ ctx: CalendarSweepCtx, tally: { outside: number; blocked: number }): Promise<boolean> {for (const ev of events) {if (deps.opts.signal?.aborted) return false;- const page = renderCalendarEventPage(ev);- const side = page ? range.side(ev.startIso, ev.endIso) : 'inside';- if (side !== 'inside') tally.outside++;- // Nothing is written or removed for an event that already ended before- // the window, so skip the page lookup.- if (side === 'before') continue;- const change = planCalendarPage(side, page?.relPath ?? null, await calendarPageRelPathByEventId(deps, ev.id), calendarRelPath(ev));- if (change.kind === 'remove') await deletePageByRelPath(deps, change.relPath, ctx.summary);- if (change.kind !== 'write' || !page) continue;- if (change.removeFirst) await deletePageByRelPath(deps, change.removeFirst, ctx.summary);- await importRendered(deps, page.relPath, page.markdown, ctx.activePack, ctx.summary, ctx.countedSlugs);- deps.tick(`event ${ev.id}`);+ const item = { key: eventHoldKey(deps.cfg.calendarId, ev.id), version: ev.etag ?? null, title: ev.summary };+ if (!await throughHolds(deps, ctx.summary, ctx.holds, item, () => applyEvent(deps, ev, range, ctx, tally))) tally.blocked++;}return !deps.opts.signal?.aborted;}+/** One event: written, moved or removed by where it falls against the sync window. */+async function applyEvent(deps: GoogleSyncDeps, ev: CalendarEventData, range: CalendarSyncWindow, ctx: CalendarSweepCtx,+ tally: { outside: number }): Promise<void> {+ assertConnectorIdentity({ event_id: ev.id, attendees: ev.attendees.map((a) => a.email) });+ const page = renderCalendarEventPage(ev);+ const side = page ? range.side(ev.startIso, ev.endIso) : 'inside';+ if (side !== 'inside') tally.outside++;+ // Nothing is written or removed for an event that already ended before+ // the window, so skip the page lookup.+ if (side === 'before') return;+ const change = planCalendarPage(side, page?.relPath ?? null, await calendarPageRelPathByEventId(deps, ev.id), calendarRelPath(ev));+ if (change.kind === 'remove') await deletePageByRelPath(deps, change.relPath, ctx.summary);+ if (change.kind !== 'write' || !page) return;+ if (change.removeFirst) await deletePageByRelPath(deps, change.removeFirst, ctx.summary);+ await importRendered(deps, page.relPath, page.markdown, ctx.activePack, ctx.summary, ctx.countedSlugs);+ deps.tick(`event ${ev.id}`);+}+/*** `--full`: delete the sweep's calendar pages whose event starts inside the* listed window but that the complete list no longer names (cancelled ordiff --git a/src/core/google/types.ts b/src/core/google/types.tsindex 8456f7d4ae..114c0d8e8b 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -312,6 +312,8 @@ export interface GmailThreadData {export interface CalendarEventData {/** Recurrence-instance id when expanded (singleEvents=true). */id: string;+ /** The event's revision: a held event whose etag changed upstream is re-attempted (GBRA-130 A-3). */+ etag?: string;summary: string;description: string;startIso: string;@@ -328,6 +330,8 @@ export interface CalendarEventData {export interface ContactData {resourceName: string;+ /** The person's revision: a held contact whose etag changed upstream is re-attempted (GBRA-130 A-3). */+ etag?: string;displayName: string | null;emails: string[];/** #6324: E.164 `canonicalForm` when Google supplies it, else the entered value; deduplicated. */@@ -344,6 +348,14 @@ export interface ContactData {deleted: boolean;}+/**+ * GBRA-130 A-3: connector item-hold keys of the Contacts and Calendar sweeps.+ * A Gmail hold keeps its bare (hex) thread id, so the prefixes never collide.+ */+export const contactHoldKey = (resourceName: string): string => `contact:${resourceName}`;+export const eventHoldKey = (calendarId: string, eventId: string): string => `event:${calendarId}:${eventId}`;+export const isGmailHoldKey = (key: string): boolean => !key.startsWith('contact:') && !key.startsWith('event:');+/** Extract the bare lowercase address from "Name <[email protected]>" or "[email protected]". */export function bareAddress(raw: string): string {const m = raw.match(/<([^>]+)>/);diff --git a/src/core/item-failure.ts b/src/core/item-failure.tsindex 2f5887b5f1..2936e5251d 100644--- a/src/core/item-failure.ts+++ b/src/core/item-failure.ts@@ -28,6 +28,8 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */export const ISOLATE_SITES = {'transcripts.ingest_session': 'A-2',+ 'google.contact': 'A-3',+ 'google.calendar_event': 'A-3',} as const satisfies Record<string, string>;export type IsolateSite = keyof typeof ISOLATE_SITES;diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex 86508b7c1e..44e776d04d 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -24,6 +24,7 @@ import type { Action } from '../agent-output.ts';import { hostFix, invalidParam, opTransport, paramUse, readFix } from './op-fix.ts';import { resolveRequestedScope, sourceScopeOpts } from './context.ts';import { validateSourceId } from '../utils.ts';+import { isGmailHoldKey } from '../google/types.ts';import { closedLoopWithActiveFact, retireLoopFact } from '../persistence/loop-fact-retirement.ts';import {addSuppression,@@ -124,7 +125,8 @@ async function heldCoverage(ctx: OperationContext, sources: GoogleSourceFreshnesconst now = Date.now();const held: HeldItemView[] = [];for (const entry of await readAllSourceHolds(ctx.engine, { sourceIds: sources.map((s) => s.id) })) {- for (const record of entry.held) {+ // Contacts and Calendar holds (GBRA-130 A-3) say nothing about mail coverage.+ for (const record of entry.held.filter((held) => isGmailHoldKey(held.key))) {const at = record.meta.upstream_at ? Date.parse(record.meta.upstream_at) : NaN;if (Number.isFinite(at) && now - at > HELD_WINDOW_MS) continue;held.push({ source_id: entry.sourceId, key: record.key, sender: record.meta.sender, ...(trusted ? { subject: record.meta.subject } : {}),diff --git a/test/pathological/a3-google-items.test.ts b/test/pathological/a3-google-items.test.tsnew file mode 100644index 0000000000..b55fa4e526--- /dev/null+++ b/test/pathological/a3-google-items.test.ts@@ -0,0 +1,286 @@+/**+ * GBRA-130 A-3: one bad Google contact or calendar event never stops the+ * Contacts or Calendar sweep, never stops Gmail, and never pins the sync token.+ *+ * 1. Protects: a failing contact (`contact:<resourceName>`) or event+ * (`event:<calendarId>:<eventId>`) is counted per item through the+ * connector item holds; its siblings and the Gmail sweep land in the same+ * run; the service's sync token stays put while the item still counts and+ * commits once only held items remain; `gbrain sources retry-held`+ * re-fetches a held item directly (people.get / events.get) with no+ * upstream edit; a transient item failure is reported and retried, never+ * held.+ * 2. Regression: a per-contact or per-event throw ending the whole service+ * sweep (siblings after it lost, token never committed).+ * 3. Existing coverage holds Gmail threads and GitHub items only+ * (connector-holds, fix-wave-4); the contacts/calendar tests stub one+ * failure and pin that it propagates (#6324 cursor contract).+ * 4. No production seam: the bad states are upstream identity text carrying+ * a NUL (a contact email, an event attendee: refused invalid_connector_text,+ * content class) and a stale `.tmp` directory left at a page path+ * (unmanaged, transient).+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseGoogleSourceConfig, readGoogleState, runGoogleSync } from '../../src/core/google/google-source.ts';+import { calendarRelPath, personSlugFromContact } from '../../src/core/google/google-render.ts';+import { readAllSourceHolds } from '../../src/core/connectors/item-holds-store.ts';+import { retryHeld } from '../../src/commands/sources-retry-held.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { sanitizeForJsonb } from '../../src/core/batch-rows.ts';+import { slugifyPath } from '../../src/core/sync.ts';+import { json, options, sourceCheckpoint, withGoogleAccount } from '../helpers/connector-fixture.ts';+import { addThread, fakeGmail, gmailFetch, type FakeGmail } from '../helpers/connector-holds-fixture.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';++const ACCOUNT = '[email protected]';+const CONFIG = { kind: 'google', g_account: ACCOUNT, g_services: 'contacts,calendar,gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };+const ENV = { CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' };+const DAY = 86_400_000;+const START = Math.floor(Date.now() / DAY) * DAY + 2 * DAY;+const EVENTS = '/calendar/v3/calendars/primary/events';++interface Person { resourceName: string; names: Array<{ displayName: string }>; emailAddresses: Array<{ value: string }>; organizations?: Array<{ name: string }> }+interface Ev { id: string; status: string; summary: string; description?: string; start: { dateTime: string }; end: { dateTime: string }; organizer: { email: string };+ attendees?: Array<{ email: string }> }+interface FakeGoogle { contacts: Map<string, Person>; events: Map<string, Ev>; contactDelta: string[]; eventDelta: string[]; tokens: { people: number; calendar: number };+ gets: string[]; gmail: FakeGmail }++const person = (resourceName: string, name: string, org?: string, email = `${name.toLowerCase().replace(/[^a-z]+/g, '.')}@example.invalid`): Person =>+ ({ resourceName, names: [{ displayName: name }], emailAddresses: [{ value: email }], ...(org ? { organizations: [{ name: org }] } : {}) });+const event = (id: string, hour: number, summary: string, description = '', attendee?: string): Ev => ({ id, status: 'confirmed', summary, description,+ start: { dateTime: new Date(START + hour * 3_600_000).toISOString() }, end: { dateTime: new Date(START + (hour + 1) * 3_600_000).toISOString() },+ organizer: { email: ACCOUNT }, ...(attendee ? { attendees: [{ email: attendee }] } : {}) });+/** Content-class bad items: identity text (an email, an attendee) carrying a NUL; their keys stay clean. */+const badContact = () => person('people/c2', 'Bob Example', undefined, 'bob.example\[email protected]');+const badEvent = () => event('e2', 2, 'Standup example', '', 'guest\[email protected]');+const BAD_KEYS = ['contact:people/c2', 'event:primary:e2'];++function fakeGoogle(): FakeGoogle {+ return { contacts: new Map(), events: new Map(), contactDelta: [], eventDelta: [], tokens: { people: 0, calendar: 0 }, gets: [], gmail: fakeGmail(ACCOUNT) };+}+const putContact = (fx: FakeGoogle, p: Person) => { fx.contacts.set(p.resourceName, p); fx.contactDelta.push(p.resourceName); };+const putEvent = (fx: FakeGoogle, ev: Ev) => { fx.events.set(ev.id, ev); fx.eventDelta.push(ev.id); };++function googleFetch(fx: FakeGoogle) {+ const gmail = gmailFetch(fx.gmail);+ return withGoogleAccount(async (url: string) => {+ const u = new URL(url);+ if (u.hostname === 'people.googleapis.com') {+ if (u.pathname === '/v1/people/me/connections') {+ const ids = u.searchParams.has('syncToken') ? fx.contactDelta : [...fx.contacts.keys()];+ return json({ connections: ids.map(id => fx.contacts.get(id)!), nextSyncToken: `ppl-${++fx.tokens.people}` });+ }+ const name = decodeURIComponent(u.pathname.slice('/v1/'.length));+ fx.gets.push(`contact:${name}`);+ const found = fx.contacts.get(name);+ return found ? json(found) : json({ error: { code: 404, message: 'Not Found' } }, 404);+ }+ if (u.hostname === 'www.googleapis.com' && u.pathname.startsWith(EVENTS)) {+ const rest = u.pathname.slice(EVENTS.length);+ if (!rest) {+ const ids = u.searchParams.has('syncToken') ? fx.eventDelta : [...fx.events.keys()];+ return json({ items: ids.map(id => fx.events.get(id)!), nextSyncToken: `cal-${++fx.tokens.calendar}` });+ }+ const id = decodeURIComponent(rest.slice(1));+ fx.gets.push(`event:primary:${id}`);+ const found = fx.events.get(id);+ return found ? json(found) : json({ error: { code: 404, message: 'Not Found' } }, 404);+ }+ return gmail(url);+ }, ACCOUNT);+}++const contactSlug = (p: Person) => personSlugFromContact({ resourceName: p.resourceName, displayName: p.names[0]!.displayName, emails: [], phones: [],+ organization: null, title: null, groups: [], deleted: false })!;+const eventRelPath = (ev: Ev) => calendarRelPath({ id: ev.id, startIso: ev.start.dateTime, summary: ev.summary } as never);++interface GoogleSource { id: string; dir: string; managed: boolean; run: (fx: FakeGoogle, engine?: BrainEngine) => ReturnType<typeof runGoogleSync> }++/** A Google source on the brain: managed (the brain's coordinator writes its pages) or unmanaged (pages land under its directory). */+async function googleSource(engine: BrainEngine, root: string, managed: boolean): Promise<GoogleSource> {+ const id = `google-${Math.random().toString(16).slice(2, 10)}`;+ const dir = join(root, '..', id);+ mkdirSync(dir);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,$3::text::jsonb)', [id, dir, JSON.stringify(CONFIG)]);+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const cfg = parseGoogleSourceConfig(CONFIG, dir);+ return { id, dir, managed, run: async (fx, using = engine) => {+ try { return await runGoogleSync(using, id, cfg, options, googleFetch(fx)); } finally { await disposePersistenceConsumer(engine); }+ } };+}++/** The contacts and calendar sync tokens the source's committed cursor carries. */+async function tokens(engine: BrainEngine, f: GoogleSource): Promise<{ contacts: string | null; calendar: string | null }> {+ const state = f.managed+ ? ((await sourceCheckpoint(engine, f.id)) as Array<{ completed_keys?: Array<{ state?: Record<string, unknown> }> }>)[0]?.completed_keys?.[0]?.state ?? {}+ : readGoogleState(f.dir) as unknown as Record<string, unknown>;+ return { contacts: (state.contacts_sync_token as string | null | undefined) ?? null, calendar: (state.calendar_sync_token as string | null | undefined) ?? null };+}++const held = async (engine: BrainEngine, id: string) => ((await readAllSourceHolds(engine, { sourceIds: [id] }))[0]?.held ?? [])+ .map(record => ({ key: record.key, code: record.code })).sort((a, b) => a.key.localeCompare(b.key));+const live = async (engine: BrainEngine, id: string, slug: string) => (await engine.executeRaw(+ 'SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [id, slug])).length === 1;++/** A clean first sweep: two contacts, two events, one Gmail thread; both sync tokens committed. */+async function seeded(engine: BrainEngine, root: string, managed: boolean) {+ const f = await googleSource(engine, root, managed);+ const fx = fakeGoogle();+ const [c1, c3] = [person('people/c1', 'Alice Example'), person('people/c3', 'Carol Example')];+ const [e1, e3] = [event('e1', 1, 'Planning example'), event('e3', 3, 'Review example')];+ for (const p of [c1, c3]) fx.contacts.set(p.resourceName, p);+ for (const ev of [e1, e3]) fx.events.set(ev.id, ev);+ addThread(fx.gmail, 'a1b2c3d4e5f60001', Date.now() - 3_600_000);+ expect((await f.run(fx)).status).not.toBe('partial');+ return { f, fx, c1, c3, e1, e3 };+}++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`A-3 google contacts and calendar (${backend})`, () => {+ for (const managed of [false, true]) {+ const mode = managed ? 'managed' : 'unmanaged';+ test(`item (${mode}): a failing contact and a failing event are counted, then held; their siblings and Gmail land, and each sync token commits once only held items remain`,+ async () => withEnv(ENV, () => managedBrain(async ({ engine, root }) => {+ const { f, fx, c1, e1 } = await seeded(engine, root, managed);+ const seededTokens = await tokens(engine, f);+ const before = await snapshotItems(engine, f.id);+ // Upstream: one bad new item and one healthy edit per service (the bad one listed first), plus new mail.+ putContact(fx, badContact());+ putContact(fx, person('people/c1', 'Alice Example', 'Acme Example'));+ putEvent(fx, badEvent());+ putEvent(fx, event('e1', 1, 'Planning example', 'An agenda.'));+ addThread(fx.gmail, 'a1b2c3d4e5f60002', Date.now() - 600_000);+ fx.gmail.history = ['a1b2c3d4e5f60002'];+ fx.gmail.historyResponseId = '101';+ const runs = [];+ for (let run = 0; run < 3; run++) runs.push(await expectUnitNotAborted(() => f.run(fx)));+ expect(runs.map(r => r.status)).toEqual(['partial', 'partial', 'partial']);+ expect(await tokens(engine, f)).toEqual(seededTokens);+ expectOthersUnchanged(before, await snapshotItems(engine, f.id),+ { expectProgress: [slugifyPath(`${contactSlug(c1)}.md`), slugifyPath(eventRelPath(e1))], progressFields: ['content_hash'] });+ const mail = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND frontmatter->>'thread_id'=$2", [f.id, 'a1b2c3d4e5f60002']);+ expect(mail).toHaveLength(1);+ const holds = await held(engine, f.id);+ for (const key of BAD_KEYS) expectItemFailure(holds.find(h => h.key === key), { key, code: 'invalid_connector_text' });+ expect(holds).toHaveLength(2);+ // Only held items remain: the next run completes and both tokens move past them.+ const fourth = await expectUnitNotAborted(() => f.run(fx));+ expect(fourth.status).not.toBe('partial');+ expect(fourth.connectorHolds).toMatchObject({ held: 2, retry_command: `gbrain sources retry-held ${f.id}` });+ const moved = await tokens(engine, f);+ expect(moved.contacts).not.toBe(seededTokens.contacts);+ expect(moved.calendar).not.toBe(seededTokens.calendar);+ }, { databaseUrl })), 240_000);++ test(`recovery (${mode}): retry-held re-fetches the held contact and event directly with no upstream edit; a re-attempt that still fails stays held without pinning a token`,+ async () => withEnv(ENV, () => managedBrain(async ({ engine, root }) => {+ const { f, fx } = await seeded(engine, root, managed);+ putContact(fx, badContact());+ putEvent(fx, badEvent());+ for (let run = 0; run < 4; run++) await expectUnitNotAborted(() => f.run(fx));+ expect((await held(engine, f.id)).map(h => h.key)).toEqual(BAD_KEYS);+ const heldTokens = await tokens(engine, f);+ // Upstream is unchanged, so no delta lists the items again: only a direct fetch reaches them.+ fx.contactDelta = [];+ fx.eventDelta = [];+ expect((await retryHeld(engine, f.id)).scheduled).toBe(2);+ fx.gets.length = 0;+ const retried = await expectUnitNotAborted(() => f.run(fx));+ expect(fx.gets.sort()).toEqual(BAD_KEYS);+ expect(retried.status).not.toBe('partial');+ expect((await held(engine, f.id)).map(h => h.key)).toEqual(BAD_KEYS);+ // Consumed: the next run re-fetches nothing, and the tokens keep moving.+ fx.gets.length = 0;+ await f.run(fx);+ expect(fx.gets).toEqual([]);+ expect((await tokens(engine, f)).contacts).not.toBe(heldTokens.contacts);+ // The provider fixes the items; a direct re-fetch now lands them and clears the holds.+ fx.contacts.set('people/c2', person('people/c2', 'Bob Example'));+ fx.events.set('e2', event('e2', 2, 'Standup example', '', '[email protected]'));+ await retryHeld(engine, f.id);+ await expectUnitNotAborted(() => f.run(fx));+ expect(await held(engine, f.id)).toEqual([]);+ expect(await live(engine, f.id, slugifyPath(`${contactSlug(badContact())}.md`))).toBe(true);+ expect(await live(engine, f.id, slugifyPath(eventRelPath(badEvent())))).toBe(true);+ }, { databaseUrl })), 240_000);+ }++ test('transient (unmanaged): a stale .tmp directory fails one contact and one event; siblings and Gmail land, the tokens wait, nothing is held, and clearing it lands both',+ async () => withEnv(ENV, () => managedBrain(async ({ engine, root }) => {+ const { f, fx, c1, e1 } = await seeded(engine, root, false);+ const seededTokens = await tokens(engine, f);+ const before = await snapshotItems(engine, f.id);+ const bob = person('people/c2', 'Bob Example');+ const standup = event('e2', 2, 'Standup example');+ const obstructions = [join(f.dir, `${contactSlug(bob)}.md.tmp`), join(f.dir, `${eventRelPath(standup)}.tmp`)];+ for (const dir of obstructions) mkdirSync(dir, { recursive: true });+ putContact(fx, bob);+ putContact(fx, person('people/c1', 'Alice Example', 'Acme Example'));+ putEvent(fx, standup);+ putEvent(fx, event('e1', 1, 'Planning example', 'An agenda.'));+ addThread(fx.gmail, 'a1b2c3d4e5f60002', Date.now() - 600_000);+ fx.gmail.history = ['a1b2c3d4e5f60002'];+ fx.gmail.historyResponseId = '101';+ for (let run = 0; run < 3; run++) expect((await expectUnitNotAborted(() => f.run(fx))).status).toBe('partial');+ expectOthersUnchanged(before, await snapshotItems(engine, f.id),+ { expectProgress: [slugifyPath(`${contactSlug(c1)}.md`), slugifyPath(eventRelPath(e1))], progressFields: ['content_hash'] });+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id=$1 AND frontmatter->>'thread_id'=$2", [f.id, 'a1b2c3d4e5f60002'])).toHaveLength(1);+ expect(await tokens(engine, f)).toEqual(seededTokens);+ expect(await held(engine, f.id)).toEqual([]);+ for (const dir of obstructions) rmSync(dir, { recursive: true });+ expect((await expectUnitNotAborted(() => f.run(fx))).status).not.toBe('partial');+ expect(await live(engine, f.id, slugifyPath(`${contactSlug(bob)}.md`))).toBe(true);+ expect(await live(engine, f.id, slugifyPath(eventRelPath(standup)))).toBe(true);+ expect((await tokens(engine, f)).contacts).not.toBe(seededTokens.contacts);+ }, { databaseUrl })), 240_000);++ const targets = [+ { title: 'run: a run-scoped failure inside a contact stops the sweep and records no hold', lookup: "frontmatter->>'google_contact_id' = $2", id: 'people/c3', token: 'contacts' as const,+ edit: (fx: FakeGoogle) => { putContact(fx, person('people/c1', 'Alice Example', 'Acme Example')); putContact(fx, person('people/c3', 'Carol Example', 'Acme Example')); },+ slug: (s: Awaited<ReturnType<typeof seeded>>) => slugifyPath(`${contactSlug(s.c3)}.md`) },+ { title: 'run: a run-scoped failure inside an event stops the sweep and records no hold', lookup: "frontmatter->>'event_id' = $2", id: 'e3', token: 'calendar' as const,+ edit: (fx: FakeGoogle) => { putEvent(fx, event('e1', 1, 'Planning example', 'An agenda.')); putEvent(fx, event('e3', 3, 'Review example', 'An agenda.')); },+ slug: (s: Awaited<ReturnType<typeof seeded>>) => slugifyPath(eventRelPath(s.e3)) },+ ];+ for (const target of targets) for (const injected of runScopedErrors()) {+ test(`${target.title} (${injected.name})`,+ async () => withEnv(ENV, () => managedBrain(async ({ engine, root }) => {+ const seed = await seeded(engine, root, true);+ const { f, fx } = seed;+ const seededTokens = await tokens(engine, f);+ const before = await snapshotItems(engine, f.id);+ target.edit(fx);+ const error = injected.error();+ const failing = new Proxy(engine, { get(target_, key) {+ const value = (target_ as unknown as Record<string | symbol, unknown>)[key];+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {+ if (sql.includes(target.lookup) && params?.[1] === target.id) throw error;+ return (value as (...a: unknown[]) => unknown).call(target_, sql, params);+ };+ return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target_) : value;+ } });+ for (let run = 0; run < 3; run++) {+ const outcome = await f.run(fx, failing).then(r => r.status, (e: unknown) => e);+ expect(outcome === error || outcome === 'partial').toBe(true);+ }+ expect(await held(engine, f.id)).toEqual([]);+ expect((await tokens(engine, f))[target.token]).toBe(seededTokens[target.token]);+ expect((await snapshotItems(engine, f.id)).get(target.slug(seed))).toEqual(before.get(target.slug(seed)));+ }, { databaseUrl })), 240_000);+ }++ test('breaker: when most contacts fail the same way at once the run is an outage and holds nothing', async () => withEnv(ENV, () => managedBrain(async ({ engine, root }) => {+ const { f, fx } = await seeded(engine, root, false);+ const seededTokens = await tokens(engine, f);+ for (let n = 4; n < 10; n++) putContact(fx, person(`people/c${n}`, `Person${String.fromCharCode(97 + n)} Example`, undefined, `p${n}\[email protected]`));+ for (let run = 0; run < 3; run++) expect((await expectUnitNotAborted(() => f.run(fx))).status).toBe('partial');+ expect(await held(engine, f.id)).toEqual([]);+ expect((await tokens(engine, f)).contacts).toBe(seededTokens.contacts);+ }, { databaseUrl })), 240_000);+ });+}diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.tsindex 8bf3bf761a..78c3afacdf 100644--- a/test/pathological/catalogue.ts+++ b/test/pathological/catalogue.ts@@ -21,4 +21,10 @@ export const CATALOGUE: Record<IsolateSite, SiteCases> = {'transcripts.ingest_session': { file: 'test/pathological/a2-transcripts-ingest.test.ts',item: 'item: a session the coordinator refuses is reported with its code and the other sessions land',run: 'run: a run-scoped failure inside a session stops the ingest' },+ 'google.contact': { file: 'test/pathological/a3-google-items.test.ts',+ item: 'a failing contact and a failing event are counted, then held',+ run: 'run: a run-scoped failure inside a contact stops the sweep and records no hold' },+ 'google.calendar_event': { file: 'test/pathological/a3-google-items.test.ts',+ item: 'a failing contact and a failing event are counted, then held',+ run: 'run: a run-scoped failure inside an event stops the sweep and records no hold' },};diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 12e8291655..34a102cf34 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -218,6 +218,8 @@ test/page-prepare-shared-origin-6517.test.tstest/page-purge-batch-sweep-6884.test.tstest/page-purge-journal-timeout-6511.test.tstest/page-state-engine.test.ts+test/pathological/a2-transcripts-ingest.test.ts+test/pathological/a3-google-items.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.ts