Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
google contacts: import phones and groups; bind the contacts cursor to its field mask (#6324)
garrytan145611186bdd
diff --git a/docs/GBRAIN_RECOMMENDED_SCHEMA.md b/docs/GBRAIN_RECOMMENDED_SCHEMA.mdindex f9da4355be..f714017d98 100644--- a/docs/GBRAIN_RECOMMENDED_SCHEMA.md+++ b/docs/GBRAIN_RECOMMENDED_SCHEMA.md@@ -184,6 +184,8 @@ aliases: ["Jenny Shao", "Jenny G. Shao", "JennyGShao", "[email protected]Aliases include: misspellings from meeting transcripts, maiden names, nicknames, email addresses, social handles, and phonetic variants. When the enrich skill encounters a new name variant for a known entity, it adds the variant to aliases — it does NOT create a new page.+Phone numbers are not aliases. A connector-rendered person page (Google Contacts) carries them under `phones:` in E.164 form, as exact identifiers for a deliberate `entity_identity_link` join; a digit string in `aliases` would match mentions it has nothing to do with.+### Deduplication protocolBefore creating any new page, the agent must:diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 2589b45ff7..ca1ddd8448 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -22,13 +22,13 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/creds/redirect.ts` — how the authorization code gets back to us: `RedirectStrategy = 'loopback' | 'paste' | 'hosted-callback'`. Loopback is an ephemeral 127.0.0.1 listener; paste mode needs NO listener (the fixed `PASTE_REDIRECT_URI` fails to load, the user pastes the full address-bar URL back) and is auto-selected by `sniffHeadless` (SSH/WSL/container/no-display). Google's device-code flow is NOT an option — Gmail/Calendar/Contacts scopes are excluded from it; don't re-litigate.- `src/core/creds/relay-client.ts` — the typed CLIENT half of the gbrain.io zero-retention consent relay (`createSession` → user clicks the consent URL → poll a one-time `claim`; the relay deletes tokens on first successful claim or at session TTL). Inert unless `GBRAIN_OAUTH_RELAY_URL` is set (unset = the BYO flow, which always works). `test/creds-relay-client.test.ts` is the server conformance spec — a server that round-trips those fixtures is compatible.- `src/core/creds/export.ts` — versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.-- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's. `GoogleSourceState.calendar_horizon_ms` is the ceiling of the last calendar list that reached it (calendar-window.ts); absent on state saved before it existed. `GoogleSourceConfig.futureDays` (#5442) and `loopsExcludeLabels` (#5445) are optional and absent when their keys are unset; `source-config.ts` parses them (`g_future_days` 1..3650 floored, `g_loops_exclude_labels` through `parseExcludeLabelTokens`) and `googleTuningConfig` is the one writer of those keys plus `g_calendar_id`, each only when set, for `addSource`. Both `sources add` parsers accept `--future-days` and `--loops-exclude-labels`: the connected-source parser validates through the operation contract (`sources-lifecycle-args.ts`), the legacy parser through `commands/sources-google-flags.ts` (`parseGoogleAddFlag`, exit 2 on a bad value), so neither `runAdd` nor `addSource` grows for a new tuning key.+- `src/core/google/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. `GoogleSourceState.contacts_person_fields` (#6324) is the People field mask `contacts_sync_token` was minted under, written only together with the token; absent on legacy state, which the sweep therefore lists fully once. `contact_groups` caches the group directory (resource name → display name) and is never authoritative on its own. `ContactData` carries `phones: string[]` and `groups: {id, name|null}[]`. `GoogleSourceConfig.futureDays` (#5442) and `loopsExcludeLabels` (#5445) are optional and absent when their keys are unset; `source-config.ts` parses them (`g_future_days` 1..3650 floored, `g_loops_exclude_labels` through `parseExcludeLabelTokens`) and `googleTuningConfig` is the one writer of those keys plus `g_calendar_id`, each only when set, for `addSource`. Both `sources add` parsers accept `--future-days` and `--loops-exclude-labels`: the connected-source parser validates through the operation contract (`sources-lifecycle-args.ts`), the legacy parser through `commands/sources-google-flags.ts` (`parseGoogleAddFlag`, exit 2 on a bad value), so neither `runAdd` nor `addSource` grows for a new tuning key.- `src/core/google/access.ts` — the pluggable Google-access seam: `GoogleAccessProvider` (`getAccessToken`/`forceRefresh`) with `CommandAccessProvider` (`--access command`: any CLI that prints a token — gog/gcloud/a gateway's mint command; parsed as a bare token line or JSON `{token|access_token, expiry|expires_in}`, cached until expiry with a 60s margin, 30s exec timeout, failures = `access_command_failed` carrying the stderr tail) and `EnvAccessProvider` (`--access env`: a live token read from a NAMED env var each call, refreshed outside gbrain; missing = `access_env_missing`). The vault flow's `GoogleTokenProvider` satisfies the same interface. The token command executes only in the locally-running sync (google config keys are unreachable over MCP; same trust class as recipe health-check argv).-- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.+- `src/core/google/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. 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` — 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-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). `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/calendar-window.ts` — which calendar events a google source keeps pages for: `[now - historyDays, now + futureDays]` (`g_future_days`, 1..3650, default `CALENDAR_HORIZON_DAYS` = 60; the parsed `futureDays` leaf exists only when the key is set, so an unset knob leaves every existing source's connector identity unchanged), checked by the sweep itself on every list because a syncToken delta cannot carry timeMin/timeMax. `CalendarSyncWindow` is built once per sweep: `side(start, end)` follows Google's rule (an event is `before` when it ends at or before the floor, `after` when it starts at or past the ceiling, unparseable dates stay `inside`); `coverageStartMs(horizon, listedWholeWindow)` says where the catch-up list for unchanged instances crossing the leading edge starts (none after a whole-window list, now for state without `calendar_horizon_ms`, the recorded horizon once the ceiling is a day past it); `startsInside` and `startsAfter` are the `--full` reconcile tests. `planCalendarPage` maps one listed event to a page change (a cancellation removes its page anywhere, aged-out history is left as it is, a page past the horizon is removed, otherwise write after removing a copy at an older path). `unlistedCalendarPages` returns sweep pages (with an `event_id`) starting inside the window that a complete `--full` list did not name; `staleCalendarPages` adds the sweep pages starting at or past the ceiling, which no windowed list can name (#5442), and is what the `--full` reconcile deletes through. `people-calendar-sweep.ts` (the contacts and calendar sweeps, peeled from `google-source.ts`) performs the changes with `importRendered`/`deletePageByRelPath`, discards the catch-up list's sync token, advances `calendar_horizon_ms` only after a list reached the ceiling, and sends reconcile deletes through the >200 mass-delete guard (a refusal marks the run partial). Tests: `test/google-calendar-window.test.ts` (pure rules), `test/google-source-reconcile.test.ts` (calendar window suite).+- `src/core/google/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.- `src/commands/creds.ts` — `gbrain creds list|remove|export|import`: the provider-agnostic vault surface; never prints a secret (list is always redacted). Provider-SPECIFIC connect flows live in their own commands. Export custody: a loud per-credential warning when a byo Google entry's consent screen is not known published-to-Production (its 7-day Testing expiry travels with the tokens).diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex 8dbecebe4a..07bb52cc60 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -123,6 +123,36 @@ Two remedies, independent of each other:pages it reaches; `gbrain doctor --only junk_entity_hubs` names thecanonical twin of each stub and the next step.+### What a contact page carries++Each page records the contact's names, email addresses, organization and+title, phone numbers and user-created contact groups:++- `emails:` is always present (empty for a phone-only contact); `phones:`+ appears when the contact has any, in E.164 form (`+15550100`) where Google+ supplies it, else as entered. Phones are exact identifiers for a manual+ `entity_identity_link` join, not aliases: a digit string never takes part+ in mention matching.+- `groups:` lists the display names of the contact's user-created groups+ (Google's built-in groups such as My Contacts or Starred are omitted). The+ names come from one bounded `contactGroups` read per sweep that needs it;+ when that read fails the sweep uses the names it cached last time, and a+ group it cannot name at all is carried as its raw `contactGroups/<id>`. A+ renamed or deleted group reaches a page when that contact next changes, or+ on `gbrain sync --full`.+- A contact with phones but no email gets a page too; one with no name+ either lives at `contact-<id-hash>` (never at its phone number). A contact+ with neither emails nor phones renders nothing.++The contacts cursor is bound to the field mask that minted it: the People+API rejects a sync token reused with different request parameters, so the+source state records the mask next to the token (`contacts_person_fields`),+commits the two together only after a sweep completed, and lists every+contact once when the mask changes (as it did when phones and groups+arrived). A sync token Google rejects with a 400 that is not an expiry gets+exactly one full-list attempt; if that list fails as well, the error+surfaces and the cursor is left alone.+## Secondary calendarsThe calendar sweep reads ONE calendar per source (so each keeps its own@@ -386,8 +416,10 @@ attached. The catalog (also emitted as structured JSON with `--json`):Cursor expiries (`historyId` older than ~a week, calendar/contacts`syncToken` 410, or a contacts HTTP 400 explicitly reporting an expired synctoken) use bounded re-lists automatically. Contacts recovery refreshes its-own cursor without restarting Gmail. Unrelated HTTP 400 errors remain-upstream failures rather than triggering a full re-list.+own cursor without restarting Gmail. A contacts HTTP 400 on a sync-token+request that is not an expiry (a token minted under other request+parameters) gets one full-list attempt; every other HTTP 400 remains an+upstream failure rather than triggering a re-list.## Custody, privacy, spenddiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e1b27c3095..6c0ff7d4d0 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -440,6 +440,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Fix wave 15 G6 (GBRA-79).{ since: '0.60.176.0', text: 'A subagent job whose final model turn produced no answer (an empty or whitespace-only body, a thinking-only turn) now ends with `stop_reason: error`, and a turn the provider stopped with `refusal` ends `refusal`; both used to be reported as a clean `end_turn`. A resumed job whose stored transcript already ends on such a turn is answered from the transcript with that stop reason instead of sending the turn back to the provider as an assistant prefill (which Haiku 5.5 and Sonnet 4.6+ reject with HTTP 400). The queue\'s terminal-state policy is unchanged; `require_writes` jobs that produced nothing already failed.' },{ since: '0.60.176.0', text: 'Embedding chunks are now capped at the documented per-input limit of four more hosted encoders: DashScope `text-embedding-v1` / `v2` (2,048 tokens; new chunks at most 1,228 estimated tokens instead of 2,000), Google `gemini-embedding-001` (2,048; it used to truncate long chunks silently), Zhipu `embedding-3` (3,072; chunks at most 1,843) and `embedding-2` (512; chunks at most 307). On a brain using one of them, the next `gbrain embed` or `embed --stale` pass splits stored chunks over the cap and re-embeds the pieces (billed as ordinary embedding tokens); other models chunk as before. A model with no declared cap whose provider rejects one chunk as too long is now split to a cap derived from that rejection and retried on the next pass, at most three times per page, instead of failing identically on every pass; the failure line names the fix when the descent stops.' },+ { since: '0.60.176.0', text: 'Google contacts now import phone numbers and user-created contact groups: person pages gain `phones:` (E.164 where Google supplies it) and `groups:` frontmatter, and a contact with phones but no email address, which used to produce no page at all, now gets one (at `contact-<id-hash>` when it also has no name). Because the People API ties a sync token to the request that minted it, the first contacts sweep after this upgrade lists every contact once (one full `connections.list` per Google source, within the usual quota) and then continues incrementally; `gbrain sync --full` is not needed. A group rename or deletion reaches a page when that contact next changes or on `--full`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/google/google-clients.ts b/src/core/google/google-clients.tsindex d88140f00b..400884e34b 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -161,6 +161,7 @@ export class GoogleApiClient {detail?.['@type'] === 'type.googleapis.com/google.rpc.ErrorInfo' && detail.reason === 'EXPIRED_SYNC_TOKEN',)) || /^Sync token (?:is )?expired\b/i.test(body.error?.message ?? '');if (expired) throw new GoogleCursorExpiredError(res.status, url);+ throw new GoogleSyncTokenRejectedError(url, body.error?.message ?? 'no detail');}throw new CredentialError('upstream', `: HTTP ${res.status} on ${apiHint} (${body.error?.message ?? 'no detail'})`);}@@ -207,6 +208,23 @@ export class GoogleCursorExpiredError extends Error {}}+/**+ * #6324: People answered a syncToken request with a 400 that is NOT the typed+ * expiry. The People API requires every other parameter of an incremental+ * request to match the call that minted the token, so a token minted under a+ * different `personFields` lands here. Still an upstream `CredentialError`+ * for every caller that does not own a contacts cursor; the contacts sweep+ * treats it as cursor-invalid and re-lists once.+ */+export class GoogleSyncTokenRejectedError extends CredentialError {+ constructor(url: string, detail: string) {+ super('upstream', `: HTTP 400 on people (${detail})`);+ this.name = 'GoogleSyncTokenRejectedError';+ this.url = url;+ }+ readonly url: string;+}+// ── Gmail ────────────────────────────────────────────────────────────────────type RawGmailPart = GmailMimePart;@@ -590,10 +608,35 @@ interface RawPerson {resourceName: string;names?: Array<{ displayName?: string; metadata?: { primary?: boolean } }>;emailAddresses?: Array<{ value?: string }>;+ phoneNumbers?: Array<{ value?: string; canonicalForm?: string }>;organizations?: Array<{ name?: string; title?: string; metadata?: { primary?: boolean } }>;+ memberships?: Array<{ contactGroupMembership?: { contactGroupResourceName?: string } }>;metadata?: { deleted?: boolean };}+interface RawContactGroup {+ resourceName?: string;+ name?: string;+ formattedName?: string;+ groupType?: string;+}++/**+ * #6324: the People field mask every contacts request carries. A syncToken is+ * only valid for requests with the parameters that minted it, so the sweep+ * records this string next to the token (`contacts_person_fields`) and+ * re-lists when it changes. Change it here and nowhere else.+ */+export const CONTACT_PERSON_FIELDS = 'names,emailAddresses,organizations,phoneNumbers,memberships';++/** Google's built-in groups (`contactGroups/myContacts`, `starred`, …) say nothing a page should carry. */+const SYSTEM_CONTACT_GROUPS = new Set(+ ['all', 'myContacts', 'starred', 'blocked', 'chatBuddies', 'friends', 'family', 'coworkers'].map((id) => `contactGroups/${id}`),+);++/** Bounded directory walk: 1000 groups a page, ten pages; past that the result is explicitly incomplete. */+const CONTACT_GROUP_PAGES = 10;+export class PeopleClient extends GoogleApiClient {/** Incremental with syncToken; full otherwise. 410 → GoogleCursorExpiredError. */async listConnections(opts: {@@ -604,7 +647,7 @@ export class PeopleClient extends GoogleApiClient {const raw = await this.drainPages<RawPerson>((t) => {const params = new URLSearchParams({- personFields: 'names,emailAddresses,organizations',+ personFields: CONTACT_PERSON_FIELDS,pageSize: '200',requestSyncToken: 'true',});@@ -631,11 +674,49 @@ export class PeopleClient extends GoogleApiClient {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 };}++ /**+ * #6324: the account's user-created contact groups, resource name → display+ * name. `complete` is false when the directory has more pages than the+ * bounded walk read; the caller keeps raw ids for whatever is missing+ * instead of treating one page as the whole directory.+ */+ async listContactGroups(opts: { signal?: AbortSignal } = {}): Promise<{ names: Record<string, string>; complete: boolean }> {+ let morePages = false;+ const raw = await this.drainPages<RawContactGroup>(+ (t) => {+ const params = new URLSearchParams({ pageSize: '1000', groupFields: 'name,groupType' });+ if (t) params.set('pageToken', t);+ return `${PEOPLE_BASE}/contactGroups?${params.toString()}`;+ },+ (body) => {+ const nextPageToken = (body.nextPageToken as string | undefined) ?? null;+ morePages = nextPageToken !== null;+ return { items: (body.contactGroups as RawContactGroup[] | undefined) ?? [], nextPageToken };+ },+ 'people',+ { ...opts, maxPages: CONTACT_GROUP_PAGES, partialOk: true },+ );+ const names: Record<string, string> = {};+ for (const g of raw) {+ if (!g.resourceName || g.groupType === 'SYSTEM_CONTACT_GROUP' || SYSTEM_CONTACT_GROUPS.has(g.resourceName)) continue;+ const name = (g.formattedName ?? g.name ?? '').trim();+ if (name) names[g.resourceName] = name;+ }+ return { names, complete: !morePages };+ }}diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.tsindex 649cb55aeb..3715db2e41 100644--- a/src/core/google/google-render.ts+++ b/src/core/google/google-render.ts@@ -343,9 +343,18 @@ export function renderCalendarEventPage(ev: CalendarEventData): RenderedPage | n// ── Person page (contacts) ───────────────────────────────────────────────────+/**+ * #6324: the page a contact with neither a name nor an email lives at, keyed+ * on its id (never on phone digits). The tombstone path lists it as a delete+ * candidate because the tombstone itself carries no phones.+ */+export function contactIdSlug(resourceName: string, dir: string = DEFAULT_CONTACTS_DIR): string {+ return `${dir}/contact-${sha8(resourceName)}`;+}+export function personSlugFromContact(c: ContactData, disambiguate = false, dir: string = DEFAULT_CONTACTS_DIR): string | null {const base = c.displayName ?? c.emails[0]?.split('@')[0] ?? null;- if (!base) return null;+ if (!base) return c.phones.length > 0 ? contactIdSlug(c.resourceName, dir) : null;const slug = base.toLowerCase().replace(/[^a-z0-9]+/g, '-')@@ -366,18 +375,23 @@ export function personSlugFromContact(c: ContactData, disambiguate = false, dir:*/export function renderPersonPage(c: ContactData, disambiguate = false, dir: string = DEFAULT_CONTACTS_DIR): RenderedPage | null {const slug = personSlugFromContact(c, disambiguate, dir);- if (!slug || c.emails.length === 0) return null;- const name = c.displayName ?? c.emails[0];+ if (!slug || (c.emails.length === 0 && c.phones.length === 0)) return null;+ const name = c.displayName ?? c.emails[0] ?? c.phones[0];+ // Phones are exact identifiers (`phones:`), not aliases: a digit string as+ // an alias would pollute mention matching.const aliases = [...new Set([...c.emails, ...(c.displayName ? [c.displayName] : [])])];+ const groups = c.groups.map((g) => g.name ?? g.id);const fm: string[] = ['---',`type: person`,`title: ${yamlStr(name)}`,`aliases: ${yamlList(aliases)}`,`emails: ${yamlList(c.emails)}`,+ ...(c.phones.length > 0 ? [`phones: ${yamlList(c.phones)}`] : []),`google_contact_id: ${yamlStr(c.resourceName)}`,...(c.organization ? [`company: ${yamlStr(c.organization)}`] : []),...(c.title ? [`role: ${yamlStr(c.title)}`] : []),+ ...(groups.length > 0 ? [`groups: ${yamlList(groups)}`] : []),'---',];const body = [@@ -386,7 +400,7 @@ export function renderPersonPage(c: ContactData, disambiguate = false, dir: stri'',[c.title && c.organization ? `${c.title} at ${c.organization}.` : c.organization ? `Works at ${c.organization}.` : null,- `Contact: ${c.emails.join(', ')}.`,+ `Contact: ${[...c.emails, ...c.phones].join(', ')}.`,`[Source: Google Contacts]`,].filter(Boolean)diff --git a/src/core/google/people-calendar-sweep.ts b/src/core/google/people-calendar-sweep.tsindex f976afa656..94d8c351bd 100644--- a/src/core/google/people-calendar-sweep.ts+++ b/src/core/google/people-calendar-sweep.ts@@ -8,9 +8,9 @@ import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, staleCalendarPages } from './calendar-window.ts';-import { CalendarClient, GoogleCursorExpiredError, PeopleClient } from './google-clients.ts';-import { calendarRelPath, personSlugFromContact, renderCalendarEventPage, renderPersonPage } from './google-render.ts';-import { DEFAULT_CALENDAR_ID, type CalendarEventData, type GoogleSourceState } from './types.ts';+import { CalendarClient, 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 { deletePageByRelPath, importRendered, type ActivePack, type GoogleSyncDeps, type GoogleSyncSummary } from './sweep-shared.ts';// ── Contacts sweep ───────────────────────────────────────────────────────────@@ -23,21 +23,28 @@ export async function sweepContacts(summary: GoogleSyncSummary,countedSlugs: Set<string>,): Promise<void> {+ const signal = deps.opts.signal ? { signal: deps.opts.signal } : {};+ // #6324: a syncToken is only valid with the request parameters that minted+ // it. A token minted under another `personFields` (legacy state has none+ // recorded) is unusable, so the sweep lists fully once and then records the+ // new token with the mask it was minted under.+ const maskChanged = state.contacts_person_fields !== CONTACT_PERSON_FIELDS;+ const syncToken = deps.opts.full || maskChanged ? null : state.contacts_sync_token;+ if (maskChanged && state.contacts_sync_token && !deps.opts.full) deps.log('[google] contacts field mask changed; full re-list');let result;try {- result = await people.listConnections({- syncToken: deps.opts.full ? null : state.contacts_sync_token,- ...(deps.opts.signal ? { signal: deps.opts.signal } : {}),- });+ result = await people.listConnections({ syncToken, ...signal });} catch (e) {- if (e instanceof GoogleCursorExpiredError) {- deps.log('[google] contacts syncToken expired; full re-list');- state.contacts_sync_token = null;- result = await people.listConnections({ syncToken: null, ...(deps.opts.signal ? { signal: deps.opts.signal } : {}) });- } else {- throw e;- }+ // One bounded recovery: an expired or rejected token drops to a single+ // full list; a failure of that list propagates and commits nothing.+ if (!syncToken) throw e;+ if (e instanceof GoogleCursorExpiredError) deps.log('[google] contacts syncToken expired; full re-list');+ else if (e instanceof GoogleSyncTokenRejectedError) deps.log('[google] contacts syncToken rejected (HTTP 400); one full re-list');+ else throw e;+ state.contacts_sync_token = null;+ 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.@@ -68,7 +75,7 @@ export async function sweepContacts(} 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)]) {+ 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);}@@ -80,7 +87,11 @@ export async function sweepContacts(if (!baseSlug) continue;const baseOwner = await ownerOf(`${baseSlug}.md`);const collides = baseOwner !== null && baseOwner !== 'hand-authored' && baseOwner !== c.resourceName;- const rendered = renderPersonPage(c, collides, contactsDir);+ 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') {@@ -97,8 +108,40 @@ export async function sweepContacts(}deps.tick(`contact ${c.resourceName}`);}- // Cursor commits only after the whole sweep succeeded.+ // 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+ // list without one keeps the token it already had.if (result.nextSyncToken) state.contacts_sync_token = result.nextSyncToken;+ else if (maskChanged) state.contacts_sync_token = null;+ state.contacts_person_fields = CONTACT_PERSON_FIELDS;+}++/**+ * #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+ * deleted or renamed group is current for every page rendered from now on,+ * an untouched contact's page refreshes when it next changes or on `--full`),+ * an incomplete read is merged over it and said so, an unreadable directory+ * falls back to the cache. A group no entry names is rendered as its raw id.+ */+async function resolveContactGroups(+ deps: GoogleSyncDeps,+ people: PeopleClient,+ state: GoogleSourceState,+ contacts: ContactData[],+): Promise<Record<string, string>> {+ const cached = state.contact_groups ?? {};+ if (!contacts.some((c) => !c.deleted && c.groups.length > 0)) return cached;+ try {+ const { names, complete } = await people.listContactGroups(deps.opts.signal ? { signal: deps.opts.signal } : {});+ if (!complete) deps.log('[google] contact groups directory exceeds the bounded read; groups it did not name keep their ids');+ state.contact_groups = complete ? names : { ...cached, ...names };+ return state.contact_groups;+ } catch (e) {+ deps.log(`[google] contact groups unavailable (${e instanceof Error ? e.message : String(e)}); pages keep cached names or raw ids`);+ return cached;+ }}/** Existing calendar page's source_path for an event id, or null. */diff --git a/src/core/google/types.ts b/src/core/google/types.tsindex 359a0f6e03..d8c04f0de9 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -132,6 +132,21 @@ export interface GoogleSourceState {*/calendar_horizon_ms?: number | null;contacts_sync_token: string | null;+ /**+ * #6324: the `personFields` mask `contacts_sync_token` was minted under+ * (`CONTACT_PERSON_FIELDS` at the time). Written together with the token+ * after a successful sweep and never on its own: People rejects a token+ * reused with different request parameters, so a mask that differs from+ * the current constant means the token is unusable and the sweep lists+ * fully. Absent on state saved before the mask grew (legacy = the old mask).+ */+ contacts_person_fields?: string | null;+ /**+ * #6324: contact-group directory cache (resource name → display name) from+ * the last successful `contactGroups` read; the fallback when the directory+ * cannot be read during a sweep. Never authoritative on its own.+ */+ contact_groups?: Record<string, string>;last_full_at: string | null;gmail_attachment_backfill?: {version: 1;@@ -279,8 +294,17 @@ export interface ContactData {resourceName: string;displayName: string | null;emails: string[];+ /** #6324: E.164 `canonicalForm` when Google supplies it, else the entered value; deduplicated. */+ phones: string[];organization: string | null;title: string | null;+ /**+ * #6324: user-created contact groups (system groups dropped). The client+ * fills `id` (`contactGroups/<id>`); the sweep resolves `name` from the+ * group directory and leaves null for a group it could not resolve, which+ * the page then carries as the raw id.+ */+ groups: Array<{ id: string; name: string | null }>;deleted: boolean;}diff --git a/test/connector-wave3.test.ts b/test/connector-wave3.test.tsindex fc5ad82f4f..cc02018f20 100644--- a/test/connector-wave3.test.ts+++ b/test/connector-wave3.test.ts@@ -383,10 +383,17 @@ test('migration 176: re-keys the newest committed checkpoint, re-walks a compactexpect(await migrateConnectorCheckpoints(engine, () => {})).toEqual({ rekeyed: [], rewalking: [], removed: { checkpoints: 0, retries: 0 } });expect(await engine.executeRaw("SELECT op,fingerprint,completed_keys FROM op_checkpoints WHERE op LIKE 'managed-connector%' ORDER BY op,fingerprint")).toEqual(snapshot);// The first post-upgrade runs: the live source resumes its legacy cursor and is pinned with unverified continuity; the compacted one re-walks once.+ // #6324: the resumed cursor carries no `contacts_person_fields`, so it was minted under the old field mask and People would+ // reject it; the first sweep lists without it and commits a token under the current mask, which the second sweep reuses.calls.length = 0;await google(engine, live, fetcher);- expect(calls.some(url => url.includes('syncToken=legacy-token'))).toBe(true);+ const connections = () => calls.filter(url => url.includes('/people/me/connections'));+ expect(connections().length).toBeGreaterThan(0);+ expect(connections().some(url => url.includes('syncToken='))).toBe(false);expect((await readConnectorSourceStatuses(engine)).get(live.id)).toMatchObject({ upgrade_recovery: 'resumed', continuity_unverified: true, account_pinned: true });+ calls.length = 0;+ await google(engine, live, fetcher);+ expect(connections().some(url => url.includes('syncToken=contacts-stable'))).toBe(true);await google(engine, compacted, fetcher);expect((await readConnectorSourceStatuses(engine)).get(compacted.id)).toMatchObject({ upgrade_recovery: 'none' });}diff --git a/test/contacts-phone-only-groups-6324.test.ts b/test/contacts-phone-only-groups-6324.test.tsnew file mode 100644index 0000000000..25ddf7f04e--- /dev/null+++ b/test/contacts-phone-only-groups-6324.test.ts@@ -0,0 +1,318 @@+/**+ * #6324: Google contacts carry phone numbers and contact groups; the contacts+ * cursor is bound to the field mask that minted it.+ *+ * Client: `CONTACT_PERSON_FIELDS` on every request (identical across pages),+ * E.164 phones, user groups without the system ones, a non-expiry 400 on a+ * syncToken request typed as `GoogleSyncTokenRejectedError`, and a bounded+ * `contactGroups` directory walk that says when it is incomplete.+ * Render: phone-only pages (nameless ones at `contact-<sha8>`), `phones:` and+ * `groups:` frontmatter, email-only pages unchanged.+ * Sweep: token and mask commit together after success only; a changed mask+ * forces one full list; expired or rejected tokens get one full-list attempt;+ * tokenless success never leaves a token the mask does not cover; the+ * tombstone of a nameless phone contact removes its page; the group directory+ * is read only when needed and degrades to the cache or raw ids.+ */+import { describe, expect, test } from 'bun:test';++import { CredentialError } from '../src/core/creds/errors.ts';+import { CONTACT_PERSON_FIELDS, GoogleSyncTokenRejectedError, PeopleClient } from '../src/core/google/google-clients.ts';+import { contactIdSlug, personSlugFromContact, renderPersonPage, sha8 } from '../src/core/google/google-render.ts';+import { sweepContacts } from '../src/core/google/people-calendar-sweep.ts';+import type { GoogleSyncDeps, GoogleSyncSummary } from '../src/core/google/sweep-shared.ts';+import type { ContactData, GoogleSourceState } from '../src/core/google/types.ts';++const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const tokens = { getAccessToken: async () => 'token', forceRefresh: async () => 'token' };++function fakePeople(handler: (u: URL, n: number) => Response | Promise<Response>) {+ const calls: URL[] = [];+ const people = new PeopleClient(tokens, async (url) => {+ const u = new URL(String(url));+ calls.push(u);+ return handler(u, calls.length);+ });+ return { people, calls };+}++function person(id: string, over: Record<string, unknown> = {}) {+ return { resourceName: `people/${id}`, ...over };+}++function contact(over: Partial<ContactData> = {}): ContactData {+ return { resourceName: 'people/c1', displayName: 'Bob Example', emails: [], phones: ['+15550100'], organization: null, title: null, groups: [], deleted: false, ...over };+}++const SYSTEM = [{ contactGroupMembership: { contactGroupResourceName: 'contactGroups/myContacts' } }, { contactGroupMembership: { contactGroupResourceName: 'contactGroups/starred' } }];+const USER_GROUP = { contactGroupMembership: { contactGroupResourceName: 'contactGroups/abc123' } };++// ── PeopleClient ─────────────────────────────────────────────────────────────++describe('PeopleClient (#6324)', () => {+ test('asks for phones and memberships; maps E.164 phones and user groups; drops system groups', async () => {+ const { people, calls } = fakePeople(() => json({+ connections: [person('c1', {+ names: [{ displayName: 'Bob Example' }],+ phoneNumbers: [{ value: '(555) 010-0', canonicalForm: '+15550100' }, { value: '+15550100' }, { value: ' 555 0101 ' }, { value: '' }],+ memberships: [...SYSTEM, USER_GROUP, USER_GROUP],+ })],+ nextSyncToken: 'ppl-1',+ }));+ const { contacts } = await people.listConnections({});+ expect(CONTACT_PERSON_FIELDS).toBe('names,emailAddresses,organizations,phoneNumbers,memberships');+ expect(calls[0].searchParams.get('personFields')).toBe(CONTACT_PERSON_FIELDS);+ expect(contacts[0].phones).toEqual(['+15550100', '555 0101']);+ expect(contacts[0].groups).toEqual([{ id: 'contactGroups/abc123', name: null }]);+ });++ test('every page of a list repeats the same parameters, the syncToken included', async () => {+ const { people, calls } = fakePeople((u) => u.searchParams.has('pageToken')+ ? json({ connections: [], nextSyncToken: 'ppl-2' })+ : json({ connections: [], nextPageToken: 'page-2' }));+ expect((await people.listConnections({ syncToken: 'ppl-1' })).nextSyncToken).toBe('ppl-2');+ expect(calls).toHaveLength(2);+ for (const key of ['personFields', 'pageSize', 'requestSyncToken', 'syncToken']) {+ expect(calls[1].searchParams.get(key)).toBe(calls[0].searchParams.get(key));+ }+ expect(calls[0].searchParams.get('syncToken')).toBe('ppl-1');+ expect(calls[1].searchParams.get('pageToken')).toBe('page-2');+ });++ test('a non-expiry 400 on a syncToken request is typed as rejected and stays a CredentialError; the same 400 on a full list is a plain upstream error', async () => {+ const { people } = fakePeople(() => json({ error: { code: 400, message: 'Request parameters do not match the sync token.' } }, 400));+ let withToken: unknown;+ await people.listConnections({ syncToken: 'old' }).catch((e) => { withToken = e; });+ expect(withToken).toBeInstanceOf(GoogleSyncTokenRejectedError);+ expect(withToken).toBeInstanceOf(CredentialError);+ expect((withToken as CredentialError).code).toBe('upstream');+ let full: unknown;+ await people.listConnections({ syncToken: null }).catch((e) => { full = e; });+ expect(full).toBeInstanceOf(CredentialError);+ expect(full).not.toBeInstanceOf(GoogleSyncTokenRejectedError);+ });++ test('listContactGroups walks pages, drops system groups, and reports an incomplete directory', async () => {+ const paged = fakePeople((u) => u.searchParams.has('pageToken')+ ? json({ contactGroups: [{ resourceName: 'contactGroups/def456', name: 'Portfolio', groupType: 'USER_CONTACT_GROUP' }] })+ : json({ contactGroups: [+ { resourceName: 'contactGroups/abc123', formattedName: 'Investors', groupType: 'USER_CONTACT_GROUP' },+ { resourceName: 'contactGroups/myContacts', name: 'myContacts', groupType: 'SYSTEM_CONTACT_GROUP' },+ ], nextPageToken: 'g2' }));+ expect(await paged.people.listContactGroups()).toEqual({ names: { 'contactGroups/abc123': 'Investors', 'contactGroups/def456': 'Portfolio' }, complete: true });+ expect(paged.calls).toHaveLength(2);+ expect(paged.calls[0].pathname).toBe('/v1/contactGroups');+ expect(paged.calls[0].searchParams.get('groupFields')).toBe('name,groupType');++ const endless = fakePeople((_u, n) => json({ contactGroups: [{ resourceName: `contactGroups/g${n}`, name: `Group ${n}` }], nextPageToken: `g${n + 1}` }));+ const result = await endless.people.listContactGroups();+ expect(result.complete).toBe(false);+ expect(endless.calls).toHaveLength(10);+ expect(Object.keys(result.names)).toHaveLength(10);+ });+});++// ── Render ───────────────────────────────────────────────────────────────────++describe('renderPersonPage (#6324)', () => {+ test('a named phone-only contact renders with phones: frontmatter and no phone alias', () => {+ const page = renderPersonPage(contact({ phones: ['+15550100', '+15550101'] }));+ expect(page?.relPath).toBe('people/bob-example.md');+ const md = page!.markdown;+ expect(md).toContain('title: "Bob Example"');+ expect(md).toContain('emails: []');+ expect(md).toContain('phones: \n - "+15550100"\n - "+15550101"');+ expect(md).toContain('aliases: \n - "Bob Example"\n');+ expect(md.match(/^aliases: \n((?: - .*\n)+)/m)![1]).not.toContain('+1555');+ expect(md).toContain('Contact: +15550100, +15550101. [Source: Google Contacts]');+ });++ test('a nameless phone-only contact lands at contact-<sha8> (id-keyed, never phone digits), disambiguation or not', () => {+ const c = contact({ displayName: null, resourceName: 'people/c9' });+ const slug = `people/contact-${sha8('people/c9')}`;+ expect(contactIdSlug('people/c9')).toBe(slug);+ expect(personSlugFromContact(c)).toBe(slug);+ expect(personSlugFromContact(c, true)).toBe(slug);+ expect(renderPersonPage(c)?.relPath).toBe(`${slug}.md`);+ expect(renderPersonPage(c)!.markdown).toContain('title: "+15550100"');+ expect(personSlugFromContact(contact({ displayName: null, phones: [] }))).toBeNull();+ expect(renderPersonPage(contact({ phones: [] }))).toBeNull();+ });++ test('email-only pages carry neither phones: nor groups:; group names render and an unresolved group keeps its id', () => {+ const emailOnly = renderPersonPage(contact({ emails: ['[email protected]'], phones: [] }))!.markdown;+ expect(emailOnly).not.toContain('phones:');+ expect(emailOnly).not.toContain('groups:');+ expect(emailOnly).toContain('Contact: [email protected].');+ const grouped = renderPersonPage(contact({ groups: [{ id: 'contactGroups/abc123', name: 'Investors' }, { id: 'contactGroups/zzz', name: null }] }))!.markdown;+ expect(grouped).toContain('groups: \n - "Investors"\n - "contactGroups/zzz"\n---');+ });+});++// ── Sweep ────────────────────────────────────────────────────────────────────++interface StoredPage { slug: string; source_path: string; contact_id: string | null; markdown: string }++function harness(state: Partial<GoogleSourceState> = {}, opts: { idLookup?: boolean; onImport?: (relPath: string) => void } = {}) {+ const pages = new Map<string, StoredPage>();+ const log: string[] = [];+ const controller = new AbortController();+ const managed = {+ async page(slug: string) {+ const p = pages.get(slug);+ return p ? { frontmatter: p.contact_id ? { google_contact_id: p.contact_id } : {} } : null;+ },+ async importMarkdown(source_path: string, markdown: string) {+ opts.onImport?.(source_path);+ const slug = source_path.replace(/\.md$/, '');+ const created = !pages.has(slug);+ pages.set(slug, { slug, source_path, contact_id: markdown.match(/^google_contact_id: "([^"]+)"/m)?.[1] ?? null, markdown });+ return { slug, chunks: 0, status: 'imported' as const, created };+ },+ async delete(slug: string) { return pages.delete(slug); },+ };+ const engine = {+ async executeRaw(sql: string, params: unknown[]) {+ if (sql.includes("frontmatter->>'google_contact_id'")) {+ if (opts.idLookup === false) return [];+ return [...pages.values()].filter((p) => p.contact_id === params[1]).map((p) => ({ source_path: p.source_path }));+ }+ if (sql.includes('source_path = $2')) return [...pages.values()].filter((p) => p.source_path === params[1]).map((p) => ({ slug: p.slug }));+ return [];+ },+ };+ const full: GoogleSourceState = { gmail_history_id: null, gmail_backfill_floor_ms: null, gmail_backfill_done: false, gmail_newest_ms: null,+ calendar_sync_token: null, contacts_sync_token: null, last_full_at: null, ...state };+ const summary: GoogleSyncSummary = { status: 'synced', added: 0, modified: 0, deleted: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], threadsSeen: 0,+ attachmentInspection: {}, extractEligibility: {}, failedFiles: 0 };+ const run = (people: PeopleClient, syncOpts: { full?: boolean } = {}) => {+ const deps = { managed, engine, sourceId: 'g', cfg: { dir: '/nonexistent/google', contactsDir: 'people', account: '[email protected]' },+ opts: { ...syncOpts, signal: controller.signal }, entry: { meta: {} }, log: (m: string) => log.push(m), tick: () => {}, exclusion: {}, extractCandidates: [], processedThreads: new Set() };+ return sweepContacts(deps as unknown as GoogleSyncDeps, people, full, undefined, summary, new Set());+ };+ return { pages, log, state: full, summary, controller, run, seed(page: StoredPage) { pages.set(page.slug, page); } };+}++const BOB = person('c1', { names: [{ displayName: 'Bob Example' }], phoneNumbers: [{ canonicalForm: '+15550100' }], memberships: [USER_GROUP] });+const NAMELESS = person('c9', { phoneNumbers: [{ canonicalForm: '+15550199' }] });++/** A People fake: full lists return `all`, syncToken lists return `delta` (or an error), the directory names one group. */+function peopleFake(all: unknown[], o: { delta?: unknown[] | ((u: URL) => Response); token?: string | null; groups?: (u: URL) => Response } = {}) {+ return fakePeople((u) => {+ if (u.pathname === '/v1/contactGroups') return o.groups ? o.groups(u) : json({ contactGroups: [{ resourceName: 'contactGroups/abc123', name: 'Investors' }] });+ if (u.searchParams.has('syncToken')) {+ if (typeof o.delta === 'function') return o.delta(u);+ return json({ connections: o.delta ?? [], nextSyncToken: o.token === undefined ? 'ppl-delta' : o.token });+ }+ return json(o.token === undefined ? { connections: all, nextSyncToken: 'ppl-1' } : o.token === null ? { connections: all } : { connections: all, nextSyncToken: o.token });+ });+}++describe('sweepContacts cursor contract (#6324)', () => {+ test('a legacy token (no recorded mask) is not reused: one full list, then token and mask commit together and the next sweep is incremental', async () => {+ const h = harness({ contacts_sync_token: 'legacy-token' });+ const { people, calls } = peopleFake([BOB]);+ await h.run(people);+ const listCalls = () => calls.filter((u) => u.pathname.endsWith('/connections'));+ expect(listCalls()).toHaveLength(1);+ expect(listCalls()[0].searchParams.has('syncToken')).toBe(false);+ expect(h.log).toContain('[google] contacts field mask changed; full re-list');+ expect(h.state.contacts_sync_token).toBe('ppl-1');+ expect(h.state.contacts_person_fields).toBe(CONTACT_PERSON_FIELDS);+ expect(h.pages.get('people/bob-example')!.markdown).toContain('groups: \n - "Investors"');+ await h.run(people);+ expect(listCalls()[1].searchParams.get('syncToken')).toBe('ppl-1');+ expect(h.state.contacts_sync_token).toBe('ppl-delta');+ });++ test('an abort mid-sweep and an import failure both commit neither token nor mask', async () => {+ const aborted = harness({ contacts_sync_token: 'legacy-token' }, { onImport: () => aborted.controller.abort() });+ await aborted.run(peopleFake([BOB, NAMELESS]).people);+ expect(aborted.pages.size).toBe(1);+ expect(aborted.state.contacts_sync_token).toBe('legacy-token');+ expect(aborted.state.contacts_person_fields).toBeUndefined();++ const failing = harness({ contacts_sync_token: 'legacy-token' }, { onImport: () => { throw new Error('fixture import outage'); } });+ await expect(failing.run(peopleFake([BOB]).people)).rejects.toThrow('fixture import outage');+ expect(failing.state.contacts_sync_token).toBe('legacy-token');+ expect(failing.state.contacts_person_fields).toBeUndefined();+ });++ test('an expired token re-lists once and commits the replacement', async () => {+ const h = harness({ contacts_sync_token: 'stale', contacts_person_fields: CONTACT_PERSON_FIELDS });+ const { people, calls } = peopleFake([BOB], { delta: () => json({ error: { code: 400, message: 'Sync token is expired.' } }, 400) });+ await h.run(people);+ expect(calls.filter((u) => u.pathname.endsWith('/connections')).map((u) => u.searchParams.get('syncToken'))).toEqual(['stale', null]);+ expect(h.log).toContain('[google] contacts syncToken expired; full re-list');+ expect(h.state.contacts_sync_token).toBe('ppl-1');+ });++ test('an unrelated 400 on a syncToken request gets exactly one full-list attempt; a second failure propagates and blesses nothing', async () => {+ const recovered = harness({ contacts_sync_token: 'mismatch', contacts_person_fields: CONTACT_PERSON_FIELDS });+ const once = peopleFake([BOB], { delta: () => json({ error: { code: 400, message: 'Request parameters do not match the sync token.' } }, 400) });+ await recovered.run(once.people);+ expect(once.calls.filter((u) => u.pathname.endsWith('/connections'))).toHaveLength(2);+ expect(recovered.log).toContain('[google] contacts syncToken rejected (HTTP 400); one full re-list');+ expect(recovered.state.contacts_sync_token).toBe('ppl-1');++ const wedged = harness({ contacts_sync_token: 'mismatch', contacts_person_fields: CONTACT_PERSON_FIELDS });+ const always = fakePeople(() => json({ error: { code: 400, message: 'Invalid personFields' } }, 400));+ await expect(wedged.run(always.people)).rejects.toBeInstanceOf(CredentialError);+ expect(always.calls.map((u) => u.searchParams.get('syncToken'))).toEqual(['mismatch', null]);+ expect(wedged.state.contacts_sync_token).toBeNull();+ expect(wedged.pages.size).toBe(0);+ });++ test('tokenless success: a changed mask leaves no cursor so the next sweep lists fully again; an unchanged mask keeps the token it had', async () => {+ const changed = harness({ contacts_sync_token: 'legacy-token' });+ const silent = peopleFake([BOB], { token: null });+ await changed.run(silent.people);+ expect(changed.state.contacts_sync_token).toBeNull();+ expect(changed.state.contacts_person_fields).toBe(CONTACT_PERSON_FIELDS);+ await changed.run(silent.people);+ expect(silent.calls.filter((u) => u.pathname.endsWith('/connections')).every((u) => !u.searchParams.has('syncToken'))).toBe(true);++ const same = harness({ contacts_sync_token: 'ppl-1', contacts_person_fields: CONTACT_PERSON_FIELDS });+ await same.run(peopleFake([BOB], { token: null }).people, { full: true });+ expect(same.state.contacts_sync_token).toBe('ppl-1');+ });++ test('a nameless phone contact lands at contact-<sha8>; its bare tombstone removes that page even when the id lookup misses', async () => {+ const h = harness({}, { idLookup: false });+ const slug = contactIdSlug('people/c9');+ await h.run(peopleFake([NAMELESS]).people);+ expect([...h.pages.keys()]).toEqual([slug]);+ expect(h.pages.get(slug)!.markdown).toContain('phones: \n - "+15550199"');+ await h.run(peopleFake([], { delta: [person('c9', { metadata: { deleted: true } })] }).people);+ expect(h.pages.size).toBe(0);+ expect(h.summary.deleted).toBe(1);+ });++ test('slug collision: a phone-only contact whose base slug another contact owns gets the disambiguated slug', async () => {+ const h = harness();+ h.seed({ slug: 'people/bob-example', source_path: 'people/bob-example.md', contact_id: 'people/other', markdown: '' });+ await h.run(peopleFake([BOB]).people);+ expect([...h.pages.keys()].sort()).toEqual(['people/bob-example', `people/bob-example-${sha8('people/c1')}`]);+ expect(h.pages.get('people/bob-example')!.contact_id).toBe('people/other');+ });++ test('group cache: the directory is read only when a listed contact has a user group; an unreadable directory falls back to the cache; an incomplete read says so and keeps raw ids', async () => {+ const plain = peopleFake([person('c2', { names: [{ displayName: 'Dana Example' }], emailAddresses: [{ value: '[email protected]' }], memberships: SYSTEM })]);+ await harness().run(plain.people);+ expect(plain.calls.some((u) => u.pathname === '/v1/contactGroups')).toBe(false);++ const cached = harness({ contact_groups: { 'contactGroups/abc123': 'Cached Investors' } });+ await cached.run(peopleFake([BOB], { groups: () => json({ error: { code: 400, message: 'fixture directory outage' } }, 400) }).people);+ expect(cached.pages.get('people/bob-example')!.markdown).toContain('groups: \n - "Cached Investors"');+ expect(cached.log.some((l) => l.startsWith('[google] contact groups unavailable'))).toBe(true);+ expect(cached.state.contact_groups).toEqual({ 'contactGroups/abc123': 'Cached Investors' });++ const partial = harness({ contact_groups: { 'contactGroups/old': 'Old Group' } });+ const bobTwoGroups = person('c1', { names: [{ displayName: 'Bob Example' }], phoneNumbers: [{ canonicalForm: '+15550100' }],+ memberships: [USER_GROUP, { contactGroupMembership: { contactGroupResourceName: 'contactGroups/zzz' } }] });+ await partial.run(peopleFake([bobTwoGroups], { groups: (u) => json({ contactGroups: [{ resourceName: 'contactGroups/abc123', name: 'Investors' }], nextPageToken: `${u.searchParams.get('pageToken') ?? 'g'}1` }) }).people);+ expect(partial.pages.get('people/bob-example')!.markdown).toContain('groups: \n - "Investors"\n - "contactGroups/zzz"');+ expect(partial.log.some((l) => l.startsWith('[google] contact groups directory exceeds the bounded read'))).toBe(true);+ expect(partial.state.contact_groups).toEqual({ 'contactGroups/old': 'Old Group', 'contactGroups/abc123': 'Investors' });+ });+});diff --git a/test/google-clients.test.ts b/test/google-clients.test.tsindex 880cdfd28f..6a0527bdc5 100644--- a/test/google-clients.test.ts+++ b/test/google-clients.test.ts@@ -23,6 +23,7 @@ import type {} from '../src/core/creds/vault.ts';import {CalendarClient,+ CONTACT_PERSON_FIELDS,extractCalendarMethod,GmailClient,GoogleApiClient,@@ -991,7 +992,7 @@ describe('PeopleClient', () => {test('listConnections requests personFields and normalizes contacts', async () => {const h = makeHarness((u) => {- expect(u.searchParams.get('personFields')).toBe('names,emailAddresses,organizations');+ expect(u.searchParams.get('personFields')).toBe(CONTACT_PERSON_FIELDS);expect(u.searchParams.get('requestSyncToken')).toBe('true');return json({connections: [@@ -1017,8 +1018,10 @@ describe('PeopleClient', () => {resourceName: 'people/c000000001',displayName: 'Alice Example', // primary name winsemails: ['[email protected]'], // trimmed, lowercased, non-addresses dropped+ phones: [],organization: 'Acme Example',title: 'Engineer',+ groups: [],deleted: false,});expect(contacts[1].deleted).toBe(true);diff --git a/test/google-render.test.ts b/test/google-render.test.tsindex 9936132256..af0ccc57f4 100644--- a/test/google-render.test.ts+++ b/test/google-render.test.ts@@ -443,8 +443,10 @@ function contact(over: Partial<ContactData> = {}): ContactData {resourceName: 'people/c000000001',displayName: 'Alice Example',emails: ['[email protected]', '[email protected]'],+ phones: [],organization: 'Acme Example',title: 'Engineer',+ groups: [],deleted: false,...over,};